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
loomchild/segment
segment/src/test/java/net/loomchild/segment/srx/io/SrxParsersTest.java
[ "public static Reader getReader(InputStream inputStream) {\n\ttry {\n\t\tReader reader = new InputStreamReader(inputStream, \"utf-8\");\n\t\treturn reader;\n\t} catch (UnsupportedEncodingException e) {\n\t\tthrow new IORuntimeException(e);\n\t}\n}", "public static InputStream getResourceStream(String name) {\n\tInputStream inputStream = Util.class.getClassLoader()\n\t\t\t.getResourceAsStream(name);\n\tif (inputStream == null) {\n\t\tthrow new ResourceNotFoundException(name);\n\t}\n\treturn inputStream;\n}", "public class LanguageRule {\n\n\tprivate List<Rule> ruleList;\n\n\tprivate String name;\n\n\t/**\n\t * Creates language rule.\n\t * \n\t * @param name language rule name\n\t * @param ruleList rule list (it will be shallow copied)\n\t */\n\tpublic LanguageRule(String name, List<Rule> ruleList) {\n\t\tthis.ruleList = new ArrayList<Rule>(ruleList);\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Creates empty language rule.\n\t * \n\t * @param name language rule name\n\t */\n\tpublic LanguageRule(String name) {\n\t\tthis(name, new ArrayList<Rule>());\n\t}\n\n\t/**\n\t * @return unmodifiable rules list\n\t */\n\tpublic List<Rule> getRuleList() {\n\t\treturn Collections.unmodifiableList(ruleList);\n\t}\n\n\t/**\n\t * Adds rule to the end of rule list.\n\t * @param rule\n\t */\n\tpublic void addRule(Rule rule) {\n\t\truleList.add(rule);\n\t}\n\n\t/**\n\t * @return language rule name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n}", "public class SrxDocument {\n\n\t/**\n\t * Default cascade value.\n\t */\n\tpublic static final boolean DEFAULT_CASCADE = true;\n\n\tprivate boolean cascade;\n\n\tprivate List<LanguageMap> languageMapList;\n\t\n\tprivate SrxDocumentCache cache;\n\n\t/**\n\t * Creates empty document.\n\t * \n\t * @param cascade true if document is cascading\n\t */\n\tpublic SrxDocument(boolean cascade) {\n\t\tthis.cascade = cascade;\n\t\tthis.languageMapList = new ArrayList<LanguageMap>();\n\t\tthis.cache = new SrxDocumentCache();\n\t}\n\n\t/**\n\t * Creates empty document with default cascade. See {@link #DEFAULT_CASCADE}.\n\t */\n\tpublic SrxDocument() {\n\t\tthis(DEFAULT_CASCADE);\n\t}\n\n\t/**\n\t * Sets if document is cascading or not.\n\t * \n\t * @param cascade true f document is cascading\n\t */\n\tpublic void setCascade(boolean cascade) {\n\t\tthis.cascade = cascade;\n\t}\n\n\t/**\n\t * @return true if document is cascading\n\t */\n\tpublic boolean getCascade() {\n\t\treturn cascade;\n\t}\n\n\t/**\n\t * Add language map to this document.\n\t * \n\t * @param pattern language code pattern\n\t * @param languageRule\n\t */\n\tpublic void addLanguageMap(String pattern, LanguageRule languageRule) {\n\t\tLanguageMap languageMap = new LanguageMap(pattern, languageRule);\n\t\tlanguageMapList.add(languageMap);\n\t}\n\n\tpublic List<LanguageMap> getLanguageMapList() {\n\t\treturn languageMapList;\n\t}\t\n\n\t/**\n\t * If cascade is true then returns all language rules matching given\n\t * language code. If cascade is false returns first language rule matching\n\t * given language code. If no matching language rules are found returns\n\t * empty list.\n\t * \n\t * @param languageCode language code, for example en_US\n\t * @return matching language rules\n\t */\n\tpublic List<LanguageRule> getLanguageRuleList(String languageCode) {\n\t\tList<LanguageRule> matchingLanguageRuleList = new ArrayList<LanguageRule>();\n\t\tfor (LanguageMap languageMap : languageMapList) {\n\t\t\tif (languageMap.matches(languageCode)) {\n\t\t\t\tmatchingLanguageRuleList.add(languageMap.getLanguageRule());\n\t\t\t\tif (!cascade) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn matchingLanguageRuleList;\n\t}\n\n\tpublic SrxDocumentCache getCache() {\n\t\treturn cache;\n\t}\n\t\n}", "public interface SrxParser {\n\n\t/**\n\t * Parses SRX document.\n\t * \n\t * @param reader reader from which read the document\n\t * @return initialized SRX document\n\t */\n\tpublic SrxDocument parse(Reader reader);\n\n}", "public class LanguageMap {\n\n\tprivate Pattern languagePattern;\n\n\tprivate LanguageRule languageRule;\n\n\t/**\n\t * Creates mapping.\n\t * \n\t * @param pattern language code pattern\n\t * @param languageRule language rule\n\t */\n\tpublic LanguageMap(String pattern, LanguageRule languageRule) {\n\t\tthis.languagePattern = Pattern.compile(pattern);\n\t\tthis.languageRule = languageRule;\n\t}\n\n\t/**\n\t * @param languageCode language code\n\t * @return true if given language code matches language pattern\n\t */\n\tpublic boolean matches(String languageCode) {\n\t\treturn languagePattern.matcher(languageCode).matches();\n\t}\n\t\n\tpublic Pattern getLanguagePattern() {\n\t\treturn languagePattern;\n\t}\n\n\t/**\n\t * @return language rule\n\t */\n\tpublic LanguageRule getLanguageRule() {\n\t\treturn languageRule;\n\t}\n\n}", "public class Rule {\n\n\tprivate boolean breaking;\n\n\tprivate String beforePattern;\n\n\tprivate String afterPattern;\n\n\t/**\n\t * Creates rule.\n\t * \n\t * @param breaking type of rule; true - break rule, false - exception rule\n\t * @param beforePattern pattern matching text before break\n\t * @param afterPattern pattern matching text after break\n\t */\n\tpublic Rule(boolean breaking, String beforePattern, String afterPattern) {\n\t\tthis.breaking = breaking;\n\t\tthis.beforePattern = beforePattern;\n\t\tthis.afterPattern = afterPattern;\n\t}\n\n\t/**\n\t * @return type of rule; true - break rule, false - exception rule\n\t */\n\tpublic boolean isBreak() {\n\t\treturn breaking;\n\t}\n\n\t/**\n\t * @return pattern matching text before break\n\t */\n\tpublic String getBeforePattern() {\n\t\treturn beforePattern;\n\t}\n\n\t/**\n\t * @return pattern matching text after break\n\t */\n\tpublic String getAfterPattern() {\n\t\treturn afterPattern;\n\t}\n\n}", "public class XmlException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -143693366659133245L;\n\n\tpublic XmlException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic XmlException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic XmlException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}" ]
import static net.loomchild.segment.util.Util.getReader; import static net.loomchild.segment.util.Util.getResourceStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.Reader; import java.util.List; import net.loomchild.segment.srx.LanguageRule; import net.loomchild.segment.srx.SrxDocument; import net.loomchild.segment.srx.SrxParser; import net.loomchild.segment.srx.LanguageMap; import net.loomchild.segment.srx.Rule; import net.loomchild.segment.util.XmlException; import org.junit.Test;
package net.loomchild.segment.srx.io; public class SrxParsersTest { private static final SrxParser ONE = new Srx1Parser(); private static final SrxParser TWO = new Srx2Parser(); private static final SrxParser ANY = new SrxAnyParser(); private static final SrxParser SAX = new Srx2SaxParser(); private static final SrxParser STAX = new Srx2StaxParser(); @Test public void testSrx1One() { testSrx1(ONE); } @Test public void testSrx1Any() { testSrx1(ANY); } @Test public void testSrx1Compare() { testCompare(SRX_1_DOCUMENT_NAME, new SrxParser[] {ONE, ANY}); } private static final String SRX_1_DOCUMENT_NAME = "net/loomchild/segment/res/test/example1.srx"; private void testSrx1(SrxParser parser) {
Reader reader = getReader(getResourceStream(SRX_1_DOCUMENT_NAME));
0
Catherine22/MobileManager
app/src/main/java/com/itheima/mobilesafe/fragments/setup/SetupFragment.java
[ "public class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter {\n private List<Fragment> fragments;\n private int counts;\n\n public MyFragmentStatePagerAdapter(FragmentManager fm, List<Fragment> fragments) {\n super(fm);\n this.fragments = fragments;\n counts = fragments.size();\n }\n\n @Override\n public Fragment getItem(int position) {\n CLog.d(\"MyFragmentStatePagerAdapter\", \"getItem\" + position);\n return fragments.get(position);\n }\n\n @Override\n public int getCount() {\n return counts;\n }\n\n public void setCounts(int counts){\n this.counts = counts;\n notifyDataSetChanged();\n }\n\n public void setFragments(List<Fragment> fragments) {\n this.fragments = fragments;\n notifyDataSetChanged();\n }\n}", "public class CustomBanner extends RelativeLayout {\n private final static String TAG = \"CustomBanner\";\n private MyViewPager vp_container, vp_background;\n private Context ctx;\n private ViewKits viewUtils;\n private LinearLayout ll_dots;\n private List<ImageView> dots = new ArrayList<>();\n private boolean showDots;\n private boolean showBackground;\n private int dotsSrcOn;\n private int dotsSrcOff;\n\n public CustomBanner(Context context, AttributeSet attrs) {\n super(context, attrs);\n ctx = context;\n viewUtils = new ViewKits(ctx);\n initAttr(attrs);\n initView();\n }\n\n\n /**\n * Initialize components\n */\n private void initView() {\n View.inflate(ctx, R.layout.banner, this);\n vp_container = (MyViewPager) this.findViewById(R.id.vp_container);\n vp_background = (MyViewPager) this.findViewById(R.id.vp_background);\n ll_dots = (LinearLayout) this.findViewById(R.id.ll_dots);\n\n if (showDots)\n ll_dots.setVisibility(VISIBLE);\n else\n ll_dots.setVisibility(GONE);\n\n if (showBackground)\n vp_background.setVisibility(VISIBLE);\n else\n vp_background.setVisibility(GONE);\n }\n\n /**\n * Set PagerAdapter on ViewPager\n *\n * @param adapter\n */\n public void setAdapter(PagerAdapter adapter) {\n if (vp_container != null)\n vp_container.setAdapter(adapter);\n }\n\n /**\n * Set PagerAdapter on Background ViewPager\n *\n * @param adapter\n */\n public void setBackgroundAdapter(PagerAdapter adapter) {\n if (vp_background != null)\n vp_background.setAdapter(adapter);\n }\n\n /**\n * Set items and effect\n *\n * @param itemCount\n * @param effect\n * @param backgroundEffect\n */\n public void setView(int itemCount, TransitionEffect effect, TransitionEffect backgroundEffect) {\n if (vp_container != null) {\n vp_container.setPageTransformer(true, BasePageTransformer.getPageTransformer(effect));\n vp_container.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n// CLog.d(TAG, position + \" \" + positionOffset + \" \" + positionOffsetPixels);\n// vp_background.scrollTo((position * Settings.DISPLAY_WIDTH_PX) + positionOffsetPixels, 0);\n\n }\n\n @Override\n public void onPageSelected(int position) {\n for (ImageView dot : dots) {\n dot.setImageResource(dotsSrcOff);\n }\n dots.get(position).setImageResource(dotsSrcOn);\n vp_background.setCurrentItem(position, true);\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n viewUtils.hideKeyboard();\n }\n });\n }\n\n if (vp_background != null) {\n vp_background.setPageTransformer(true, BasePageTransformer.getPageTransformer(backgroundEffect));\n }\n setDotsView(itemCount);\n }\n\n private void setDotsView(int itemCount) {\n for (int i = 0; i < itemCount; i++) {\n ImageView dot = new ImageView(ctx);\n if (i == 0)\n dot.setImageResource(dotsSrcOn);\n else\n dot.setImageResource(dotsSrcOff);\n LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n imgParams.setMargins(10, 10, 10, 10);\n imgParams.gravity = Gravity.CENTER;\n dot.setLayoutParams(imgParams);\n dots.add(dot);\n ll_dots.addView(dot, imgParams);\n }\n }\n\n private void initAttr(AttributeSet attrs) {\n showBackground = attrs.getAttributeBooleanValue(\"http://schemas.android.com/apk/com.itheima.mobilesafe\", \"show_background\", false);\n showDots = attrs.getAttributeBooleanValue(\"http://schemas.android.com/apk/com.itheima.mobilesafe\", \"show_dots\", false);\n dotsSrcOn = attrs.getAttributeIntValue(\"http://schemas.android.com/apk/com.itheima.mobilesafe\", \"dots_src_on\", android.R.drawable.presence_online);\n dotsSrcOff = attrs.getAttributeIntValue(\"http://schemas.android.com/apk/com.itheima.mobilesafe\", \"dots_src_off\", android.R.drawable.presence_invisible);\n }\n}", "public enum TransitionEffect {\n DEFAULT,\n ALPHA,\n STACK,\n FADE,\n ZOOM,\n ZOOMSTACK,\n ZOOMFADE\n}", "public class BroadcastActions {\n public final static String ADMIN_PERMISSION = \"ADMIN_PERMISSION\";\n public final static String SAFE_PHONE = \"SAFE_PHONE\";\n public final static String DISABLE_SWIPING = \"DISABLE_SWIPING\";\n public final static String LOCATION_INFO = \"LOCATION_INFO\";\n public final static String FINISHED_UNINSTALLING = \"FINISHED_UNINSTALLING\";\n public final static String STOP_WATCHDOG = \"STOP_WATCHDOG\";\n public final static String UPDATE_WATCHDOG = \"UPDATE_WATCHDOG\";\n}", "@SuppressWarnings(\"unused\")\npublic class CLog {\n private static final boolean DEBUG = BuildConfig.SHOW_LOG;\n\n public static String getTag() {\n String tag = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getTag\")) {\n tag = \"(\" + ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber() + \")\";\n }\n }\n return tag;\n }\n\n public static void v(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.v(tab, message);\n }\n }\n\n public static void d(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.d(tab, message);\n }\n }\n\n public static void e(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.e(tab, message);\n }\n }\n\n public static void w(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.w(tab, message);\n }\n }\n\n public static void i(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.i(tab, message);\n }\n }\n\n}" ]
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.itheima.mobilesafe.R; import com.itheima.mobilesafe.adapter.MyFragmentStatePagerAdapter; import com.itheima.mobilesafe.ui.my_viewpager.CustomBanner; import com.itheima.mobilesafe.ui.my_viewpager.TransitionEffect; import com.itheima.mobilesafe.utils.BroadcastActions; import com.itheima.mobilesafe.utils.CLog; import java.util.ArrayList; import java.util.List; import tw.com.softworld.messagescenter.Client; import tw.com.softworld.messagescenter.CustomReceiver; import tw.com.softworld.messagescenter.Result;
package com.itheima.mobilesafe.fragments.setup; /** * Created by Catherine on 2016/8/12. * Soft-World Inc. * catherine919@soft-world.com.tw */ public class SetupFragment extends Fragment { private static final String TAG = "SetupFragment"; private Client client;
private MyFragmentStatePagerAdapter forwardAdapter, backAdapter;
0
Nike-Inc/wingtips
wingtips-apache-http-client/src/main/java/com/nike/wingtips/apache/httpclient/WingtipsApacheHttpClientInterceptor.java
[ "@SuppressWarnings(\"WeakerAccess\")\npublic class Tracer {\n\n /**\n * The options for how {@link Span} objects are represented when they are completed. To change how {@link Tracer} serializes spans when logging them\n * call {@link #setSpanLoggingRepresentation(SpanLoggingRepresentation)}.\n */\n public enum SpanLoggingRepresentation {\n /**\n * Causes spans to be output in the logs using {@link Span#toJSON()}.\n */\n JSON,\n /**\n * Causes spans to be output in the logs using {@link Span#toKeyValueString()}.\n */\n KEY_VALUE\n }\n\n /**\n * The options for which {@link Span} fields are put into and taken out of the logger {@link MDC} as {@link Tracer}\n * works with spans.\n */\n public enum SpanFieldForLoggerMdc {\n /**\n * MDC key for storing the current span's {@link Span#getTraceId()}.\n */\n TRACE_ID(\"traceId\"),\n /**\n * MDC key for storing the current span's {@link Span#getSpanId()}.\n */\n SPAN_ID(\"spanId\"),\n /**\n * MDC key for storing the current span's {@link Span#getParentSpanId()}.\n */\n PARENT_SPAN_ID(\"parentSpanId\"),\n /**\n * MDC key for storing the current {@link Span} as a JSON string.\n *\n * <p>WARNING: This can get expensive in some use cases where processing hops threads frequently and the span\n * state is changed often (i.e. lots of tags). Make sure you absolutely need this before including it in a call\n * to {@link #setSpanFieldsForLoggerMdc(SpanFieldForLoggerMdc...)} or {@link #setSpanFieldsForLoggerMdc(Set)}.\n */\n FULL_SPAN_JSON(\"spanJson\");\n\n /**\n * The key to use when calling {@link MDC#put(String, String)} or {@link MDC#remove(String)}.\n */\n public final String mdcKey;\n\n SpanFieldForLoggerMdc(String mdcKey) {\n this.mdcKey = mdcKey;\n }\n\n /**\n * @param span The span to grab the value from.\n * @return The string from the given span associated with this {@link SpanFieldForLoggerMdc}.\n */\n public @Nullable String getMdcValueForSpan(@NotNull Span span) {\n switch (this) {\n case TRACE_ID:\n return span.getTraceId();\n case SPAN_ID:\n return span.getSpanId();\n case PARENT_SPAN_ID:\n return span.getParentSpanId();\n case FULL_SPAN_JSON:\n return span.toJSON();\n default:\n throw new IllegalStateException(\"Unhandled SpanFieldForLoggerMdc type: \" + this);\n }\n }\n }\n\n private static final String VALID_WINGTIPS_SPAN_LOGGER_NAME = \"VALID_WINGTIPS_SPANS\";\n private static final String INVALID_WINGTIPS_SPAN_LOGGER_NAME = \"INVALID_WINGTIPS_SPANS\";\n\n private static final Logger classLogger = LoggerFactory.getLogger(Tracer.class);\n private static final Logger validSpanLogger = LoggerFactory.getLogger(VALID_WINGTIPS_SPAN_LOGGER_NAME);\n private static final Logger invalidSpanLogger = LoggerFactory.getLogger(INVALID_WINGTIPS_SPAN_LOGGER_NAME);\n\n /**\n * ThreadLocal that keeps track of the stack of {@link Span} objects associated with the thread. This is treated as a LIFO stack.\n */\n private static final ThreadLocal<Deque<Span>> currentSpanStackThreadLocal = new ThreadLocal<>();\n\n /**\n * The singleton instance for this class.\n */\n private static final Tracer INSTANCE = new Tracer();\n\n\n /**\n * The sampling strategy this instance will use. Default to sampling everything. Never allow this field to be set to null.\n */\n private RootSpanSamplingStrategy rootSpanSamplingStrategy = new SampleAllTheThingsStrategy();\n\n /**\n * The list of span lifecycle listeners that should be notified when span lifecycle events occur.\n * Note that we use a {@link CopyOnWriteArrayList} to prevent {@link java.util.ConcurrentModificationException}s\n * from occurring if spans are being started/completed/etc while this list is being changed. This is deemed\n * acceptable since iterations over this list happens frequently, but changes to the list should be rare.\n */\n private final List<SpanLifecycleListener> spanLifecycleListeners = new CopyOnWriteArrayList<>();\n\n /**\n * The span representation that should be used when logging completed spans.\n */\n private SpanLoggingRepresentation spanLoggingRepresentation = SpanLoggingRepresentation.JSON;\n\n /**\n * The set of span fields that should be put into and taken out of the logger {@link MDC} as {@link Tracer} works\n * with spans.\n */\n private SpanFieldForLoggerMdc[] spanFieldsForLoggerMdc =\n new SpanFieldForLoggerMdc[]{ SpanFieldForLoggerMdc.TRACE_ID };\n private Set<SpanFieldForLoggerMdc> cachedUnmodifiableSpanFieldsForLoggerMdc =\n Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(spanFieldsForLoggerMdc)));\n\n private Tracer() { /* Intentionally private to enforce singleton pattern. */ }\n\n /**\n * @return The singleton instance of this class.\n */\n public static Tracer getInstance() {\n return INSTANCE;\n }\n\n /**\n * The {@link Span} set as the \"current\" one for this thread.\n * <p/>\n * NOTE: If {@link #currentSpanStackThreadLocal} is null or empty for this thread it will try to reconstitute the {@link Span} from the logging {@link org.slf4j.MDC}.\n * This is useful in some situations, for example async request processing where the thread changes but the MDC is smart enough to transfer the span anyway.\n * In any case as a caller you don't have to care - you'll just get the {@link Span} appropriate for the caller, or null if one hasn't been set up yet.\n */\n public Span getCurrentSpan() {\n Deque<Span> spanStack = currentSpanStackThreadLocal.get();\n\n return (spanStack == null) ? null : spanStack.peek();\n }\n\n /**\n * Starts new span stack (i.e. new incoming request) without a parent span by creating a root span with the given span name.\n * If you have parent span info then you should call {@link #startRequestWithChildSpan(Span, String)} or\n * {@link #startRequestWithSpanInfo(String, String, String, boolean, String, SpanPurpose)} instead). The newly created root span will have a\n * span purpose of {@link SpanPurpose#SERVER}.\n * <p/>\n * NOTE: This method will cause the returned span's {@link Span#getUserId()} to contain null. If you have a user ID you should use\n * {@link #startRequestWithRootSpan(String, String)} instead.\n * <p/>\n * <b>WARNING:</b> This wipes out any existing spans on the span stack for this thread and starts fresh, therefore this should only be called at the request's\n * entry point when it's expected that the span stack should be empty. If you need to start a child span in the middle of a request somewhere then you should call\n * {@link #startSubSpan(String, SpanPurpose)} instead.\n *\n * @param spanName - The span name to use for the new span - should never be null.\n * @return The new span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n public Span startRequestWithRootSpan(String spanName) {\n return startRequestWithRootSpan(spanName, null);\n }\n\n /**\n * Similar to {@link #startRequestWithRootSpan(String)} but takes in an optional {@code userId} to populate the returned {@link Span#getUserId()}.\n * If {@code userId} is null then this method is equivalent to calling {@link #startRequestWithRootSpan(String)}. If you have parent span info then you should call\n * {@link #startRequestWithChildSpan(Span, String)} or {@link #startRequestWithSpanInfo(String, String, String, boolean, String, SpanPurpose)} instead).\n * The newly created root span will have a span purpose of {@link SpanPurpose#SERVER}.\n * <p/>\n * <b>WARNING:</b> This wipes out any existing spans on the span stack for this thread and starts fresh, therefore this should only be called at the request's\n * entry point when it's expected that the span stack should be empty. If you need to start a child span in the middle of a request somewhere then you should call\n * {@link #startSubSpan(String, SpanPurpose)} instead.\n *\n * @param spanName - The span name to use for the new span - should never be null.\n * @param userId - The ID of the user that should be associated with the {@link Span} - can be null.\n * @return The new span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n public Span startRequestWithRootSpan(String spanName, String userId) {\n boolean sampleable = isNextRootSpanSampleable();\n String traceId = TraceAndSpanIdGenerator.generateId();\n return doNewRequestSpan(traceId, null, spanName, sampleable, userId, SpanPurpose.SERVER);\n }\n\n /**\n * Starts a new span stack (i.e. new incoming request) with the given span as the new child span's parent (if you do not have a parent then you should call\n * {@link #startRequestWithRootSpan(String)} or {@link #startRequestWithRootSpan(String, String)} instead). The newly created child span will have a\n * span purpose of {@link SpanPurpose#SERVER}.\n * <p/>\n * <b>WARNING:</b> This wipes out any existing spans on the span stack for this thread and starts fresh, therefore this should only be called at the request's\n * entry point when it's expected that the span stack should be empty. If you need to start a child span in the middle of a request somewhere then you should call\n * {@link #startSubSpan(String, SpanPurpose)} instead.\n *\n * @param parentSpan The span to use as the parent span - should never be null (if you need to start a span without a parent then call\n * {@link #startRequestWithRootSpan(String)} instead).\n * @param childSpanName The span name to use for the new child span - should never be null.\n * @return The new child span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n public Span startRequestWithChildSpan(Span parentSpan, String childSpanName) {\n if (parentSpan == null) {\n throw new IllegalArgumentException(\"parentSpan cannot be null. \" +\n \"If you don't have a parent span then you should call one of the startRequestWithRootSpan(...) methods instead.\");\n }\n\n String parentIdForChildSpan = parentSpan.getSpanId();\n boolean addBadParentIdIndicatorTag = false;\n if (HttpRequestTracingUtils.hasInvalidSpanIdBecauseCallerDidNotSendOne(parentSpan)) {\n parentIdForChildSpan = null;\n addBadParentIdIndicatorTag = true;\n }\n\n Span result = startRequestWithSpanInfo(\n parentSpan.getTraceId(), parentIdForChildSpan, childSpanName, parentSpan.isSampleable(),\n parentSpan.getUserId(), SpanPurpose.SERVER\n );\n\n if (addBadParentIdIndicatorTag) {\n result.putTag(CHILD_OF_SPAN_FROM_HEADERS_WHERE_CALLER_DID_NOT_SEND_SPAN_ID_TAG_KEY, \"true\");\n }\n\n return result;\n }\n\n /**\n * Starts a new span stack (i.e. new incoming request) with the given span info used to create the new span. This method is agnostic on whether the span is a root span\n * or child span - the arguments you pass in (specifically the value of {@code parentSpanId}) will determine root vs child. The other {@code startRequestWith...()} methods\n * should be preferred to this where it makes sense, but if your use case doesn't match those methods then this method allows maximum flexibility in creating a span for\n * a new request.\n * <p/>\n * <b>WARNING:</b> This wipes out any existing spans on the span stack for this thread and starts fresh, therefore this should only be called at the request's\n * entry point when it's expected that the span stack should be empty. If you need to start a child span in the middle of a request somewhere then you should call\n * {@link #startSubSpan(String, SpanPurpose)} instead.\n *\n * @param traceId The new span's {@link Span#getTraceId()} - if this is null then a new random trace ID will be generated for the returned span. If you have parent span info\n * then this should be the parent span's <b>trace</b> ID (not the parent span's span ID).\n * @param parentSpanId The parent span's {@link Span#getSpanId()} - if this is null then the returned {@link Span#getParentSpanId()} will be null causing the returned span\n * to be a root span. If it's non-null then the returned span will be a child span with {@link Span#getParentSpanId()} matching this value.\n * @param newSpanName The span name to use for the new span - should never be null.\n * @param sampleable The new span's {@link Span#isSampleable()} value. Determines whether or not this span should be logged when it is completed.\n * @param userId The new span's {@link Span#getUserId()} value.\n * @param spanPurpose The span's purpose, or null if the purpose is unknown. See the javadocs for {@link SpanPurpose} for details on what each enum option means.\n * For new request spans, this should usually be {@link SpanPurpose#SERVER}.\n *\n * @return The new span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n public Span startRequestWithSpanInfo(String traceId, String parentSpanId, String newSpanName, boolean sampleable, String userId, SpanPurpose spanPurpose) {\n return doNewRequestSpan(traceId, parentSpanId, newSpanName, sampleable, userId, spanPurpose);\n }\n\n /**\n * Starts a new child sub-span using the {@link #getCurrentSpan()} current span as its parent and pushes this new sub-span onto the span stack so that it becomes the\n * current span. When this new child sub-span is completed using {@link #completeSubSpan()} then it will be popped off the span stack and its parent will once again\n * become the current span.\n * <p/>\n * <b>WARNING:</b> This does *NOT* wipe out any existing spans on the span stack - it pushes a new one onto the stack. If you're calling from a spot in the code where\n * you know there should never be any existing spans on the thread's span stack (i.e. new incoming request) you should call one of the {@code startRequest...()} methods\n * instead.\n *\n * @param spanName The {@link Span#getSpanName()} to use for the new child sub-span.\n * @param spanPurpose The {@link SpanPurpose} for the new sub-span. Since this is a sub-span it should almost always be either {@link SpanPurpose#CLIENT}\n * (if this sub-span encompasses an outbound/downstream/out-of-process call), or {@link SpanPurpose#LOCAL_ONLY}. See the javadocs\n * for {@link SpanPurpose} for full details on what each enum option means.\n * @return The new child sub-span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n public Span startSubSpan(String spanName, SpanPurpose spanPurpose) {\n Span parentSpan = getCurrentSpan();\n if (parentSpan == null) {\n classLogger.error(\n \"WINGTIPS USAGE ERROR - Expected getCurrentSpan() to return a span for use as a parent for a new child sub-span but null was returned instead. This probably \" +\n \"means the request's overall span was never started. The child sub-span will still be started without any parent. wingtips_usage_error=true bad_span_stack=true\",\n new Exception(\"Stack trace for debugging purposes\")\n );\n }\n\n Span childSpan = (parentSpan != null)\n ? parentSpan.generateChildSpan(spanName, spanPurpose)\n : Span.generateRootSpanForNewTrace(spanName, spanPurpose).withSampleable(isNextRootSpanSampleable()).build();\n\n pushSpanOntoCurrentSpanStack(childSpan);\n\n notifySpanStarted(childSpan);\n notifyIfSpanSampled(childSpan);\n\n return childSpan;\n }\n\n /**\n * This method is here for the (hopefully rare) cases where you want to start a new span but don't control the\n * context where your code is executed (e.g. a third party library) - this method will start a new overall request\n * span or a new subspan depending on the current thread's span stack state at the time this method is called.\n * In other words this method is a shortcut for the following code:\n *\n * <pre>\n * Tracer tracer = Tracer.getInstance();\n * if (tracer.getCurrentSpanStackSize() == 0) {\n * return tracer.startRequestWithRootSpan(spanName);\n * }\n * else {\n * return tracer.startSubSpan(spanName, SpanPurpose.LOCAL_ONLY);\n * }\n * </pre>\n *\n * <p>This method assumes {@link SpanPurpose#SERVER} if the returned span is an overall request span, and\n * {@link SpanPurpose#LOCAL_ONLY} if it's a subspan. If you know the span purpose already and this behavior is\n * not what you want (i.e. when surrounding a HTTP client or database call and you want to use {@link\n * SpanPurpose#CLIENT}) then use the {@link #startSpanInCurrentContext(String, SpanPurpose)} method instead.\n *\n * <p><b>WARNING:</b> As stated above, this method is here to support libraries where they need to create a span\n * for some work, but do not necessarily know how or where they are going to be used in a project, and therefore\n * don't know whether tracing has been setup yet with an overall request span. Most of the time you will know where\n * you are in relation to overall request span or subspan, and should use the appropriate\n * {@code Tracer.startRequestWith*(...)} or {@code Tracer.startSubSpan(...)} methods directly as those methods spit\n * out error logging when the span stack is not in the expected state (indicating a Wingtips usage error). Using\n * this method everywhere can swallow critical error logging that would otherwise let you know Wingtips isn't being\n * used correctly and that your distributed tracing info is potentially unreliable.\n *\n * <p><b>This method is the equivalent of swallowing exceptions when Wingtips isn't being used correctly - all\n * diagnostic debugging information will be lost. This method should not be used simply because it is\n * convenient!</b>\n *\n * @param spanName The {@link Span#getSpanName()} to use for the new span.\n * @return A new span that might be the root span of a new span stack (i.e. if the current span stack is empty),\n * or a new subspan (i.e. if the current span stack is *not* empty). NOTE: Please read the warning in this method's\n * javadoc - abusing this method can lead to broken tracing without any errors showing up in the logs.\n */\n public Span startSpanInCurrentContext(String spanName) {\n // If the current span stack is empty, then we start a new overall request span.\n // Otherwise we start a subspan.\n if (getCurrentSpanStackSize() == 0) {\n return startRequestWithRootSpan(spanName);\n }\n else {\n return startSubSpan(spanName, SpanPurpose.LOCAL_ONLY);\n }\n }\n\n /**\n * This method is here for the (hopefully rare) cases where you want to start a new span but don't control the\n * context where your code is executed (e.g. a third party library) - this method will start a new overall request\n * span or a new subspan depending on the current thread's span stack state at the time this method is called.\n * In other words this method is a shortcut for the following code:\n *\n * <pre>\n * Tracer tracer = Tracer.getInstance();\n * if (tracer.getCurrentSpanStackSize() == 0) {\n * boolean sampleable = tracer.isNextRootSpanSampleable();\n * return tracer.startRequestWithSpanInfo(null, null, spanName, sampleable, null, spanPurpose);\n * }\n * else {\n * return tracer.startSubSpan(spanName, spanPurpose);\n * }\n * </pre>\n *\n * <p>This method lets you pass in the {@link SpanPurpose} for the new span. If you only need the default behavior\n * of {@link SpanPurpose#SERVER} for overall request span and {@link SpanPurpose#LOCAL_ONLY} for subspan, then\n * you can call {@link #startSpanInCurrentContext(String)} instead.\n *\n * <p><b>WARNING:</b> As stated above, this method is here to support libraries where they need to create a span\n * for some work, but do not necessarily know how or where they are going to be used in a project, and therefore\n * don't know whether tracing has been setup yet with an overall request span. Most of the time you will know where\n * you are in relation to overall request span or subspan, and should use the appropriate\n * {@code Tracer.startRequestWith*(...)} or {@code Tracer.startSubSpan(...)} methods directly as those methods spit\n * out error logging when the span stack is not in the expected state (indicating a Wingtips usage error). Using\n * this method everywhere can swallow critical error logging that would otherwise let you know Wingtips isn't being\n * used correctly and that your distributed tracing info is potentially unreliable.\n *\n * <p><b>This method is the equivalent of swallowing exceptions when Wingtips isn't being used correctly - all\n * diagnostic debugging information will be lost. This method should not be used simply because it is\n * convenient!</b>\n *\n * @param spanName The {@link Span#getSpanName()} to use for the new span.\n * @param spanPurpose The {@link SpanPurpose} for the new span. This will be honored regardless of whether the\n * returned span is an overall request span or a subspan.\n * @return A new span that might be the root span of a new span stack (i.e. if the current span stack is empty),\n * or a new subspan (i.e. if the current span stack is *not* empty). NOTE: Please read the warning in this method's\n * javadoc - abusing this method can lead to broken tracing without any errors showing up in the logs.\n */\n public Span startSpanInCurrentContext(String spanName, SpanPurpose spanPurpose) {\n // If the current span stack is empty, then we start a new overall request span. Otherwise we start a subspan.\n // In either case, honor the passed-in spanPurpose.\n if (getCurrentSpanStackSize() == 0) {\n boolean sampleable = isNextRootSpanSampleable();\n return startRequestWithSpanInfo(null, null, spanName, sampleable, null, spanPurpose);\n }\n else {\n return startSubSpan(spanName, spanPurpose);\n }\n }\n\n /**\n * Helper method that starts a new span for a fresh request.\n * <p/>\n * <b>WARNING:</b> This wipes out any existing spans on the span stack for this thread and starts fresh, therefore this should only be called at the request's\n * entry point when it's expected that the span stack should be empty. If you need to start a child span in the middle of a request somewhere then you should call\n * {@link #startSubSpan(String, SpanPurpose)} instead.\n *\n * @param traceId The new span's {@link Span#getTraceId()} - if this is null then a new random trace ID will be generated for the returned span. If you have parent span info\n * then this should be the parent span's <b>trace</b> ID (not the parent span's span ID).\n * @param parentSpanId The parent span's {@link Span#getSpanId()} - if this is null then the returned {@link Span#getParentSpanId()} will be null causing the returned span\n * to be a root span. If it's non-null then the returned span will be a child span with {@link Span#getParentSpanId()} matching this value.\n * @param newSpanName The span name to use for the new span - should never be null.\n * @param sampleable The new span's {@link Span#isSampleable()} value. Determines whether or not this span should be logged when it is completed.\n * @param userId The new span's {@link Span#getUserId()} value.\n * @param spanPurpose The span's purpose, or null if the purpose is unknown. See the javadocs for {@link SpanPurpose} for details on what each enum option means.\n *\n * @return The new span (which is now also the current one that will be returned by {@link #getCurrentSpan()}).\n */\n protected Span doNewRequestSpan(String traceId, String parentSpanId, String newSpanName, boolean sampleable, String userId, SpanPurpose spanPurpose) {\n if (newSpanName == null)\n throw new IllegalArgumentException(\"spanName cannot be null\");\n\n Span span = Span\n .newBuilder(newSpanName, spanPurpose)\n .withTraceId(traceId)\n .withParentSpanId(parentSpanId)\n .withSampleable(sampleable)\n .withUserId(userId)\n .build();\n\n // Since this is a \"starting from scratch/new request\" call we clear out and restart the current span stack even if it already had something in it.\n startNewSpanStack(span);\n\n notifySpanStarted(span);\n notifyIfSpanSampled(span);\n\n return span;\n }\n\n /**\n * Helper method that starts a new span stack for a fresh request and sets it on {@link #currentSpanStackThreadLocal}. Since this is assuming a fresh request it expects\n * {@link #currentSpanStackThreadLocal} to have a clean/empty/null stack in it right now. If it has a non-empty stack then it will log an error and clear it out\n * so that the given {@code firstEntry} argument is the only thing that will be on the stack after this method call. Delegates to {@link #pushSpanOntoCurrentSpanStack(Span)}\n * to push the {@code firstEntry} onto the clean stack so it can handle the MDC and debug logging, etc.\n */\n protected void startNewSpanStack(Span firstEntry) {\n // Log an error if we don't have a null/empty existing stack.\n Deque<Span> existingStack = currentSpanStackThreadLocal.get();\n if (existingStack != null && !existingStack.isEmpty()) {\n boolean first = true;\n StringBuilder lostTraceIds = new StringBuilder();\n for (Span span : existingStack) {\n if (!first)\n lostTraceIds.append(',');\n lostTraceIds.append(span.getTraceId());\n first = false;\n }\n classLogger.error(\"WINGTIPS USAGE ERROR - We were asked to start a new span stack (i.e. new request) but there was a stack already on this thread with {} old spans. \" +\n \"This probably means completeRequestSpan() was not called on the previous request this thread handled. The old spans will be cleared out \" +\n \"and lost. wingtips_usage_error=true, dirty_span_stack=true, lost_trace_ids={}\",\n existingStack.size(), lostTraceIds.toString(), new Exception(\"Stack trace for debugging purposes\")\n );\n\n }\n\n currentSpanStackThreadLocal.set(new LinkedList<Span>());\n pushSpanOntoCurrentSpanStack(firstEntry);\n }\n\n /**\n * Uses {@link #spanLoggingRepresentation} to decide how to serialize the given span, and then returns the result of the serialization.\n */\n protected String serializeSpanToDesiredStringRepresentation(Span span) {\n switch(spanLoggingRepresentation) {\n case JSON:\n return span.toJSON();\n case KEY_VALUE:\n return span.toKeyValueString();\n default:\n throw new IllegalStateException(\"Unknown span logging representation type: \" + spanLoggingRepresentation);\n }\n }\n\n /**\n * Pushes the given span onto the {@link #currentSpanStackThreadLocal} stack. If the stack is null it will create a new one. Also pushes the span info into the logging\n * {@link org.slf4j.MDC} so it is available there.\n */\n protected void pushSpanOntoCurrentSpanStack(Span pushMe) {\n Deque<Span> currentStack = currentSpanStackThreadLocal.get();\n if (currentStack == null) {\n currentStack = new LinkedList<>();\n currentSpanStackThreadLocal.set(currentStack);\n }\n\n currentStack.push(pushMe);\n configureMDC(pushMe);\n // We don't want to call serializeSpanToDesiredStringRepresentation(...) unless absolutely necessary, so check\n // that debug logging is enabled before making the classLogger.debug(...) call.\n if (classLogger.isDebugEnabled()) {\n classLogger.debug(\"** starting sample for span {}\", serializeSpanToDesiredStringRepresentation(pushMe));\n }\n }\n\n /**\n * Completes the current span by calling {@link #completeAndLogSpan(Span, boolean)} on it, empties the MDC by calling{@link #unconfigureMDC()}, and clears out the\n * {@link #currentSpanStackThreadLocal} stack.\n * <p/>\n * This should be called by the overall request when the request is done. At the point this method is called there should just be one span left on the\n * {@link #currentSpanStackThreadLocal} stack - the overall request span. If there is more than 1 then that indicates a bug with the usage of this class where\n * a child span is created but not completed. If this error case is detected then and *all* spans will be logged/popped and an error message will be logged with\n * details on what went wrong.\n */\n public void completeRequestSpan() {\n Deque<Span> currentSpanStack = currentSpanStackThreadLocal.get();\n if (currentSpanStack != null) {\n // Keep track of data as we go in case we need to output an error (we should only have 1 span in the stack)\n int originalSize = currentSpanStack.size();\n StringBuilder badTraceIds = new StringBuilder();\n\n while (!currentSpanStack.isEmpty()) {\n // Get the next span on the stack.\n Span span = currentSpanStack.pop();\n\n // Check if it's a \"bad\" span (i.e. not the last).\n boolean isBadSpan = false;\n if (!currentSpanStack.isEmpty()) {\n // There's still at least one more span, so this one is \"bad\".\n isBadSpan = true;\n if (badTraceIds.length() > 0)\n badTraceIds.append(',');\n badTraceIds.append(span.getTraceId());\n }\n\n completeAndLogSpan(span, isBadSpan);\n }\n\n // Output an error message if we had any bad spans.\n if (originalSize > 1) {\n classLogger.error(\n \"WINGTIPS USAGE ERROR - We were asked to fully complete a request span (i.e. end of the request) but there was more than one span on this thread's stack (\" +\n \"{} total spans when there should only be one). This probably means completeSubSpan() was not called on child sub-span(s) this thread \" +\n \"generated - they should always be in finally clauses or otherwise guaranteed to complete. The bad child sub-spans were logged but the total \" +\n \"time spent on the bad child sub-spans will not be correct. wingtips_usage_error=true, dirty_span_stack=true, bad_subspan_trace_ids={}\",\n originalSize, badTraceIds.toString(), new Exception(\"Stack trace for debugging purposes\")\n );\n }\n }\n\n currentSpanStackThreadLocal.remove();\n unconfigureMDC();\n }\n\n /**\n * Completes the current child sub-span by calling {@link #completeAndLogSpan(Span, boolean)} on it and then {@link #configureMDC(Span)} on the sub-span's parent\n * (which becomes the new current span).\n * <p/>\n * <b>WARNING:</b> This only works if there are at least 2 spans in the {@link #currentSpanStackThreadLocal} stack - one for the child sub-span and one for the parent span.\n * If you're trying to complete the overall request's span you should be calling {@link #completeRequestSpan()} instead. If there are 0 or 1 spans on the stack then\n * this method will log an error and do nothing.\n */\n public void completeSubSpan() {\n Deque<Span> currentSpanStack = currentSpanStackThreadLocal.get();\n if (currentSpanStack == null || currentSpanStack.size() < 2) {\n int stackSize = (currentSpanStack == null) ? 0 : currentSpanStack.size();\n classLogger.error(\n \"WINGTIPS USAGE ERROR - Expected to find a child sub-span on the stack to complete, but the span stack was size {} instead (there should be at least 2 for \" +\n \"this method to be able to find a child sub-span). wingtips_usage_error=true, bad_span_stack=true\",\n stackSize, new Exception(\"Stack trace for debugging purposes\")\n );\n // Nothing to do\n return;\n }\n\n // We have at least two spans. Pop off the child sub-span and complete/log it.\n Span subSpan = currentSpanStack.pop();\n completeAndLogSpan(subSpan, false);\n\n // Now configure the MDC with the new current span.\n //noinspection ConstantConditions\n configureMDC(currentSpanStack.peek());\n }\n\n /**\n * @return the given span's *current* status relative to this {@link Tracer} on the current thread at the time this\n * method is called. This status is recalculated every time this method is called and is only relevant/correct until\n * this {@link Tracer}'s state is modified (i.e. by starting a subspan, completing a span, using any of the\n * asynchronous helper methods to modify the span stack in any way, etc), so it should only be considered relevant\n * for the moment the call is made.\n *\n * <p>NOTE: Most app-level developers should not need to worry about this at all.\n *\n * @see TracerManagedSpanStatus\n */\n public TracerManagedSpanStatus getCurrentManagedStatusForSpan(Span span) {\n // See if this span is the current span.\n if (span.equals(getCurrentSpan())) {\n // This is the current span. It is therefore managed. Now we just need to see if it's the root span or\n // a subspan. If the span stack size is 1 then it's the root span, otherwise it's a subspan.\n if (getCurrentSpanStackSize() == 1) {\n // It's the root span.\n return TracerManagedSpanStatus.MANAGED_CURRENT_ROOT_SPAN;\n }\n else {\n // It's a subspan.\n return TracerManagedSpanStatus.MANAGED_CURRENT_SUB_SPAN;\n }\n }\n else {\n // This is not the current span - find out if it's managed or unmanaged.\n Deque<Span> currentSpanStack = currentSpanStackThreadLocal.get();\n if (currentSpanStack != null && currentSpanStack.contains(span)) {\n // It's on the stack, therefore it's managed. Now we just need to find out if it's the root span or not.\n if (span.equals(currentSpanStack.peekLast())) {\n // It is the root span.\n return TracerManagedSpanStatus.MANAGED_NON_CURRENT_ROOT_SPAN;\n }\n else {\n // It is a subspan.\n return TracerManagedSpanStatus.MANAGED_NON_CURRENT_SUB_SPAN;\n }\n }\n else {\n // This span is not in Tracer's current span stack at all, therefore it is unmanaged.\n return TracerManagedSpanStatus.UNMANAGED_SPAN;\n }\n }\n }\n\n /**\n * Handles the implementation of {@link Span#close()} (for {@link java.io.Closeable}) for spans to allow them to be\n * used in try-with-resources statements. We do the work here instead of in {@link Span#close()} itself since we\n * have more visibility into whether a span is valid to be closed or not given the current state of the span stack.\n * <ul>\n * <li>\n * If the given span is already completed ({@link Span#isCompleted()} returns true) then an error will be\n * logged and nothing will be done.\n * </li>\n * <li>\n * If the span is the current span ({@link #getCurrentSpan()} equals the given span), then {@link\n * #completeRequestSpan()} or {@link #completeSubSpan()} will be called, whichever is appropriate.\n * </li>\n * <li>\n * If the span is *not* the current span ({@link #getCurrentSpan()} does not equal the given span), then\n * this may or may not be an error depending on whether the given span is managed by {@link Tracer} or not.\n * <ul>\n * <li>\n * If the span is managed by us (i.e. it is contained in the span stack somewhere even though it's\n * not the current span) then this is a wingtips usage error - the span should not be completed\n * yet - and an error will be logged and the given span will be completed and logged to the\n * \"invalid span logger\".\n * </li>\n * <li>\n * Otherwise the span is not managed by us, and since there may be valid use cases for manually\n * managing spans we must assume the call was intentional. No error will be logged, and the span\n * will be completed and logged to the \"valid span logger\".\n * </li>\n * <li>\n * In either case, the current span stack and MDC info will be left untouched if the given span\n * is not the current span.\n * </li>\n * </ul>\n * </li>\n * </ul>\n *\n * <p>NOTE: This is intentionally package-scoped. Only {@link Span#close()} should ever call this method.\n */\n void handleSpanCloseMethod(Span span) {\n // See if this span has already been completed - if so then this method should not have been called.\n if (span.isCompleted()) {\n classLogger.debug(\n \"POSSIBLE WINGTIPS USAGE ERROR - An attempt was made to close() a span that was already completed. \"\n + \"This call to Span.close() will be ignored. \"\n + \"possible_wingtips_usage_error=true, already_completed_span=true, trace_id={}, span_id={}\",\n span.getTraceId(), span.getSpanId()\n );\n return;\n }\n\n // What we do next depends on the span's TracerManagedSpanStatus state.\n TracerManagedSpanStatus currentManagedState = getCurrentManagedStatusForSpan(span);\n switch(currentManagedState) {\n case MANAGED_CURRENT_ROOT_SPAN:\n // This is the current span, and it's the root span. Complete it as the overall request span.\n completeRequestSpan();\n break;\n case MANAGED_CURRENT_SUB_SPAN:\n // This is the current span, and it's a subspan. Complete it as a subspan.\n completeSubSpan();\n break;\n case MANAGED_NON_CURRENT_ROOT_SPAN: //intentional fall-through\n case MANAGED_NON_CURRENT_SUB_SPAN:\n // This span is one being managed by Tracer but it's not the current one, therefore this is an invalid\n // wingtips usage situation.\n classLogger.error(\n \"WINGTIPS USAGE ERROR - An attempt was made to close() a Tracer-managed span that was not the \"\n + \"current span. This span will be completed as an invalid span but Tracer's current span stack \"\n + \"and the current MDC info will be left alone. \"\n + \"wingtips_usage_error=true, closed_non_current_span=true, trace_id={}, span_id={}\",\n span.getTraceId(), span.getSpanId(), new Exception(\"Stack trace for debugging purposes\")\n );\n completeAndLogSpan(span, true);\n break;\n case UNMANAGED_SPAN:\n // This span is not in Tracer's current span stack at all. Assume that this span is managed outside\n // Tracer and that this call is intentional (not an error).\n classLogger.debug(\n \"A Span.close() call was made on a span not managed by Tracer. This is assumed to be intentional, \"\n + \"but might indicate an error depending on how your application works. \"\n + \"trace_id={}, span_id={}\",\n span.getTraceId(), span.getSpanId()\n );\n completeAndLogSpan(span, false);\n break;\n default:\n throw new IllegalStateException(\"Unhandled TracerManagedSpanStatus type: \" + currentManagedState.name());\n }\n }\n\n /**\n * Calls {@link Span#complete()} to complete the span and logs it (but only if the span's {@link Span#isSampleable()} returns true). If the span is valid then it will\n * be logged to {@link #validSpanLogger}, and if it is invalid then it will be logged to {@link #invalidSpanLogger}.\n *\n * @param span The span to complete and log\n * @param containsIncorrectTimingInfo Pass in true if you know the given span contains incorrect timing information (e.g. a child sub-span that wasn't completed normally\n * when it was supposed to have been completed), pass in false if the span's timing info is good. This affects how the span is logged.\n */\n protected void completeAndLogSpan(Span span, boolean containsIncorrectTimingInfo) {\n // Call span.complete(), and keep track of whether our call completed it (in case it was previously completed).\n boolean thisCallCompletedTheSpan = span.complete();\n\n if (!thisCallCompletedTheSpan) {\n // The span was completed previously (or simultaneously by another thread). We didn't complete the span,\n // so we shouldn't do any notifications or logging. This *can* indicate an error in Wingtips usage,\n // but there are some use cases where it can happen legitimately. So we'll log a debug warning.\n classLogger.debug(\n \"POSSIBLE WINGTIPS USAGE ERROR - An attempt was made to complete a span that was already completed. \"\n + \"This call will be ignored. \"\n + \"possible_wingtips_usage_error=true, already_completed_span=true, trace_id={}, span_id={}\",\n span.getTraceId(), span.getSpanId()\n );\n return;\n }\n\n // Notify listeners after completion but before logging to allow listeners to do final span modifications and\n // have them be reflected in the log message (e.g. change span name, add tags/annotations, etc).\n notifySpanCompleted(span);\n\n // Log the span if it was sampleable.\n if (span.isSampleable()) {\n String infoTag = containsIncorrectTimingInfo ? \"[INCORRECT_TIMING] \" : \"\";\n Logger loggerToUse = containsIncorrectTimingInfo ? invalidSpanLogger : validSpanLogger;\n // Only attempt to log if loggerToUse.isInfoEnabled() returns true, so that we don't incur the cost of\n // serialization via serializeSpanToDesiredStringRepresentation(span) unless it will actually get used.\n // This will save CPU if the application has turned off logging in their logger config, but\n // otherwise allowed Wingtips to function normally.\n if (loggerToUse.isInfoEnabled()) {\n loggerToUse.info(\n \"{}[DISTRIBUTED_TRACING] {}\", infoTag, serializeSpanToDesiredStringRepresentation(span)\n );\n }\n }\n }\n\n /**\n * Sets the span variables on the MDC context.\n */\n protected void configureMDC(@NotNull Span span) {\n for (SpanFieldForLoggerMdc mdcField : this.spanFieldsForLoggerMdc) {\n MDC.put(mdcField.mdcKey, mdcField.getMdcValueForSpan(span));\n }\n }\n\n\n /**\n * Removes the MDC parameters.\n */\n protected void unconfigureMDC() {\n for (SpanFieldForLoggerMdc mdcField : this.spanFieldsForLoggerMdc) {\n MDC.remove(mdcField.mdcKey);\n }\n }\n\n /**\n * Allows you to set the {@link #rootSpanSamplingStrategy} used by this instance. This will throw an {@link IllegalArgumentException} if you pass in null.\n */\n public void setRootSpanSamplingStrategy(RootSpanSamplingStrategy strategy) {\n if (strategy == null)\n throw new IllegalArgumentException(\"RootSpanSamplingStrategy cannot be null\");\n\n this.rootSpanSamplingStrategy = strategy;\n }\n\n /**\n * Delegates to {@link #rootSpanSamplingStrategy}'s {@link RootSpanSamplingStrategy#isNextRootSpanSampleable()} method to determine whether the next root span should be\n * sampled.\n * <br/>\n * NOTE: This method is not deterministic - you may get a different response every time you call it. Therefore you should not call this method multiple times for the same\n * root span. Call it once and store the result for a given root span.\n *\n * @return true when the next root span should be sampled, false otherwise.\n */\n protected boolean isNextRootSpanSampleable() {\n return rootSpanSamplingStrategy.isNextRootSpanSampleable();\n }\n\n /**\n * Adds the given listener to the {@link #spanLifecycleListeners} list using {@link java.util.List#add(Object)}. This method will do nothing if you pass in null.\n * <p/>\n * <b>WARNING:</b> It's important that any {@link SpanLifecycleListener} you add is extremely lightweight or you risk distributed tracing becoming a major bottleneck for\n * high throughput services. If any expensive work needs to be done in a {@link SpanLifecycleListener} then it should be done asynchronously on a thread or threadpool\n * separate from the application worker threads.\n */\n public void addSpanLifecycleListener(SpanLifecycleListener listener) {\n if (listener != null) {\n this.spanLifecycleListeners.add(listener);\n }\n }\n\n /**\n * Prepends the given listener to the {@link #spanLifecycleListeners} list by using {@link List#add(int, Object)}\n * and passing 0 for the index. This method will do nothing if you pass in null.\n *\n * <p><b>WARNING:</b> It's important that any {@link SpanLifecycleListener} you add is extremely lightweight or you\n * risk distributed tracing becoming a major bottleneck for high throughput services. If any expensive work needs\n * to be done in a {@link SpanLifecycleListener} then it should be done asynchronously on a thread or threadpool\n * separate from the application worker threads.\n */\n public void addSpanLifecycleListenerFirst(SpanLifecycleListener listener) {\n if (listener != null) {\n this.spanLifecycleListeners.add(0, listener);\n }\n }\n\n /**\n * Returns the value of calling {@link java.util.List#remove(Object)} on {@link #spanLifecycleListeners}.\n */\n public boolean removeSpanLifecycleListener(SpanLifecycleListener listener) {\n //noinspection SimplifiableIfStatement\n if (listener == null)\n return false;\n\n return this.spanLifecycleListeners.remove(listener);\n }\n\n /**\n * Calls {@link List#clear()} on {@link #spanLifecycleListeners} to remove all {@link SpanLifecycleListener}s.\n * This is here primarily to ease unit testing where you need to \"reset\" {@link Tracer} between tests.\n */\n public void removeAllSpanLifecycleListeners() {\n this.spanLifecycleListeners.clear();\n }\n\n /**\n * @return The {@link #spanLifecycleListeners} list of span lifecycle listeners associated with this instance, wrapped in a {@link Collections#unmodifiableList(List)}\n * to prevent direct modification. This will never return null.\n */\n public List<SpanLifecycleListener> getSpanLifecycleListeners() {\n return Collections.unmodifiableList(this.spanLifecycleListeners);\n }\n\n /**\n * @return The currently selected option for how spans will be serialized when they are completed and logged.\n */\n public SpanLoggingRepresentation getSpanLoggingRepresentation() {\n return spanLoggingRepresentation;\n }\n\n /**\n * Sets the option for how spans will be serialized when they are completed and logged.\n */\n public void setSpanLoggingRepresentation(SpanLoggingRepresentation spanLoggingRepresentation) {\n if (spanLoggingRepresentation == null)\n throw new IllegalArgumentException(\"spanLoggingRepresentation cannot be null.\");\n\n this.spanLoggingRepresentation = spanLoggingRepresentation;\n }\n\n /**\n * @return The currently selected options for which span fields will be placed in the logger {@link MDC} as\n * {@link Tracer} works with spans, wrapped in a {@link Collections#unmodifiableSet(Set)} to prevent direct\n * modification. This will never return null.\n */\n public Set<SpanFieldForLoggerMdc> getSpanFieldsForLoggerMdc() {\n return cachedUnmodifiableSpanFieldsForLoggerMdc;\n }\n\n /**\n * Tells {@link Tracer} which {@link Span} fields should be included in the logger {@link MDC} when the current\n * span for a thread changes. The default behavior without calling this method just includes\n * {@link SpanFieldForLoggerMdc#TRACE_ID}.\n *\n * <p>NOTE: It's recommended that you always include {@link SpanFieldForLoggerMdc#TRACE_ID}.\n *\n * @param fieldsForMdc The fields you want included in the logger {@link MDC}. You can pass null or an empty array,\n * in which case the MDC will never be updated with span info. NOTE: It's recommended that you always include\n * {@link SpanFieldForLoggerMdc#TRACE_ID}.\n */\n public void setSpanFieldsForLoggerMdc(SpanFieldForLoggerMdc ... fieldsForMdc) {\n if (fieldsForMdc == null) {\n fieldsForMdc = new SpanFieldForLoggerMdc[0];\n }\n \n setSpanFieldsForLoggerMdc(new LinkedHashSet<>(Arrays.asList(fieldsForMdc)));\n }\n\n /**\n * Tells {@link Tracer} which {@link Span} fields should be included in the logger {@link MDC} when the current\n * span for a thread changes. The default behavior without calling this method just includes\n * {@link SpanFieldForLoggerMdc#TRACE_ID}.\n *\n * <p>NOTE: It's recommended that you always include {@link SpanFieldForLoggerMdc#TRACE_ID}.\n *\n * @param fieldsForMdc The fields you want included in the logger {@link MDC}. You can pass null or an empty set,\n * in which case the MDC will never be updated with span info. NOTE: It's recommended that you always include\n * {@link SpanFieldForLoggerMdc#TRACE_ID}.\n */\n public void setSpanFieldsForLoggerMdc(Set<SpanFieldForLoggerMdc> fieldsForMdc) {\n if (fieldsForMdc == null) {\n fieldsForMdc = Collections.emptySet();\n }\n\n this.spanFieldsForLoggerMdc = fieldsForMdc.toArray(new SpanFieldForLoggerMdc[0]);\n this.cachedUnmodifiableSpanFieldsForLoggerMdc =\n Collections.unmodifiableSet(new LinkedHashSet<>(fieldsForMdc));\n\n if (!fieldsForMdc.contains(SpanFieldForLoggerMdc.TRACE_ID)) {\n classLogger.warn(\n \"setSpanFieldsForLoggerMdc(...) was called without including TRACE_ID. This is not recommended! \"\n + \"It's recommended that you always include TRACE_ID unless you really know what you're doing. \"\n + \"span_fields_for_mdc_received={}\", fieldsForMdc\n );\n }\n }\n\n /**\n * Notifies all listeners that the given span was started using {@link SpanLifecycleListener#spanStarted(Span)}\n */\n protected void notifySpanStarted(Span span) {\n for (SpanLifecycleListener tll : spanLifecycleListeners) {\n tll.spanStarted(span);\n }\n }\n\n /**\n * Notifies all listeners that the given span was sampled using {@link SpanLifecycleListener#spanSampled(Span)}, <b>but only if the span's {@link Span#isSampleable()}\n * method returns true!</b> If the span is not sampleable then this method does nothing.\n */\n protected void notifyIfSpanSampled(Span span) {\n if (span.isSampleable()) {\n for (SpanLifecycleListener tll : spanLifecycleListeners) {\n tll.spanSampled(span);\n }\n }\n }\n\n /**\n * Notifies all listeners that the given span was completed using {@link SpanLifecycleListener#spanCompleted(Span)}\n */\n protected void notifySpanCompleted(Span span) {\n for (SpanLifecycleListener tll : spanLifecycleListeners) {\n tll.spanCompleted(span);\n }\n }\n\n /**\n * @return A *copy* of the current thread's tracing information. Since this creates copies of the span stack and MDC\n * info it can have a noticeable performance impact if used too many times (i.e. tens or hundreds of times per\n * request for high throughput services). NOTE: This is usually not needed unless you're doing asynchronous\n * processing and need to pass tracing state across thread boundaries.\n */\n public TracingState getCurrentTracingStateCopy() {\n return new TracingState(getCurrentSpanStackCopy(), MDC.getCopyOfContextMap());\n }\n\n /**\n * IMPORTANT: This method is not for typical thread-per-request application usage - most of the time you just want {@link #getCurrentSpan()}. This method is here to\n * facilitate complex asynchronous threading situations.\n * <p/>\n * Returns a *COPY* of the current span stack. A copy is returned instead of the original to prevent you from directly modifying the stack - you should use the start/complete\n * request span/sub-span methods to manipulate the stack. But sometimes you need to see what the stack looks like, or store it at a certain state so you can reconstitute\n * it later (you can sort of do this with {@link #unregisterFromThread()} which also returns the span stack, but that unregisters everything and sometimes you need to\n * store for later without interrupting current state).\n * <p/>\n * This method may return null or an empty stack, depending on its current state.\n */\n public Deque<Span> getCurrentSpanStackCopy() {\n Deque<Span> currentStack = currentSpanStackThreadLocal.get();\n if (currentStack == null)\n return null;\n\n return new LinkedList<>(currentStack);\n }\n\n /**\n * @return The size of the current span stack - useful when you want to know the size, but don't want to incur the\n * cost of {@link #getCurrentSpanStackCopy()}.\n */\n public int getCurrentSpanStackSize() {\n Deque<Span> currentStack = currentSpanStackThreadLocal.get();\n if (currentStack == null)\n return 0;\n\n return currentStack.size();\n }\n\n /**\n * \"Unregisters\" the current span stack from this thread, removes span-related info from the logging MDC, and returns the span stack that was unregistered so it\n * can be stored and re-registered later (if desired). This is used in asynchronous projects/frameworks where multiple in-progress requests might be handled by the same thread\n * before any of the requests can finish (e.g. Netty, where the worker I/O threads might process a portion of request A, flip over to request B to do some work, then go back\n * to request A, etc). This method lets you unregister the tracing info from the current thread when it is about to switch to processing a different request so the tracing\n * info can be stored in some kind of request context state that follows the request, and won't pollute the thread's span stack and MDC info when the new request starts being\n * processed.\n * <br/>\n * When processing switches back to the original request, you can call {@link #registerWithThread(java.util.Deque)} to set the thread's span stack and MDC info back to the\n * way it was when you first called this unregister method for the original request.\n * <p/>\n * <b>WARNING:</b> This method should NOT be called if you're in an environment where a single thread is guaranteed to process a request from start to finish without jumping\n * to a different request in the middle. In that case just use the normal start and complete span methods and ignore this method.\n */\n public Deque<Span> unregisterFromThread() {\n Deque<Span> currentValue = currentSpanStackThreadLocal.get();\n currentSpanStackThreadLocal.remove();\n unconfigureMDC();\n return currentValue;\n }\n\n /**\n * @return true if the two given stacks contain the same spans in the same order, false otherwise.\n */\n protected boolean containsSameSpansInSameOrder(Deque<Span> stack, Deque<Span> other) {\n if (stack == other)\n return true;\n\n if (stack == null || other == null)\n return false;\n\n if (stack.size() != other.size())\n return false;\n\n Iterator<Span> stackIterator = stack.iterator();\n Iterator<Span> otherIterator = other.iterator();\n\n while (stackIterator.hasNext()) {\n Span t1 = stackIterator.next();\n Span t2 = otherIterator.next();\n\n if (t1 != t2) {\n // Not the same instance, and at least one is non-null.\n if (t1 == null || t2 == null)\n return false;\n\n if (!t1.equals(t2))\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * \"Registers\" a *COPY* of the given span stack with this thread (sets up the ThreadLocal span stack with a copy of the given argument) and sets up the MDC appropriately\n * based on what you pass in. This is used in asynchronous projects/frameworks where multiple in-progress requests might be handled by the same thread\n * before any of the requests can finish (e.g. Netty, where the worker I/O threads might process a portion of request A, flip over to request B to do some work, then go back\n * to request A, etc). When the worker thread was about to stop working on the original request and move to a new one you would call {@link #unregisterFromThread()}\n * and store the result with some kind of context state that follows the original request, and when processing switches back to the original request you would call\n * this method to set the thread's span stack and MDC info back to the way it was so you could continue where you left off.\n * <p/>\n * In a properly functioning project/framework this thread would not have any span information in its stack when this method was called, so if there are any spans already\n * on this thread then this method will mark them as invalid, complete them, and log an appropriate error message before registering the stack passed into this method.\n * <p/>\n * NOTE: A *copy* of the given stack is registered so that changes to the stack you pass in don't affect the stack stored here. This prevents a host of subtle annoying bugs.\n * <p/>\n * <b>WARNING:</b> This method should NOT be called if you're in an environment where a single thread is guaranteed to process a request from start to finish without jumping\n * to a different request in the middle. In that case just use the normal start and complete span methods and ignore this method.\n */\n public void registerWithThread(Deque<Span> registerMe) {\n Deque<Span> currentSpanStack = currentSpanStackThreadLocal.get();\n\n // Do nothing if the passed-in stack is functionally identical to what we already have.\n if (!containsSameSpansInSameOrder(currentSpanStack, registerMe)) {\n // Not the same span stack. See if there was an old stale stack still around.\n if (currentSpanStack != null && currentSpanStack.size() > 0) {\n // Whoops, someone else is trying to register with this thread while it's already in the middle of handling spans.\n int originalSize = currentSpanStack.size();\n StringBuilder badTraceIds = new StringBuilder();\n\n // Complete and output all the spans, but they will all be marked \"bad\".\n while (!currentSpanStack.isEmpty()) {\n Span span = currentSpanStack.pop();\n\n if (badTraceIds.length() > 0)\n badTraceIds.append(',');\n badTraceIds.append(span.getTraceId());\n\n completeAndLogSpan(span, true);\n }\n\n // Output an error message\n classLogger.error(\"WINGTIPS USAGE ERROR - We were asked to register a span stack with this thread (i.e. for systems that use threads asynchronously to perform work on \" +\n \"multiple requests at a time before any given request is completed) but there was already a non-empty span stack on this thread ({} total \" +\n \"spans when there should be zero). This probably means unregisterFromThread() was not called the last time this request's thread dropped it \" +\n \"to go work on a different request. Whenever a thread stops work on a request to go do something else when the request is not complete it \" +\n \"should unregisterFromThread() in a finally block or some other way to guarantee it doesn't leave an unfinished stack dangling. The bad \" +\n \"request span/sub-spans were logged but the reported total time spent on them will not be correct. wingtips_usage_error=true, dirty_span_stack=true, \" +\n \"bad_child_span_ids={}\",\n originalSize, badTraceIds.toString(), new Exception(\"Stack trace for debugging purposes\")\n );\n }\n\n // At this point any errors have been handled and we can register the new stack. Make sure we register a copy so that changes to the original don't affect our stack.\n registerMe = (registerMe == null) ? null : new LinkedList<>(registerMe);\n currentSpanStackThreadLocal.set(registerMe);\n }\n\n // Make sure we fix the MDC to the passed-in info.\n Span newStackLatestSpan = (registerMe == null || registerMe.isEmpty()) ? null : registerMe.peek();\n if (newStackLatestSpan == null)\n unconfigureMDC();\n else\n configureMDC(newStackLatestSpan);\n }\n\n}", "public class ApacheHttpClientTagAdapter extends HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> {\n\n @SuppressWarnings(\"WeakerAccess\")\n protected static final ApacheHttpClientTagAdapter DEFAULT_INSTANCE = new ApacheHttpClientTagAdapter();\n\n /**\n * @return A reusable, thread-safe, singleton instance of this class that can be used by anybody who wants to use\n * this class and does not need any customization.\n */\n @SuppressWarnings(\"unchecked\")\n public static ApacheHttpClientTagAdapter getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n @Override\n public @Nullable String getRequestPath(@Nullable HttpRequest request) {\n if (request == null) {\n return null;\n }\n\n if (request instanceof HttpRequestWrapper) {\n String path = ((HttpRequestWrapper) request).getURI().getPath();\n // The path shouldn't have a query string on it, but call stripQueryString() just in case.\n return stripQueryString(path);\n }\n\n // At this point it's not a HttpRequestWrapper. It can be parsed from request.getRequestLine().getUri().\n // Gross, but doable.\n String requestLine = request.getRequestLine().getUri();\n\n // Chop out the query string (if any).\n requestLine = stripQueryString(requestLine);\n\n // If it starts with '/' then there's nothing left for us to do - it's already the path.\n if (requestLine.startsWith(\"/\")) {\n return requestLine;\n }\n\n // Doesn't start with '/'. We expect it to start with http at this point.\n if (!requestLine.toLowerCase().startsWith(\"http\")) {\n // Didn't start with http. Not sure what to do with this at this point, so return null.\n return null;\n }\n\n // It starts with http. Chop out the scheme and host/port.\n int schemeColonAndDoubleSlashIndex = requestLine.indexOf(\"://\");\n if (schemeColonAndDoubleSlashIndex < 0) {\n // It didn't have a colon-double-slash after the scheme. Not sure what to do at this point, so return null.\n return null;\n }\n\n int firstSlashIndexAfterSchemeDoubleSlash = requestLine.indexOf('/', (schemeColonAndDoubleSlashIndex + 3));\n if (firstSlashIndexAfterSchemeDoubleSlash < 0) {\n // No other slashes after the scheme colon-double-slash, so no real path. The path at this point is\n // effectively \"/\".\n return \"/\";\n }\n\n return requestLine.substring(firstSlashIndexAfterSchemeDoubleSlash);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n protected String stripQueryString(String str) {\n int queryIndex = str.indexOf('?');\n return (queryIndex == -1) ? str : str.substring(0, queryIndex);\n }\n\n @Override\n public @Nullable Integer getResponseHttpStatus(@Nullable HttpResponse response) {\n if (response == null) {\n return null;\n }\n\n StatusLine statusLine = response.getStatusLine();\n if (statusLine == null) {\n return null;\n }\n\n return statusLine.getStatusCode();\n }\n\n @Override\n public @Nullable String getRequestHttpMethod(@Nullable HttpRequest request) {\n if (request == null) {\n return null;\n }\n \n return request.getRequestLine().getMethod();\n }\n\n @Override\n public @Nullable String getRequestUriPathTemplate(@Nullable HttpRequest request, @Nullable HttpResponse response) {\n // Nothing we can do by default - this needs to be overridden on a per-project basis and given some smarts\n // based on project-specific knowledge.\n return null;\n }\n\n @Override\n public @Nullable String getRequestUrl(@Nullable HttpRequest request) {\n if (request == null) {\n return null;\n } \n\n String uri = request.getRequestLine().getUri();\n\n if (request instanceof HttpRequestWrapper && uri.startsWith(\"/\")) {\n HttpRequestWrapper wrapper = (HttpRequestWrapper) request;\n HttpHost target = wrapper.getTarget();\n if (target != null) {\n uri = wrapper.getTarget().toURI() + uri;\n }\n }\n \n return uri;\n }\n\n @Override\n public @Nullable String getHeaderSingleValue(@Nullable HttpRequest request, @NotNull String headerKey) {\n if (request == null) {\n return null;\n }\n\n Header matchingHeader = request.getFirstHeader(headerKey);\n\n if (matchingHeader == null) {\n return null;\n }\n\n return matchingHeader.getValue();\n }\n\n @Override\n public @Nullable List<String> getHeaderMultipleValue(@Nullable HttpRequest request, @NotNull String headerKey) {\n if (request == null) {\n return null;\n }\n\n Header[] matchingHeaders = request.getHeaders(headerKey);\n\n if (matchingHeaders == null || matchingHeaders.length == 0) {\n return null;\n }\n\n List<String> returnList = new ArrayList<>(matchingHeaders.length);\n for (Header header : matchingHeaders) {\n returnList.add(header.getValue());\n }\n\n return returnList;\n }\n\n @Override\n public @Nullable String getSpanHandlerTagValue(@Nullable HttpRequest request, @Nullable HttpResponse response) {\n return \"apache.httpclient\";\n }\n}", "public abstract class HttpTagAndSpanNamingAdapter<REQ, RES> {\n\n /**\n * Returns the value that should be used for the \"error\" {@link com.nike.wingtips.Span#putTag(String, String)}\n * associated with the given response, or null if this response does not indicate an error. The criteria for\n * determining an error can change depending on whether it's a client span or server span, or there may even be\n * project-specific logic.\n *\n * <p>By default, this method considers a response to indicate an error if the {@link\n * #getResponseHttpStatus(Object)} is greater than or equal to 400, and will return that status code as a string.\n * This is a client-span-centric view - implementations of this class that represent server spans may want to\n * override this to have it only consider status codes greater than or equal to 500 to be errors.\n *\n * <p>NOTE: It's important that you return something non-empty and non-blank if want the span to be considered an\n * error. In particular, empty strings or strings that consist of only whitespace may be treated by callers\n * of this method the same as {@code null}.\n *\n * @param response The response object to be inspected - <b>this may be null!</b>\n *\n * @return The value that should be used for the \"error\" {@link com.nike.wingtips.Span#putTag(String, String)}\n * associated with the given response, or null if this response does not indicate an error.\n */\n public @Nullable String getErrorResponseTagValue(@Nullable RES response) {\n Integer statusCode = getResponseHttpStatus(response);\n if (statusCode != null && statusCode >= 400) {\n return statusCode.toString();\n }\n\n // Status code does not indicate an error, so return null.\n return null;\n }\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n *\n * @return The full URL of the request, including scheme, host, path, and query params, or null if the full URL\n * could not be determined. e.g.: {@code http://some.host:8080/foo/bar/12345?thing=stuff}\n */\n public abstract @Nullable String getRequestUrl(@Nullable REQ request);\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n *\n * @return The path of the request (similar to {@link #getRequestUrl(Object)}, but omits scheme, host, and query\n * params), or null if the path could not be determined. e.g.: {@code /foo/bar/12345}\n */\n public abstract @Nullable String getRequestPath(@Nullable REQ request);\n\n /**\n * Returns the path template associated with the given request/response (i.e. {@code /foo/:id} instead of\n * {@code /foo/12345}), or null if the path template could not be determined.\n *\n * @param request The request object to be inspected - <b>this may be null!</b>\n * @param response The response object to be inspected - <b>this may be null!</b>\n *\n * @return The path template associated with the given request/response, or null if the path template could\n * not be determined. e.g.: <code>/foo/bar/{id}</code>\n */\n public abstract @Nullable String getRequestUriPathTemplate(@Nullable REQ request, @Nullable RES response);\n\n /**\n * @param response The response object to be inspected - <b>this may be null!</b>\n *\n * @return The HTTP status code (e.g. 200, 400, 503, etc) for the given response, or null if the HTTP status code\n * could not be determined.\n */\n public abstract @Nullable Integer getResponseHttpStatus(@Nullable RES response);\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n *\n * @return The HTTP method (e.g. \"GET\", \"POST\", etc) for the given request, or null if the HTTP method could not\n * be determined.\n */\n public abstract @Nullable String getRequestHttpMethod(@Nullable REQ request);\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n * @param headerKey The header key (name) to look for - should never be null.\n *\n * @return The single header value associated with the given header key, or null if no such header exists for\n * the given request. If there are multiple values associated with the header key, then only the first one will\n * be returned.\n */\n public abstract @Nullable String getHeaderSingleValue(@Nullable REQ request, @NotNull String headerKey);\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n * @param headerKey The header key (name) to look for - should never be null.\n *\n * @return All the header values associated with the given header key, or null if no such header exists for the\n * given request. Implementations may choose to return an empty list instead of null if no such header exists.\n */\n public abstract @Nullable List<String> getHeaderMultipleValue(@Nullable REQ request, @NotNull String headerKey);\n\n /**\n * @param request The request object to be inspected - <b>this may be null!</b>\n *\n * @return The desired prefix that should be prepended before any span name produced by {@link\n * #getInitialSpanName(Object)} or {@link #getFinalSpanName(Object, Object)}, or null if no prefix is desired.\n * Defaults to null - if you want a non-null prefix you'll need to override this method.\n */\n public @Nullable String getSpanNamePrefix(@Nullable REQ request) {\n return null;\n }\n\n /**\n * By default this method uses a combination of {@link #getSpanNamePrefix(Object)} and {@link\n * HttpRequestTracingUtils#generateSafeSpanName(Object, Object, HttpTagAndSpanNamingAdapter)} to generate a name.\n * You can override this method if you need different behavior.\n *\n * @param request The request object to be inspected - <b>this may be null!</b>\n *\n * @return The initial span name that this adapter wants to use for a span around the given request, or null\n * if this adapter can't (or doesn't want to) come up with a name. Callers should always check for a null return\n * value, and come up with a reasonable fallback name in that case.\n */\n public @Nullable String getInitialSpanName(@Nullable REQ request) {\n String prefix = getSpanNamePrefix(request);\n\n String defaultSpanName = HttpRequestTracingUtils.generateSafeSpanName(request, null, this);\n\n return (StringUtils.isBlank(prefix))\n ? defaultSpanName\n : prefix + \"-\" + defaultSpanName;\n }\n\n /**\n * By default this method uses a combination of {@link #getSpanNamePrefix(Object)} and {@link\n * HttpRequestTracingUtils#generateSafeSpanName(Object, Object, HttpTagAndSpanNamingAdapter)} to generate a name.\n * You can override this method if you need different behavior.\n *\n * @param request The request object to be inspected - <b>this may be null!</b>\n * @param response The response object to be inspected - <b>this may be null!</b>\n *\n * @return The final span name that this adapter wants to use for a span around the given request, or null\n * if this adapter can't (or doesn't want to) come up with a name. Callers should always check for a null return\n * value, and should not change the preexisting initial span name if this returns null.\n */\n public @Nullable String getFinalSpanName(@Nullable REQ request, @Nullable RES response) {\n String prefix = getSpanNamePrefix(request);\n\n String defaultSpanName = HttpRequestTracingUtils.generateSafeSpanName(request, response, this);\n\n return (StringUtils.isBlank(prefix))\n ? defaultSpanName\n : prefix + \"-\" + defaultSpanName;\n }\n\n /**\n * @return The value that should be used for the {@link WingtipsTags#SPAN_HANDLER} tag, or null if you don't want\n * that tag added to spans. See the javadocs for {@link WingtipsTags#SPAN_HANDLER} for more details on what this\n * value should look like.\n */\n public abstract @Nullable String getSpanHandlerTagValue(@Nullable REQ request, @Nullable RES response);\n}", "@SuppressWarnings(\"WeakerAccess\")\npublic abstract class HttpTagAndSpanNamingStrategy<REQ, RES> {\n\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * Handles tagging the given span with tags related to the given request, according to this tag strategy's\n * requirements.\n *\n * <p>This method does the actual request-tagging work for the public-facing {@link\n * #handleRequestTagging(Span, Object, HttpTagAndSpanNamingAdapter)}.\n *\n * @param span The span to tag - will never be null.\n * @param request The incoming request - will never be null.\n * @param adapter The adapter to handle the incoming request - will never be null.\n */\n protected abstract void doHandleRequestTagging(\n @NotNull Span span,\n @NotNull REQ request,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, ?> adapter\n );\n\n /**\n * Handles tagging the given span with tags related to the given response and/or error, according to this\n * tag strategy's requirements.\n *\n * <p>This method does the actual response-and-error-tagging work for the public-facing {@link\n * #handleResponseTaggingAndFinalSpanName(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}.\n *\n * @param span The span to name - will never be null.\n * @param request The request object - this may be null.\n * @param response The response object - this may be null.\n * @param error The error that prevented the request/response from completing normally, or null if no such error\n * occurred.\n * @param adapter The adapter to handle the request and response - will never be null.\n */\n protected abstract void doHandleResponseAndErrorTagging(\n @NotNull Span span,\n @Nullable REQ request,\n @Nullable RES response,\n @Nullable Throwable error,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter\n );\n\n /**\n * Returns the span name that should be used for the given request according to this strategy and/or the given\n * adapter. By default this will delegate to the adapter's {@link\n * HttpTagAndSpanNamingAdapter#getInitialSpanName(Object)} unless this strategy overrides\n * {@link #doGetInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}.\n *\n * <p><b>NOTE: This method may return null if the strategy and adapter have no opinion, or if something goes wrong.\n * Callers must always check for a null return value, and generate a backup span name in those cases.</b>\n *\n * <p>This method is final and delegates to {@link #doGetInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}.\n * That delegate method call is surrounded with a try/catch so that this method will never throw an exception.\n * If an exception occurs then the error will be logged and null will be returned. Since this method is final, if\n * you want to override the behavior of this method then you should override {@link\n * #doGetInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}.\n *\n * @param request The incoming request - should never be null.\n * @param adapter The adapter to handle the incoming request - should never be null (use {@link NoOpHttpTagAdapter}\n * if you don't want a real impl).\n *\n * @return The span name that should be used for the given request according to this strategy and/or the given\n * adapter, or null if the span name should be deferred to the caller.\n */\n public final @Nullable String getInitialSpanName(\n @NotNull REQ request,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, ?> adapter\n ) {\n //noinspection ConstantConditions\n if (request == null || adapter == null) {\n return null;\n }\n\n try {\n return doGetInitialSpanName(request, adapter);\n }\n catch (Throwable t) {\n // Impl methods should never throw an exception. If you're seeing this error pop up, the impl needs to\n // be fixed.\n logger.error(\n \"An unexpected error occurred while getting the initial span name. The error will be swallowed to \"\n + \"avoid doing any damage and null will be returned, but your span name may not be what you expect. \"\n + \"This error should be fixed.\",\n t\n );\n return null;\n }\n }\n\n /**\n * Handles tagging the given span with tags related to the given request based on rules specific to this\n * particular class' implementation.\n *\n * <p>This method is final and delegates to {@link\n * #doHandleRequestTagging(Span, Object, HttpTagAndSpanNamingAdapter)}. That delegate method call is surrounded\n * with a try/catch so that this method will never throw an exception. If an exception occurs then the error\n * will be logged but will not propagate outside this method. Since this method is final, if you want to override\n * the behavior of this method then you should override {@link\n * #doHandleRequestTagging(Span, Object, HttpTagAndSpanNamingAdapter)}.\n *\n * @param span The span to tag - should never be null.\n * @param request The incoming request - should never be null.\n * @param adapter The adapter to handle the incoming request - should never be null (use {@link NoOpHttpTagAdapter}\n * if you don't want a real impl).\n */\n public final void handleRequestTagging(\n @NotNull Span span,\n @NotNull REQ request,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, ?> adapter\n ) {\n //noinspection ConstantConditions\n if (span == null || request == null || adapter == null) {\n return;\n }\n\n try {\n doHandleRequestTagging(span, request, adapter);\n }\n catch (Throwable t) {\n // Impl methods should never throw an exception. If you're seeing this error pop up, the impl needs to\n // be fixed.\n logger.error(\n \"An unexpected error occurred while handling request tagging. The error will be swallowed to avoid \"\n + \"doing any damage, but your span may be missing some expected tags. This error should be fixed.\",\n t\n );\n }\n }\n\n /**\n * Handles tagging the given span with tags related to the given response and/or error, and also handles setting\n * the span's final span name.\n *\n * <p>The span name is finalized here after the response because the ideal span name includes the low-cardinality\n * HTTP path template (e.g. {@code /foo/:id} rather than {@code /foo/12345}), however in many frameworks you don't\n * know the path template until after the request has been processed. So calling this method may cause the span's\n * {@link Span#getSpanName()} to change.\n *\n * <p>This method is final and delegates to the following methods to do the actual work:\n * <ul>\n * <li>\n * {@link #doHandleResponseAndErrorTagging(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}\n * </li>\n * <li>\n * {@link #doDetermineAndSetFinalSpanName(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}\n * </li>\n * <li>{@link #doExtraWingtipsTagging(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}</li>\n * </ul>\n *\n * Those delegate method calls are surrounded with try/catch blocks so that this method will never throw an\n * exception, and an exception in one won't prevent the others from executing. If an exception occurs then the\n * error will be logged but will not propagate outside this method. Since this method is final, if you want to\n * override the behavior of this method then you should override the relevant delegate method(s).\n *\n * @param span The span to tag - should never be null.\n * @param request The request object - this can be null if you don't have it anymore when this method is called,\n * however you should pass it if at all possible as it may be critical to determining the final span name.\n * @param response The response object - this can be null if an exception was thrown (thus preventing the response\n * object from being created).\n * @param error The error that prevented the request/response from completing normally, or null if no such error\n * occurred.\n * @param adapter The adapter to handle the request and response - should never be null (use\n * {@link NoOpHttpTagAdapter} if you don't want a real impl).\n */\n public final void handleResponseTaggingAndFinalSpanName(\n @NotNull Span span,\n @Nullable REQ request,\n @Nullable RES response,\n @Nullable Throwable error,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter\n ) {\n //noinspection ConstantConditions\n if (span == null || adapter == null) {\n return;\n }\n\n try {\n doHandleResponseAndErrorTagging(span, request, response, error, adapter);\n }\n catch (Throwable t) {\n // Impl methods should never throw an exception. If you're seeing this error pop up, the impl needs to\n // be fixed.\n logger.error(\n \"An unexpected error occurred while handling response tagging. The error will be swallowed to avoid \"\n + \"doing any damage, but your span may be missing some expected tags. This error should be fixed.\",\n t\n );\n }\n\n try {\n doDetermineAndSetFinalSpanName(span, request, response, error, adapter);\n }\n catch (Throwable t) {\n // Impl methods should never throw an exception. If you're seeing this error pop up, the impl needs to\n // be fixed.\n logger.error(\n \"An unexpected error occurred while finalizing the span name. The error will be swallowed to avoid \"\n + \"doing any damage, but the final span name may not be what you expect. This error should be fixed.\",\n t\n );\n }\n\n try {\n doExtraWingtipsTagging(span, request, response, error, adapter);\n }\n catch (Throwable t) {\n // Impl methods should never throw an exception. If you're seeing this error pop up, the impl needs to\n // be fixed.\n logger.error(\n \"An unexpected error occurred while doing Wingtips tagging. The error will be swallowed to avoid \"\n + \"doing any damage, but the final span name may not be what you expect. This error should be fixed.\",\n t\n );\n }\n }\n\n /**\n * Returns the span name that should be used for the given request according to this strategy and/or the given\n * adapter. By default this will delegate to the adapter's {@link\n * HttpTagAndSpanNamingAdapter#getInitialSpanName(Object)} unless you override this method.\n *\n * <p><b>NOTE: This method may return null if the strategy and adapter have no opinion, or if something goes wrong.\n * Callers must always check for a null return value, and generate a backup span name in those cases.</b>\n *\n * <p>This method does the actual work for the public-facing {@link\n * #getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}.\n *\n * @param request The incoming request - will never be null.\n * @param adapter The adapter to handle the incoming request - will never be null.\n *\n * @return The span name that should be used for the given request according to this strategy and/or the given\n * adapter, or null if the span name should be deferred to the caller.\n */\n protected @Nullable String doGetInitialSpanName(\n @NotNull REQ request,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, ?> adapter\n ) {\n return adapter.getInitialSpanName(request);\n }\n\n /**\n * Determines the final span name that should be used for the given request/response according to this strategy\n * and/or the given adapter, and then calls {@link SpanMutator#changeSpanName(Span, String)} to actually change\n * the span name (if and only if a non-blank final span name is generated).\n *\n * <p>By default this will delegate to the adapter's {@link\n * HttpTagAndSpanNamingAdapter#getFinalSpanName(Object, Object)} for generating the final span name unless you\n * override this method.\n *\n * <p>This method does the actual final-span-naming work for the public-facing {@link\n * #handleResponseTaggingAndFinalSpanName(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}.\n *\n * @param span The span to name - will never be null.\n * @param request The request object - this may be null.\n * @param response The response object - this may be null.\n * @param error The error that prevented the request/response from completing normally, or null if no such error\n * occurred.\n * @param adapter The adapter to handle the request and response - will never be null.\n */\n protected void doDetermineAndSetFinalSpanName(\n @NotNull Span span,\n @Nullable REQ request,\n @Nullable RES response,\n @Nullable Throwable error,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter\n ) {\n String finalSpanName = adapter.getFinalSpanName(request, response);\n\n if (StringUtils.isNotBlank(finalSpanName)) {\n SpanMutator.changeSpanName(span, finalSpanName);\n }\n }\n\n /**\n * Adds any extra tags that Wingtips wants to add that aren't normally a part of specific tag strategies like\n * Zipkin or OpenTracing.\n *\n * <p>By default this will add the {@link WingtipsTags#SPAN_HANDLER} tag with the value that comes from\n * {@link HttpTagAndSpanNamingAdapter#getSpanHandlerTagValue(Object, Object)}.\n *\n * <p>This method does the actual extra-wingtips-tagging work for the public-facing {@link\n * #handleResponseTaggingAndFinalSpanName(Span, Object, Object, Throwable, HttpTagAndSpanNamingAdapter)}.\n *\n * @param span The span to tag - will never be null.\n * @param request The request object - this may be null.\n * @param response The response object - this may be null.\n * @param error The error that prevented the request/response from completing normally, or null if no such error\n * occurred.\n * @param adapter The adapter to handle the request and response - will never be null.\n */\n @SuppressWarnings(\"unused\")\n protected void doExtraWingtipsTagging(\n @NotNull Span span,\n @Nullable REQ request,\n @Nullable RES response,\n @Nullable Throwable error,\n @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter\n ) {\n putTagIfValueIsNotBlank(span, WingtipsTags.SPAN_HANDLER, adapter.getSpanHandlerTagValue(request, response));\n }\n\n /**\n * A helper method that can be used by subclasses for putting a tag value on the given span (via {@link\n * Span#putTag(String, String)}) if and only if the tag value is not null and its {@link Object#toString()} is not\n * blank (according to {@link StringUtils#isBlank(CharSequence)}).\n *\n * @param span The span to tag - should never be null.\n * @param tagKey The key to use when calling {@link Span#putTag(String, String)} - should never be null.\n * @param tagValue The tag value to use if and only if it is not null and its {@link Object#toString()} is not\n * blank.\n */\n protected void putTagIfValueIsNotBlank(\n @NotNull Span span,\n @NotNull String tagKey,\n @Nullable Object tagValue\n ) {\n //noinspection ConstantConditions\n if (tagValue == null || span == null || tagKey == null) {\n return;\n }\n\n // tagValue is not null. Convert to string and check for blank.\n String tagValueString = tagValue.toString();\n\n if (StringUtils.isBlank(tagValueString)) {\n return;\n }\n\n // tagValue is not blank. Add it to the given span.\n span.putTag(tagKey, tagValueString);\n }\n\n}", "public class NoOpHttpTagAdapter<REQ, RES> extends HttpTagAndSpanNamingAdapter<REQ, RES> {\n\n @SuppressWarnings(\"WeakerAccess\")\n protected static final NoOpHttpTagAdapter<?, ?> DEFAULT_INSTANCE = new NoOpHttpTagAdapter<>();\n\n /**\n * @return A reusable, thread-safe, singleton instance of this class that can be used by anybody who wants to use\n * this class and does not need any customization.\n */\n @SuppressWarnings(\"unchecked\")\n public static <REQ, RES> NoOpHttpTagAdapter<REQ, RES> getDefaultInstance() {\n return (NoOpHttpTagAdapter<REQ, RES>) DEFAULT_INSTANCE;\n }\n\n @Override\n public @Nullable String getErrorResponseTagValue(@Nullable RES response) {\n return null;\n }\n\n @Override\n public @Nullable String getRequestUrl(@Nullable REQ request) {\n return null;\n }\n\n @Override\n public @Nullable String getRequestPath(@Nullable REQ request) {\n return null;\n }\n\n @Override\n public @Nullable Integer getResponseHttpStatus(@Nullable RES response) {\n return null;\n }\n\n @Override\n public @Nullable String getRequestHttpMethod(@Nullable REQ request) {\n return null;\n }\n\n @Override\n public @Nullable String getHeaderSingleValue(@Nullable REQ request, @NotNull String headerKey) {\n return null;\n }\n\n @Override\n public @Nullable List<String> getHeaderMultipleValue(@Nullable REQ request, @NotNull String headerKey) {\n return null;\n }\n\n @Override\n public @Nullable String getSpanNamePrefix(@Nullable REQ request) {\n return null;\n }\n\n @Override\n public @Nullable String getInitialSpanName(@Nullable REQ request) {\n return null;\n }\n\n @Override\n public @Nullable String getFinalSpanName(@Nullable REQ request, @Nullable RES response) {\n return null;\n }\n\n @Override\n public @Nullable String getRequestUriPathTemplate(@Nullable REQ request, @Nullable RES response) {\n return null;\n }\n\n @Override\n public @Nullable String getSpanHandlerTagValue(@Nullable REQ request, @Nullable RES response) {\n return null;\n }\n}" ]
import com.nike.internal.util.StringUtils; import com.nike.wingtips.Span; import com.nike.wingtips.Tracer; import com.nike.wingtips.apache.httpclient.tag.ApacheHttpClientTagAdapter; import com.nike.wingtips.apache.httpclient.util.WingtipsApacheHttpClientUtil; import com.nike.wingtips.tags.HttpTagAndSpanNamingAdapter; import com.nike.wingtips.tags.HttpTagAndSpanNamingStrategy; import com.nike.wingtips.tags.NoOpHttpTagAdapter; import com.nike.wingtips.tags.NoOpHttpTagStrategy; import com.nike.wingtips.tags.ZipkinHttpTagStrategy; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.jetbrains.annotations.NotNull; import static com.nike.wingtips.apache.httpclient.util.WingtipsApacheHttpClientUtil.propagateTracingHeaders;
package com.nike.wingtips.apache.httpclient; /** * (NOTE: {@link WingtipsHttpClientBuilder} is strongly recommended instead of these interceptors if you have control * over which {@link HttpClientBuilder} is used to create your {@link HttpClient}s. Reasons for this are described at * the bottom of this class javadoc.) * * <p>This class is an implementation of both {@link HttpRequestInterceptor} and {@link HttpResponseInterceptor} for * propagating Wingtips tracing information on a {@link HttpClient} call's request headers, with an option to surround * requests in a subspan. The subspan option defaults to on and is highly recommended since the subspans will * provide you with timing info for your downstream calls separate from any parent span that may be active at the time * this interceptor executes. * * <p>In order for tracing to be propagated and any subspan to be completed correctly you need to add this as *both* * a request and response interceptor. Forgetting to add this as both a request and response interceptor could leave * your tracing in a broken state. Ideally this is added as the first {@link * HttpClientBuilder#addInterceptorFirst(HttpRequestInterceptor)} and the last {@link * HttpClientBuilder#addInterceptorLast(HttpResponseInterceptor)} so that any subspan surrounds as much of the request * as possible, including other interceptors. You can use the {@link #addTracingInterceptors(HttpClientBuilder)} * helper method to guarantee this interceptor gets added to both the request and response sides, although there's no * way to enforce the ideal request-interceptor-first and response-interceptor-last scenario with a helper method * when you have any other interceptors (you would have to add it as a request and response interceptor yourself at * the appropriate times). * * <p>If the subspan option is enabled but there's no current span on the current thread when this interceptor executes, * then a new root span (new trace) will be created rather than a subspan. In either case the newly created span will * have a {@link Span#getSpanPurpose()} of {@link Span.SpanPurpose#CLIENT} since this interceptor is for a client call. * The {@link Span#getSpanName()} for the newly created span will be generated by {@link * #getSubspanSpanName(HttpRequest, HttpTagAndSpanNamingStrategy, HttpTagAndSpanNamingAdapter)}. Instantiate this * class with a custom {@link HttpTagAndSpanNamingStrategy} and/or {@link HttpTagAndSpanNamingAdapter} (preferred), * or override that method (last resort) if you want a different span naming format. * * <p>Note that if you have the subspan option turned off then this interceptor will propagate the {@link * Tracer#getCurrentSpan()}'s tracing info downstream if it's available, but will do nothing if no current span exists * on the current thread when this interceptor executes as there's no tracing info to propagate. Turning on the * subspan option mitigates this as it guarantees there will be a span to propagate. * * <p>As mentioned at the top of this class' javadocs, {@link WingtipsHttpClientBuilder} is recommended instead of * these interceptors if you have control over which {@link HttpClientBuilder} is used to create your {@link * HttpClient}s. Reasons for this: * <ul> * <li> * There are certain types of exceptions that can occur that prevent the response interceptor side of this * class from executing, thus preventing the subspan around the request from completing. This is a consequence * of how the Apache HttpClient interceptors work. The only way to guarantee subspan completion is to use * {@link WingtipsHttpClientBuilder} instead of this interceptor. * </li> * <li> * There are several ways for interceptors to be accidentally wiped out, e.g. {@link * HttpClientBuilder#setHttpProcessor(HttpProcessor)}. * </li> * <li> * {@link WingtipsHttpClientBuilder} makes sure that any subspan *fully* surrounds the request, including all * other interceptors that are executed. * </li> * <li> * You have to remember to add this interceptor as both a request interceptor ({@link HttpRequestInterceptor}) * *and* response interceptor ({@link HttpResponseInterceptor}) on {@link HttpClientBuilder}, or tracing will * be broken. * </li> * </ul> * That said, these interceptors do work perfectly well as long as they are setup correctly *and* you never experience * any of the exceptions that cause the response interceptor to be ignored (this is usually impossible to guarantee, * making it a major issue for most use cases - again, please use {@link WingtipsHttpClientBuilder} if you can). * * @author Nic Munroe */ @SuppressWarnings("WeakerAccess") public class WingtipsApacheHttpClientInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor { /** * Static default instance of this class. This class is thread-safe so you can reuse this default instance instead * of creating new objects. */ public static final WingtipsApacheHttpClientInterceptor DEFAULT_IMPL = new WingtipsApacheHttpClientInterceptor(); /** * This is just {@link #DEFAULT_IMPL} explicitly typed to {@link HttpRequestInterceptor} so that you can call * {@link HttpClientBuilder#addInterceptorFirst(HttpRequestInterceptor)} or {@link * HttpClientBuilder#addInterceptorLast(HttpRequestInterceptor)} without having to explicitly cast it to * {@link HttpRequestInterceptor}. */ public static final HttpRequestInterceptor DEFAULT_REQUEST_IMPL = DEFAULT_IMPL; /** * This is just {@link #DEFAULT_IMPL} explicitly typed to {@link HttpResponseInterceptor} so that you can call * {@link HttpClientBuilder#addInterceptorFirst(HttpResponseInterceptor)} or {@link * HttpClientBuilder#addInterceptorLast(HttpResponseInterceptor)} without having to explicitly cast it to * {@link HttpResponseInterceptor}. */ public static final HttpResponseInterceptor DEFAULT_RESPONSE_IMPL = DEFAULT_IMPL; protected static final String SPAN_TO_CLOSE_HTTP_CONTEXT_ATTR_KEY = WingtipsApacheHttpClientInterceptor.class.getSimpleName() + "-span_to_close"; protected final boolean surroundCallsWithSubspan; protected final HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> tagAndNamingStrategy;
protected final HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> tagAndNamingAdapter;
2
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
[ "public static final int NONE = 0 ;", "public static final int NOT_NULL = 1 ;", "public static final int OBJECT_TYPE = 4 ;", "public static final int PRIMITIVE_TYPE = 2 ;", "public static final int UNSIGNED_TYPE = 8 ;" ]
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
package org.telosys.tools.generic.model.types; public class TypeConverterForCSharpTest { private TypeConverter getTypeConverter() { return new TypeConverterForCSharp() ; } private LanguageType getType(AttributeTypeInfo typeInfo ) { LanguageType lt = getTypeConverter().getType(typeInfo); System.out.println( typeInfo + " --> " + lt ); return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- ");
checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String");
0
kimkevin/AndroidStarterKit
ask-app/src/main/java/com/androidstarterkit/tool/ResourceTransfer.java
[ "public class ElementConstraints {\n public static final String MANIFEST = \"manifest\";\n public static final String APPLICATION = \"application\";\n public static final String ACTIVITY = \"activity\";\n public static final String INTENT_FILTER = \"intent-filter\";\n public static final String ACTION = \"action\";\n public static final String USES_PERMISSION = \"uses-permission\";\n\n public static final String RESOURCE = \"resources\";\n}", "public enum Extension {\n JAVA(\".java\"), XML(\".xml\"), GRADLE(\".gradle\"), PRO(\".pro\"), JSON(\".json\");\n\n private String extensionName;\n\n Extension(String extensionName) {\n this.extensionName = extensionName;\n }\n\n @Override\n public String toString() {\n return extensionName.toLowerCase();\n }\n}", "public class SyntaxConstraints {\n public static final String IDENTIFIER_PACKAGE = \"package\";\n public static final String IDENTIFIER_IMPORT = \"import\";\n\n public static final String REPLACE_STRING = \"%%\";\n public static final String DEFAULT_INDENT = \" \";\n public static final String NEWLINE = \"\\n\";\n}", "public class RemoteDirectory extends Directory {\n public static final String MODULE_NAME = \"ask-remote-module\";\n public static final String SAMPLE_ACTIVITY_NAME = \"SampleActivity.java\";\n public static final String PACKAGE_NAME = \"com/androidstarterkit/module\";\n\n private MainActivity mainActivity;\n private SlidingTabFragment sampleTabFragment;\n\n private MainActivity bakMainActivity;\n private SlidingTabFragment bakSampleTabFragment;\n\n public RemoteDirectory(String projectPathname) throws CommandException {\n super(projectPathname + \"/\" + MODULE_NAME\n , new String[] { \"java\", \"xml\", \"gradle\", \"json\" }\n , new String[] { \"build\", \"libs\" });\n\n mainActivity = new MainActivity(getChildDirPath(SAMPLE_ACTIVITY_NAME) + \"/\" + SAMPLE_ACTIVITY_NAME);\n sampleTabFragment = new SlidingTabFragment(getChildDirPath(SlidingTabFragment.FILE_NAME) + \"/\" + SlidingTabFragment.FILE_NAME);\n }\n\n public String getFilePathFromJavaDir(String key) {\n String applicationIdPath = FileUtils.changeDotToSlash(applicationId);\n\n int index;\n try {\n index = getChildDirPath(key).indexOf(applicationIdPath);\n } catch (NullPointerException exception) {\n return null;\n }\n\n try {\n return getChildDirPath(key).substring(index).replace(applicationIdPath, \"\");\n } catch (StringIndexOutOfBoundsException exception) {\n return getChildDirPath(key);\n }\n }\n\n public MainActivity getMainActivity() {\n return mainActivity;\n }\n\n public void changeMainFragmentByTabType(TabType tabType, List<LayoutGroup> layoutGroups) {\n bakMainActivity = new MainActivity(mainActivity.getPath());\n\n String fragmentName;\n if (tabType != null) {\n fragmentName = tabType.getFragmentName();\n } else {\n fragmentName = layoutGroups.get(0).getClassName();\n }\n\n Pattern pattern = Pattern.compile(\"\\\\.add\\\\(R\\\\.id\\\\.\\\\w+,\\\\s*new\\\\s*(\\\\w+)\\\\s*\\\\(\");\n\n List<String> codelines = mainActivity.getCodelines();\n for (int i = 0, li = codelines.size(); i < li; i++) {\n String codeline = codelines.get(i);\n Matcher matcher = pattern.matcher(codeline);\n if (matcher.find()) {\n codelines.set(i, codeline.replace(matcher.group(1), fragmentName));\n }\n }\n\n mainActivity.apply();\n\n List<ClassInfo> classInfos = new ArrayList<>();\n classInfos.add(new ClassInfo(fragmentName));\n defineImportClassString(mainActivity, classInfos);\n }\n\n public void injectLayoutModulesToFragment(List<LayoutGroup> layoutGroups) {\n if (layoutGroups.size() <= 1) {\n return;\n }\n\n bakSampleTabFragment = new SlidingTabFragment(sampleTabFragment.getPath());\n\n List<String> codelines = sampleTabFragment.getCodelines();\n\n Iterator<String> iterator = codelines.iterator();\n while (iterator.hasNext()) {\n String codeline = iterator.next();\n if (codeline.contains(\"fragmentInfos.add\")) {\n iterator.remove();\n }\n }\n\n for (int i = 0, li = codelines.size(); i < li; i++) {\n String codeline = codelines.get(i);\n\n if (codeline.contains(\"List<FragmentInfo> fragmentInfos = new ArrayList<>();\") && layoutGroups.size() > 0) {\n final String ADD_FRAGMENT_TO_LIST_STRING = \"fragmentInfos.add(new FragmentInfo(\" + SyntaxConstraints.REPLACE_STRING + \".class));\";\n\n String layoutCodeline = \"\";\n\n final String intent = FileUtils.extractIndentInLine(codeline);\n\n for (LayoutGroup layoutGroup : layoutGroups) {\n layoutCodeline += intent + ADD_FRAGMENT_TO_LIST_STRING.replace(SyntaxConstraints.REPLACE_STRING, layoutGroup.getClassName()) + \"\\n\";\n }\n\n sampleTabFragment.setCodeline(i + 1, layoutCodeline);\n }\n }\n\n sampleTabFragment.apply();\n }\n\n private void defineImportClassString(InjectionJavaFile javaFile, List<ClassInfo> addedClassInfos) {\n List<String> importedClassStrings = new ArrayList<>();\n for (int i = 0, li = addedClassInfos.size(); i < li; i++) {\n String classname = addedClassInfos.get(i).getName();\n if (getFilePathFromJavaDir(classname + Extension.JAVA.toString()) != null) {\n String importedClassString = SyntaxConstraints.IDENTIFIER_IMPORT + \" \"\n + applicationId\n + getFilePathFromJavaDir(classname + Extension.JAVA.toString()).replaceAll(\"/\", \".\") + \".\"\n + classname + \";\";\n if (!importedClassStrings.contains(importedClassString)) {\n importedClassStrings.add(importedClassString);\n }\n }\n }\n\n List<String> codelines = javaFile.getCodelines();\n for (int i = 0, li = codelines.size(); i < li; i++) {\n String codeline = codelines.get(i);\n\n if (codeline.contains(SyntaxConstraints.IDENTIFIER_PACKAGE)) {\n javaFile.addCodelines(i + 1, importedClassStrings);\n break;\n }\n }\n\n javaFile.apply();\n }\n\n public void recover() {\n if (bakMainActivity != null) {\n bakMainActivity.apply();\n }\n\n if (bakSampleTabFragment != null) {\n bakSampleTabFragment.apply();\n }\n }\n}", "public class SourceDirectory extends Directory {\n private RemoteDirectory remoteDirectory;\n\n private String projectPathname;\n private String mainPath;\n private String javaPath;\n private String resPath;\n private String layoutPath;\n\n private ResourceTransfer resourceTransfer;\n\n private List<ClassInfo> transformedClassInfos;\n\n public SourceDirectory(String projectPathname, String sourceModuleName, RemoteDirectory remoteDirectory) {\n super(projectPathname + \"/\" + sourceModuleName\n , new String[]{\"java\", \"gradle\", \"xml\"}\n , new String[]{\"build\", \"libs\", \"test\", \"androidTest\", \"res\"});\n this.projectPathname = projectPathname;\n this.remoteDirectory = remoteDirectory;\n\n transformedClassInfos = new ArrayList<>();\n\n resourceTransfer = new ResourceTransfer(this);\n\n mainPath = FileUtils.linkPathWithSlash(getPath(), \"src/main\");\n javaPath = FileUtils.linkPathWithSlash(mainPath, \"java\", applicationId.replaceAll(\"\\\\.\", \"/\"));\n resPath = FileUtils.linkPathWithSlash(mainPath, \"res\");\n layoutPath = FileUtils.linkPathWithSlash(resPath, ResourceType.LAYOUT.toString());\n }\n\n public BuildGradle getProjectBuildGradle() {\n return new BuildGradle(projectPathname);\n }\n\n public ProguardRules getProguardRules() {\n return new ProguardRules(getPath());\n }\n\n public MainActivity getMainActivity() {\n return new MainActivity(getChildDirPath(getMainActivityExtName()), getMainActivityExtName());\n }\n\n public String getMainPath() {\n return mainPath;\n }\n\n public String getJavaPath() {\n return javaPath;\n }\n\n public String getResPath() {\n return resPath;\n }\n\n public String getLayoutPath() {\n return layoutPath;\n }\n\n public void transformAndroidManifest() {\n AndroidManifest remoteAndroidManifestFile = remoteDirectory.getAndroidManifestFile();\n\n System.out.println(PrintUtils.prefixDash(0) + remoteAndroidManifestFile.getName());\n\n Map<String, String> remoteActivityAttributes = remoteAndroidManifestFile.getMainActivityAttributes();\n remoteActivityAttributes.keySet().stream()\n .filter(key -> !key.equals(AttributeContraints.NAME))\n .forEach(key -> {\n androidManifestFile.addMainActivityAttribute(key, remoteActivityAttributes.get(key));\n\n resourceTransfer.extractValuesInXml(remoteActivityAttributes.get(key)\n , (String resourceTypeName, String elementName) -> {\n try {\n resourceTransfer.transferValueFromRemote(remoteDirectory, resourceTypeName, elementName, 1);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n });\n });\n\n androidManifestFile.apply();\n }\n\n public void takeFileFromRemote(File remoteFile, int depth) throws CommandException {\n final String remoteFileNameEx = remoteFile.getName();\n\n String sourceFullPathname;\n\n if (remoteFile instanceof MainActivity) {\n sourceFullPathname = FileUtils.linkPathWithSlash(javaPath\n , androidManifestFile.getMainActivityNameEx());\n } else {\n sourceFullPathname = FileUtils.linkPathWithSlash(javaPath\n , FileUtils.removeFirstSlash(remoteDirectory.getFilePathFromJavaDir(remoteFileNameEx))\n , remoteFileNameEx);\n }\n\n System.out.println(PrintUtils.prefixDash(depth) + remoteFileNameEx);\n\n Scanner scanner;\n try {\n scanner = new Scanner(remoteFile);\n } catch (FileNotFoundException e) {\n throw new CommandException(CommandException.FILE_NOT_FOUND, remoteFile.getName());\n }\n\n List<String> codeLines = new ArrayList<>();\n\n while (scanner.hasNext()) {\n String codeLine = scanner.nextLine();\n\n codeLine = changePackage(codeLine);\n\n if (remoteFile instanceof MainActivity) {\n codeLine = changeMainActivityName(codeLine);\n }\n\n resourceTransfer.extractResourceFileInJava(codeLine, (resourceTypeName, layoutName) -> {\n try {\n resourceTransfer.transferResourceFileFromRemote(remoteDirectory, resourceTypeName, layoutName, depth + 1);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n });\n\n resourceTransfer.extractValuesInJava(codeLine, (resourceTypeName, elementName) -> {\n try {\n resourceTransfer.transferValueFromRemote(remoteDirectory, resourceTypeName, elementName, depth + 1);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n });\n\n codeLines.add(codeLine);\n }\n\n File sourceFile = new File(sourceFullPathname);\n FileUtils.writeFile(sourceFile, codeLines);\n fileMap.put(sourceFile.getName(), sourceFile.getPath().replaceAll(\"/\" + sourceFile.getName(), \"\"));\n\n findDeclaredClasses(depth, remoteFile.getPath());\n }\n\n private String changePackage(String codeLine) {\n if (codeLine.contains(\"package\") || codeLine.contains(\"import\")) {\n return codeLine.replace(remoteDirectory.getApplicationId(), getApplicationId());\n }\n\n return codeLine;\n }\n\n private String changeMainActivityName(String codeLine) {\n return codeLine.replace(remoteDirectory.getMainActivityName(), getMainActivityName());\n }\n\n private void findDeclaredClasses(int depth, String pathname) throws CommandException {\n Pattern pattern = Pattern.compile(\".+(com/androidstarterkit/module/.+)\");\n Matcher matcher = pattern.matcher(pathname);\n\n while (matcher.find()) {\n pathname = FileUtils.removeExtension(matcher.group(1));\n }\n\n ClassDisassembler javap = new ClassDisassembler(FileUtils.getRootPath() + \"/ask-remote-module/build/intermediates/classes/debug\"\n , RemoteDirectory.PACKAGE_NAME);\n javap.extractClasses(pathname);\n\n javap.getInternalClassInfos().stream()\n .filter(classInfo -> remoteDirectory.getFilePathFromJavaDir(classInfo.getName() + Extension.JAVA.toString()) != null)\n .filter(classInfo -> !isTransformed(classInfo))\n .forEach(classInfo -> {\n transformedClassInfos.add(classInfo);\n\n takeFileFromRemote(remoteDirectory.getChildFile(classInfo.getName(), Extension.JAVA), depth + 1);\n });\n\n javap.getExternalClassInfos().forEach(classInfo -> {\n for (String dependencyKey : externalLibrary.getKeys()) {\n if (classInfo.getName().equals(dependencyKey)) {\n appBuildGradleFile.addDependency(externalLibrary.getInfo(dependencyKey).getLibrary());\n androidManifestFile.addPermissions(externalLibrary.getInfo(dependencyKey).getPermissions());\n break;\n }\n }\n });\n\n androidManifestFile.apply();\n }\n\n private boolean isTransformed(ClassInfo classInfo) {\n for (ClassInfo transformedClassInfo : transformedClassInfos) {\n if (classInfo.equals(transformedClassInfo)) {\n return true;\n }\n }\n return false;\n }\n}", "public class FileUtils {\n\n public static String getRootPath() {\n File projectDir = new File(\".\");\n\n try {\n int index = projectDir.getCanonicalPath().indexOf(AskConfig.DEFAULT_ASK_APP_NAME);\n\n if (index > 0) {\n return projectDir.getCanonicalPath().substring(0, index - 1);\n }\n return projectDir.getCanonicalPath();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static String linkPathWithSlash(String... args) {\n String path = \"\";\n for (int i = 0, li = args.length; i < li; i++) {\n path += args[i];\n\n if (i != li - 1) {\n path += \"/\";\n }\n }\n return path;\n }\n\n public static void writeFile(File file, List<String> lineList) {\n writeFile(file, toString(lineList));\n }\n\n public static void writeFile(File file, String content) {\n if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {\n return;\n }\n\n FileWriter fileWriter;\n try {\n fileWriter = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(fileWriter);\n bw.write(content);\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void writeFile(String pathName, String fileName, String content) {\n File destDir = new File(pathName);\n if (!destDir.exists() && !destDir.mkdirs()) {\n return;\n }\n\n writeFile(FileUtils.linkPathWithSlash(pathName, fileName), content);\n }\n\n public static void writeFile(String filePath, String content) {\n File file = new File(filePath);\n\n try {\n if (!file.exists()) {\n file.createNewFile();\n }\n\n writeFile(file, content);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static List<String> readFileAsString(File file) {\n Scanner scanner;\n List<String> stringList = new ArrayList<>();\n\n try {\n scanner = new Scanner(file);\n\n while (scanner.hasNextLine()) {\n String e = scanner.nextLine();\n stringList.add(e);\n }\n } catch (FileNotFoundException e) {\n throw new RuntimeException(\"Failed to find : \" + file.getPath());\n }\n\n return stringList;\n }\n\n public static void copyFile(File moduleFile,\n String sourceFilePath) throws IOException {\n File destDir = new File(sourceFilePath);\n if (!destDir.exists() && !destDir.mkdirs()) {\n return;\n }\n\n File sourceFile = moduleFile;\n File destFile = new File(linkPathWithSlash(sourceFilePath, moduleFile.getName()));\n\n if (!sourceFile.exists()) {\n return;\n }\n\n if (!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileChannel sourceChannel;\n FileChannel destinationChannel;\n\n sourceChannel = new FileInputStream(sourceFile).getChannel();\n destinationChannel = new FileOutputStream(destFile).getChannel();\n\n if (destinationChannel != null && sourceChannel != null) {\n destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n }\n\n if (sourceChannel != null) {\n sourceChannel.close();\n }\n\n if (destinationChannel != null) {\n destinationChannel.close();\n }\n }\n\n public static void copyDirectory(File src, File dest) throws IOException{\n if (src.isDirectory()) {\n if (!dest.exists()) {\n dest.mkdirs();\n }\n\n String files[] = src.list();\n\n for (String file : files) {\n File srcFile = new File(src, file);\n File destFile = new File(dest, file);\n copyDirectory(srcFile,destFile);\n }\n\n } else {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dest);\n\n byte[] buffer = new byte[1024];\n\n int length;\n while ((length = in.read(buffer)) > 0) {\n out.write(buffer, 0, length);\n }\n\n in.close();\n out.close();\n }\n }\n\n public static String changeDotToSlash(String str) {\n return str.replaceAll(\"\\\\.\", \"/\");\n }\n\n public static String getStringBetweenQuotes(String str) {\n Pattern pattern = Pattern.compile(\"\\\"([^\\\"]*)\\\"\");\n Matcher matcher = pattern.matcher(str);\n while (matcher.find()) {\n return matcher.group(1);\n }\n return null;\n }\n\n public static String getFilenameFromDotPath(String pathname) {\n int index = pathname.lastIndexOf(\".\");\n if (index < 0) {\n index = 0;\n } else {\n index += 1;\n }\n return pathname.substring(index, pathname.length());\n }\n\n public static String getFilenameFromSlashPath(String pathname) {\n int index = pathname.lastIndexOf(\"/\");\n if (index < 0) {\n index = 0;\n } else {\n index += 1;\n }\n return pathname.substring(index, pathname.length());\n }\n\n public static String removeExtension(String filename) {\n return filename.substring(0, filename.lastIndexOf('.'));\n }\n\n public static String removeFirstSlash(String path) {\n if (path.length() > 0 && path.charAt(0) == '/') {\n path = path.substring(1);\n }\n\n return path;\n }\n\n public static String extractIndentInLine(String line) {\n String intent = \"\";\n for (int i = 0, li = line.length(); i < li; i++) {\n if (line.toCharArray()[i] == ' ') {\n intent += \" \";\n } else {\n return intent;\n }\n }\n return intent;\n }\n\n public static String toString(List<String> strList) {\n final String EoL = System.getProperty(\"line.separator\");\n\n StringBuilder sb = new StringBuilder();\n for (String line : strList) {\n sb.append(line).append(EoL);\n }\n\n return sb.toString();\n }\n\n public static String getStringWithRemovedComment(String line) {\n return line.replaceAll(\"//.*\", \"\");\n }\n\n public static int getOpenCurlyBracketCount(String line) {\n int count = 0;\n for ( int i = 0; i < line.length(); i++ ) {\n if (line.charAt(i) == '{') {\n count++;\n }\n }\n return count;\n }\n\n public static int getCloseCurlyBracketCount(String line) {\n int count = 0;\n for ( int i = 0; i < line.length(); i++ ) {\n if (line.charAt(i) == '}') {\n count++;\n }\n }\n return count;\n }\n}", "public class PrintUtils {\n public static String prefixDash(int depth) {\n String dash;\n\n if (depth <= 0) {\n dash = \"├─ \";\n } else {\n dash = \"│\";\n }\n\n for (int i = 0; i < depth; i++) {\n dash += \" \";\n }\n\n if (depth > 0) {\n dash += \"└─ \";\n }\n\n return dash + (depth > 0 ? \" \" : \"\");\n }\n}", "public class StringUtils {\n public static boolean isValid(String str) {\n return str != null && str.length() > 0;\n }\n}", "public class SyntaxUtils {\n public static String createStartElement(String elemetName) {\n return \"<\" + elemetName + \">\";\n }\n\n public static String createEndElement(String elementName) {\n return \"</\" + elementName + \">\";\n }\n\n public static boolean hasStartElement(String codeLine, String resourceTypeName) {\n return codeLine.contains(\"<\" + resourceTypeName);\n }\n\n public static boolean hasEndElement(String codeLine, String resourceTypeName) {\n return codeLine.contains(\"</\" + resourceTypeName) || codeLine.contains(\"/>\");\n }\n\n public static List<String> appendIndentForPrefix(List<String> codelines, int indentCount) {\n List<String> indentCodelines = new ArrayList<>();\n\n for (String codeline : codelines) {\n indentCodelines.add(appendIndentForPrefix(codeline, indentCount));\n }\n\n return indentCodelines;\n }\n\n public static String appendIndentForPrefix(String codeline, int indentCount) {\n String indent = \"\";\n for (int i = 0; i < indentCount; i++) {\n indent += SyntaxConstraints.DEFAULT_INDENT;\n }\n\n return indent + codeline;\n }\n\n public static String createIndentAsString(int depth) {\n String intent = \"\";\n for (int i = 0; i < depth; i++) {\n intent += \" \";\n }\n return intent;\n }\n}" ]
import com.androidstarterkit.android.api.ElementConstraints; import com.androidstarterkit.android.api.Extension; import com.androidstarterkit.constraints.SyntaxConstraints; import com.androidstarterkit.directory.RemoteDirectory; import com.androidstarterkit.directory.SourceDirectory; import com.androidstarterkit.util.FileUtils; import com.androidstarterkit.util.PrintUtils; import com.androidstarterkit.util.StringUtils; import com.androidstarterkit.util.SyntaxUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.List; import java.util.Scanner;
package com.androidstarterkit.tool; public class ResourceTransfer implements ResourceExtractable, ResourceTransferable { private static final String TAG = ResourceTransfer.class.getSimpleName(); private SourceDirectory sourceDirectory; public ResourceTransfer(SourceDirectory sourceDirectory) { this.sourceDirectory = sourceDirectory; } @Override public void extractResourceFileInJava(String input, ResourceMatcher.Handler handler) { ResourceMatcher matcher = new ResourceMatcher(input, ResourceMatcher.MatchType.RES_FILE_IN_JAVA); matcher.match(handler); } @Override public void extractValuesInJava(String codeLine, ResourceMatcher.Handler handler) { ResourceMatcher matcher = new ResourceMatcher(codeLine, ResourceMatcher.MatchType.RES_VALUE_IN_JAVA); matcher.match(handler); } @Override public void extractResourceFileInXml(String input, ResourceMatcher.Handler handler) { ResourceMatcher matcher = new ResourceMatcher(input, ResourceMatcher.MatchType.RES_FILE_IN_XML); matcher.match(handler); } @Override public void extractValuesInXml(String input, ResourceMatcher.Handler handler) { ResourceMatcher matcher = new ResourceMatcher(input, ResourceMatcher.MatchType.RES_VALUE_IN_XML); matcher.match(handler); } @Override public void transferResourceFileFromRemote(RemoteDirectory remoteDirectory, String resourceTypeName, String layoutName , int depth) throws FileNotFoundException { File moduleXmlFile = remoteDirectory.getChildFile(layoutName, Extension.XML); String codelines = ""; Scanner scanner = new Scanner(moduleXmlFile); System.out.println(PrintUtils.prefixDash(depth) + resourceTypeName + "/" + moduleXmlFile.getName()); while (scanner.hasNext()) { String xmlCodeline = scanner.nextLine() .replace(remoteDirectory.getApplicationId(), sourceDirectory.getApplicationId()) .replace(remoteDirectory.getMainActivityName(), sourceDirectory.getMainActivityName()); extractResourceFileInXml(xmlCodeline, (resourceTypeName1, layoutName1) -> { try { transferResourceFileFromRemote(remoteDirectory, resourceTypeName1, layoutName1, depth + 1); } catch (FileNotFoundException e) { e.printStackTrace(); } }); extractValuesInXml(xmlCodeline, (resourceTypeName12, elementName) -> { try { transferValueFromRemote(remoteDirectory, resourceTypeName12, elementName, depth + 1); } catch (FileNotFoundException e) { e.printStackTrace(); } }); codelines += xmlCodeline + "\n"; addDependencyToBuildGradle(xmlCodeline); } FileUtils.writeFile(sourceDirectory.getResPath() + "/" + resourceTypeName , moduleXmlFile.getName() , codelines); } public void transferValueFromRemote(RemoteDirectory remoteDirectory, String resourceTypeName , String valueName, int depth) throws FileNotFoundException { List<File> valueFiles = remoteDirectory.getChildFiles(resourceTypeName + "s", Extension.XML); if (valueFiles == null) { throw new FileNotFoundException(); } for (File moduleValueFile : valueFiles) { String relativeValueFolderPath = moduleValueFile.getPath().replace(moduleValueFile.getName(), ""); relativeValueFolderPath = relativeValueFolderPath.substring(relativeValueFolderPath.indexOf("values") , relativeValueFolderPath.length() - 1); Scanner scanner = new Scanner(moduleValueFile); String elementLines = ""; boolean isCopying = false; // Get line from module xml file while (scanner.hasNext()) { String xmlCodeLine = scanner.nextLine(); if (xmlCodeLine.contains(valueName) || isCopying) { elementLines += xmlCodeLine + SyntaxConstraints.NEWLINE; if (SyntaxUtils.hasEndElement(xmlCodeLine, resourceTypeName)) { break; } else { isCopying = true; } } } if (StringUtils.isValid(elementLines)) { String codeLines = ""; String sampleValuePathname = FileUtils.linkPathWithSlash(sourceDirectory.getResPath() , relativeValueFolderPath , moduleValueFile.getName()); File sampleValueFile = new File(FileUtils.linkPathWithSlash(sampleValuePathname)); if (!sampleValueFile.exists()) { sampleValueFile = createResourceFile(sampleValuePathname); System.out.println(PrintUtils.prefixDash(depth) + resourceTypeName + "/" + sampleValueFile.getName()); } scanner = new Scanner(sampleValueFile); boolean isDuplicatedElement = false; while (scanner.hasNext()) { String xmlCodeLine = scanner.nextLine(); // Check if it has already element if (isDuplicatedElement || xmlCodeLine.contains(valueName)) { isDuplicatedElement = !SyntaxUtils.hasEndElement(xmlCodeLine, resourceTypeName); continue; } // Check if it is end of element
if (SyntaxUtils.hasEndElement(xmlCodeLine, ElementConstraints.RESOURCE)
0
RandoApp/Rando-android
src/main/java/com/github/randoapp/api/listeners/UserFetchResultListener.java
[ "public class User {\n public List<Rando> randosIn;\n public List<Rando> randosOut;\n public String email;\n\n @Override\n public String toString() {\n return \"User{\" +\n \"randosIn=\" + randosIn +\n \", randosOut=\" + randosOut +\n \", email='\" + email + '\\'' +\n '}';\n }\n}", "public interface OnFetchUser {\n void onFetch(User user);\n}", "public class Rando implements Serializable {\n\n public enum Status {\n IN, OUT\n }\n\n public int id;\n public String randoId;\n public String imageURL;\n public UrlSize imageURLSize = new UrlSize();\n public Date date;\n public String mapURL;\n public UrlSize mapURLSize = new UrlSize();\n public Status status;\n public String detected;\n public Integer rating;\n\n public boolean isToUpload() {\n return Constants.TO_UPLOAD_RANDO_ID.equals(randoId);\n }\n\n public boolean isUnwanted() {\n return detected != null && detected.contains(\"\\\"unwanted\\\"\");\n }\n\n public static Rando fromJSON(String jsonRandoString, Rando.Status status) {\n try {\n return fromJSON(new JSONObject(jsonRandoString), status);\n } catch (JSONException e){\n return null;\n }\n }\n\n public static Rando fromJSON(JSONObject jsonRando, Rando.Status status) throws JSONException {\n Rando rando = new Rando();\n JSONObject userRandoUrlSizes = jsonRando.getJSONObject(IMAGE_URL_SIZES_PARAM);\n JSONObject userMapUrlSizes = jsonRando.getJSONObject(MAP_URL_SIZES_PARAM);\n\n rando.randoId = jsonRando.getString(RANDO_ID_PARAM);\n rando.imageURL = jsonRando.getString(IMAGE_URL_PARAM);\n rando.status = status;\n rando.imageURLSize.small = userRandoUrlSizes.getString(SMALL_PARAM);\n rando.imageURLSize.medium = userRandoUrlSizes.getString(MEDIUM_PARAM);\n rando.imageURLSize.large = userRandoUrlSizes.getString(LARGE_PARAM);\n\n rando.mapURL = jsonRando.getString(MAP_URL_PARAM);\n rando.mapURLSize.small = userMapUrlSizes.getString(SMALL_PARAM);\n rando.mapURLSize.medium = userMapUrlSizes.getString(MEDIUM_PARAM);\n rando.mapURLSize.large = userMapUrlSizes.getString(LARGE_PARAM);\n\n rando.date = new Date(jsonRando.getLong(CREATION_PARAM));\n\n if (jsonRando.has(DETECTED_PARAM)){\n JSONArray detected = jsonRando.getJSONArray(DETECTED_PARAM);\n rando.detected = detected.join(\",\");\n }\n\n if (jsonRando.has(RATING_PARAM)){\n rando.rating = jsonRando.getInt(RATING_PARAM);\n }\n return rando;\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 Rando rando = (Rando) o;\n\n if (imageURL != null ? !imageURL.equals(rando.imageURL) : rando.imageURL != null)\n return false;\n if (imageURLSize != null ? !imageURLSize.equals(rando.imageURLSize) : rando.imageURLSize != null)\n return false;\n if (mapURL != null ? !mapURL.equals(rando.mapURL) : rando.mapURL != null) return false;\n if (mapURLSize != null ? !mapURLSize.equals(rando.mapURLSize) : rando.mapURLSize != null)\n return false;\n if (randoId != null ? !randoId.equals(rando.randoId) : rando.randoId != null) return false;\n if (status != rando.status) return false;\n if (detected != null ? !detected.equals(rando.detected) : rando.detected != null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = randoId != null ? randoId.hashCode() : 0;\n result = 31 * result + (imageURL != null ? imageURL.hashCode() : 0);\n result = 31 * result + (imageURLSize != null ? imageURLSize.hashCode() : 0);\n result = 31 * result + (mapURL != null ? mapURL.hashCode() : 0);\n result = 31 * result + (mapURLSize != null ? mapURLSize.hashCode() : 0);\n result = 31 * result + (status != null ? status.hashCode() : 0);\n result = 31 * result + (detected != null ? detected.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"Rando{\" +\n \"id=\" + id +\n \", randoId='\" + randoId + '\\'' +\n \", imageURL='\" + imageURL + '\\'' +\n \", imageURLSize=\" + imageURLSize +\n \", date=\" + date +\n \", mapURL='\" + mapURL + '\\'' +\n \", mapURLSize=\" + mapURLSize +\n \", status=\" + status +\n \", detected='\" + detected + '\\'' +\n \", rating=\" + rating +\n \", toUpload=\" + isToUpload() +\n '}';\n }\n\n public String getBestImageUrlBySize(int size) {\n return getBestUrlBySize(size, imageURLSize);\n }\n\n public String getBestMapUrlBySize(int size) {\n return getBestUrlBySize(size, mapURLSize);\n }\n\n private String getBestUrlBySize(int imageSize, Rando.UrlSize urls) {\n if (imageSize >= Constants.SIZE_LARGE) {\n return urls.large;\n } else if (imageSize >= Constants.SIZE_MEDIUM) {\n return urls.medium;\n }\n return urls.small;\n }\n\n\n\n public class UrlSize implements Serializable {\n public String small;\n public String medium;\n public String large;\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof UrlSize)) return false;\n\n UrlSize urlSize = (UrlSize) o;\n\n if (large != null ? !large.equals(urlSize.large) : urlSize.large != null)\n return false;\n if (medium != null ? !medium.equals(urlSize.medium) : urlSize.medium != null)\n return false;\n if (small != null ? !small.equals(urlSize.small) : urlSize.small != null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = small != null ? small.hashCode() : 0;\n result = 31 * result + (medium != null ? medium.hashCode() : 0);\n result = 31 * result + (large != null ? large.hashCode() : 0);\n return result;\n }\n }\n\n public boolean isMapEmpty() {\n return mapURLSize == null || (TextUtils.isEmpty(mapURLSize.large) && TextUtils.isEmpty(mapURLSize.medium) && TextUtils.isEmpty(mapURLSize.small));\n }\n\n public static class DateComparator implements Comparator<Rando> {\n\n @Override\n public int compare(Rando lhs, Rando rhs) {\n Log.d(Rando.DateComparator.class, \"Compare date: \", Long.toString(rhs.date.getTime()), \" == \", Long.toString(lhs.date.getTime()), \" > \", Integer.toString((int) (rhs.date.getTime() - lhs.date.getTime())));\n return (int) (rhs.date.getTime() - lhs.date.getTime());\n }\n }\n}", "public class Log {\n\n public static void i(Class clazz, String... msgs) {\n android.util.Log.i(clazz.getName(), concatenate(msgs));\n }\n\n public static void d(Class clazz, String... msgs) {\n android.util.Log.d(clazz.getName(), concatenate(msgs));\n }\n\n public static void w(Class clazz, String... msgs) {\n android.util.Log.w(clazz.getName(), concatenate(msgs));\n }\n\n public static void e(Class clazz, String... msgs) {\n android.util.Log.e(clazz.getName(), concatenate(msgs));\n }\n\n public static void e(Class clazz, String comment, Throwable throwable) {\n android.util.Log.e(clazz.getName(), comment + \" error:\", throwable);\n }\n\n public static void v(Class clazz, String... msgs) {\n android.util.Log.v(clazz.getName(), concatenate(msgs));\n }\n\n private static String concatenate(String[] msgs) {\n if (msgs == null) {\n return \"\";\n }\n\n StringBuilder sb = new StringBuilder();\n for (String msg : msgs) {\n sb.append(msg).append(\" \");\n }\n return sb.toString();\n }\n\n}", "public class Preferences {\n public static final String AUTH_TOKEN_DEFAULT_VALUE = \"\";\n public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = \"\";\n public static final String ACCOUNT_DEFAULT_VALUE = \"\";\n public static final int STATISTICS_DEFAULT_VALUE = 0;\n\n private static Object monitor = new Object();\n\n public static String getAuthToken(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(AUTH_TOKEN, AUTH_TOKEN_DEFAULT_VALUE);\n }\n }\n\n public static void setAuthToken(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(AUTH_TOKEN, token).apply();\n }\n }\n }\n\n public static void removeAuthToken(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();\n }\n }\n\n\n public static String getAccount(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);\n }\n }\n\n public static void setAccount(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();\n }\n }\n }\n\n public static void removeAccount(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(ACCOUNT).apply();\n }\n }\n\n public static Location getLocation(Context context) {\n Location location = new Location(LOCATION);\n synchronized (monitor) {\n double lat = Double.valueOf(getSharedPreferences(context).getString(LATITUDE_PARAM, \"0\"));\n double lon = Double.valueOf(getSharedPreferences(context).getString(LONGITUDE_PARAM, \"0\"));\n location.setLatitude(lat);\n location.setLongitude(lon);\n }\n return location;\n }\n\n public static void setLocation(Context context, Location location) {\n if (location != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(LONGITUDE_PARAM, String.valueOf(location.getLongitude())).apply();\n getSharedPreferences(context).edit().putString(LATITUDE_PARAM, String.valueOf(location.getLatitude())).apply();\n }\n }\n }\n\n public static void removeLocation(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply();\n getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply();\n }\n }\n\n public static boolean isTrainingFragmentShown() {\n //TODO: change to return real value when Training will be Implemented.\n return true;\n //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0);\n }\n\n public static void setTrainingFragmentShown(Context context, int i) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply();\n }\n }\n\n public static void removeTrainingFragmentShown(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply();\n }\n }\n\n public static void setBanResetAt(Context context, long resetAt) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply();\n }\n }\n\n public static long getBanResetAt(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L);\n }\n }\n\n private static SharedPreferences getSharedPreferences(Context context) {\n synchronized (monitor) {\n return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);\n }\n }\n\n public static String getFirebaseInstanceId(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(FIREBASE_INSTANCE_ID, FIREBASE_INSTANCE_ID_DEFAULT_VALUE);\n }\n }\n\n public static void setFirebaseInstanceId(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply();\n }\n }\n }\n\n public static void removeFirebaseInstanceId(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply();\n }\n }\n\n public static Facing getCameraFacing(Context context) {\n synchronized (monitor) {\n Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name()));\n return facing;\n }\n }\n\n public static void setCameraFacing(Context context, Facing facing) {\n synchronized (monitor) {\n if (facing != null) {\n getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply();\n }\n }\n }\n\n public static Grid getCameraGrid(Context context) {\n synchronized (monitor) {\n return Grid.valueOf(getSharedPreferences(context).getString(CAMERA_GRID_STRING, Grid.OFF.name()));\n }\n }\n\n public static void setCameraGrid(Context context, Grid cameraGrid) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply();\n }\n }\n\n public static Flash getCameraFlashMode(Context context, Facing facing) {\n synchronized (monitor) {\n if (facing != null) {\n return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name()));\n } else {\n return Flash.OFF;\n }\n }\n }\n\n public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) {\n synchronized (monitor) {\n if (flashMode != null && facing != null) {\n getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply();\n }\n }\n }\n\n public static void removeCameraFlashMode(Context context, Facing facing) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply();\n }\n }\n\n public static void setUserStatistics(Context context, Statistics statistics) {\n synchronized (monitor) {\n if (statistics != null) {\n getSharedPreferences(context).edit().putInt(USER_STATISTICS_LIKES, statistics.getLikes()).apply();\n getSharedPreferences(context).edit().putInt(USER_STATISTICS_DISLIKES, statistics.getDislikes()).apply();\n }\n }\n }\n\n public static Statistics getUserStatistics(Context context) {\n synchronized (monitor) {\n return Statistics.of(\n getSharedPreferences(context).getInt(USER_STATISTICS_LIKES, STATISTICS_DEFAULT_VALUE),\n getSharedPreferences(context).getInt(USER_STATISTICS_DISLIKES, STATISTICS_DEFAULT_VALUE));\n }\n }\n}", "public static final String EMAIL_PARAM = \"email\";", "public static final String IN_RANDOS_PARAM = \"in\";", "public static final String OUT_RANDOS_PARAM = \"out\";" ]
import android.content.Context; import com.android.volley.Response; import com.github.randoapp.api.beans.User; import com.github.randoapp.api.callback.OnFetchUser; import com.github.randoapp.db.model.Rando; import com.github.randoapp.log.Log; import com.github.randoapp.preferences.Preferences; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import static com.github.randoapp.Constants.EMAIL_PARAM; import static com.github.randoapp.Constants.IN_RANDOS_PARAM; import static com.github.randoapp.Constants.OUT_RANDOS_PARAM;
package com.github.randoapp.api.listeners; public class UserFetchResultListener implements Response.Listener<JSONObject> { private OnFetchUser listener; private Context context; private UserFetchResultListener() { super(); } public UserFetchResultListener(final Context context, final OnFetchUser listener) { this.listener = listener; this.context = context; } @Override public void onResponse(JSONObject response) { try { User fetchedUser = new User(); fetchedUser.email = response.getString(EMAIL_PARAM); Preferences.setAccount(this.context, fetchedUser.email); JSONArray jsonInRandos = response.getJSONArray(IN_RANDOS_PARAM); JSONArray jsonOutRandos = response.getJSONArray(OUT_RANDOS_PARAM); List<Rando> inRandos = new ArrayList<>(jsonInRandos.length()); List<Rando> outRandos = new ArrayList<>(jsonOutRandos.length()); fetchedUser.randosIn = inRandos; fetchedUser.randosOut = outRandos; for (int i = 0; i < jsonInRandos.length(); i++) { inRandos.add(Rando.fromJSON(jsonInRandos.getJSONObject(i), Rando.Status.IN)); } for (int i = 0; i < jsonOutRandos.length(); i++) { outRandos.add(Rando.fromJSON(jsonOutRandos.getJSONObject(i), Rando.Status.OUT)); } listener.onFetch(fetchedUser); } catch (JSONException e) {
Log.e(UserFetchResultListener.class, "onResponse method", e);
3
iobeam/iobeam-client-java
src/test/java/com/iobeam/api/client/RestClientTest.java
[ "public class ApiException extends Exception {\n\n public ApiException(final String message) {\n super(message);\n }\n}", "public abstract class AbstractAuthHandler implements AuthHandler {\n\n private final static Logger logger = Logger.getLogger(AbstractAuthHandler.class.getName());\n private final String authTokenFilePath;\n private boolean forceRefresh = false;\n\n public AbstractAuthHandler() {\n this(\"auth.token\");\n }\n\n public AbstractAuthHandler(final String authTokenFilePath) {\n this.authTokenFilePath = authTokenFilePath;\n }\n\n protected AuthToken readToken() {\n if (authTokenFilePath == null) {\n return null;\n }\n\n try {\n final AuthToken token = AuthUtils.readToken(authTokenFilePath);\n\n if (token.isValid()) {\n logger.info(\"read valid auth token from file '\" + authTokenFilePath + \"'\");\n }\n return token;\n } catch (Exception e) {\n // Ignore\n }\n return null;\n }\n\n protected void writeToken(final AuthToken token) {\n if (authTokenFilePath == null) {\n return;\n }\n\n try {\n AuthUtils.writeToken(token, authTokenFilePath);\n logger.info(\"wrote auth token to file '\" + authTokenFilePath + \"'\");\n } catch (IOException e) {\n // Ignore\n }\n }\n\n @Override\n public void setForceRefresh(final boolean forceRefresh) {\n this.forceRefresh = forceRefresh;\n }\n\n public abstract AuthToken refreshToken() throws IOException, ApiException;\n\n @Override\n public AuthToken call() throws Exception {\n\n if (!forceRefresh) {\n final AuthToken token = readToken();\n\n if (token != null && token.isValid()) {\n return token;\n }\n }\n\n final AuthToken token = refreshToken();\n\n if (token != null && token.isValid()) {\n logger.info(\"Refreshed auth token: \" + token);\n writeToken(token);\n return token;\n }\n\n return null;\n }\n}", "public interface AuthHandler extends Callable<AuthToken> {\n\n public void setForceRefresh(boolean force);\n\n public AuthToken refreshToken() throws IOException, ApiException;\n}", "public abstract class AuthToken implements Serializable {\n\n private static final long serialVersionUID = 2L;\n private final String token;\n\n public AuthToken(final String token) {\n this.token = token;\n }\n\n public String getToken() {\n return token;\n }\n\n public abstract String getType();\n\n public boolean isValid() {\n return true;\n }\n\n private void readObject(final ObjectInputStream in)\n throws IOException, ClassNotFoundException {\n in.defaultReadObject();\n }\n\n @Override\n public String toString() {\n return \"AuthToken{\" +\n \"token='\" + token + '\\'' +\n \"type='\" + getType() + '\\'' +\n '}';\n }\n}", "public class ProjectBearerAuthToken extends AuthToken {\n\n private final long projectId;\n private final long expires;\n\n public ProjectBearerAuthToken(final long projectId,\n final String token,\n final Date expires) {\n super(token);\n this.projectId = projectId;\n this.expires = expires.getTime();\n }\n\n @Override\n public String getType() {\n return \"Bearer\";\n }\n\n @Override\n public boolean isValid() {\n return !hasExpired();\n }\n\n public long getProjectId() {\n return projectId;\n }\n\n public Date getExpires() {\n return new Date(expires);\n }\n\n public boolean hasExpired() {\n return System.currentTimeMillis() > expires;\n }\n\n public static ProjectBearerAuthToken fromJson(final JSONObject json) throws ParseException {\n return new ProjectBearerAuthToken(json.getLong(\"project_id\"),\n json.getString(\"token\"),\n Util.parseToDate(json.getString(\"expires\")));\n }\n\n @Override\n public String toString() {\n return \"ProjectBearerAuthToken{\" +\n \"projectId=\" + projectId +\n \", expires=\" + expires +\n '}';\n }\n}", "public class RequestBuilder implements Serializable {\n\n private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 4000;\n private static final int DEFAULT_READ_TIMEOUT_MILLIS = 2000;\n private final String url;\n private RequestMethod method = RequestMethod.GET;\n private Object content = null;\n private long contentLength = 0;\n private ContentType contentType = ContentType.NONE;\n private final Map<String, List<String>> headers = new HashMap<String, List<String>>();\n private final Map<String, Object> parameters = new HashMap<String, Object>();\n private boolean doInput = true;\n private boolean doOutput = false;\n private boolean enableGzip = true;\n private int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT_MILLIS;\n private int readTimeoutMillis = DEFAULT_READ_TIMEOUT_MILLIS;\n\n public RequestBuilder(final String url) {\n this.url = url;\n }\n\n public RequestBuilder(final RequestBuilder builder) {\n this.url = builder.url;\n this.headers.putAll(builder.headers);\n this.parameters.putAll(builder.parameters);\n this.doInput = builder.doInput;\n this.doOutput = builder.doOutput;\n this.connectTimeoutMillis = builder.connectTimeoutMillis;\n this.readTimeoutMillis = builder.readTimeoutMillis;\n this.method = builder.method;\n this.content = builder.content;\n this.contentLength = builder.contentLength;\n this.contentType = builder.contentType;\n }\n\n public HttpURLConnection build() throws IOException {\n /*\n In case we want to use OkHttp with SPDY support:\n\n final OkUrlFactory urlFactory = new OkUrlFactory(new OkHttpClient());\n final HttpURLConnection conn = urlFactory.open(new URL(buildUrl()));\n */\n final HttpURLConnection conn = (HttpURLConnection) new URL(buildUrl()).openConnection();\n\n conn.setDoInput(doInput);\n conn.setDoOutput(doOutput);\n conn.setReadTimeout(readTimeoutMillis);\n conn.setConnectTimeout(connectTimeoutMillis);\n conn.setRequestMethod(method.name());\n conn.setInstanceFollowRedirects(false);\n conn.setRequestProperty(\"Accept\", \"application/json\");\n\n if (enableGzip) {\n conn.setRequestProperty(\"Accept-Encoding\", \"gzip\");\n }\n\n if (contentType != ContentType.NONE) {\n conn.addRequestProperty(\"Content-Type\", contentType.getValue());\n }\n\n if (doOutput && contentLength > 0 && contentLength <= Integer.MAX_VALUE) {\n // Must cast contentLength to int here, since long version of\n // setFixedLengthStreamingMode isn't available early versions of\n // Android\n conn.setFixedLengthStreamingMode((int) contentLength);\n }\n\n for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {\n for (final String value : entry.getValue()) {\n conn.addRequestProperty(entry.getKey(), value);\n }\n }\n\n return conn;\n }\n\n public RequestMethod getMethod() {\n return method;\n }\n\n private RequestBuilder addHeader(final String name,\n final String value,\n final boolean clear) {\n List<String> values = headers.get(name);\n\n if (values == null) {\n values = new LinkedList<String>();\n } else if (clear) {\n values.clear();\n }\n values.add(value);\n headers.put(name, values);\n\n return this;\n }\n\n public RequestBuilder addHeader(final String name,\n final String value) {\n addHeader(name, value, false);\n return this;\n }\n\n public RequestBuilder setHeader(final String name,\n final String value) {\n addHeader(name, value, true);\n return this;\n }\n\n public Map<String, List<String>> getHeaders() {\n return headers;\n }\n\n public RequestBuilder setReadTimeout(final int millis) {\n readTimeoutMillis = millis;\n return this;\n }\n\n public RequestBuilder setConnectTimeout(final int millis) {\n connectTimeoutMillis = millis;\n return this;\n }\n\n public RequestBuilder setEnableGzip(final boolean enableGzip) {\n this.enableGzip = enableGzip;\n return this;\n }\n\n public RequestBuilder setDoInput(final boolean doInput) {\n this.doInput = doInput;\n return this;\n }\n\n public RequestBuilder setDoOutput(final boolean doOutput) {\n this.doOutput = doOutput;\n return this;\n }\n\n public RequestBuilder setRequestMethod(final RequestMethod method) {\n this.method = method;\n return this;\n }\n\n public RequestBuilder setContent(final Object content) {\n this.content = content;\n\n if (content != null) {\n setDoOutput(true);\n } else {\n setDoOutput(false);\n }\n return this;\n }\n\n public Object getContent() {\n return content;\n }\n\n public RequestBuilder setContentType(final ContentType type) {\n contentType = type;\n return this;\n }\n\n public ContentType getContentType() {\n return contentType;\n }\n\n public RequestBuilder setContentLength(final long length) {\n this.contentLength = length;\n\n if (length > 0) {\n setDoOutput(true);\n } else {\n setDoOutput(false);\n }\n return this;\n }\n\n public String getBaseUrl() {\n return url;\n }\n\n private String buildUrl() {\n final StringBuilder builder = new StringBuilder(url);\n final Iterator<Map.Entry<String, Object>> it = parameters.entrySet().iterator();\n\n if (it.hasNext()) {\n builder.append(\"?\");\n }\n\n while (it.hasNext()) {\n final Map.Entry<String, Object> entry = it.next();\n\n try {\n builder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"))\n .append(\"=\")\n .append(URLEncoder.encode(entry.getValue().toString(), \"UTF-8\"));\n\n if (it.hasNext()) {\n builder.append(\"&\");\n }\n } catch (UnsupportedEncodingException e) {\n // Ignore, potentially log.\n }\n }\n\n return builder.toString();\n }\n\n public void addParameter(final String key, final String value) {\n if (key != null && value != null) {\n parameters.put(key, value);\n }\n }\n\n public void addParameter(final String key, final int value) {\n if (key != null) {\n parameters.put(key, value);\n }\n }\n\n public void addParameter(final String key, final long value) {\n if (key != null) {\n parameters.put(key, value);\n }\n }\n\n public void addParameter(final String key, final boolean value) {\n if (key != null) {\n parameters.put(key, value);\n }\n }\n\n @Override\n public String toString() {\n return \"RequestBuilder{\" +\n \"url='\" + url + '\\'' +\n \", content=\" + content +\n \", method=\" + method +\n \", contentLength=\" + contentLength +\n \", contentType=\" + contentType +\n \", doOutput=\" + doOutput +\n \", doInput=\" + doInput +\n \", connectTimeoutMillis=\" + connectTimeoutMillis +\n \", readTimeoutMillis=\" + readTimeoutMillis +\n '}';\n }\n}", "public enum StatusCode {\n\n OK(200),\n CREATED(201),\n ACCEPTED(202),\n NO_CONTENT(204),\n\n MOVED_PERMANENTLY(301),\n FOUND(302),\n SEE_OTHER(303),\n NOT_MODIFIED(304),\n\n BAD_REQUEST(400),\n UNAUTHORIZED(401),\n FORBIDDEN(403),\n NOT_FOUND(404),\n METHOD_NOT_ALLOWED(405),\n NOT_ACCEPTABLE(406),\n REQUEST_TIMEOUT(408),\n CONFLICT(409),\n LENGTH_REQUIRED(411),\n PRECONDITION_FAILED(412),\n REQUEST_ENTITY_TOO_LARGE(413),\n TOO_MANY_REQUESTS(429),\n\n INTERNAL_SERVER_ERROR(500),\n NOT_IMPLEMENTED(501),\n BAD_GATEWAY(502),\n SERVICE_UNAVAILABLE(503),\n HTTP_VERSION_NOT_SUPPORTED(504);\n\n private static final EnumMap<StatusCode, String> descriptions =\n new EnumMap<StatusCode, String>(StatusCode.class);\n\n private static final Map<Integer, StatusCode> reverseLookup =\n new HashMap<Integer, StatusCode>();\n\n static {\n for (final StatusCode status : StatusCode.values()) {\n descriptions.put(status, status.name().toLowerCase().replace('_', ' '));\n reverseLookup.put(status.getCode(), status);\n }\n }\n\n private final int status;\n\n private StatusCode(final int status) {\n this.status = status;\n }\n\n public int getCode() {\n return status;\n }\n\n public String getDescription() {\n return descriptions.get(this);\n }\n\n public static StatusCode fromValue(final int statusCode) {\n return reverseLookup.get(statusCode);\n }\n}" ]
import com.iobeam.api.ApiException; import com.iobeam.api.auth.AbstractAuthHandler; import com.iobeam.api.auth.AuthHandler; import com.iobeam.api.auth.AuthToken; import com.iobeam.api.auth.ProjectBearerAuthToken; import com.iobeam.api.http.RequestBuilder; import com.iobeam.api.http.StatusCode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Date; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.iobeam.api.client; @RunWith(MockitoJUnitRunner.class) public class RestClientTest { @Spy private final RequestBuilder reqBuilder = new RequestBuilder("http://localhost:14634/foo"); @Spy private final RestClient client = new RestClient(); private AuthToken validToken; private AuthToken expiredToken = new ProjectBearerAuthToken(0, "faketoken", new Date(0)); private HttpURLConnection conn; @Before public void setUp() throws Exception { conn = spy(reqBuilder.build()); doReturn(conn).when(reqBuilder).build(); doNothing().when(conn).connect(); doReturn(401).when(conn).getResponseCode(); doReturn(0).when(conn).getContentLength(); doReturn(true).when(conn).getDoInput(); long validTime = System.currentTimeMillis() + 60000; validToken = new ProjectBearerAuthToken(0, "faketokenworks", new Date(validTime)); } @Test public void testRequestWithExpiredAuthTokenShouldRefreshToken() throws Exception {
final AuthHandler handler = spy(new AbstractAuthHandler() {
2
amitshekhariitbhu/RxJava2-Android-Samples
app/src/main/java/com/rxjava2/android/samples/ui/cache/CacheExampleActivity.java
[ "public class Data {\n\n public String source;\n\n @SuppressWarnings(\"CloneDoesntDeclareCloneNotSupportedException\")\n @Override\n public Data clone() {\n return new Data();\n }\n}", "public class DataSource {\n\n private final MemoryDataSource memoryDataSource;\n private final DiskDataSource diskDataSource;\n private final NetworkDataSource networkDataSource;\n\n public DataSource(MemoryDataSource memoryDataSource,\n DiskDataSource diskDataSource,\n NetworkDataSource networkDataSource) {\n this.memoryDataSource = memoryDataSource;\n this.diskDataSource = diskDataSource;\n this.networkDataSource = networkDataSource;\n }\n\n public Observable<Data> getDataFromMemory() {\n return memoryDataSource.getData();\n }\n\n public Observable<Data> getDataFromDisk() {\n return diskDataSource.getData().doOnNext(data ->\n memoryDataSource.cacheInMemory(data)\n );\n }\n\n public Observable<Data> getDataFromNetwork() {\n return networkDataSource.getData().doOnNext(data -> {\n diskDataSource.saveToDisk(data);\n memoryDataSource.cacheInMemory(data);\n });\n }\n\n}", "public class DiskDataSource {\n\n private Data data;\n\n public Observable<Data> getData() {\n return Observable.create(emitter -> {\n if (data != null) {\n emitter.onNext(data);\n }\n emitter.onComplete();\n });\n }\n\n public void saveToDisk(Data data) {\n this.data = data.clone();\n this.data.source = \"disk\";\n }\n\n}", "public class MemoryDataSource {\n\n private Data data;\n\n public Observable<Data> getData() {\n return Observable.create(emitter -> {\n if (data != null) {\n emitter.onNext(data);\n }\n emitter.onComplete();\n });\n }\n\n public void cacheInMemory(Data data) {\n this.data = data.clone();\n this.data.source = \"memory\";\n }\n\n}", "public class NetworkDataSource {\n\n public Observable<Data> getData() {\n return Observable.create(emitter -> {\n Data data = new Data();\n data.source = \"network\";\n emitter.onNext(data);\n emitter.onComplete();\n });\n }\n\n}", "public final class AppConstant {\n\n private AppConstant() {\n // This class in not publicly instantiable.\n }\n\n public static final String LINE_SEPARATOR = \"\\n\";\n\n}" ]
import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.rxjava2.android.samples.R; import com.rxjava2.android.samples.ui.cache.model.Data; import com.rxjava2.android.samples.ui.cache.source.DataSource; import com.rxjava2.android.samples.ui.cache.source.DiskDataSource; import com.rxjava2.android.samples.ui.cache.source.MemoryDataSource; import com.rxjava2.android.samples.ui.cache.source.NetworkDataSource; import com.rxjava2.android.samples.utils.AppConstant; import androidx.appcompat.app.AppCompatActivity; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers;
package com.rxjava2.android.samples.ui.cache; public class CacheExampleActivity extends AppCompatActivity { private static final String TAG = CacheExampleActivity.class.getSimpleName(); Button btn; TextView textView;
DataSource dataSource;
1
SergioDim3nsions/RealmContactsForAndroid
presentation/src/main/java/sergio/vasco/androidforexample/presentation/sections/profile/ProfilePresenter.java
[ "public interface Bus {\n void post(Object object);\n void postInmediate(Object object);\n void register(Object object);\n void unregister(Object object);\n}", "public interface InteractorInvoker {\n void execute(Interactor interactor);\n void execute(Interactor interactor, InteractorPriority priority);\n}", "public class InsertContactsIntoDataBaseInteractor implements Interactor {\n\n private Contact contact;\n private ContactsRepository contactsRepository;\n private Bus bus;\n\n public InsertContactsIntoDataBaseInteractor(Bus bus,ContactsRepository contactsRepository) {\n this.bus = bus;\n this.contactsRepository = contactsRepository;\n }\n\n @Override public void execute() throws Throwable {\n contactsRepository.insertContact(contact);\n }\n\n public void setContact(Contact contact) {\n this.contact = contact;\n }\n}", "public abstract class Presenter {\n public abstract void onResume();\n public abstract void onPause();\n}", "public class PresentationContactMapper {\n\n public Contact presentationContactToContact(PresentationContact presentationContact){\n Contact contact = new Contact();\n contact.setIdContact(presentationContact.getIdContact());\n contact.setFirstName(presentationContact.getFirstName());\n contact.setLastName(presentationContact.getLastName());\n contact.setEmail(presentationContact.getEmail());\n contact.setPhone(presentationContact.getPhone());\n return contact;\n }\n\n public PresentationContact contactToPresentationContact(Contact contact){\n PresentationContact presentationContact = new PresentationContact();\n presentationContact.setIdContact(contact.getIdContact());\n presentationContact.setFirstName(contact.getFirstName());\n presentationContact.setLastName(contact.getLastName());\n presentationContact.setEmail(contact.getEmail());\n presentationContact.setPhone(contact.getPhone());\n return presentationContact;\n }\n\n public List<PresentationContact> ContactsListToPresentationContactList(List<Contact> contactList){\n List<PresentationContact> presentationContactList = new ArrayList<>();\n\n for (Contact contact : contactList) {\n PresentationContact presentationContact = contactToPresentationContact(contact);\n presentationContactList.add(presentationContact);\n }\n return presentationContactList;\n }\n}", "public class PresentationContact {\n\n private int idContact;\n private String firstName;\n private String lastName;\n private int phone;\n private String email;\n\n public int getIdContact() {\n return idContact;\n }\n\n public void setIdContact(int idContact) {\n this.idContact = idContact;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public int getPhone() {\n return phone;\n }\n\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n}", "public interface MainView {\n void showLoader();\n void hideLoader();\n void loadContacts(List<PresentationContact> contactList);\n}" ]
import sergio.vasco.androidforexample.domain.abstractions.Bus; import sergio.vasco.androidforexample.domain.interactors.InteractorInvoker; import sergio.vasco.androidforexample.domain.interactors.main.InsertContactsIntoDataBaseInteractor; import sergio.vasco.androidforexample.presentation.Presenter; import sergio.vasco.androidforexample.presentation.mappers.PresentationContactMapper; import sergio.vasco.androidforexample.presentation.model.PresentationContact; import sergio.vasco.androidforexample.presentation.sections.main.MainView;
package sergio.vasco.androidforexample.presentation.sections.profile; /** * Name: Sergio Vasco * Date: 29/1/16. */ public class ProfilePresenter extends Presenter { private ProfileView view; private Bus bus; private InteractorInvoker interactorInvoker; private InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor; private PresentationContactMapper presentationContactMapper; public ProfilePresenter(ProfileView view, Bus bus, InteractorInvoker interactorInvoker, InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor, PresentationContactMapper presentationContactMapper) { this.view = view; this.bus = bus; this.interactorInvoker = interactorInvoker; this.insertContactsIntoDataBaseInteractor = insertContactsIntoDataBaseInteractor; this.presentationContactMapper = presentationContactMapper; } @Override public void onResume() { //bus.register(this); } @Override public void onPause() { //bus.unregister(this); }
public void createNewContact(PresentationContact presentationContact){
5
ajitsing/Sherlock
sherlock/src/main/java/com/singhajit/sherlock/crashes/activity/CrashActivity.java
[ "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 CrashViewModel {\n private Crash crash;\n private AppInfoViewModel appInfoViewModel;\n\n public CrashViewModel() {\n }\n\n public CrashViewModel(Crash crash) {\n populate(crash);\n }\n\n public String getPlace() {\n String[] placeTrail = crash.getPlace().split(\"\\\\.\");\n return placeTrail[placeTrail.length - 1];\n }\n\n public String getExactLocationOfCrash() {\n return crash.getPlace();\n }\n\n public String getReasonOfCrash() {\n return crash.getReason();\n }\n\n public String getStackTrace() {\n return crash.getStackTrace();\n }\n\n public String getCrashInfo() {\n StringBuilder crashInfo = new StringBuilder();\n crashInfo.append(\"Device Info:\\n\");\n\n crashInfo.append(\"Name: \");\n crashInfo.append(getDeviceName() + \"\\n\");\n\n crashInfo.append(\"Brand: \");\n crashInfo.append(getDeviceBrand() + \"\\n\");\n\n crashInfo.append(\"Android API: \");\n crashInfo.append(getDeviceAndroidApiVersion() + \"\\n\\n\");\n\n crashInfo.append(\"App Info:\\n\");\n crashInfo.append(getAppInfoViewModel().getDetails());\n crashInfo.append(\"\\n\");\n\n crashInfo.append(\"StackTrace:\\n\");\n crashInfo.append(getStackTrace() + \"\\n\");\n\n return crashInfo.toString();\n }\n\n public String getDeviceManufacturer() {\n return crash.getDeviceInfo().getManufacturer();\n }\n\n public String getDeviceName() {\n return crash.getDeviceInfo().getName();\n }\n\n public String getDeviceAndroidApiVersion() {\n return crash.getDeviceInfo().getSdk();\n }\n\n public String getDeviceBrand() {\n return crash.getDeviceInfo().getBrand();\n }\n\n public AppInfoViewModel getAppInfoViewModel() {\n return appInfoViewModel;\n }\n\n public int getIdentifier() {\n return crash.getId();\n }\n\n public String getDate() {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"h:mm a EEE, MMM d, yyyy\");\n return simpleDateFormat.format(crash.getDate());\n }\n\n public void populate(Crash crash) {\n this.crash = crash;\n this.appInfoViewModel = new AppInfoViewModel(crash.getAppInfo());\n }\n}", "public interface CrashActions {\n void openSendApplicationChooser(String crashDetails);\n\n void renderAppInfo(AppInfoViewModel viewModel);\n\n void render(CrashViewModel viewModel);\n}", "public class AppInfoAdapter extends RecyclerView.Adapter<AppInfoViewHolder> {\n private final List<AppInfoRowViewModel> appInfoViewModels;\n\n public AppInfoAdapter(AppInfoViewModel appInfoViewModel) {\n this.appInfoViewModels = appInfoViewModel.getAppInfoRowViewModels();\n }\n\n @Override\n public AppInfoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n LayoutInflater inflater = LayoutInflater.from(parent.getContext());\n LinearLayout appInfoView = (LinearLayout) inflater.inflate(R.layout.app_info_row, parent, false);\n return new AppInfoViewHolder(appInfoView);\n }\n\n @Override\n public void onBindViewHolder(AppInfoViewHolder holder, int position) {\n holder.render(appInfoViewModels.get(position));\n }\n\n @Override\n public int getItemCount() {\n return appInfoViewModels.size();\n }\n}", "public class CrashPresenter {\n private final SherlockDatabaseHelper database;\n private final CrashActions actions;\n\n public CrashPresenter(SherlockDatabaseHelper database, CrashActions actions) {\n this.database = database;\n this.actions = actions;\n }\n\n public void render(int crashId) {\n Crash crash = database.getCrashById(crashId);\n CrashViewModel crashViewModel = new CrashViewModel(crash);\n\n actions.render(crashViewModel);\n actions.renderAppInfo(crashViewModel.getAppInfoViewModel());\n }\n\n public void shareCrashDetails(CrashViewModel viewModel) {\n actions.openSendApplicationChooser(viewModel.getCrashInfo());\n }\n}", "public class AppInfoViewModel {\n private ArrayList<AppInfoRowViewModel> appInfoRowViewModels;\n\n public AppInfoViewModel(AppInfo appInfo) {\n Map<String, String> appDetails = appInfo.getAppDetails();\n appInfoRowViewModels = toAppInfoRowViewModels(appDetails);\n }\n\n private ArrayList<AppInfoRowViewModel> toAppInfoRowViewModels(Map<String, String> appDetails) {\n ArrayList<AppInfoRowViewModel> viewModels = new ArrayList<>();\n for (String key : appDetails.keySet()) {\n viewModels.add(new AppInfoRowViewModel(key, appDetails.get(key)));\n }\n return viewModels;\n }\n\n public String getDetails() {\n StringBuilder builder = new StringBuilder();\n for (AppInfoRowViewModel appInfoRowViewModel : appInfoRowViewModels) {\n builder.append(appInfoRowViewModel.getAttr() + \": \" + appInfoRowViewModel.getVal() + \"\\n\");\n }\n\n return builder.toString();\n }\n\n public List<AppInfoRowViewModel> getAppInfoRowViewModels() {\n return appInfoRowViewModels;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.singhajit.sherlock.R; import com.singhajit.sherlock.core.database.SherlockDatabaseHelper; import com.singhajit.sherlock.core.investigation.CrashViewModel; import com.singhajit.sherlock.crashes.action.CrashActions; import com.singhajit.sherlock.crashes.adapter.AppInfoAdapter; import com.singhajit.sherlock.crashes.presenter.CrashPresenter; import com.singhajit.sherlock.crashes.viewmodel.AppInfoViewModel;
package com.singhajit.sherlock.crashes.activity; public class CrashActivity extends BaseActivity implements CrashActions { public static final String CRASH_ID = "com.singhajit.sherlock.CRASH_ID"; private CrashViewModel viewModel = new CrashViewModel();
private CrashPresenter presenter;
4
Fedict/dcattools
scrapers/src/main/java/be/fedict/dcat/scrapers/infocenter/HtmlInfocenter.java
[ "public class Cache {\n private static final Logger logger = LoggerFactory.getLogger(Cache.class);\n \n private DB db = null;\n private static final String CACHE = \"cache\";\n private static final String URLS = \"urls\";\n private static final String PAGES = \"pages\";\n\n /**\n * Store list of URLs.\n * \n * @param urls \n */\n public void storeURLList(List<URL> urls) {\n ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);\n map.put(Cache.URLS, urls);\n db.commit();\n }\n \n /**\n * Get the list of URLs in the cache.\n * \n * @return \n */\n public List<URL> retrieveURLList() {\n ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);\n return map.getOrDefault(Cache.URLS, new ArrayList<>());\n }\n \n /**\n * Store a web page\n * \n * @param id\n * @param page\n * @param lang \n */\n public void storePage(URL id, String lang, Page page) {\n logger.debug(\"Storing page {} with lang {} to cache\", id, lang);\n ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n Map<String, Page> p = map.getOrDefault(id, new HashMap<>());\n p.put(lang, page);\n map.put(id, p);\n db.commit();\n }\n \n /**\n * Retrieve a page from the cache.\n * \n * @param id\n * @return page object\n */\n public Map<String, Page> retrievePage(URL id) {\n logger.debug(\"Retrieving page {} from cache\", id);\n ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n return map.getOrDefault(id, Collections.emptyMap());\n }\n\t\n\t/**\n * Get the list of pages in the cache.\n * \n * @return \n */\n public Set<URL> retrievePageList() {\n\t\tConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);\n return (map == null) ? Collections.emptySet() : map.keySet();\n }\n \n /**\n * Store a map to the cache.\n * \n * @param id\n * @param map \n */\n public void storeMap(URL id, Map<String,String> map) {\n ConcurrentMap<URL, Map<String,String>> m = db.hashMap(Cache.PAGES);\n m.put(id, map);\n db.commit();\n }\n \n /**\n * Retrieve a map from the cache.\n * \n * @param id\n * @return \n */\n public Map<String,String> retrieveMap(URL id) {\n ConcurrentMap<URL, Map<String,String>> map = db.hashMap(Cache.PAGES);\n return map.getOrDefault(id, Collections.emptyMap());\n }\n \n /**\n * Close cache\n */\n public void shutdown() {\n logger.info(\"Closing cache file\");\n db.close();\n }\n \n\t/**\n\t * Constructor\n\t * \n\t * @param f \n\t */\n public Cache(File f) {\n logger.info(\"Opening cache file {}\", f.getAbsolutePath());\n db = DBMaker.fileDB(f).make();\n }\n}", "public class Page implements Serializable {\n private static final long serialVersionUID = 14846132166L;\n \n private URL url;\n private String content;\n\n /**\n * Get the URL of this page.\n * \n * @return the url\n */\n public URL getUrl() {\n return url;\n }\n\n /**\n * Set the URL of this page.\n * \n * @param url the url to set\n */\n public void setUrl(URL url) {\n this.url = url;\n }\n\n /**\n * Get the content/body of this page.\n * \n * @return the content\n */\n public String getContent() {\n return content;\n }\n\n /**\n * Set the content/body of this page.\n * \n * @param content the content to set\n */\n public void setContent(String content) {\n this.content = content;\n }\n \n /**\n * Constructor\n * \n * @param url\n * @param content \n */\n public Page(URL url, String content) {\n this.url = url;\n this.content = content;\n }\n \n /**\n * Empty constructor.\n */\n public Page() {\n this.url = null;\n this.content = \"\";\n }\n}", "public class Storage {\n private final static Logger logger = LoggerFactory.getLogger(Storage.class);\n \n\tpublic final static String DATAGOVBE = \"http://data.gov.be\";\n\n private Repository repo = null;\n private ValueFactory fac = null;\n private RepositoryConnection conn = null;\n \n /**\n * Get triple store.\n * \n * @return \n */\n public Repository getRepository() {\n return repo;\n }\n\n /**\n * Delete the triple store file.\n */\n public void deleteRepository() {\n if (repo != null) {\n logger.info(\"Removing RDF backend file\");\n \n if(!repo.getDataDir().delete()) {\n logger.warn(\"Could not remove RDF backend file\");\n }\n repo = null;\n }\n }\n \n /**\n * Get value factory.\n * \n * @return \n */\n public ValueFactory getValueFactory() {\n return fac;\n }\n\n\t/**\n\t * Get parser configuration\n\t * \n\t * @return \n\t */\n\tprivate ParserConfig getParserConfig() {\n\t\tParserConfig cfg = new ParserConfig();\n\t\tcfg.set(BasicParserSettings.VERIFY_URI_SYNTAX, false);\n\t\tcfg.set(BasicParserSettings.SKOLEMIZE_ORIGIN, DATAGOVBE);\n\t\tcfg.set(XMLParserSettings.FAIL_ON_SAX_NON_FATAL_ERRORS, false);\n\t\treturn cfg;\n\t}\n\n /**\n * Create IRI using value factory.\n * \n * @param str string\n * @return trimmed IRI \n */\n public IRI getURI(String str) {\n\t\treturn fac.createIRI(str.trim());\n }\n \n /**\n * Check if a triple exists.\n * \n * @param subj\n * @param pred\n * @return\n * @throws RepositoryException \n */\n public boolean has(IRI subj, IRI pred) throws RepositoryException {\n return conn.hasStatement(subj, pred, null, false);\n }\n\n /**\n * Get multiple values from map structure.\n * \n * @param map\n * @param prop\n * @param lang\n * @return \n */\n public static List<String> getMany(Map<Resource, ListMultimap<String, String>> map, \n IRI prop, String lang) {\n List<String> res = new ArrayList<>();\n \n ListMultimap<String, String> multi = map.get(prop);\n if (multi != null && !multi.isEmpty()) {\n List<String> list = multi.get(lang);\n if (list != null && !list.isEmpty()) {\n res = list;\n }\n }\n return res;\n }\n \n /**\n * Get one value from map structure.\n * \n * @param map\n * @param prop\n * @param lang\n * @return \n */\n public static String getOne(Map<Resource, ListMultimap<String, String>> map, \n IRI prop, String lang) {\n String res = \"\";\n \n ListMultimap<String, String> multi = map.get(prop);\n if (multi != null && !multi.isEmpty()) {\n List<String> list = multi.get(lang);\n if (list != null && !list.isEmpty()) {\n res = list.get(0);\n }\n }\n return res;\n }\n\n /**\n * Add to the repository\n * \n * @param in\n * @param format\n * @throws RepositoryException \n * @throws RDFParseException \n * @throws IOException \n */\n public void add(InputStream in, RDFFormat format) \n throws RepositoryException, RDFParseException, IOException {\n conn.add(in, DATAGOVBE, format, (Resource) null);\n }\n \n /**\n * Add an IRI property to the repository.\n * \n * @param subj\n * @param pred\n * @param obj\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, IRI obj) throws RepositoryException {\n conn.add(subj, pred, obj);\n }\n\n /**\n * Add a value to the repository.\n * \n * @param subj\n * @param pred\n * @param obj\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, Value obj) throws RepositoryException {\n conn.add(subj, pred, obj);\n }\n \n\t\n /**\n * Add an URL property to the repository.\n * \n * @param subj\n * @param pred\n * @param url\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, URL url) throws RepositoryException {\n String s = url.toString().replace(\" \", \"%20\");\n conn.add(subj, pred, fac.createIRI(s));\n }\n \n /**\n * Add a date property to the repository.\n * \n * @param subj\n * @param pred\n * @param date\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, Date date) throws RepositoryException {\n conn.add(subj, pred, fac.createLiteral(date));\n }\n \n /**\n * Add a string property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @throws RepositoryException \n */\n public void add(IRI subj, IRI pred, String value) throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n \n /**\n * Add a language string property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @param lang\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, String value, String lang) \n throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value, lang));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n\n /**\n * Add a typed property to the repository.\n * \n * @param subj\n * @param pred\n * @param value\n * @param dtype\n * @throws RepositoryException \n */\n public void add(Resource subj, IRI pred, String value, IRI dtype) \n throws RepositoryException {\n\t\tif ((value != null) && !value.isEmpty()) {\n\t\t\tconn.add(subj, pred, fac.createLiteral(value, dtype));\n\t\t} else {\n\t\t\tlogger.warn(\"Skipping empty or null value for {} {}\", subj, pred);\n\t\t}\n }\n\n /**\n * Escape spaces in object URIs to avoid SPARQL issues\n * \n * @param pred \n * @throws RepositoryException \n */\n public void escapeURI(IRI pred) throws RepositoryException {\n int i = 0;\n try (RepositoryResult<Statement> stmts = \n conn.getStatements(null, pred, null, false)) {\n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n Value val = stmt.getObject();\n // Check if object is Literal or URI\n\t\t\t\tif (val instanceof Resource) {\n String uri = val.stringValue();\n\t\t\t\t\tif (uri.contains(\" \") || uri.contains(\"\\\\\") || uri.contains(\"[\") || uri.contains(\"]\")) {\n // Check if URI contains a space or brackets\n\t\t\t\t\t\tif (uri.startsWith(\"[\") && uri.endsWith(\"]\")) {\n\t\t\t\t\t\t\turi = uri.substring(1, uri.length() - 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString esc = uri.replace(\" \", \"%20\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\\\\\\\\", \"%5c\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\\\\", \"%5c\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"[\", \"%5b\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"]\", \"%5d\");\n\t\t\t\t\t\tlogger.debug(\"Changing {} into {}\", uri, esc);\n\t\t\t\t\t\tIRI obj = fac.createIRI(esc);\n\t\t\t\t\t\tconn.add(stmt.getSubject(), stmt.getPredicate(), obj);\n\t\t\t\t\t\tconn.remove(stmt);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n }\n }\n }\n logger.info(\"Replaced characters in {} URIs\", i);\n }\n \n /**\n * Execute SPARQL Update query\n * \n * @param sparql\n * @throws RepositoryException\n */\n public void queryUpdate(String sparql) throws RepositoryException {\n try {\n Update upd = conn.prepareUpdate(QueryLanguage.SPARQL, sparql);\n upd.execute();\n } catch (MalformedQueryException | UpdateExecutionException ex) {\n throw new RepositoryException(ex);\n }\n }\n \n /**\n * Get the list of all URIs of a certain class.\n * \n * @param rdfClass\n * @return list of subjects\n * @throws RepositoryException \n */\n public List<IRI> query(IRI rdfClass) throws RepositoryException {\n ArrayList<IRI> lst = new ArrayList<>();\n int i = 0;\n \n try (RepositoryResult<Statement> stmts = \n conn.getStatements(null, RDF.TYPE, rdfClass, false)) {\n \n if (! stmts.hasNext()) {\n logger.warn(\"No results for class {}\", rdfClass.stringValue());\n }\n\n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n lst.add((IRI) stmt.getSubject());\n i++;\n }\n }\n logger.debug(\"Retrieved {} statements for {}\", i, rdfClass.stringValue());\n return lst;\n }\n \n /**\n * Get a DCAT Dataset or a Distribution.\n * \n * @param uri\n * @return \n * @throws org.eclipse.rdf4j.repository.RepositoryException \n */\n public Map<Resource, ListMultimap<String, String>> queryProperties(Resource uri) \n throws RepositoryException {\n Map<Resource, ListMultimap<String, String>> map = new HashMap<>();\n \n try (RepositoryResult<Statement> stmts = conn.getStatements(uri, null, null, true)) {\n if (! stmts.hasNext()) {\n logger.warn(\"No properties for {}\", uri.stringValue());\n }\n \n while(stmts.hasNext()) {\n Statement stmt = stmts.next();\n IRI pred = stmt.getPredicate();\n Value val = stmt.getObject();\n \n String lang = \"\";\n if (val instanceof Literal) {\n String l = ((Literal) val).getLanguage().orElse(null);\n if (l != null) {\n lang = l;\n }\n }\n /* Handle multiple values for different languages */\n ListMultimap<String, String> multi = map.get(pred);\n if (multi == null) {\n multi = ArrayListMultimap.create();\n map.put(pred, multi);\n }\n multi.put(lang, val.stringValue());\n }\n }\n \n return map;\n }\n\n /**\n * Initialize RDF repository\n * \n * @throws RepositoryException \n */\n public void startup() throws RepositoryException {\n logger.info(\"Opening RDF repository\");\n conn = repo.getConnection();\n fac = repo.getValueFactory();\n\n\t\tconn.setParserConfig(getParserConfig());\n }\n \n /**\n * Stop the RDF repository\n * \n * @throws RepositoryException \n */\n public void shutdown() throws RepositoryException {\n logger.info(\"Closing RDF repository\");\n conn.commit();\n conn.close();\n repo.shutDown();\n }\n \n /**\n * Read contents of N-Triples input into a RDF repository\n * \n * @param in\n * @throws RepositoryException \n * @throws java.io.IOException \n * @throws org.eclipse.rdf4j.rio.RDFParseException \n */\n public void read(Reader in) throws RepositoryException, IOException, RDFParseException {\n this.read(in, RDFFormat.NTRIPLES);\n }\n \n /**\n * Read contents of input into a RDF repository\n * \n * @param in\n * @param format RDF input format\n * @throws RepositoryException \n * @throws IOException \n * @throws RDFParseException \n */\n public void read(Reader in, RDFFormat format) throws RepositoryException,\n IOException, RDFParseException {\n logger.info(\"Reading triples from input stream\");\n\t\tconn.setParserConfig(getParserConfig());\n conn.add(in, DATAGOVBE, format);\n }\n \n /**\n * Write contents of RDF repository to N-Triples output\n * \n * @param out\n * @throws RepositoryException \n */\n public void write(Writer out) throws RepositoryException {\n this.write(out, RDFFormat.NTRIPLES);\n } \n \n /**\n * Write contents of RDF repository to N-Triples output\n * \n * @param out\n * @param format RDF output format\n * @throws RepositoryException \n */\n public void write(Writer out, RDFFormat format) throws RepositoryException {\n RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out);\n try {\n conn.export(writer);\n } catch (RDFHandlerException ex) {\n logger.warn(\"Error writing RDF\");\n }\n }\n \n /**\n * RDF store\n * \n */\n public Storage() {\n logger.info(\"Opening RDF store\");\n \n MemoryStore mem = new MemoryStore();\n mem.setPersist(false);\n repo = new SailRepository(mem);\n }\n}", "public abstract class Html extends BaseScraper {\n\t\t/**\n\t * Return an absolute URL\n\t *\n\t * @param rel relative URL\n\t * @return\n\t * @throws MalformedURLException\n\t */\n\tprotected URL makeAbsURL(String rel) throws MalformedURLException {\n\t\t// Check if URL is already absolute\n\t\tif (rel.startsWith(\"http:\") || rel.startsWith(\"https:\")) {\n\t\t\treturn new URL(rel);\n\t\t}\n\t\treturn new URL(getBase().getProtocol(), getBase().getHost(), rel);\n\t}\n\n\n\t/**\n\t * Generate DCAT Dataset\n\t *\n\t * @param store RDF store\n\t * @param id dataset id\n\t * @param page\n\t * @throws MalformedURLException\n\t * @throws RepositoryException\n\t */\n\tprotected abstract void generateDataset(Storage store, String id, Map<String, Page> page)\n\t\t\tthrows MalformedURLException, RepositoryException;\n\n\t/**\n\t * Generate DCAT.\n\t *\n\t * @param cache\n\t * @param store\n\t * @throws RepositoryException\n\t * @throws MalformedURLException\n\t */\n\t@Override\n\tpublic void generateDcat(Cache cache, Storage store) throws RepositoryException, MalformedURLException {\n\t\tlogger.info(\"Generate DCAT\");\n\n\t\t/* Get the list of all datasets */\n\t\tList<URL> urls = cache.retrieveURLList();\n\t\tfor (URL u : urls) {\n\t\t\tMap<String, Page> page = cache.retrievePage(u);\n\t\t\tString id = makeHashId(u.toString());\n\t\t\tgenerateDataset(store, id, page);\n\t\t}\n\t\tgenerateCatalog(store);\n\t}\n\t\n\t/**\n\t * Get the list of all the downloads (DCAT Dataset).\n\t *\n\t * @return List of URLs\n\t * @throws IOException\n\t */\n\tprotected abstract List<URL> scrapeDatasetList() throws IOException;\n\t\n\t/**\n\t * Scrape a dataset\n\t * \n\t * @param u url\n\t * @throws IOException \n\t */\n\tprotected void scrapeDataset(URL u) throws IOException {\n\t\tCache cache = getCache();\n\t\tString html = makeRequest(u);\n\t\tcache.storePage(u, \"\", new Page(u, html));\n\t}\n\t\n\t/**\n\t * Scrape the site.\n\t *\n\t * @throws IOException\n\t */\n\t@Override\n\tpublic void scrape() throws IOException {\n\t\tlogger.info(\"Start scraping\");\n\t\tCache cache = getCache();\n\n\t\tList<URL> urls = cache.retrieveURLList();\n\t\tif (urls.isEmpty()) {\n\t\t\turls = scrapeDatasetList();\n\t\t\tcache.storeURLList(urls);\n\t\t}\n\n\t\tlogger.info(\"Found {} datasets on page\", String.valueOf(urls.size()));\n\t\tlogger.info(\"Start scraping (waiting between requests)\");\n\n\t\tint i = 0;\n\t\tfor (URL u : urls) {\n\t\t\tMap<String, Page> page = cache.retrievePage(u);\n\t\t\tif (page.isEmpty()) {\n\t\t\t\tsleep();\n\t\t\t\tif (++i % 100 == 0) {\n\t\t\t\t\tlogger.info(\"Download {}...\", Integer.toString(i));\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tscrapeDataset(u);\n\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\tlogger.error(\"Failed to scrape {}\", u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlogger.info(\"Done scraping\");\n\t}\n\n\t/**\n\t * Constructor\n\t *\n\t * @param prop\n\t * @throws IOException\n\t */\n\tprotected Html(Properties prop) throws IOException {\n\t\tsuper(prop);\n\t}\n}", "public class MDR_LANG {\r\n public static final String NAMESPACE = \r\n \"http://publications.europa.eu/resource/authority/language/\";\r\n \r\n public final static String PREFIX = \"mdrlang\";\r\n \r\n public final static IRI DE;\r\n public final static IRI EN;\r\n public final static IRI FR;\r\n public final static IRI NL;\r\n \r\n public final static Map<String,IRI> MAP = new HashMap<>();\r\n \r\n static {\r\n\tValueFactory factory = SimpleValueFactory.getInstance();\r\n \r\n DE = factory.createIRI(MDR_LANG.NAMESPACE, \"DEU\");\r\n EN = factory.createIRI(MDR_LANG.NAMESPACE, \"ENG\");\r\n FR = factory.createIRI(MDR_LANG.NAMESPACE, \"FRA\");\r\n NL = factory.createIRI(MDR_LANG.NAMESPACE, \"NLD\");\r\n \r\n MAP.put(\"de\", DE);\r\n MAP.put(\"en\", EN);\r\n MAP.put(\"fr\", FR);\r\n MAP.put(\"nl\", NL);\r\n }\r\n}\r" ]
import be.fedict.dcat.scrapers.Cache; import be.fedict.dcat.scrapers.Page; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.scrapers.Html; import be.fedict.dcat.vocab.MDR_LANG; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.swing.text.html.HTML; import javax.swing.text.html.HTML.Tag; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.DCAT; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.repository.RepositoryException; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements;
/* * Copyright (c) 2017, FPS BOSA DG DT * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * * 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 be.fedict.dcat.scrapers.infocenter; /** * Infocenter / federal statistics scraper. * * @see https://infocenter.belgium.be * @author Bart Hanssens */ public class HtmlInfocenter extends Html { public final static String LANG_LINK = "blgm_lSwitch"; private final static String HEADER = "h1 a[href]"; private final static String LINKS_DATASETS = "div.menu ul.no-style a[href]"; private final static String LINKS_SECOND = "div.nav-stats-wrapper ul.stats-second-menu li a"; /** * Get the URL of the page in another language * * @param page * @param lang * @return URL of the page in another language * @throws IOException */ private URL switchLanguage(String page, String lang) throws IOException { Elements lis = Jsoup.parse(page) .getElementsByClass(HtmlInfocenter.LANG_LINK); for (Element li : lis) { if (li.text().equals(lang)) { String href = li.attr(HTML.Attribute.HREF.toString()); if (href != null && !href.isEmpty()) { return new URL(href); } } } logger.warn("No {} translation for page {}", lang, page); return null; } /** * Scrape dataset * * @param u * @throws IOException */ @Override protected void scrapeDataset(URL u) throws IOException {
Cache cache = getCache();
0
MarkusBernhardt/xml-doclet
src/test/java/com/github/markusbernhardt/xmldoclet/ClassTest.java
[ "public class Class1 {\n\n}", "public class Class3 {\n\t/**\n\t * method1\n\t * \n\t * @return int\n\t */\n\tpublic int method1() {\n\t\treturn 0;\n\t}\n}", "public class Class4 {\n\t/**\n\t * field1\n\t */\n\tpublic int field1;\n}", "public class Class5 extends Class3 {\n\n}", "@SuppressWarnings(\"serial\")\npublic class Class6 implements java.io.Serializable {\n\n}", "public abstract class Class8 {\n\n}", "public class Class9 implements java.io.Externalizable {\n\n\tpublic void writeExternal(ObjectOutput out) throws IOException {\n\t\t// To change body of implemented methods use File | Settings | File\n\t\t// Templates.\n\t}\n\n\tpublic void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n\t\t// To change body of implemented methods use File | Settings | File\n\t\t// Templates.\n\t}\n}", "@AnnotationCascade(\r\n\t\tchildren= {\r\n\t\t\t@AnnotationCascadeChild(name=\"primitive\",\r\n\t\t\t\t\tdummyData= {\"A\", \"B\", \"C\"}\r\n\t\t\t\t\t),\r\n\t\t\t@AnnotationCascadeChild(name=\"nested\",\r\n\t\t\tsubAnnotations= {\r\n\t\t\t\t\t@Annotation3(id=4),\r\n\t\t\t\t\t@Annotation3(id=5),\r\n\t\t\t\t\t@Annotation3(id=666)\r\n\t\t\t\t\t\r\n\t\t\t})\r\n\t\t\t}\r\n\t\t)\r\npublic class ClassAnnotationCascade implements Interface2 {\r\n\t\r\n\tpublic void test() {\r\n\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic int method1() {\r\n\t\treturn 0;\r\n\t}\r\n}\r" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.github.markusbernhardt.xmldoclet.simpledata.Annotation3; import com.github.markusbernhardt.xmldoclet.simpledata.AnnotationCascadeChild; import com.github.markusbernhardt.xmldoclet.simpledata.Class1; import com.github.markusbernhardt.xmldoclet.simpledata.Class2; import com.github.markusbernhardt.xmldoclet.simpledata.Class3; import com.github.markusbernhardt.xmldoclet.simpledata.Class4; import com.github.markusbernhardt.xmldoclet.simpledata.Class5; import com.github.markusbernhardt.xmldoclet.simpledata.Class6; import com.github.markusbernhardt.xmldoclet.simpledata.Class7; import com.github.markusbernhardt.xmldoclet.simpledata.Class8; import com.github.markusbernhardt.xmldoclet.simpledata.Class9; import com.github.markusbernhardt.xmldoclet.simpledata.ClassAnnotationCascade; import com.github.markusbernhardt.xmldoclet.xjc.AnnotationArgument; import com.github.markusbernhardt.xmldoclet.xjc.AnnotationInstance; import com.github.markusbernhardt.xmldoclet.xjc.Class; import com.github.markusbernhardt.xmldoclet.xjc.Constructor; import com.github.markusbernhardt.xmldoclet.xjc.Field; import com.github.markusbernhardt.xmldoclet.xjc.Method; import com.github.markusbernhardt.xmldoclet.xjc.Package; import com.github.markusbernhardt.xmldoclet.xjc.Root; import com.github.markusbernhardt.xmldoclet.xjc.TypeInfo; import com.github.markusbernhardt.xmldoclet.xjc.TypeParameter;
assertEquals(returnNode.getQualified(), "int"); assertNull(returnNode.getDimension()); assertEquals(returnNode.getGeneric().size(), 0); assertNull(returnNode.getWildcard()); } /** * testing a class with 1 field */ @Test public void testClass4() { String[] sourceFiles = new String[] { "./src/test/java/com/github/markusbernhardt/xmldoclet/simpledata/Class4.java" }; Root rootNode = executeJavadoc(null, null, null, sourceFiles, null, new String[] { "-dryrun" }); Package packageNode = rootNode.getPackage().get(0); Class classNode = packageNode.getClazz().get(0); Field field = classNode.getField().get(0); assertEquals(rootNode.getPackage().size(), 1); assertNull(packageNode.getComment()); assertEquals(packageNode.getName(), "com.github.markusbernhardt.xmldoclet.simpledata"); assertEquals(packageNode.getAnnotation().size(), 0); assertEquals(packageNode.getEnum().size(), 0); assertEquals(packageNode.getInterface().size(), 0); assertEquals(packageNode.getClazz().size(), 1); assertEquals(classNode.getComment(), "Class4"); assertEquals(classNode.getConstructor().size(), 1); assertEquals(classNode.getName(), Class4.class.getSimpleName()); assertEquals(classNode.getQualified(), Class4.class.getName()); assertEquals(classNode.getScope(), "public"); assertEquals(classNode.getField().size(), 1); assertEquals(classNode.getMethod().size(), 0); assertEquals(classNode.getAnnotation().size(), 0); assertEquals(classNode.getInterface().size(), 0); assertEquals(classNode.getClazz().getQualified(), Object.class.getName()); assertFalse(classNode.isAbstract()); assertFalse(classNode.isExternalizable()); assertTrue(classNode.isIncluded()); assertFalse(classNode.isSerializable()); assertFalse(classNode.isException()); assertFalse(classNode.isError()); assertEquals(classNode.getGeneric().size(), 0); // test field assertEquals(field.getComment(), "field1"); assertEquals(field.getName(), "field1"); assertEquals(field.getScope(), "public"); assertEquals(field.getType().getQualified(), "int"); assertNull(field.getType().getDimension()); assertEquals(field.getType().getGeneric().size(), 0); assertNull(field.getType().getWildcard()); assertFalse(field.isStatic()); assertFalse(field.isTransient()); assertFalse(field.isVolatile()); assertFalse(field.isFinal()); assertNull(field.getConstant()); assertEquals(field.getAnnotation().size(), 0); } /** * testing a class that extends another class with 1 method */ @Test public void testClass5() { String[] sourceFiles = new String[] { "./src/test/java/com/github/markusbernhardt/xmldoclet/simpledata/Class5.java", "./src/test/java/com/github/markusbernhardt/xmldoclet/simpledata/Class3.java" }; Root rootNode = executeJavadoc(null, null, null, sourceFiles, null, new String[] { "-dryrun" }); Package packageNode = rootNode.getPackage().get(0); Class classNode = packageNode.getClazz().get(0); assertEquals(rootNode.getPackage().size(), 1); assertNull(packageNode.getComment()); assertEquals(packageNode.getName(), "com.github.markusbernhardt.xmldoclet.simpledata"); assertEquals(packageNode.getAnnotation().size(), 0); assertEquals(packageNode.getEnum().size(), 0); assertEquals(packageNode.getInterface().size(), 0); assertEquals(packageNode.getClazz().size(), 2); assertEquals(classNode.getComment(), "Class5"); assertEquals(classNode.getConstructor().size(), 1); assertEquals(classNode.getName(), Class5.class.getSimpleName()); assertEquals(classNode.getQualified(), Class5.class.getName()); assertEquals(classNode.getScope(), "public"); assertEquals(classNode.getMethod().size(), 0); assertEquals(classNode.getField().size(), 0); assertEquals(classNode.getAnnotation().size(), 0); assertEquals(classNode.getInterface().size(), 0); assertEquals(classNode.getClazz().getQualified(), "com.github.markusbernhardt.xmldoclet.simpledata.Class3"); assertFalse(classNode.isAbstract()); assertFalse(classNode.isExternalizable()); assertTrue(classNode.isIncluded()); assertFalse(classNode.isSerializable()); assertFalse(classNode.isException()); assertFalse(classNode.isError()); assertEquals(classNode.getGeneric().size(), 0); } /** * testing a class that implements one interface */ @Test public void testClass6() { String[] sourceFiles = new String[] { "./src/test/java/com/github/markusbernhardt/xmldoclet/simpledata/Class6.java" }; Root rootNode = executeJavadoc(null, null, null, sourceFiles, null, new String[] { "-dryrun" }); Package packageNode = rootNode.getPackage().get(0); Class classNode = packageNode.getClazz().get(0); TypeInfo interfaceNode = classNode.getInterface().get(0); assertEquals(rootNode.getPackage().size(), 1); assertNull(packageNode.getComment()); assertEquals(packageNode.getName(), "com.github.markusbernhardt.xmldoclet.simpledata"); assertEquals(packageNode.getAnnotation().size(), 0); assertEquals(packageNode.getEnum().size(), 0); assertEquals(packageNode.getInterface().size(), 0); assertEquals(packageNode.getClazz().size(), 1);
assertEquals(classNode.getComment(), "Class6");
4
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/conn/DefaultCommandExecutor.java
[ "public class FastDfsConnectException extends FastDfsUnavailableException {\n public FastDfsConnectException(String message, Throwable t) {\n super(message, t);\n }\n}", "public class FastDfsException extends RuntimeException {\n public FastDfsException(String message) {\n super(message);\n }\n\n public FastDfsException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public class ConnectionPool extends GenericKeyedObjectPool<InetSocketAddress, Connection> {\n /**\n * 默认构造函数\n */\n public ConnectionPool(KeyedPooledObjectFactory<InetSocketAddress, Connection> factory, GenericKeyedObjectPoolConfig config) {\n super(factory, config);\n }\n\n /**\n * 默认构造函数\n */\n public ConnectionPool(KeyedPooledObjectFactory<InetSocketAddress, Connection> factory) {\n super(factory);\n }\n}", "public class TrackerLocator {\n /**\n * 日志\n */\n private static final Logger logger = LoggerFactory.getLogger(TrackerLocator.class);\n\n /**\n * 连接不可经过10分钟以后重试连接\n */\n private static final int DEFAULT_RETRY_AFTER_SECOND = 10 * 60;\n\n /**\n * 连接中断以后经过N秒后可以重试\n */\n private int retryAfterSecond = DEFAULT_RETRY_AFTER_SECOND;\n\n /**\n * 方便随意快速读取\n */\n private Map<String, TrackerAddressState> trackerAddressMap = new HashMap<String, TrackerAddressState>();\n\n /**\n * 轮询圈(用户轮询获取连接地址)\n */\n private CircularList<TrackerAddressState> trackerAddressCircular = new CircularList<TrackerAddressState>();\n\n /**\n * 初始化Tracker服务器地址\n * 配置方式为 ip:port 如 192.168.1.2:21000\n */\n public TrackerLocator(Set<String> trackerSet) {\n logger.debug(\"开始初始化Tracker Server地址:{}\", trackerSet);\n for (String addressStr : trackerSet) {\n if (StringUtils.isBlank(addressStr)) {\n continue;\n }\n String[] parts = StringUtils.split(addressStr, \":\", 2);\n if (parts.length != 2) {\n logger.warn(\"Tracker Server地址格式无效[{}], 跳过此配置(正确格式 host:port)\", addressStr);\n continue;\n }\n InetSocketAddress address;\n try {\n address = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));\n } catch (Throwable e) {\n logger.warn(\"创建InetSocketAddress失败, Tracker Server地址[{}], 跳过此配置\", addressStr);\n continue;\n }\n if (trackerAddressMap.get(addressStr) == null) {\n TrackerAddressState holder = new TrackerAddressState(address);\n trackerAddressCircular.add(holder);\n trackerAddressMap.put(address.toString(), holder);\n }\n }\n if (logger.isDebugEnabled()) {\n String tmp = \"\\r\\n\" +\n \"#=======================================================================================================================#\\r\\n\" +\n \"# 初始化Tracker Server地址完毕\\r\\n\" +\n \"#\\t trackerAddressMap#keySet: \" + trackerAddressMap.keySet() + \"\\r\\n\" +\n \"#\\t trackerAddressCircular: \" + trackerAddressCircular + \"\\r\\n\" +\n \"#=======================================================================================================================#\\r\\n\";\n logger.debug(tmp);\n }\n }\n\n /**\n * 获取Tracker服务器地址(使用轮询)\n */\n public InetSocketAddress getTrackerAddress() {\n TrackerAddressState holder;\n // 遍历连接地址,抓取当前有效的地址\n for (int i = 0; i < trackerAddressCircular.size(); i++) {\n holder = trackerAddressCircular.next();\n if (holder.canTryToConnect(retryAfterSecond)) {\n return holder.getAddress();\n }\n }\n throw new FastDfsUnavailableException(\"找不到可用的 Tracker Server - {}\" + trackerAddressMap.keySet());\n }\n\n /**\n * 设置连接是否有效\n *\n * @param address 连接地址\n * @param available true有效,false无效\n */\n public void setActive(InetSocketAddress address, boolean available) {\n TrackerAddressState holder = trackerAddressMap.get(address.toString());\n if (holder == null) {\n logger.warn(\"TrackerAddressMap获取TrackerAddressState为null, key={}, 设置连接是否有效失败[{}]\", address, available);\n return;\n }\n holder.setAvailable(available);\n }\n\n public void setRetryAfterSecond(int retryAfterSecond) {\n this.retryAfterSecond = retryAfterSecond;\n }\n}", "public abstract class AbstractCommand<T> implements BaseCommand<T> {\n /**\n * 日志\n */\n private static final Logger logger = LoggerFactory.getLogger(AbstractCommand.class);\n\n /**\n * 请求对象\n */\n protected BaseRequest request;\n\n /**\n * 响应对象\n */\n protected BaseResponse<T> response;\n\n /**\n * 对服务端发出请求然后接收反馈\n */\n public T execute(Connection conn) {\n // 封装socket交易 send\n try {\n send(conn.getOutputStream(), conn.getCharset());\n } catch (IOException e) {\n throw new FastDfsIOException(\"Socket IO异常 发送消息异常\", e);\n }\n try {\n return receive(conn.getInputStream(), conn.getCharset());\n } catch (IOException e) {\n throw new FastDfsIOException(\"Socket IO异常 接收消息异常\", e);\n }\n }\n\n /**\n * 将报文输出规范为模板方法<br/>\n * 1.输出报文头<br/>\n * 2.输出报文参数<br/>\n * 3.输出文件内容<br/>\n */\n private void send(OutputStream out, Charset charset) throws IOException {\n // 报文分为三个部分\n // 报文头\n byte[] head = request.getHeadByte(charset);\n // 请求参数\n byte[] param = request.encodeParam(charset);\n // 交易文件流\n InputStream inputFile = request.getInputFile();\n long fileSize = request.getFileSize();\n logger.debug(\"发出请求 - 报文头[{}], 请求参数[{}]\", request.getHead(), param);\n // 输出报文头\n out.write(head);\n // 输出交易参数\n if (null != param) {\n out.write(param);\n }\n // 输出文件流\n if (null != inputFile) {\n sendFileContent(inputFile, fileSize, out);\n }\n }\n\n /**\n * 发送文件\n */\n private void sendFileContent(InputStream ins, long size, OutputStream ous) throws IOException {\n logger.debug(\"开始上传文件流, 大小为[{}]\", size);\n long remainBytes = size;\n byte[] buff = new byte[256 * 1024];\n int bytes;\n while (remainBytes > 0) {\n if ((bytes = ins.read(buff, 0, remainBytes > buff.length ? buff.length : (int) remainBytes)) < 0) {\n throw new IOException(\"数据流已结束, 不匹配预期的大小\");\n }\n ous.write(buff, 0, bytes);\n remainBytes -= bytes;\n logger.debug(\"剩余上传数据量[{}]\", remainBytes);\n }\n }\n\n /**\n * 接收相应数据,这里只能解析报文头\n * 报文内容(参数+文件)只能靠接收对象(对应的Response对象)解析\n */\n private T receive(InputStream in, Charset charset) throws IOException {\n // 解析报文头\n ProtocolHead head = ProtocolHead.createFromInputStream(in);\n logger.debug(\"服务端返回报文头{}\", head);\n // 校验报文头\n head.validateResponseHead();\n // 解析报文体\n return response.decode(head, in, charset);\n }\n}", "public abstract class StorageCommand<T> extends AbstractCommand<T> {\n}", "public abstract class TrackerCommand<T> extends AbstractCommand<T> {\n}", "@SuppressWarnings(\"Duplicates\")\npublic class StringUtils {\n\n /**\n * <pre>\n * StringUtils.isBlank(null) = true\n * StringUtils.isBlank(\"\") = true\n * StringUtils.isBlank(\" \") = true\n * StringUtils.isBlank(\"bob\") = false\n * StringUtils.isBlank(\" bob \") = false\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if the CharSequence is null, empty or whitespace\n * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)\n */\n public static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>\n * <p>\n * <p>The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.</p>\n * <p>\n * <p>A {@code null} input String returns {@code null}.</p>\n * <p>\n * <pre>\n * StringUtils.split(null) = null\n * StringUtils.split(\"\") = []\n * StringUtils.split(\"abc def\") = [\"abc\", \"def\"]\n * StringUtils.split(\"abc def\") = [\"abc\", \"def\"]\n * StringUtils.split(\" abc \") = [\"abc\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, {@code null} if null String input\n */\n public static String[] split(final String str) {\n return split(str, null, -1);\n }\n\n /**\n * <p>Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.</p>\n * <p>\n * <p>The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.</p>\n * <p>\n * <p>A {@code null} input String returns {@code null}.</p>\n * <p>\n * <pre>\n * StringUtils.split(null, *) = null\n * StringUtils.split(\"\", *) = []\n * StringUtils.split(\"a.b.c\", '.') = [\"a\", \"b\", \"c\"]\n * StringUtils.split(\"a..b.c\", '.') = [\"a\", \"b\", \"c\"]\n * StringUtils.split(\"a:b:c\", '.') = [\"a:b:c\"]\n * StringUtils.split(\"a b c\", ' ') = [\"a\", \"b\", \"c\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, {@code null} if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return splitWorker(str, separatorChar, false);\n }\n\n /**\n * <pre>\n * StringUtils.split(null, *) = null\n * StringUtils.split(\"\", *) = []\n * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n * StringUtils.split(\"abc def\", \" \") = [\"abc\", \"def\"]\n * StringUtils.split(\"abc def\", \" \") = [\"abc\", \"def\"]\n * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * {@code null} splits on whitespace\n * @return an array of parsed Strings, {@code null} if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n * <pre>\n * StringUtils.split(null, *, *) = null\n * StringUtils.split(\"\", *, *) = []\n * StringUtils.split(\"ab cd ef\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n * StringUtils.split(\"ab cd ef\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n * StringUtils.split(\"ab:cd:ef\", \":\", 0) = [\"ab\", \"cd\", \"ef\"]\n * StringUtils.split(\"ab:cd:ef\", \":\", 2) = [\"ab\", \"cd:ef\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * {@code null} splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, {@code null} if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return splitWorker(str, separatorChars, max, false);\n }\n\n /**\n * Performs the logic for the {@code split} and\n * {@code splitPreserveAllTokens} methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be {@code null}\n * @param separatorChar the separate character\n * @param preserveAllTokens if {@code true}, adjacent separators are\n * treated as empty token separators; if {@code false}, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, {@code null} if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len == 0) {\n return new String[0];\n }\n final List<String> list = new ArrayList<String>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Performs the logic for the {@code split} and\n * {@code splitPreserveAllTokens} methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be {@code null}\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if {@code true}, adjacent separators are\n * treated as empty token separators; if {@code false}, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, {@code null} if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len == 0) {\n return new String[0];\n }\n final List<String> list = new ArrayList<String>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n final char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * <pre>\n * StringUtils.capitalize(null) = null\n * StringUtils.capitalize(\"\") = \"\"\n * StringUtils.capitalize(\"cat\") = \"Cat\"\n * StringUtils.capitalize(\"cAt\") = \"CAt\"\n * </pre>\n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, {@code null} if null String input\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n\n final char firstChar = str.charAt(0);\n if (Character.isTitleCase(firstChar)) {\n // already capitalized\n return str;\n }\n\n return new StringBuilder(strLen)\n .append(Character.toTitleCase(firstChar))\n .append(str.substring(1))\n .toString();\n }\n\n /**\n * <pre>\n * StringUtils.defaultIfBlank(null, \"NULL\") = \"NULL\"\n * StringUtils.defaultIfBlank(\"\", \"NULL\") = \"NULL\"\n * StringUtils.defaultIfBlank(\" \", \"NULL\") = \"NULL\"\n * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n * StringUtils.defaultIfBlank(\"\", null) = null\n * </pre>\n *\n * @param <T> the specific kind of CharSequence\n * @param str the CharSequence to check, may be null\n * @param defaultStr the default CharSequence to return\n * if the input is whitespace, empty (\"\") or {@code null}, may be null\n * @return the passed in CharSequence, or the default\n */\n public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) {\n return isBlank(str) ? defaultStr : str;\n }\n}" ]
import org.cleverframe.fastdfs.exception.FastDfsConnectException; import org.cleverframe.fastdfs.exception.FastDfsException; import org.cleverframe.fastdfs.pool.ConnectionPool; import org.cleverframe.fastdfs.pool.TrackerLocator; import org.cleverframe.fastdfs.protocol.AbstractCommand; import org.cleverframe.fastdfs.protocol.storage.StorageCommand; import org.cleverframe.fastdfs.protocol.tracker.TrackerCommand; import org.cleverframe.fastdfs.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Set;
package org.cleverframe.fastdfs.conn; /** * 连接池管理<br/> * 负责借出连接,在连接上执行业务逻辑,然后归还连<br/> * <b>注意: 当前类最好使用单例,一个应用只需要一个实例</b> * 作者:LiZW <br/> * 创建时间:2016/11/20 19:26 <br/> */ public class DefaultCommandExecutor implements CommandExecutor { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(DefaultCommandExecutor.class); /** * Tracker定位 */ private TrackerLocator trackerLocator; /** * 连接池 */ private ConnectionPool pool; /** * 构造函数 * * @param trackerStr Tracker Server服务器IP地址,格式 host:port(多个用用“,”隔开) * @param pool 连接池 */ public DefaultCommandExecutor(String trackerStr, ConnectionPool pool) { logger.debug("初始化Tracker Server连接 {}", trackerStr); Set<String> trackerSet = new HashSet<String>(); String[] trackerArray = StringUtils.split(trackerStr, ","); for (String tracker : trackerArray) { if (StringUtils.isBlank(tracker)) { continue; } trackerSet.add(tracker.trim()); } if (trackerSet.size() <= 0) { throw new RuntimeException("Tracker Server服务器IP地址解析失败:[" + trackerStr + "]"); } this.pool = pool; trackerLocator = new TrackerLocator(trackerSet); } /** * 构造函数 * * @param trackerSet Tracker Server服务器IP地址集合 * @param pool 连接池 */ public DefaultCommandExecutor(Set<String> trackerSet, ConnectionPool pool) { logger.debug("初始化Tracker Server连接 {}", trackerSet); this.pool = pool; trackerLocator = new TrackerLocator(trackerSet); } @Override public <T> T execute(TrackerCommand<T> command) { Connection conn; InetSocketAddress address; try { // 获取Tracker服务器地址(使用轮询) address = trackerLocator.getTrackerAddress(); // 从连接池中获取连接 conn = getConnection(address); } catch (Throwable e) { throw new RuntimeException("获取Tracker服务器地址失败", e); } logger.debug("获取到Tracker连接地址{}", address); return executeCmd(address, conn, command); } @Override public <T> T execute(InetSocketAddress address, StorageCommand<T> command) { Connection conn; try { // 从连接池中获取连接 conn = getConnection(address); } catch (Throwable e) { throw new RuntimeException("获取Storage服务器地址失败", e); } logger.debug("获取到Storage连接地址{}", address); return executeCmd(address, conn, command); } /** * 从连接池里获取连接<br/> * <b>注意: 返回的连接使用完必须还回给连接池, 调用pool.returnObject</b> * * @param address 连接池 资源KEY * @return 返回连接, 使用完必须返回给连接池 */ private Connection getConnection(InetSocketAddress address) { Connection conn; try { // 从连接池中获取连接 conn = pool.borrowObject(address); trackerLocator.setActive(address, true); } catch (FastDfsConnectException e) { trackerLocator.setActive(address, false); throw e; } catch (Throwable e) { throw new RuntimeException("从连接池中获取连接异常", e); } return conn; } /** * 在Server上执行命令, 执行完毕 把链接还回连接池 * * @param address 连接池 资源KEY * @param conn 连接池连接资源 * @param command Server命令对象 * @return 返回请求响应对象 */ private <T> T executeCmd(InetSocketAddress address, Connection conn, AbstractCommand<T> command) { // 发送请求 try { logger.debug("发送请求, 服务器地址[{}], 请求类型[{}]", address, command.getClass().getSimpleName()); return command.execute(conn);
} catch (FastDfsException e) {
1
guillaume-alvarez/ShapeOfThingsThatWere
core/src/com/galvarez/ttw/model/AIDiplomaticSystem.java
[ "public enum Action {\n\n NO_CHANGE(\"no change\", null, null, allOf(State.class), a -> false),\n\n DECLARE_WAR(\"declare war\", State.WAR, State.WAR, complementOf(of(State.WAR)), a -> true),\n\n MAKE_PEACE(\"make peace\", State.NONE, State.NONE, of(State.WAR), a -> false),\n\n SIGN_TREATY(\"sign a treaty\", State.TREATY, State.TREATY, of(State.WAR, State.NONE, State.TRIBUTE,\n State.PROTECTORATE), a -> a == MAKE_PEACE),\n\n SURRENDER(\"surrender\", State.TRIBUTE, State.PROTECTORATE, of(State.WAR), a -> a == MAKE_PEACE || a == SIGN_TREATY);\n\n public final String str;\n\n public final Set<State> before;\n\n private final State afterMe;\n\n private final State afterYou;\n\n private final Predicate<Action> compatibleWith;\n\n private Action(String str, State afterMe, State afterYou, Set<State> before, Predicate<Action> compatibleWith) {\n this.str = str;\n this.afterMe = afterMe;\n this.afterYou = afterYou;\n this.before = before;\n this.compatibleWith = compatibleWith;\n }\n\n public boolean compatibleWith(Action targetProposal) {\n return targetProposal == this || compatibleWith.test(targetProposal);\n }\n\n}", "public enum State {\n NONE, WAR, TREATY, PROTECTORATE, TRIBUTE;\n}", "public final class AIControlled extends Component {\n\n public int lastMove;\n\n public MapPosition lastPosition;\n\n public int armiesTargetsComputationTurn = Integer.MIN_VALUE;\n\n public final List<MapPosition> armiesTargets = new ArrayList<>();\n\n public AIControlled() {\n }\n\n}", "public final class Diplomacy extends Component {\n\n public final Map<Entity, State> relations = new HashMap<>();\n\n public final ObjectIntMap<Entity> lastChange = new ObjectIntMap<>();\n\n public final Map<Entity, Action> proposals = new HashMap<>();\n\n public final EnumSet<State> knownStates = EnumSet.of(State.NONE);\n\n public Diplomacy() {\n }\n\n public State getRelationWith(Entity other) {\n if (other == null)\n return State.NONE;\n State state = relations.get(other);\n return state != null ? state : State.NONE;\n }\n\n public boolean hasRelationWith(Entity other) {\n if (other == null)\n return false;\n else\n return relations.containsKey(other) || proposals.containsKey(other) || lastChange.containsKey(other);\n }\n\n public Action getProposalTo(Entity other) {\n Action action = proposals.get(other);\n return action != null ? action : Action.NO_CHANGE;\n }\n\n /** Get all empires whose state is the one passed as a parameter. */\n public List<Entity> getEmpires(State state) {\n List<Entity> others = new ArrayList<Entity>();\n for (Entry<Entity, State> e : relations.entrySet()) {\n if (e.getValue() == state)\n others.add(e.getKey());\n }\n return others;\n }\n\n}", "public final class InfluenceSource extends Component {\n\n private float power = InfluenceSystem.INITIAL_POWER;\n\n /** In per mille. */\n public int growth;\n\n /** Usually compared to power. */\n public int health = InfluenceSystem.INITIAL_POWER;\n\n public final Set<MapPosition> influencedTiles = new HashSet<>();\n\n public final List<Entity> secondarySources = new ArrayList<>();\n\n public final Modifiers modifiers = new Modifiers();\n\n public static final class Modifiers {\n\n public final Map<Terrain, Integer> terrainBonus = new EnumMap<Terrain, Integer>(Terrain.class);\n\n public Modifiers() {\n for (Terrain t : Terrain.values())\n terrainBonus.put(t, Integer.valueOf(0));\n }\n\n }\n\n public int power() {\n return (int) power;\n }\n\n public void addToPower(float f) {\n power += f;\n }\n\n public void setPower(int power) {\n this.power = power;\n }\n\n}", "public final class GameMap {\n\n public final Terrain[][] map;\n\n private final Entity[][] entityByCoord;\n\n private final MapPosition[][] posByCoord;\n\n private final Influence[][] influenceByCoord;\n\n public final int width, height;\n\n /** Represents the whole map as a single image. */\n public final Texture texture;\n\n public final Empire[] empires;\n\n public GameMap(Terrain[][] map, Collection<Empire> empires) {\n this.map = map;\n this.empires = empires.toArray(new Empire[0]);\n width = map.length;\n height = map[0].length;\n\n entityByCoord = new Entity[width][height];\n influenceByCoord = new Influence[width][height];\n posByCoord = new MapPosition[width][height];\n\n Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);\n\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n MapPosition pos = posByCoord[x][y] = new MapPosition(x, y);\n influenceByCoord[x][y] = new Influence(pos, map[x][y]);\n pixmap.setColor(map[x][y].getColor());\n pixmap.drawPixel(x, y);\n }\n }\n\n texture = new Texture(pixmap);\n pixmap.dispose();\n }\n\n public Entity getEntityAt(int x, int y) {\n if (isOnMap(x, y))\n return entityByCoord[x][y];\n else\n return null;\n }\n\n public Entity getEntityAt(MapPosition pos) {\n return getEntityAt(pos.x, pos.y);\n }\n\n public boolean hasEntity(MapPosition pos) {\n return getEntityAt(pos) != null;\n }\n\n public Terrain getTerrainAt(MapPosition pos) {\n return getTerrainAt(pos.x, pos.y);\n }\n\n public Terrain getTerrainAt(int x, int y) {\n if (isOnMap(x, y))\n return map[x][y];\n else\n throw new IllegalStateException(\"(\" + x + \", \" + y + \") is outside map boundaries.\");\n }\n\n public Influence getInfluenceAt(MapPosition pos) {\n return getInfluenceAt(pos.x, pos.y);\n }\n\n public Influence getInfluenceAt(int x, int y) {\n if (isOnMap(x, y))\n return influenceByCoord[x][y];\n else\n throw new IllegalStateException(\"(\" + x + \", \" + y + \") is outside map boundaries.\");\n }\n\n public boolean isOnMap(MapPosition p) {\n return isOnMap(p.x, p.y);\n }\n\n public boolean isOnMap(int x, int y) {\n return x >= 0 && x < posByCoord.length && y >= 0 && y < posByCoord[0].length;\n }\n\n public MapPosition getPositionAt(int x, int y) {\n if (isOnMap(x, y))\n return posByCoord[x][y];\n else\n throw new IllegalStateException(\"(\" + x + \", \" + y + \") is outside map boundaries.\");\n }\n\n public void setEntity(Entity e, int x, int y) {\n entityByCoord[x][y] = e;\n }\n\n public void setEntity(Entity e, MapPosition p) {\n setEntity(e, p.x, p.y);\n }\n\n public void moveEntity(Entity e, MapPosition from, MapPosition to) {\n entityByCoord[from.x][from.y] = null;\n entityByCoord[to.x][to.y] = e;\n }\n\n public Array<MapPosition> getNeighbors(int x, int y, int n) {\n Array<MapPosition> coordinates = new Array<MapPosition>();\n int min;\n int myrow;\n for (int row = y - n; row < y + n + 1; row++) {\n min = MyMath.min(2 * (row - y + n), n, -2 * (row - y - n) + 1);\n for (int col = x - min; col < x + min + 1; col++) {\n if ((col < 0) || (col >= width))\n continue;\n if (x == col && y == row)\n continue;\n else if (x % 2 == 0)\n myrow = 2 * y - row;\n else\n myrow = row;\n if ((myrow < 0) || (myrow >= height))\n continue;\n coordinates.add(new MapPosition(col, myrow));\n }\n }\n return coordinates;\n }\n\n public Array<MapPosition> getNeighbors(MapPosition pos) {\n return getNeighbors(pos.x, pos.y, 1);\n }\n\n}", "public final class Influence implements Iterable<IntIntMap.Entry> {\n\n public final MapPosition position;\n\n public final Terrain terrain;\n\n /** Entity id to influence score. */\n private final IntIntMap influence = new IntIntMap();\n\n /**\n * Entity id to influence delta from last turn. Only for display when starting\n * a new turn, player needs to know how things evolve.\n */\n private final IntIntMap influenceDelta = new IntIntMap();\n\n /**\n * Entity id to influence target for next turn. Used to compute the increment\n * at each turn.\n */\n private final IntIntMap influenceTarget = new IntIntMap();\n\n private int mainInfluence = 0;\n\n private int mainInfluenceSource = -1;\n\n private int secondInfluenceDiff = 0;\n\n public Influence(MapPosition position, Terrain terrain) {\n this.position = position;\n this.terrain = terrain;\n }\n\n /** Set the source influence to the tile. */\n public void setInfluence(Entity source, int inf) {\n influence.put(source.getId(), inf);\n recomputeMain();\n }\n\n /** Move the source influence on the tile. */\n public void moveInfluence(Entity from, Entity to) {\n influence.getAndIncrement(to.getId(), 0, influence.remove(from.getId(), 0));\n recomputeMain();\n }\n\n /** Remove the source influence from the tile. */\n public void removeInfluence(Entity source) {\n influence.remove(source.getId(), 0);\n influenceDelta.remove(source.getId(), 0);\n recomputeMain();\n }\n\n public Iterable<IntIntMap.Entry> getDelta() {\n return influenceDelta;\n }\n\n public int getDelta(Entity source) {\n return influenceDelta.get(source.getId(), 0);\n }\n\n public void clearInfluenceTarget() {\n influenceTarget.clear();\n }\n\n public void increaseTarget(Entity source, int target) {\n influenceTarget.getAndIncrement(source.getId(), 0, target);\n }\n\n /** Make each participant influence closer to target and compute delta. */\n public void computeNewInfluence() {\n influenceDelta.clear();\n\n // make sure all involved empires have a target influence\n for (Entry e : influence) {\n if (!influenceTarget.containsKey(e.key))\n influenceTarget.put(e.key, 0);\n }\n\n // then compute the delta and apply it\n for (Entry e : influenceTarget) {\n final int current = influence.get(e.key, 0);\n final int target = e.value;\n int delta = 0;\n if (target > current)\n delta = max(1, (target - current) / 10);\n else if (target < current)\n delta = -max(1, (current - target) / 10);\n\n if (delta != 0) {\n // do nothing if same obviously\n influence.put(e.key, max(0, current + delta));\n influenceDelta.put(e.key, delta);\n }\n }\n recomputeMain();\n }\n\n private void recomputeMain() {\n int secondInfluence = Integer.MIN_VALUE;\n mainInfluence = terrain.moveCost() - 1;\n mainInfluenceSource = -1;\n if (influence.size > 0) {\n for (Iterator<Entry> it = influence.iterator(); it.hasNext();) {\n Entry e = it.next();\n if (e.value > mainInfluence) {\n secondInfluence = mainInfluence;\n mainInfluenceSource = e.key;\n mainInfluence = e.value;\n } else if (e.value <= 0) {\n it.remove();\n } else if (e.value > secondInfluence) {\n secondInfluence = e.value;\n }\n }\n }\n if (secondInfluence > 0)\n secondInfluenceDiff = mainInfluence - secondInfluence;\n }\n\n public int getInfluence(Entity e) {\n return influence.get(e.getId(), 0);\n }\n\n public int getSecondInfluenceDiff() {\n return secondInfluenceDiff;\n }\n\n public int getMainInfluenceSource() {\n return mainInfluenceSource;\n }\n\n public Entity getMainInfluenceSource(World world) {\n if (hasMainInfluence())\n return world.getEntity(mainInfluenceSource);\n else\n return null;\n }\n\n public int requiredInfluence(Entity e) {\n if (isMainInfluencer(e))\n return 0;\n int current = influence.get(e.getId(), 0);\n return max(terrain.moveCost(), mainInfluence + 1) - current;\n }\n\n public boolean isMainInfluencer(Entity e) {\n return e.getId() == mainInfluenceSource;\n }\n\n public boolean hasMainInfluence() {\n return mainInfluenceSource >= 0;\n }\n\n public boolean hasInfluence(Entity source) {\n return influence.get(source.getId(), 0) > 0;\n }\n\n public int getMaxInfluence() {\n int max = 0;\n for (Entry e : influence)\n if (e.value > max)\n max = e.value;\n return max(max, terrain.moveCost());\n }\n\n public int getTotalInfluence() {\n int total = 0;\n for (Entry e : influence)\n total += e.value;\n return max(total, terrain.moveCost());\n }\n\n @Override\n public Iterator<Entry> iterator() {\n return influence.iterator();\n }\n\n @Override\n public int hashCode() {\n return position.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n else\n return (obj instanceof Influence) && position.equals(((Influence) obj).position);\n }\n\n @Override\n public String toString() {\n return terrain + influence.toString();\n }\n\n}", "public final class MapPosition extends Component {\r\n\r\n public final int x, y;\r\n\r\n public MapPosition(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return x + y * 31;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this)\r\n return true;\r\n else if (obj instanceof MapPosition) {\r\n MapPosition p = (MapPosition) obj;\r\n return x == p.x && y == p.y;\r\n }\r\n return false;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"(\" + x + \",\" + y + \")\";\r\n }\r\n}\r", "public final class Name extends Component {\r\n\r\n public String name;\r\n\r\n public Name(String name) {\r\n this.name = name;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return name;\r\n }\r\n\r\n}\r" ]
import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Wire; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.utils.IntIntMap; import com.badlogic.gdx.utils.IntIntMap.Entry; import com.galvarez.ttw.model.DiplomaticSystem.Action; import com.galvarez.ttw.model.DiplomaticSystem.State; import com.galvarez.ttw.model.components.AIControlled; import com.galvarez.ttw.model.components.Diplomacy; import com.galvarez.ttw.model.components.InfluenceSource; import com.galvarez.ttw.model.map.GameMap; import com.galvarez.ttw.model.map.Influence; import com.galvarez.ttw.model.map.MapPosition; import com.galvarez.ttw.rendering.components.Name;
package com.galvarez.ttw.model; @Wire public final class AIDiplomaticSystem extends EntityProcessingSystem { private static final Logger log = LoggerFactory.getLogger(AIDiplomaticSystem.class); private ComponentMapper<Diplomacy> relations; private ComponentMapper<MapPosition> positions; private ComponentMapper<InfluenceSource> influences; private DiplomaticSystem diplomaticSystem; private final GameMap map; @SuppressWarnings("unchecked") public AIDiplomaticSystem(GameMap map) { super(Aspect.getAspectForAll(AIControlled.class, Diplomacy.class)); this.map = map; } @Override protected boolean checkProcessing() { return true; } @Override protected void process(Entity entity) { Diplomacy diplo = relations.get(entity); // first check if we could revolt from overlord List<Entity> lords = diplo.getEmpires(State.TRIBUTE); if (lords.size() > 0) for (Entity lord : lords) if (isWeaker(lord, entity))
if (makeProposal(entity, diplo, lord, Action.DECLARE_WAR))
0
OpenWatch/OpenWatch-Android
app/OpenWatch/src/org/ale/openwatch/account/Authentication.java
[ "public class Analytics {\n\n public static final String LOGIN_FAILED = \"Login Failed - Bad Password\";\n public static final String LOGIN_PROGRESS = \"Login Progress - Pre-existing Account\";\n public static final String LOGIN_EXISTING = \"Login Success - Existing Account\";\n public static final String LOGIN_NEW = \"Login Success - New Account\";\n public static final String LOGIN_ATTEMPT = \"Login Attempt\";\n public static final String ONBOARD_COMPLETE = \"Onboarding Complete\";\n public static final String agent = \"agent\";\n public static final String VIEWING_FANCY_LOGIN = \"Viewing Fancy Login Screen\";\n public static final String VIEWING_LOGIN = \"Viewing Login Screen\";\n public static final String SESSION_EXPIRED = \"Session Expired\";\n public static final String FORGOT_PASSWORD = \"Forgot Password\";\n\n public static final String SELECTED_FEED = \"Selected Feed\";\n public static final String feed = \"feed\";\n\n public static final String JOINED_MISSION = \"Joined Mission\";\n public static final String LEFT_MISSION = \"Left Mission\";\n public static final String VIEWED_MISSION = \"Viewed Mission\";\n public static final String VIEWED_MISSION_PUSH = \"Viewed Push for Mission\";\n public static final String mission = \"mission\";\n\n public static final String SHOWED_RECORDING_SCREEN = \"Showed Recording Screen\";\n public static final String FAILED_TO_START_RECORDING = \"Failed to Start Recording\";\n public static final String FAILED_TO_STOP_RECORDING = \"Failed to Stop Recording\";\n public static final String STARTED_RECORDING = \"Started Recording\";\n public static final String STOPPED_RECORDING = \"Stopped Recording\";\n public static final String POST_VIDEO = \"Post Video\";\n public static final String ow_public = \"ow\";\n public static final String to_fb = \"fb\";\n public static final String to_twitter = \"twitter\";\n\n private static MixpanelAPI mixpanelAPI;\n\n private static MixpanelAPI getInstance(Context c){\n if(mixpanelAPI == null)\n mixpanelAPI = MixpanelAPI.getInstance(c, SECRETS.MIXPANEL_KEY);\n return mixpanelAPI;\n }\n\n public static void cleanUp(){\n if(mixpanelAPI != null)\n mixpanelAPI.flush();\n }\n\n public static void trackEvent(Context c, String name){\n trackEvent(c, name, null);\n }\n\n public static void trackEvent(Context c, String name, JSONObject event){\n getInstance(c).track(name, event);\n }\n\n public static void registerProperty(Context c, JSONObject properties){\n getInstance(c).registerSuperProperties(properties);\n }\n\n public static void identifyUser(Context c, String id){\n getInstance(c).identify(id);\n }\n}", "public class OWApplication extends Application {\n\t\n\t// Keep track of whether per-launch actions have been performed\n\tpublic static boolean per_launch_sync = false;\n\t\n\t//Hold user info in memory\n\tpublic static Map user_data = null;\n\t\n\tpublic void onCreate (){\n\t\tsuper.onCreate();\n\t\tImageLoader.getInstance().init(getImageLoaderConfiguration());\n\t}\n\t\n\tprivate ImageLoaderConfiguration getImageLoaderConfiguration(){\n\t\tDisplayImageOptions displayOptions = new DisplayImageOptions.Builder()\n\t\t.cacheInMemory()\n\t\t.cacheOnDisc()\n .showImageOnFail(R.drawable.thumbnail_placeholder)\n .showStubImage(R.drawable.thumbnail_placeholder)\n\t\t.build();\n\t\t\t\n\t\tImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())\n\t\t.defaultDisplayImageOptions(displayOptions)\n .memoryCache(new LruMemoryCache(2 * 1024 * 1024))\n .memoryCacheSize(2 * 1024 * 1024)\n .discCacheSize(25 * 1024 * 1024)\n .discCacheFileCount(100)\n\t\t.build();\n\t\t\n\t\treturn config;\n\t}\n\n}", "public class Constants {\n\n public static final String SUPPORT_EMAIL = \"team@openwatch.net\";\n public static final String GOOGLE_STORE_URL = \"https://play.google.com/store/apps/details?id=org.ale.openwatch\";\n public static final String APPLE_STORE_URL = \"https://itunes.apple.com/us/app/openwatch-social-muckraking/id642680756?mt=8\";\n\n // Facebook\n public static final String FB_APP_ID = \"297496017037529\";\n\n // Twitter\n public static final String TWITTER_CONSUMER_KEY = \"rRMW0cVIED799WgbeoA\";\n\t\n\t// Set this flag to toggle between production \n\t// and development endpoint addresses\n\tpublic static final boolean USE_DEV_ENDPOINTS = false;\n\t\n\tpublic static final String PROD_HOST = \"https://openwatch.net/\";\n\tpublic static final String PROD_CAPTURE_HOST = \"https://capture.openwatch.net/\";\n\n public static final String DEV_HOST = \"https://staging.openwatch.net/\";\n public static final String DEV_CAPTURE_HOST = \"https://capture-staging.openwatch.net/\";\n\n\t//public static final String DEV_HOST = \"http://192.168.1.27:8000/\";\n //public static final String DEV_CAPTURE_HOST = \"http://192.168.1.27:5000/\";\n\n public static final String PASSWORD_RESET_ENDPOINT = \"accounts/password/reset/\";\n\t\n\t// OpenWatch web service root url and endpoints\n\tpublic static final String OW_MEDIA_URL;\n\tpublic static final String OW_API_URL;\n\tpublic static final String OW_URL;\n\t\n\tstatic {\n\t\tif(USE_DEV_ENDPOINTS){\n\t\t\tOW_MEDIA_URL = DEV_CAPTURE_HOST;\n\t\t\tOW_URL = DEV_HOST;\n\t\t\tOW_API_URL = DEV_HOST + \"api/\";\n\t\t}else{\n\t\t\tOW_MEDIA_URL = PROD_CAPTURE_HOST;\n\t\t\tOW_URL = PROD_HOST;\n\t\t\tOW_API_URL = PROD_HOST + \"api/\";\n\t\t}\n\t}\n\n\n\n\n // For view tag\n\tpublic static enum CONTENT_TYPE { VIDEO, PHOTO, AUDIO, STORY, INVESTIGATION, MISSION };\n\t// for fileUtils and OWServiceRequests. TODO Delete following\n\t//public static enum MEDIA_TYPE { VIDEO, PHOTO, AUDIO };\n\t//public static HashMap<MEDIA_TYPE, String> API_ENDPOINT_BY_MEDIA_TYPE = new HashMap<MEDIA_TYPE, String>() {{put(MEDIA_TYPE.VIDEO, \"v\"); put(MEDIA_TYPE.PHOTO, \"p\"); put(MEDIA_TYPE.AUDIO, \"a\"); }};\n\tpublic static HashMap<CONTENT_TYPE, String> API_ENDPOINT_BY_CONTENT_TYPE = new HashMap<CONTENT_TYPE, String>() {{ put(CONTENT_TYPE.VIDEO, \"v\"); put(CONTENT_TYPE.PHOTO, \"p\"); put(CONTENT_TYPE.AUDIO, \"a\");put(CONTENT_TYPE.MISSION, \"mission\"); put(CONTENT_TYPE.INVESTIGATION, \"i\"); put(CONTENT_TYPE.STORY, \"s\"); }};\n\tpublic static final String OW_CONTENT_TYPE = \"owcontent_type\";\n\t\n\t// Date Formatter for OW server time\n\tpublic static SimpleDateFormat utc_formatter = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.US);\n\t// Human readable\n\tpublic static SimpleDateFormat user_date_formatter = new SimpleDateFormat(\"MMM dd, yyyy\", Locale.US);\n\tpublic static SimpleDateFormat user_datetime_formatter = new SimpleDateFormat(\"MMM dd, yyyy h:mm a\", Locale.US);\n\tpublic static SimpleDateFormat user_time_formatter = new SimpleDateFormat(\"h:mm a\", Locale.US);\n\t\n\tstatic{\n\t\tutc_formatter.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\tuser_datetime_formatter.setTimeZone(TimeZone.getDefault());\n\t\tuser_time_formatter.setTimeZone(TimeZone.getDefault());\n\t\tuser_date_formatter.setTimeZone(TimeZone.getDefault());\n\t}\n\t\n\tpublic static final String USER_AGENT_BASE = \"OpenWatch/\";\n\t\n\tstatic{\n\t\t\n\t}\n\n\t// SharedPreferences titles\n\tpublic static final String PROFILE_PREFS = \"Profile\";\n public static final String GCM_PREFS = \"gcm\";\n\t\n\t// External storage \n\tpublic static final String ROOT_OUTPUT_DIR = \"OpenWatch\";\n\tpublic static final String VIDEO_OUTPUT_DIR = \"video\";\n\tpublic static final String PHOTO_OUTPUT_DIR = \"photo\";\n\tpublic static final String AUDIO_OUTPUT_DIR = \"audio\";\n\t\n\t// User profile keys. Used for SharedPreferences and Intent Extras\n\tpublic static final String EMAIL = \"email\";\n\tpublic static final String AUTHENTICATED = \"authenticated\";\n\tpublic static final String DB_READY = \"db_ready\";\n\tpublic static final String PUB_TOKEN = \"public_upload_token\"; \t\t// used for profile and to parse server login response\n\tpublic static final String PRIV_TOKEN = \"private_upload_token\";\t\t// used for profile and to parse server login response\n\tpublic static final String REGISTERED = \"registered\"; \n\tpublic static final String VIEW_TAG_MODEL = \"model\";\t\t// key set on listview item holding corresponding model pk\n\tpublic static final String INTERNAL_DB_ID = \"id\";\n public static final String SERVER_ID = \"server_id\";\n\tpublic static final String INTERNAL_USER_ID = \"id\";\n\tpublic static final String IS_LOCAL_RECORDING = \"is_local\";\n\tpublic static final String IS_USER_RECORDING = \"is_user_recording\";\n\tpublic static final String FEED_TYPE = \"feed_type\";\n public static final String OBLIGATORY_TAG = \"tag\";\n public static final String MISSION_TIP = \"mtip\";\n public static final int CAMERA_ACTION_CODE = 444;\n public static final String TWITTER_TOKEN = \"ttoken\";\n public static final String TWITTER_SECRET = \"tsecret\";\n public static final String LAST_MISSION_DATE = \"last_mission_date\";\n public static final String LAST_MISSION_ID = \"last_mission_id\";\n public static final String JOINED_FIRST_MISSION = \"joined_first_mission\";\n public static final String MISSION_SERVER_OBJ_ID = \"msid\";\n public static final String VICTORY = \"victory\";\n\n\t\n\t// Email REGEX\n\tpublic static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(\n \"[a-zA-Z0-9+._%-+]{1,256}\" +\n \"@\" +\n \"[a-zA-Z0-9][a-zA-Z0-9-]{0,64}\" +\n \"(\" +\n \".\" +\n \"[a-zA-Z0-9][a-zA-Z0-9-]{0,25}\" +\n \")+\"\n );\n\t\n\t// API Request timeout (ms)\n\tpublic static final int TIMEOUT = 5000;\n\t\n\t// openwatch.net api endpoints\n\tpublic static final String OW_STORY_VIEW = \"s/\";\n\tpublic static final String OW_RECORDING_VIEW = \"v/\";\n\tpublic static final String OW_LOGIN = \"login_account\";\n\tpublic static final String OW_SIGNUP = \"create_account\";\n\tpublic static final String OW_REGISTER = \"register_app\";\n\tpublic static final String OW_RECORDING = \"recording\";\n\tpublic static final String OW_RECORDINGS = \"recordings\";\n public static final String OW_FEATURED_MEDIA = \"featured_media\";\n\tpublic static final String OW_STORY = \"story\";\n\tpublic static final String OW_TAGS = \"tags\";\n\tpublic static final String OW_TAG = \"tag\";\n\tpublic static final String OW_UPDATE_META = \"update_metadata\";\n\tpublic static final String OW_FEED = \"feed\";\n\t\n\t// Feed names\n\tpublic static final String OW_LOCAL = \"local\";\n\tpublic static final String OW_FEATURED = \"featured\";\n\tpublic static final String OW_FOLLOWING = \"following\";\n public static final String OW_RAW = \"raw\";\n\t// Feed types : Each is related to an API endpoint in OWServiceRequests getFeed\n\t/*\n public static enum OWFeedType{\n\t\tTOP, LOCAL, FOLLOWING, USER, RAW\n\t}\n\t*/\n public static enum OWFeedType{\n TOP, LOCAL, USER, RAW, MISSION, FEATURED_MEDIA\n }\n\n public static HashMap<String, Integer> FEED_TO_TITLE = new HashMap<String, Integer>() {{put(OWFeedType.FEATURED_MEDIA.toString().toLowerCase(), R.string.tab_featured_media); put(OWFeedType.MISSION.toString().toLowerCase(), R.string.tab_missions); put(OWFeedType.TOP.toString().toLowerCase(), R.string.tab_featured); put(OWFeedType.LOCAL.toString().toLowerCase(), R.string.tab_local); put(OWFeedType.RAW.toString().toLowerCase(), R.string.tab_Raw); put(OWFeedType.USER.toString().toLowerCase(), R.string.tab_local_user_recordings); }};\n\t\n\tpublic static ArrayList<String> OW_FEEDS = new ArrayList<String>();\n\tstatic{\n\t\tOWFeedType[] feed_types = OWFeedType.values();\n\t\tfor(int x=0; x< feed_types.length; x++){\n\t\t\tOW_FEEDS.add(feed_types[x].toString().toLowerCase());\n\t\t}\n\t}\n\t\n\tpublic static boolean isOWFeedTypeGeoSensitive(String feed_type){\n if(feed_type == null)\n return false;\n\t\tif(feed_type.trim().toLowerCase().compareTo(OWFeedType.LOCAL.toString().toLowerCase()) == 0)\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * To be removed\n\t * For user with external OWServiceRequests\n\t * @param type\n\t * @return\n\t */\n\tpublic static String feedExternalEndpointFromType(OWFeedType type, int page){\n\t\t/*\n\t\tString endpoint = \"\";\n\n\t\tswitch(type){\n\t\tcase USER:\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_RECORDINGS;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_FEED + File.separator + feedInternalEndpointFromType(type);\n\t\t\tbreak;\n\t\t}\n\t\treturn endpoint + File.separator + String.valueOf(page);\n\t\t*/\n\t\treturn feedExternalEndpointFromString(type.toString().toLowerCase(), page);\n\t}\n\t\n\tpublic static String feedExternalEndpointFromString(String type, int page){\n\t\tString endpoint = \"\";\n\t\tif(!OW_FEEDS.contains(type) ){\n // tag feed\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_TAG + File.separator + \"?tag=\"+ type + \"&page=\" + String.valueOf(page);\n\t\t}else{\n if(type.equals(\"top\")){\n endpoint = Constants.OW_API_URL + API_ENDPOINT_BY_CONTENT_TYPE.get(CONTENT_TYPE.INVESTIGATION) + \"/?page=\" + String.valueOf(page);\n }else if(type.equals(\"mission\")){\n endpoint = Constants.OW_API_URL + API_ENDPOINT_BY_CONTENT_TYPE.get(CONTENT_TYPE.MISSION) + \"/?page=\" + String.valueOf(page);\n }else\n\t\t\t endpoint = Constants.OW_API_URL + Constants.OW_FEED + File.separator + \"?type=\"+ type + \"&page=\" + String.valueOf(page);\n\t\t}\n\t\t\n\t\treturn endpoint;\n\t}\n\t\n\t/**\n\t * For user with the internal ContentProvider\n\t * To remove\n\t * @param type\n\t * @return\n\t */\n\tpublic static String feedInternalEndpointFromType(OWFeedType type){\n\t\tString endpoint = \"\";\n\t\tswitch(type){\n\t\tcase TOP:\n\t\t\tendpoint = Constants.OW_FEATURED;\n\t\t\tbreak;\n\t\tcase LOCAL:\n\t\t\tendpoint = Constants.OW_LOCAL;\n\t\t\tbreak;\n\t\t//case FOLLOWING:\n\t\t//\tendpoint = Constants.OW_FOLLOWING;\n\t\t//\tbreak;\n\t\tcase USER:\n\t\t\tendpoint = Constants.OW_RECORDINGS;\n\t\t\tbreak;\n case FEATURED_MEDIA:\n endpoint = Constants.OW_FEATURED_MEDIA;\n break;\n case RAW:\n endpoint = Constants.OW_RAW;\n break;\n\t\t}\n\t\treturn endpoint;\n\t}\n\t\n\t// OpenWatch web service POST keys\n\tpublic static final String OW_EMAIL = \"email_address\";\n\tpublic static final String OW_PW = \"password\";\n\tpublic static final String OW_SIGNUP_TYPE = \"signup_type\";\n\t\n\t// OpenWatch web service response keys\n\tpublic static final String OW_SUCCESS = \"success\";\n\tpublic static final String OW_ERROR = \"code\";\n\tpublic static final String OW_REASON = \"reason\";\n\tpublic static final String OW_SERVER_ID = \"id\";\n\tpublic static final String OW_THUMB_URL = \"thumbnail_url\";\n\tpublic static final String OW_LAST_EDITED = \"last_edited\";\n\tpublic static final String OW_CREATION_TIME = \"reported_creation_time\";\n\tpublic static final String OW_ACTIONS = \"clicks\";\n\tpublic static final String OW_NO_VALUE = \"None\";\n\tpublic static final String OW_USER = \"user\";\n\tpublic static final String OW_VIEWS = \"views\";\n\tpublic static final String OW_TITLE = \"title\";\n\tpublic static final String OW_USERNAME = \"username\";\n public static final String OW_FIRST_NAME = \"first_name\";\n public static final String OW_LAST_NAME = \"last_name\";\n\tpublic static final String OW_CLICKS = \"clicks\";\n\tpublic static final String OW_UUID = \"uuid\";\n\tpublic static final String OW_VIDEO_URL = \"video_url\";\n\tpublic static final String OW_FIRST_POSTED = \"first_posted\";\n\tpublic static final String OW_END_LOCATION = \"end_location\";\n\tpublic static final String OW_START_LOCATION = \"start_location\";\n\tpublic static final String OW_BLURB = \"bio\";\n\tpublic static final String OW_SLUG = \"slug\";\n\tpublic static final String OW_BODY = \"body\";\n\tpublic static final String OW_NAME = \"name\";\n public static final String OW_EXPIRES = \"expires\";\n public static final String OW_AGENTS = \"agents\";\n public static final String OW_SUBMISSIONS = \"submissions\";\n\t\n\t// OpenWatch media capture web service url and endpoints\n\tpublic static final String OW_MEDIA_START = \"start\";\n\tpublic static final String OW_MEDIA_END = \"end\";\n\tpublic static final String OW_MEDIA_UPLOAD = \"upload\";\n\tpublic static final String OW_MEDIA_HQ_UPLOAD = \"upload_hq\";\n\tpublic static final String OW_MEDIA_UPDATE_META = \"update_metadata\";\n\n public static final String OW_HQ_FILENAME = \"hq.mp4\";\n\t\n\t// OpenWatch media capture web service POST keys\n\tpublic static final String OW_REC_START = \"recording_start\";\n\tpublic static final String OW_REC_END = \"recording_end\";\n\tpublic static final String OW_REC_UUID = \"uuid\";\n\tpublic static final String OW_ALL_FILES = \"all_files\";\n\tpublic static final String OW_UP_TOKEN = \"upload_token\";\n\tpublic static final String OW_FILE = \"upload\";\n\tpublic static final String OW_MEDIA_TITLE = \"title\";\n\tpublic static final String OW_DESCRIPTION = \"description\";\n\tpublic static final String OW_EDIT_TIME = \"last_edited\";\n\tpublic static final String OW_START_LOC = \"start_location\";\n\tpublic static final String OW_END_LOC = \"end_location\";\n\tpublic static final String OW_START_LAT = \"start_lat\";\n\tpublic static final String OW_START_LON = \"start_lon\";\n\tpublic static final String OW_END_LAT = \"end_lat\";\n\tpublic static final String OW_END_LON = \"end_lon\";\n\tpublic static final String OW_LAT = \"latitude\";\n\tpublic static final String OW_LON = \"longitude\";\n public static final String OW_USD = \"usd\";\n public static final String OW_KARMA = \"karma\";\n public static final String OW_ACTIVE = \"active\";\n public static final String OW_COMPLETED = \"completed\";\n public static final String OW_MEDIA_BUCKET = \"media_url\";\n\t\n\t// Hit counts\n\tpublic static enum HIT_TYPE { VIEW, CLICK };\n\tpublic static final String OW_STATUS = \"status\";\n\tpublic static final String OW_HIT_URL = \"increase_hitcount\";\n\tpublic static final String OW_HIT_SERVER_ID = \"serverID\";\n\tpublic static final String OW_HIT_MEDIA_TYPE = \"media_type\";\n\tpublic static final String OW_HIT_TYPE = \"hit_type\";\n\tpublic static final String OW_HITS = \"hits\";\n\n // BroadcastReceiver Intent filter\n public static final String OW_SYNC_STATE_FILTER = \"server_object_sync\";\n public static final String OW_SYNC_STATE_STATUS = \"status\";\n public static final String OW_SYNC_STATE_MODEL_ID = \"model_id\";\n public static final String OW_SYNC_STATE_CHILD_ID = \"child_model_id\";\n public static final int OW_SYNC_STATUS_BEGIN = 0;\n public static final int OW_SYNC_STATUS_BEGIN_BULK = 10;\n public static final int OW_SYNC_STATUS_END_BULK = 20;\n public static final int OW_SYNC_STATUS_FAILED = -1;\n public static final int OW_SYNC_STATUS_SUCCESS = 1;\n\n // General\n public static final String USD = \"$\";\n\n}", "public class DBConstants {\n\t\n\tpublic static final String ID = \"_id\";\n\t\n\t// Recordings Database table and column names\n\t// These correlate to field names in OWRecording\n\tpublic static final String DB_NAME = \"OpenWatchDB\";\n\n // Generic\n public static final String SYNCED = \"synced\";\n public static final String SERVER_ID = \"server_id\";\n public static final String TITLE = \"title\";\n public static final String USERNAME = \"username\";\n public static final String THUMBNAIL_URL = \"thumbnail_url\";\n public static final String DESCRIPTION = \"description\";\n public static final String LAST_EDITED = \"last_edited\";\n public static final String FIRST_POSTED = \"first_posted\";\n public static final String ACTIONS = \"actions\";\n public static final String VIEWS = \"views\";\n\t\n\t// OWMediaObject table\n\tpublic static final String MEDIA_OBJECT_TABLENAME = \"owserverobject\";\n\tpublic static final String MEDIA_OBJECT_STORY = \"story\";\n public static final String MEDIA_OBJECT_MISSION = \"mission\";\n\tpublic static final String MEDIA_OBJECT_USER = \"user\";\n\tpublic static final String MEDIA_OBJECT_VIDEO = \"video_recording\";\n\tpublic static final String MEDIA_OBJECT_AUDIO = \"audio\";\n\tpublic static final String MEDIA_OBJECT_PHOTO = \"photo\";\n public static final String MEDIA_OBJECT_INVESTIGATION = \"investigation\";\n\tpublic static final String MEDIA_OBJECT_LOCAL_VIDEO = \"local_video_recording\";\n public static final String MEDIA_OBJECT_USER_THUMBNAIL = \"user_thumbnail_url\";\n public static final String MEDIA_OBJECT_METRO_CODE = \"metro_code\";\n\t\n\t// Local Video Recordings Table\n\tpublic static final String LOCAL_RECORDINGS_TABLENAME = \"owlocalvideorecording\";\n public static final String LOCAL_RECORDINGS_LQ_SYNCED = \"ly_synced\";\n public static final String LOCAL_RECORDINGS_HQ_SYNCED = \"hq_synced\";\n\t\n\t// Video Recording Table\n\tpublic static final String RECORDINGS_TABLENAME = \"owvideorecording\";\n\tpublic static final String RECORDINGS_TABLE_TITLE = \"title\";\n\tpublic static final String RECORDINGS_TABLE_DESC = \"description\";\n\tpublic static final String RECORDINGS_TABLE_THUMB_URL = \"thumbnail_url\";\n\tpublic static final String RECORDINGS_TABLE_CREATION_TIME = \"creation_time\";\n\tpublic static final String RECORDINGS_TABLE_UUID = \"uuid\";\n\tpublic static final String RECORDINGS_TABLE_FIRST_POSTED = \"first_posted\";\n\tpublic static final String RECORDINGS_TABLE_USER_ID = \"user_id\";\n\tpublic static final String RECORDINGS_TABLE_USERNAME = \"username\";\n\tpublic static final String RECORDINGS_TABLE_LAST_EDITED = \"last_edited\";\n\tpublic static final String RECORDINGS_TABLE_SERVER_ID = \"server_id\";\n\tpublic static final String RECORDINGS_TABLE_VIDEO_URL = \"video_url\";\n\tpublic static final String RECORDINGS_TABLE_BEGIN_LAT = \"begin_lat\";\n\tpublic static final String RECORDINGS_TABLE_BEGIN_LON = \"begin_lon\";\n\tpublic static final String RECORDINGS_TABLE_END_LAT = \"end_lat\";\n\tpublic static final String RECORDINGS_TABLE_END_LON = \"end_lon\";\n\tpublic static final String RECORDINGS_TABLE_LOCAL = \"local\";\n\t\n\t// Tag table\n\tpublic static final String TAG_TABLENAME = \"owtag\";\n\tpublic static final String TAG_TABLE_NAME = \"name\";\n\tpublic static final String TAB_TABLE_FEATURED = \"is_featured\";\n\tpublic static final String TAG_TABLE_RECORDINGS = \"recordings\";\n\tpublic static final String TAG_TABLE_SERVER_ID = \"server_id\";\n\t\n\t// User table\n\tpublic static final String USER_TABLENAME = \"owuser\";\n\tpublic static final String USER_USERNAME = \"username\";\n\tpublic static final String USER_SERVER_ID = \"server_id\";\n\tpublic static final String USER_RECORDINGS = \"recordings\";\n\tpublic static final String USER_TAGS = \"tags\";\n\t\n\t// Feed table\n\tpublic static final String FEED_TABLENAME = \"owfeed\";\n\tpublic static final String FEED_NAME = \"name\";\n\t\n\t// OWMediaObject - Feed Relation table\n\tpublic static final String FEED_MEDIA_OBJ_TABLENAME = \"owfeed_owserverobject\";\n\n\t// Story table\n\tpublic static final String STORY_TABLENAME = \"owstory\";\n\tpublic static final String STORY_SERVER_ID = \"server_id\";\n\t\n\t// Story - Feed Relation Table\n\tpublic static final String FEED_STORY_TABLENAME = \"owfeed_owstory\";\n\t\n\t// Photo table\n\tpublic static final String PHOTO_TABLENAME = \"owphoto\";\n\t\n\t// Audio table\n\tpublic static final String AUDIO_TABLENAME = \"owaudio\";\n\t\n\t// Investigation table\n\tpublic static final String INVESTIGATION_TABLENAME = \"owinvestigation\";\n\n // Mission Table\n public static final String MISSION_TABLENAME = \"owmission\";\n public static final String EXPIRES = \"expires\";\n\n}", "public class HttpClient {\n\tprivate static final String TAG = \"HttpClient\";\n\n private static final boolean USE_SSL_PINNING = true;\n\t\n\tpublic static String USER_AGENT = null;\n\n // Cache http clients\n private static AsyncHttpClient asyncHttpClient;\n\n\t/**\n\t * Returns a new AsyncHttpClient initialized with a PersistentCookieStore\n\t * \n\t * @param c\n\t * the context used to get SharePreferences for cookie\n\t * persistence and sslsocketfactory creation\n\t * @return an initialized AsyncHttpClient\n\t */\n\tpublic static AsyncHttpClient setupAsyncHttpClient(Context c) {\n if(asyncHttpClient != null){\n //Log.i(\"setupAsyncHttpClient\",\"client cached\");\n return asyncHttpClient;\n }else{\n //Log.i(\"setupAsyncHttpClient\",\"client not cached\");\n }\n\t\tAsyncHttpClient httpClient = setupVanillaAsyncHttpClient();\n\t\tPersistentCookieStore cookie_store = new PersistentCookieStore(c);\n\t\thttpClient.setCookieStore(cookie_store);\n\t\t// List cookies = cookie_store.getCookies();\n\t\t// Log.i(TAG, \"Setting cookie store. size: \" +\n\t\t// cookie_store.getCookies().size());\n\t\tif(USER_AGENT == null){\n\t\t\tUSER_AGENT = Constants.USER_AGENT_BASE;\n\t\t\ttry {\n\t\t\t\tPackageInfo pInfo = c.getPackageManager().getPackageInfo(\n\t\t\t\t\t\tc.getPackageName(), 0);\n\t\t\t\tUSER_AGENT += pInfo.versionName;\n\t\t\t} catch (NameNotFoundException e) {\n\t\t\t\tLog.e(TAG, \"Unable to read PackageName in RegisterApp\");\n\t\t\t\te.printStackTrace();\n\t\t\t\tUSER_AGENT += \"unknown\";\n\t\t\t}\n\t\t\tUSER_AGENT += \" (Android API \" + Build.VERSION.RELEASE + \")\";\n\t\t}\n\t\thttpClient.setUserAgent(USER_AGENT);\n\t\t// Pin SSL cert if not hitting dev endpoint\n\t\tif(!Constants.USE_DEV_ENDPOINTS && USE_SSL_PINNING){\n\t\t\thttpClient.setSSLSocketFactory(createApacheOWSSLSocketFactory(c));\n\t\t}\n asyncHttpClient = httpClient;\n\t\treturn asyncHttpClient;\n\t}\n\n\t// For non ssl, no-cookie store use\n\t\n\tprivate static AsyncHttpClient setupVanillaAsyncHttpClient() {\n\t\treturn new AsyncHttpClient();\n\t}\n\t\n\tpublic static DefaultHttpClient setupDefaultHttpClient(Context c){\n //if(defaultHttpClient != null)\n // return defaultHttpClient;\n\n\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n\t\tPersistentCookieStore cookie_store = new PersistentCookieStore(c);\n\t\thttpClient.setCookieStore(cookie_store);\n\t\tSSLSocketFactory socketFactory;\n\t\ttry {\n\t\t\t// Pin SSL cert if not hitting dev endpoint\n\t\t\tif(!Constants.USE_DEV_ENDPOINTS && USE_SSL_PINNING){\n\t\t\t\tsocketFactory = new SSLSocketFactory(loadOWKeyStore(c));\n\t\t\t\tScheme sch = new Scheme(\"https\", socketFactory, 443);\n\t\t httpClient.getConnectionManager().getSchemeRegistry().register(sch);\n\t\t\t}\n //defaultHttpClient = httpClient;\n\t //return defaultHttpClient;\n return httpClient;\n\t\t} catch (KeyManagementException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (UnrecoverableKeyException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (KeyStoreException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n return null;\n\t}\n\n\t/**\n\t * For Android-Async-Http's AsyncClient\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic static SSLSocketFactory createApacheOWSSLSocketFactory(\n\t\t\tContext context) {\n\t\ttry {\n\t\t\t// Pass the keystore to the SSLSocketFactory. The factory is\n\t\t\t// responsible\n\t\t\t// for the verification of the server certificate.\n\t\t\tSSLSocketFactory sf = new SSLSocketFactory(loadOWKeyStore(context));\n\t\t\t// Hostname verification from certificate\n\t\t\t// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506\n\t\t\tsf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);\n\t\t\treturn sf;\n\t\t} catch (Exception e) {\n\t\t\tthrow new AssertionError(e);\n\t\t}\n\t}\n\n\n\tprivate static KeyStore loadOWKeyStore(Context c) {\n\t\tKeyStore trusted = null;\n\t\ttry {\n\t\t\t// Get an instance of the Bouncy Castle KeyStore format\n\t\t\ttrusted = KeyStore.getInstance(\"BKS\");\n\t\t\t// Get the raw resource, which contains the keystore with\n\t\t\t// your trusted certificates (root and any intermediate certs)\n\t\t\tInputStream in = c.getResources().openRawResource(R.raw.owkeystore);\n\t\t\ttry {\n\t\t\t\t// Initialize the keystore with the provided trusted\n\t\t\t\t// certificates\n\t\t\t\t// Also provide the password of the keystore\n\t\t\t\ttrusted.load(in, SECRETS.SSL_KEYSTORE_PASS.toCharArray());\n\t\t\t} finally {\n\t\t\t\tin.close();\n\t\t\t}\n\n\t\t} catch (Exception e) {\n\t\t\tthrow new AssertionError(e);\n\t\t}\n\n\t\treturn trusted;\n\t}\n\n public static void clearCookieStore(Context c){\n PersistentCookieStore cookie_store = new PersistentCookieStore(c);\n cookie_store.clear();\n }\n\n}", "public class OWServiceRequests {\n\n\tprivate static final String TAG = \"OWServiceRequests\";\n\n public interface RequestCallback {\n\t\tpublic void onFailure();\n\t\tpublic void onSuccess();\n\t}\n\t\n\tpublic interface PaginatedRequestCallback{\n\t\tpublic void onSuccess(int page, int object_count, int total_pages);\n\t\tpublic void onFailure(int page);\n\t}\n\n\n\tpublic static void increaseHitCount(final Context app_context, int server_id, final int media_obj_id, final CONTENT_TYPE content_type, final HIT_TYPE hit_type){\n\t\tfinal String METHOD = \"increaseHitCount\";\n\t\tJsonHttpResponseHandler post_handler = new JsonHttpResponseHandler(){\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, METHOD + \"success! \" + response.toString());\n\t\t\t\ttry {\n\t\t\t\t\tif (response.has(Constants.OW_STATUS) && response.getString(Constants.OW_STATUS).compareTo(Constants.OW_SUCCESS) ==0) {\n\t\t\t\t\n\t\t\t\t\t\tOWServerObject obj = OWServerObject.objects(app_context, OWServerObject.class).get(media_obj_id);\n\t\t\t\t\t\tif(response.has(Constants.OW_HITS)){\n\t\t\t\t\t\t\tswitch(hit_type){\n\t\t\t\t\t\t\t\tcase VIEW:\n\t\t\t\t\t\t\t\t\tobj.setViews(app_context, response.getInt(Constants.OW_HITS));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase CLICK:\n\t\t\t\t\t\t\t\t\tobj.setActions(app_context, response.getInt(Constants.OW_HITS));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tobj.save(app_context);\n\t\t\t\t\t}\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\tLog.e(TAG, \"Error processing hitcount response\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tJSONObject params = new JSONObject();\n\t\ttry {\n\t\t\tparams.put(Constants.OW_HIT_SERVER_ID, server_id);\n\t\t\tparams.put(Constants.OW_HIT_MEDIA_TYPE, content_type.toString().toLowerCase());\n\t\t\tparams.put(Constants.OW_HIT_TYPE, hit_type.toString().toLowerCase());\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.post(app_context, Constants.OW_API_URL + Constants.OW_HIT_URL, Utils.JSONObjectToStringEntity(params),\n\t\t\t\t\"application/json\", post_handler);\n\t\t\n\t}\n\n\tpublic static void getStory(final Context app_context, final int id,\n\t\t\tfinal RequestCallback callback) {\n\t\tfinal String METHOD = \"getStory\";\n\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, METHOD + \"success! \" + response.toString());\n\t\t\t\tif (response.has(Constants.OW_STORY)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tOWStory.createOrUpdateOWStoryWithJson(app_context,\n\t\t\t\t\t\t\t\tresponse.getJSONObject(Constants.OW_STORY));\n\t\t\t\t\t\tcallback.onSuccess();\n\t\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\t\tLog.e(TAG,\n\t\t\t\t\t\t\t\t\"Error creating or updating Recording with json\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse) {\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t\tcallback.onFailure();\n\t\t\t}\n\t\t};\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.get(Constants.OW_API_URL + \"s\"\n\t\t\t\t+ File.separator + String.valueOf(id), get_handler);\n\t\tLog.i(TAG, METHOD + \" : \" + Constants.OW_API_URL + \"s\"\n\t\t\t\t+ File.separator + String.valueOf(id));\n\t}\n\n\tpublic static void getRecording(final Context app_context,\n\t\t\tfinal String uuid, final RequestCallback callback) {\n\t\tfinal String METHOD = \"getRecording\";\n\t\tif (uuid == null)\n\t\t\treturn;\n\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tif (response.has(Constants.OW_RECORDING)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tOWVideoRecording.createOrUpdateOWRecordingWithJson(\n\t\t\t\t\t\t\t\tapp_context,\n\t\t\t\t\t\t\t\tresponse.getJSONObject(Constants.OW_RECORDING));\n\t\t\t\t\t\tcallback.onSuccess();\n\t\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\t\tLog.e(TAG,\n\t\t\t\t\t\t\t\t\"Error creating or updating Recording with json\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse) {\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t\tcallback.onFailure();\n\t\t\t}\n\t\t};\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.get(Constants.OW_API_URL + Constants.OW_RECORDING\n\t\t\t\t+ File.separator + uuid, get_handler);\n\t\tLog.i(TAG, METHOD + \" : \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_RECORDING + File.separator + uuid);\n\t}\n\t\n\t/**\n\t * Gets the device's current location and posts it in OW standard format\n\t * along with a request for a feed.\n\t * \n\t * OW standard location format:\n\t * {\n \t *\t'location': {\n * \t\t'latitude':39.00345433,\n * \t\t'longitude':-70.2440393\n \t *\t}\n`\t * }\n\t * @param app_context\n\t * @param page\n\t * @param cb\n\t */\n\tpublic static void getGeoFeed(final Context app_context, final Location gps_location, final String feed_name, final int page, final PaginatedRequestCallback cb){\n\n String urlparams = \"\";\n if(gps_location != null){\n urlparams += String.format(\"&latitude=%f&longitude=%f\",gps_location.getLatitude(), gps_location.getLongitude());\n Log.i(TAG, String.format(\"got location for geo feed: lat: %f , lon: %f\", gps_location.getLatitude(), gps_location.getLongitude()));\n }\n\n getFeed(app_context, urlparams, feed_name, page, cb);\n\n\t}\n\t\n\tpublic static void getFeed(final Context app_context, final String feed_name, final int page, final PaginatedRequestCallback cb){\n\t\tgetFeed(app_context, \"\", feed_name, page, cb);\n\t}\n\t\n\n\t/**\n\t * Parse an OpenWatch.net feed, saving its contents to the databasee\n\t * \n\t * @param app_context\n */\n private static String last_feed_name;\n private static long last_request_time = System.currentTimeMillis();\n private static final long request_threshold = 250; // ignore duplicate requests separated by less than this many ms\n\tprivate static void getFeed(final Context app_context, String getParams, final String ext_feed_name, final int page, final PaginatedRequestCallback cb){\n if(last_feed_name != null && last_feed_name.compareTo(ext_feed_name) == 0){\n if(System.currentTimeMillis() - last_request_time < request_threshold){\n Log.i(TAG, String.format(\"Aborting request for feed %s, last completed %d ms ago\", last_feed_name, last_request_time - System.currentTimeMillis()));\n if(cb != null)\n cb.onFailure(page);\n return;\n }\n }\n last_feed_name = ext_feed_name;\n last_request_time = System.currentTimeMillis();\n\t\tfinal String METHOD = \"getFeed\";\n\t\tfinal String feed_name = ext_feed_name.trim().toLowerCase();\n\t\t\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler(){\n\t\t\t@Override\n \t\tpublic void onSuccess(JSONObject response){\n\t\t\t\tif(response.has(\"objects\")){\n\t\t\t\t\tint internal_user_id = 0;\n Log.i(TAG, String.format(\"got %s feed response: \",feed_name) );\n\t\t\t\t\t//Log.i(TAG, String.format(\"got %s feed response: %s \",feed_name, response.toString()) );\n\t\t\t\t\tif(feed_name.compareTo(OWFeedType.USER.toString().toLowerCase()) == 0){\n\t\t\t\t\t\tSharedPreferences profile = app_context.getSharedPreferences(Constants.PROFILE_PREFS, 0);\n\t\t\t\t internal_user_id = profile.getInt(Constants.INTERNAL_USER_ID, 0);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tParseFeedTask parseTask = new ParseFeedTask(app_context, cb, feed_name, page, internal_user_id);\n\t\t\t\t\tparseTask.execute(response);\n\t\t\t\t\t\n\t\t\t\t}else try {\n if(response.has(\"success\") && response.getBoolean(\"success\") == false){\n handleOWApiError(app_context, response);\n }else{\n Log.e(TAG, \"Feed response format unexpected\" + response.toString());\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse){\n\t\t\t\tif(cb != null)\n\t\t\t\t\tcb.onFailure(page);\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t};\n\t\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString endpoint = Constants.feedExternalEndpointFromString(feed_name, page);\n\n\t\thttp_client.get(endpoint + getParams, get_handler);\n\n\t\tLog.i(TAG, \"getFeed: \" + endpoint+getParams);\n\t}\n\n\t/**\n\t * Parses a Feed, updating the database and notifying\n\t * the appropriate feed uris of changed content\n\t * @author davidbrodsky\n\t *\n\t */\n\tpublic static class ParseFeedTask extends AsyncTask<JSONObject, Void, Boolean> {\n\t\t\n\t\tPaginatedRequestCallback cb;\n\t\tContext c;\n\t\tString feed_name;\n\t\tboolean success = false;\n\t\t\n\t\tint object_count = -1;\n\t\tint page_count = -1;\n\t\tint page_number = -1;\n\t\tint user_id = -1;\n\t\t\n\t\tint current_page = -1;\n\t\t\n\t\tpublic ParseFeedTask(Context c, PaginatedRequestCallback cb, String feed_name, int current_page, int user_id){\n\t\t\tthis.cb = cb;\n\t\t\tthis.c = c;\n\t\t\tthis.feed_name = feed_name;\n\t\t\tthis.current_page = current_page;\n\t\t\tthis.user_id = user_id;\n\t\t}\n\t\t\n\n\t\t@Override\n\t\tprotected Boolean doInBackground(JSONObject... params) {\n // Benchmarking\n long start_time = System.currentTimeMillis();\n //Log.i(\"Benchmark\", String.format(\"begin parsing %s feed\", feed_name));\n\t\t\tDatabaseAdapter adapter = DatabaseAdapter.getInstance(c);\n\t\t\tadapter.beginTransaction();\n\t\t\t\n\t\t\tJSONObject response = params[0];\n\t\t\ttry{\n\t\t\t\t//If we're fetching the first page, it \n\t\t\t\t//means we're rebuilding this feed\n\t\t\t\tif(current_page == 1){\n\t\t\t\t\tFilter filter = new Filter();\n\t\t\t\t\tfilter.is(DBConstants.FEED_NAME, feed_name);\n\t\t\t\t\tQuerySet<OWFeed> feedset = OWFeed.objects(c, OWFeed.class).filter(filter);\n\t\t\t\t\tfor(OWFeed feed : feedset){\n\t\t\t\t\t\tfeed.delete(c);\n\t\t\t\t\t}\n\t\t\t\t}\n //Benchmark\n long obj_start_time;\n\t\t\t\t// Now parse the new data and create the feed anew\n\t\t\t\tJSONArray json_array = response.getJSONArray(\"objects\");\n\t\t\t\tJSONObject json_obj;\n\t\t\t\tfor(int x=0; x<json_array.length(); x++){\n\t\t\t\t\tjson_obj = json_array.getJSONObject(x);\n\t\t\t\t\tif(json_obj.has(\"type\")){\n\t\t\t\t\t\tif(json_obj.getString(\"type\").compareTo(\"video\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWVideoRecording.createOrUpdateOWRecordingWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name), adapter);\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated video in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"story\") == 0){\n\t\t\t\t\t\t\tOWStory.createOrUpdateOWStoryWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"photo\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWPhoto.createOrUpdateOWPhotoWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated photo in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"audio\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWAudio.createOrUpdateOWAudioWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated audio in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"investigation\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWInvestigation.createOrUpdateOWInvestigationWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated inv in %d ms\", System.currentTimeMillis() - obj_start_time));\n }else if(json_obj.getString(\"type\").compareTo(\"mission\") == 0){\n OWMission.createOrUpdateOWMissionWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n }\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tadapter.commitTransaction();\n\t\t\t\tUri baseUri;\n /*\n\t\t\t\tif(feed_name.compareTo(OWFeedType.USER.toString().toLowerCase()) == 0){\n\t\t\t\t\tbaseUri = OWContentProvider.getUserRecordingsUri(user_id);\n\t\t\t\t}else{\n\t\t\t\t\tbaseUri = OWContentProvider.getFeedUri(feed_name);\n\t\t\t\t}\n\t\t\t\t*/\n baseUri = OWContentProvider.getFeedUri(feed_name);\n\t\t\t\tLog.i(\"URI\" + feed_name, \"notify change on uri: \" + baseUri.toString());\n\t\t\t\tc.getContentResolver().notifyChange(baseUri, null); \n\t\n\t\t\t\t\n\t\t\t\tif(cb != null){\n\t\t\t\t\tif(response.has(\"meta\")){\n\t\t\t\t\t\tJSONObject meta = response.getJSONObject(\"meta\");\n\t\t\t\t\t\tif(meta.has(\"object_count\"))\n\t\t\t\t\t\t\tobject_count = meta.getInt(\"object_count\");\n\t\t\t\t\t\tif(meta.has(\"page_count\"))\n\t\t\t\t\t\t\tpage_count = meta.getInt(\"page_count\");\n\t\t\t\t\t\tif(meta.has(\"page_number\")){\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\tpage_number = Integer.parseInt(meta.getString(\"page_number\"));\n\t\t\t\t\t\t\t}catch(Exception e){};\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tsuccess = true;\n // Benchmark\n long end_time = System.currentTimeMillis();\n Log.i(\"Benchmark\", String.format(\"finish parsing %s feed in %d ms\", feed_name, end_time-start_time));\n\t\t\t}catch(JSONException e){\n\t\t\t\tadapter.rollbackTransaction();\n\t\t\t\tLog.e(TAG, \"Error parsing \" + feed_name + \" feed response\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\t\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t@Override\n\t protected void onPostExecute(Boolean result) {\n\t super.onPostExecute(result);\n\t if(success)\n\t \tcb.onSuccess(page_number, object_count, page_count);\n\t }\n\t\t\n\t}\n\t/*\n\tpublic static void syncOWMobileGeneratedObject(final Context app_context, OWMobileGeneratedObject object ){\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"getMeta response: \" + response.toString());\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"syncRecording fail: \" + response);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"syncRecording finish\");\n\t\t\t}\n\n\t\t};\n\t\t\n\t}*/\n\t\n\tpublic static void createOWServerObject(final Context app_context, final OWServerObjectInterface object, final RequestCallback cb){\n\t\tJsonHttpResponseHandler post_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"createObject response: \" + response.toString());\n\t\t\t\ttry {\n\t\t\t\t\tif(response.has(\"success\") && response.getBoolean(\"success\")){\n\t\t\t\t\t\tLog.i(TAG, \"create object success!\");\n\t\t\t\t\t\tobject.updateWithJson(app_context, response.getJSONObject(\"object\"));\n if(cb != null)\n cb.onSuccess();\n\t\t\t\t\t\tsendOWMobileGeneratedObjectMedia(app_context, object);\n\t\t\t\t\t}\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"createObject fail: \" + response);\n\t\t\t\te.printStackTrace();\n if(cb != null)\n cb.onFailure();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"createObject finish\");\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, String.format(\"Commencing Create OWServerObject: %s with json: %s\", endpointForContentType(object.getContentType(app_context)), object.toJsonObject(app_context) ));\n\t\t//Log.i(TAG, object.getType().toString());\n\t\t//Log.i(TAG, object.toJsonObject(app_context).toString());\n\t\t//Log.i(TAG, Utils.JSONObjectToStringEntity(object.toJsonObject(app_context)).toString());\n\t\thttp_client.post(app_context, endpointForContentType(object.getContentType(app_context)) , Utils\n\t\t\t\t.JSONObjectToStringEntity(object.toJsonObject(app_context)), \"application/json\", post_handler);\n\t}\n\n public static void sendOWMobileGeneratedObjectMedia(final Context app_context, final OWServerObjectInterface object){\n sendOWMobileGeneratedObjectMedia(app_context, object, null);\n }\n\n\tpublic static void sendOWMobileGeneratedObjectMedia(final Context app_context, final OWServerObjectInterface object, final RequestCallback cb){\n\t\tnew Thread(){\n\t\t\tpublic void run(){\n\t\t\t\tString file_response;\n\t\t\t\ttry {\n String filepath = object.getMediaFilepath(app_context);\n if(filepath == null){\n Log.e(TAG, String.format(\"Error, OWServerobject %d has null filepath\", ((Model)object).getId()));\n object.setSynced(app_context, true); // set object synced, because we have no hope of ever syncing it mobile file deleted\n return;\n }\n\t\t\t\t\tfile_response = OWMediaRequests.ApacheFilePost(app_context, instanceEndpointForOWMediaObject(app_context, object), object.getMediaFilepath(app_context), \"file_data\");\n\t\t\t\t\tLog.i(TAG, \"binary media sent! response: \" + file_response);\n if(file_response.contains(\"object\")){\n // BEGIN OWServerObject Sync Broadcast\n Log.d(\"OWPhotoSync\", \"Broadcasting sync success message\");\n object.setSynced(app_context, true);\n //if(object.getMediaType(app_context) == MEDIA_TYPE.PHOTO)\n //(Photo)\n Intent intent = new Intent(Constants.OW_SYNC_STATE_FILTER);\n // You can also include some extra data.\n intent.putExtra(\"status\", 1);\n intent.putExtra(\"child_model_id\", ((Model)object).getId());\n LocalBroadcastManager.getInstance(app_context).sendBroadcast(intent);\n // END OWServerObject Sync Broadcast\n if(cb != null)\n cb.onSuccess();\n\n }else{\n if(cb != null)\n cb.onFailure();\n }\n\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (ClientProtocolException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (NullPointerException e){\n e.printStackTrace();\n }\n\t\t\t\t\n\t\t\t}\n\t\t}.start();\n\n\t}\n\n private static String instanceEndpointForOWUser(Context c, OWUser u){\n return Constants.OW_API_URL + \"u/\" + String.valueOf(u.server_id.get()) + \"/\";\n }\n\t\n\tprivate static String instanceEndpointForOWMediaObject(Context c, OWServerObjectInterface object){\n\t\tCONTENT_TYPE contentType = object.getContentType(c);\n if(contentType == CONTENT_TYPE.VIDEO || contentType == CONTENT_TYPE.AUDIO || contentType == CONTENT_TYPE.PHOTO)\n\t\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + object.getUUID(c) +\"/\";\n\t\telse\n\t\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + object.getServerId(c) +\"/\";\n\t}\n\n private static String instanceEndpointForOWMediaObject(Context c, CONTENT_TYPE contentType, String serverIdOrUUID){\n if(contentType == CONTENT_TYPE.VIDEO || contentType == CONTENT_TYPE.AUDIO || contentType == CONTENT_TYPE.PHOTO)\n return Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + serverIdOrUUID +\"/\";\n else\n return Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + serverIdOrUUID +\"/\";\n }\n\t\n\tprivate static String endpointForContentType(CONTENT_TYPE type){\n\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(type) + \"/\";\n\t}\n\n public static void syncOWServerObject(final Context app_context,\n final OWServerObjectInterface object) {\n syncOWServerObject(app_context, object, false, null);\n }\n\n public static void syncOWServerObject(final Context app_context, final OWServerObjectInterface object, RequestCallback cb){\n syncOWServerObject(app_context, object, false, cb);\n }\n\t\n\n\t/**\n\t * Fetch server recording data, check last_edited, and push update if\n\t * necessary. if forcePushLocalData, push local data even if server's last-edited\n * is greater than local\n\t * \n\t * @param app_context\n\t */\n\tpublic static void syncOWServerObject(final Context app_context,\n\t\t\t final OWServerObjectInterface object, final boolean forcePushLocalData, final RequestCallback cb) {\n\t\tfinal String METHOD = \"syncRecording\";\n\t\tfinal int model_id = ((Model)object).getId();\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"getMeta response: \" + response.toString());\n\t\t\t\tif (response.has(\"id\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t//JSONObject object_json = response\n\t\t\t\t\t\t//\t\t.getJSONObject(\"object\");\n\t\t\t\t\t\t// response was successful\n\t\t\t\t\t\tOWServerObject server_object = OWServerObject.objects(\n\t\t\t\t\t\t\t\tapp_context, OWServerObject.class).get(\n\t\t\t\t\t\t\t\tmodel_id);\n if(server_object == null)\n Log.e(TAG, String.format(\"Could not locate OWServerObject with id: %d\", model_id) );\n\t\t\t\t\t\tDate last_edited_remote = Constants.utc_formatter\n\t\t\t\t\t\t\t\t.parse(response.getString(\"last_edited\"));\n\t\t\t\t\t\tDate last_edited_local = Constants.utc_formatter.parse(server_object\n\t\t\t\t\t\t\t\t.getLastEdited(app_context));\n\t\t\t\t\t\tLog.i(TAG,\n\t\t\t\t\t\t\t\t\"Sync dates. Remote: \"\n\t\t\t\t\t\t\t\t\t\t+ response\n\t\t\t\t\t\t\t\t\t\t\t\t.getString(\"last_edited\")\n\t\t\t\t\t\t\t\t\t\t+ \" local: \"\n\t\t\t\t\t\t\t\t\t\t+ server_object.getLastEdited(app_context));\n\t\t\t\t\t\t// If local recording has no server_id, pull in fields\n\t\t\t\t\t\t// generated by server as there's no risk of conflict\n\t\t\t\t\t\tboolean doSave = false;\n\t\t\t\t\t\t// using the interface methods requires saving before\n\t\t\t\t\t\t// the object ref is lost\n\t\t\t\t\t\tif (response.has(Constants.OW_SERVER_ID)) {\n\t\t\t\t\t\t\tserver_object.server_id.set(response\n\t\t\t\t\t\t\t\t\t.getInt(Constants.OW_SERVER_ID));\n\t\t\t\t\t\t\t// recording.setServerId(app_context,\n\t\t\t\t\t\t\t// recording_json.getInt(Constants.OW_SERVER_ID));\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.has(Constants.OW_FIRST_POSTED)) {\n\t\t\t\t\t\t\tserver_object.first_posted.set(response\n\t\t\t\t\t\t\t\t\t.getString(Constants.OW_FIRST_POSTED));\n\t\t\t\t\t\t\t// recording.setFirstPosted(app_context,\n\t\t\t\t\t\t\t// recording_json.getString(Constants.OW_FIRST_POSTED));\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.has(Constants.OW_THUMB_URL)) {\n\t\t\t\t\t\t\tserver_object.thumbnail_url.set(response\n\t\t\t\t\t\t\t\t\t.getString(Constants.OW_THUMB_URL));\n\t\t\t\t\t\t\t// recording.setThumbnailUrl(app_context,\n\t\t\t\t\t\t\t// recording_json.getString(Constants.OW_THUMB_URL));\n\t\t\t\t\t\t\t// recording.media_object.get(app_context).save(app_context);\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (doSave == true) {\n\t\t\t\t\t\t\t// media_obj.save(app_context);\n\t\t\t\t\t\t\tserver_object.save(\n\t\t\t\t\t\t\t\t\tapp_context);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tOWServerObjectInterface child_obj = (OWServerObjectInterface) server_object.getChildObject(app_context);\n\t\t\t\t\t\tif(child_obj == null)\n\t\t\t\t\t\t\tLog.e(TAG, \"getChildObject returned null for OWServerObject \" + String.valueOf(server_object.getId()));\n\n\t\t\t\t\t\tif (!forcePushLocalData && last_edited_remote.after(last_edited_local)) {\n\t\t\t\t\t\t\t// copy remote data to local\n\t\t\t\t\t\t\tLog.i(TAG, \"remote recording data is more recent\");\n\t\t\t\t\t\t\t//server_object.updateWithJson(app_context, object_json);\n\t\t\t\t\t\t\t// call child object's updateWithJson -> calls OWServerObject's updateWithJson\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(child_obj != null){\n\t\t\t\t\t\t\t\tchild_obj.updateWithJson(app_context, response);\n if(cb != null)\n cb.onSuccess();\n }\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t} else if ( forcePushLocalData || last_edited_remote.before(last_edited_local)) {\n\t\t\t\t\t\t\t// copy local to remote\n\t\t\t\t\t\t\tLog.i(TAG, \"local recording data is more recent\");\n\t\t\t\t\t\t\tif(child_obj != null){\n\t\t\t\t\t\t\t\tOWServiceRequests.editOWServerObject(app_context,\n\t\t\t\t\t\t\t\t\tchild_obj, new JsonHttpResponseHandler() {\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\tpublic void onSuccess(\n\t\t\t\t\t\t\t\t\t\t\t\tJSONObject response) {\n\t\t\t\t\t\t\t\t\t\t\tLog.i(TAG,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"editRecording response: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ response);\n\n if(cb != null)\n cb.onSuccess();\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\tpublic void onFailure(Throwable e,\n\t\t\t\t\t\t\t\t\t\t\t\tJSONObject response) {\n\t\t\t\t\t\t\t\t\t\t\tLog.i(TAG, \"editRecording failed: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ response);\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\n if(cb != null)\n cb.onFailure();\n\t\t\t\t\t\t\t\t\t\t}\n\t\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} catch (Exception e) {\n\t\t\t\t\t\tLog.e(TAG, METHOD + \"failed to handle response\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}else try {\n if(response.has(\"success\") && response.getBoolean(\"success\") == false){\n handleOWApiError(app_context, response);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"syncRecording fail: \" + response);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"syncRecording finish\");\n\t\t\t}\n\n\t\t};\n\t\tgetOWServerObjectMeta(app_context, object, \"\", get_handler);\n\n\t}\n\n private static void handleOWApiError(Context app_context, JSONObject response){\n try {\n if(response.has(\"code\") && response.getInt(\"code\") == 406){\n SharedPreferences profile = app_context.getSharedPreferences(\n Constants.PROFILE_PREFS, app_context.MODE_PRIVATE);\n if(profile.contains(Constants.EMAIL) && profile.getBoolean(Constants.AUTHENTICATED, false)){\n // Auth cookie wrong / missing. Prompt user to re-login\n Analytics.trackEvent(app_context, Analytics.SESSION_EXPIRED, null);\n Authentication.logOut(app_context);\n OWUtils.goToLoginActivityWithMessage(app_context, app_context.getString(R.string.message_account_expired));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n\tpublic static void getOWServerObjectMeta(Context app_context, OWServerObjectInterface object, String http_get_string, JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tif(http_get_string == null)\n\t\t\thttp_get_string = \"\";\n if(object == null)\n return;\n\t\tLog.i(TAG, \"Commencing Get Recording Meta: \" + instanceEndpointForOWMediaObject(app_context, object) + http_get_string);\n\t\thttp_client.get(instanceEndpointForOWMediaObject(app_context, object) + http_get_string, response_handler);\n\t}\n\n public static void updateOrCreateOWServerObject(final Context app_context, CONTENT_TYPE contentType, String serverIdOrUUID, String http_get_string, final RequestCallback cb) {\n JsonHttpResponseHandler response_handler = new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n //Log.i(TAG, \"flag object success \" + response.toString());\n try {\n String type = response.getString(\"type\");\n if(type.compareTo(CONTENT_TYPE.MISSION.toString().toLowerCase()) == 0)\n OWMission.createOrUpdateOWMissionWithJson(app_context, response);\n // TODO: The rest\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n };\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n if(http_get_string == null)\n http_get_string = \"\";\n Log.i(TAG, \"Commencing Get Object Meta: \" + instanceEndpointForOWMediaObject(app_context, contentType, serverIdOrUUID) + http_get_string);\n http_client.get(instanceEndpointForOWMediaObject(app_context, contentType, serverIdOrUUID) + http_get_string, response_handler);\n }\n\n\t/**\n\t * Post recording data to server. object should be a child OW object. i.e: NOT OWServerObject\n\t * \n\t * @param app_context\n\t * @param response_handler\n\t */\n\tpublic static void editOWServerObject(Context app_context,\n\t\t\tOWServerObjectInterface object, JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG,\n\t\t\t\t\"Commencing Edit Recording: \"\n\t\t\t\t\t\t+ object.toJsonObject(app_context));\n\t\thttp_client.post(app_context, instanceEndpointForOWMediaObject(app_context, object), Utils\n\t\t\t\t.JSONObjectToStringEntity(object.toJsonObject(app_context)),\n\t\t\t\t\"application/json\", response_handler);\n\t}\n\n public static void postMissionAction(final Context app_context, OWServerObject serverObject, final OWMission.ACTION action){\n JSONObject json = new JSONObject();\n final int modelId = serverObject.getId();\n try {\n json.put(\"action\", action.toString().toLowerCase());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n JsonHttpResponseHandler response_handler = new JsonHttpResponseHandler() {\n @Override\n public void onSuccess(JSONObject response) {\n try {\n if(response.has(\"success\") && response.getBoolean(\"success\")){\n OWServerObject serverObject = OWServerObject.objects(app_context, OWServerObject.class).get(modelId);\n serverObject.mission.get(app_context).updateWithActionComplete(app_context, action);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n };\n\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n http_client.post(app_context, instanceEndpointForOWMediaObject(app_context, serverObject), Utils.JSONObjectToStringEntity(json), \"application/json\", response_handler);\n }\n\n public static void flagOWServerObjet(Context app_context, OWServerObjectInterface object){\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n JSONObject json = new JSONObject();\n try {\n json.put(\"flagged\", true);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n http_client.post(app_context, instanceEndpointForOWMediaObject(app_context, object), Utils.JSONObjectToStringEntity(json), \"application/json\", new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n Log.i(TAG, \"flag object success \" + response.toString());\n }\n @Override\n public void onFailure(Throwable e, String response) {\n Log.i(TAG, \"flag object failure: \" + response);\n\n }\n\n @Override\n public void onFinish() {\n Log.i(TAG, \"flag object finish: \");\n\n }\n });\n }\n\n\tpublic static void setTags(final Context app_context, QuerySet<OWTag> tags) {\n\t\tfinal String METHOD = \"setTags\";\n\t\tJSONObject result = new JSONObject();\n\t\tJSONArray tag_list = new JSONArray();\n\t\tfor (OWTag tag : tags) {\n\t\t\ttag_list.put(tag.toJson());\n\t\t}\n\t\ttry {\n\t\t\tresult.put(Constants.OW_TAGS, tag_list);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tAsyncHttpClient client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString url = Constants.OW_API_URL + Constants.OW_TAGS;\n\t\tLog.i(TAG,\n\t\t\t\t\"commencing \" + METHOD + \" : \" + url + \" json: \"\n\t\t\t\t\t\t+ result.toString());\n\t\tclient.post(app_context, url, Utils.JSONObjectToStringEntity(result),\n\t\t\t\t\"application/json\", new JsonHttpResponseHandler() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" success : \" + response.toString());\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" failure: \" + response);\n\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onFinish() {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" finish: \");\n\n\t\t\t\t\t}\n\t\t\t\t});\n\t}\n\n public static void sendOWUserAvatar(final Context app_context, final OWUser user, final File image, final RequestCallback cb){\n new Thread(){\n public void run(){\n try {\n String fileResponse = OWMediaRequests.ApacheFilePost(app_context, instanceEndpointForOWUser(app_context, user), image.getAbsolutePath(), \"file_data\");\n if(fileResponse.contains(\"object\")){\n try {\n JSONObject jsonResponse= new JSONObject(fileResponse);\n OWUser.objects(app_context, OWUser.class).get(user.getId()).updateWithJson(app_context, jsonResponse);\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }else{\n if(cb != null)\n cb.onFailure();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n }.start();\n\n }\n\n /*\n Immediatley send user agent_applicant status, then re-send location on success\n */\n\n public static void syncOWUser(final Context app_context, final OWUser user, final RequestCallback cb){\n final AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG,\n \"Commencing Edit User to: \" + instanceEndpointForOWUser(app_context, user) + \" \"\n + user.toJSON());\n\n final JsonHttpResponseHandler _cb = new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n Log.i(TAG, \"Edit user response: \" + response.toString());\n if(response.has(\"object\")){\n try {\n user.updateWithJson(app_context, response.getJSONObject(\"object\"));\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n if(cb != null)\n cb.onFailure();\n }\n }\n }\n\n @Override\n public void onFailure(Throwable e, String response) {\n Log.i(TAG, \"Edit user response: \" + response.toString());\n if(cb != null)\n cb.onFailure();\n }\n\n };\n\n if(user.agent_applicant.get() == true){\n DeviceLocation.getLastKnownLocation(app_context, false, new DeviceLocation.GPSRequestCallback() {\n @Override\n public void onSuccess(Location result) {\n if(result != null){\n user.lat.set(result.getLatitude());\n user.lon.set(result.getLongitude());\n user.save(app_context);\n Log.i(TAG, String.format(\"Got user location %fx%f\", result.getLatitude(), result.getLongitude()));\n http_client.post(app_context, instanceEndpointForOWUser(app_context, user), Utils\n .JSONObjectToStringEntity(user.toJSON()),\n \"application/json\", _cb);\n }\n }\n });\n }\n\n http_client.post(app_context, instanceEndpointForOWUser(app_context, user), Utils\n .JSONObjectToStringEntity(user.toJSON()),\n \"application/json\", _cb);\n }\n\n\t/**\n\t * Merges server tag list with stored. Assume names are unchanging (treated\n\t * as primary key)\n\t * \n\t * @param app_context\n\t * @param cb\n\t */\n\tpublic static void getTags(final Context app_context,\n\t\t\tfinal RequestCallback cb) {\n\t\tfinal String METHOD = \"getTags\";\n\t\tAsyncHttpClient client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString url = Constants.OW_API_URL + Constants.OW_TAGS;\n\t\tLog.i(TAG, \"commencing getTags: \" + url);\n\t\tclient.get(url, new JsonHttpResponseHandler() {\n\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\n\t\t\t\tJSONArray array_json;\n\t\t\t\ttry {\n\t\t\t\t\tarray_json = (JSONArray) response.get(\"tags\");\n\t\t\t\t\tJSONObject tag_json;\n\n\t\t\t\t\tint tag_count = OWTag.objects(app_context, OWTag.class)\n\t\t\t\t\t\t\t.count();\n\n\t\t\t\t\tDatabaseAdapter adapter = DatabaseAdapter\n\t\t\t\t\t\t\t.getInstance(app_context);\n\t\t\t\t\tadapter.beginTransaction();\n\n\t\t\t\t\tOWTag tag = null;\n\t\t\t\t\tfor (int x = 0; x < array_json.length(); x++) {\n\t\t\t\t\t\ttag_json = array_json.getJSONObject(x);\n\t\t\t\t\t\ttag = OWTag.getOrCreateTagFromJson(app_context, tag_json);\n\t\t\t\t\t\ttag.save(app_context);\n\t\t\t\t\t\t//Log.i(TAG,\n\t\t\t\t\t\tLog.i(\"TAGGIN\",\n\t\t\t\t\t\t\t\tMETHOD + \" saved tag: \" + tag.name.get()\n\t\t\t\t\t\t\t\t\t\t+ \" featured: \"\n\t\t\t\t\t\t\t\t\t\t+ String.valueOf(tag.is_featured.get()));\n\n\t\t\t\t\t}\n\n\t\t\t\t\tadapter.commitTransaction();\n\t\t\t\t\tLog.i(TAG, \"getTags success :\" + response.toString());\n\t\t\t\t\tif (cb != null)\n\t\t\t\t\t\tcb.onSuccess();\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\tLog.e(TAG, METHOD + \" failed to parse JSON: \" + response);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, METHOD + \" failure: \" + response);\n\t\t\t\tif (cb != null)\n\t\t\t\t\tcb.onFailure();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, METHOD + \" finished\");\n\t\t\t}\n\n\t\t});\n\t}\n\n\t/**\n\t * Login an existing account with the OpenWatch service\n\t */\n\tpublic static void userLogin(Context app_context, StringEntity post_body,\n JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing login to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_LOGIN);\n\t\thttp_client.post(app_context,\n\t\t\t\tConstants.OW_API_URL + Constants.OW_LOGIN, post_body,\n\t\t\t\t\"application/json\", response_handler);\n\n\t}\n\n\t/**\n\t * Create a new account with the OpenWatch servicee\n\t */\n\tpublic static void userSignup(Context app_context, StringEntity post_body,\n JsonHttpResponseHandler response_handler) {\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing signup to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_SIGNUP);\n\t\thttp_client.post(app_context, Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_SIGNUP, post_body, \"application/json\",\n\t\t\t\tresponse_handler);\n\n\t}\n\n /**\n * Create a new account with the OpenWatch servicee\n */\n public static void quickUserSignup(Context app_context, String email,\n JsonHttpResponseHandler response_handler) {\n\n JSONObject json = new JSONObject();\n StringEntity se = null;\n try {\n json.put(\"email\", email);\n se = new StringEntity(json.toString());\n } catch (JSONException e) {\n Log.e(TAG, \"Error loading email to json\");\n e.printStackTrace();\n return;\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Error creating StringEntity from json\");\n e.printStackTrace();\n return;\n }\n\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG, \"Commencing signup to: \" + Constants.OW_API_URL\n + \"quick_signup\");\n http_client.post(app_context, Constants.OW_API_URL\n + \"quick_signup\", se, \"application/json\",\n response_handler);\n\n }\n\n\t/**\n\t * Registers this mobile app with the OpenWatch service sends the\n\t * application version number\n\t */\n\tpublic static void RegisterApp(Context app_context,\n\t\t\tString public_upload_token, JsonHttpResponseHandler response_handler) {\n\t\tPackageInfo pInfo;\n\t\tString app_version = \"Android-\";\n\t\ttry {\n\t\t\tpInfo = app_context.getPackageManager().getPackageInfo(\n\t\t\t\t\tapp_context.getPackageName(), 0);\n\t\t\tapp_version += pInfo.versionName;\n\t\t} catch (NameNotFoundException e) {\n\t\t\tLog.e(TAG, \"Unable to read PackageName in RegisterApp\");\n\t\t\te.printStackTrace();\n\t\t\tapp_version += \"unknown\";\n\t\t}\n\n\t\tHashMap<String, String> params = new HashMap<String, String>();\n\t\tparams.put(Constants.PUB_TOKEN, public_upload_token);\n\t\tparams.put(Constants.OW_SIGNUP_TYPE, app_version);\n\t\tGson gson = new Gson();\n\t\tStringEntity se = null;\n\t\ttry {\n\t\t\tse = new StringEntity(gson.toJson(params));\n\t\t} catch (UnsupportedEncodingException e1) {\n\t\t\tLog.e(TAG, \"Failed to put JSON string in StringEntity\");\n\t\t\te1.printStackTrace();\n\t\t\treturn;\n\t\t}\n\n\t\t// Post public_upload_token, signup_type\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing ap registration to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_REGISTER + \" pub_token: \" + public_upload_token\n\t\t\t\t+ \" version: \" + app_version);\n\t\thttp_client.post(app_context, Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_REGISTER, se, \"application/json\",\n\t\t\t\tresponse_handler);\n\n\t}\n\n\tpublic static void onLaunchSync(final Context app_context) {\n\t\tRequestCallback cb = new RequestCallback() {\n\n\t\t\t@Override\n\t\t\tpublic void onFailure() {\n\t\t\t\tLog.i(TAG, \"per_launch_sync failed\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onSuccess() {\n\t\t\t\t((OWApplication) app_context).per_launch_sync = true;\n\t\t\t\tLog.i(TAG, \"per_launch_sync success\");\n\t\t\t}\n\t\t};\n\n\t\tOWServiceRequests.getTags(app_context, cb);\n\t}\n\n public static void checkOWEmailAvailable(Context app_context, String email, JsonHttpResponseHandler response_handler){\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG, \"Checking email available: \" + email);\n http_client.get(app_context, Constants.OW_API_URL + \"email_available?email=\" + email, response_handler);\n }\n}", "public class OWUser extends Model{\n\tprivate static final String TAG = \"OWUser\";\n\t\n\tpublic CharField username = new CharField();\n public CharField first_name = new CharField();\n public CharField last_name = new CharField();\n public CharField blurb = new CharField();\n\tpublic CharField thumbnail_url = new CharField();\n\tpublic IntegerField server_id = new IntegerField();\n public CharField gcm_registration_id = new CharField();\n\n public DoubleField lat = new DoubleField();\n public DoubleField lon = new DoubleField();\n\n public BooleanField agent_applicant = new BooleanField();\n public BooleanField agent_approved = new BooleanField();\n\t\n\tpublic OneToManyField<OWUser, OWVideoRecording> recordings = new OneToManyField<OWUser, OWVideoRecording>(OWUser.class, OWVideoRecording.class);\n\tpublic ManyToManyField<OWUser, OWTag> tags = new ManyToManyField<OWUser, OWTag>(OWUser.class, OWTag.class);\n\n @Override\n protected void migrate(Context context) {\n /*\n Migrator automatically keeps track of which migrations have been run.\n All we do is add a migration for each change that occurs after the initial app release\n */\n Migrator<OWUser> migrator = new Migrator<OWUser>(OWUser.class);\n\n migrator.addField(\"first_name\", new CharField());\n\n migrator.addField(\"last_name\", new CharField());\n\n migrator.addField(\"blurb\", new CharField());\n\n migrator.addField(\"gcm_registration_id\", new CharField());\n\n // roll out all migrations\n migrator.migrate(context);\n }\n\t\n\tpublic OWUser(){\n\t\tsuper();\n\t}\n\t\n\tpublic OWUser(Context c){\n\t\tsuper();\n\t\tsave(c);\n\t}\n\t\n\tpublic JSONObject toJSON(){\n\t\tJSONObject json_obj = new JSONObject();\n\t\ttry{\n\t\t\tif(this.username.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_USERNAME, this.username.get());\n if(this.first_name.get() != null)\n json_obj.put(Constants.OW_FIRST_NAME, this.first_name.get());\n if(this.last_name.get() != null)\n json_obj.put(Constants.OW_LAST_NAME, this.last_name.get());\n if(this.blurb.get() != null)\n json_obj.put(Constants.OW_BLURB, this.blurb.get());\n\t\t\tif(this.server_id.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_SERVER_ID, this.server_id.get());\n\t\t\tif(this.thumbnail_url.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_THUMB_URL, thumbnail_url.get());\n if(this.agent_applicant.get() != null)\n json_obj.put(\"agent_applicant\", agent_applicant.get());\n if(this.gcm_registration_id.get() != null)\n json_obj.put(\"google_push_token\", gcm_registration_id.get());\n if(this.lat.get() != null && this.lon.get() != null){\n json_obj.put(Constants.OW_LAT, lat.get());\n json_obj.put(Constants.OW_LON, lon.get());\n }\n\t\t}catch (JSONException e){\n\t\t\tLog.e(TAG, \"Error serialiazing OWUser\");\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn json_obj;\n\t}\n\t\n\tpublic void updateWithJson(Context c, JSONObject json){\n\t\ttry {\n\t\t\tif(json.has(DBConstants.USER_SERVER_ID))\n\t\t\t\tserver_id.set(json.getInt(DBConstants.USER_SERVER_ID));\n\t\t\tif(json.has(Constants.OW_USERNAME))\n\t\t\t\tusername.set(json.getString(Constants.OW_USERNAME));\n if(json.has(Constants.OW_FIRST_NAME))\n first_name.set(json.getString(Constants.OW_FIRST_NAME));\n if(json.has(Constants.OW_LAST_NAME))\n last_name.set(json.getString(Constants.OW_LAST_NAME));\n if(json.has(Constants.OW_BLURB))\n blurb.set(json.getString(Constants.OW_BLURB));\n if(json.has(Constants.OW_LAT) && json.has(Constants.OW_LON)){\n lat.set(json.getDouble(Constants.OW_LAT));\n lon.set(json.getDouble(Constants.OW_LON));\n }\n if(json.has(Constants.OW_THUMB_URL))\n thumbnail_url.set(json.getString(Constants.OW_THUMB_URL));\n if(json.has(\"agent_approved\"))\n agent_approved.set(json.getBoolean(\"agent_approved\"));\n if(json.has(\"agent_applicant\"))\n agent_applicant.set(json.getBoolean(\"agent_applicant\"));\n\t\t\tif(json.has(Constants.OW_TAGS)){\n this.tags.reset();\n JSONArray tag_array = json.getJSONArray(\"tags\");\n OWTag tag = null;\n DatabaseAdapter.getInstance(c).beginTransaction();\n for(int x=0;x<tag_array.length();x++){\n tag = OWTag.getOrCreateTagFromJson(c, tag_array.getJSONObject(x));\n tag.save(c);\n this.addTag(c, tag, false);\n }\n DatabaseAdapter.getInstance(c).commitTransaction();\n } // end tags update\n\t\t\tthis.save(c);\n\t\t} catch (JSONException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic void addTag(Context c, OWTag tag, boolean syncWithOW){\n\t\tthis.tags.add(tag);\n\t\tsave(c);\n\t\tif(syncWithOW)\n\t\t\tOWServiceRequests.setTags(c, tags.get(c, this));\n\t}\n\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import com.loopj.android.http.JsonHttpResponseHandler; import com.orm.androrm.Filter; import com.orm.androrm.QuerySet; import org.ale.openwatch.Analytics; import org.ale.openwatch.OWApplication; import org.ale.openwatch.constants.Constants; import org.ale.openwatch.constants.DBConstants; import org.ale.openwatch.http.HttpClient; import org.ale.openwatch.http.OWServiceRequests; import org.ale.openwatch.model.OWUser; import org.json.JSONException; import org.json.JSONObject;
package org.ale.openwatch.account; /** * Sauce for interpreting * ow account api responses * found in http.OWServiceRequests * and manipulating stored user state * in SharedPreferences and httpclient cookiestore * Created by davidbrodsky on 5/16/13. */ public class Authentication { private static final String TAG = "Authentication"; public interface AuthenticationCallback{ public void onComplete(); } /** * Save the OpenWatch service login response data to SharedPreferences this * includes the public and private upload token, authentication state, and * the submitted email. * * @author davidbrodsky * */ public static void setUserAuthenticated(Context c, JSONObject server_response, String expected_email) { try {
Analytics.identifyUser(c, String.valueOf(server_response.getInt(DBConstants.USER_SERVER_ID)));
3
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/client/gui/ScreenChalk.java
[ "@Mod(\"runicarcana\")\npublic class RunicArcana\n{\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n public static final String MODID = \"runicarcana\";\n\n //Capability Registration\n @CapabilityInject(ISymbolHandler.class)\n public static Capability<ISymbolHandler> SYMBOL_CAP = null;\n\n @CapabilityInject(IArcanaHandler.class)\n public static Capability<IArcanaHandler> ARCANA_CAP = null;\n\n public static IProxy proxy;\n\n public RunicArcana() {\n // Register the setup method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetupComplete);\n // Register the enqueueIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);\n // Register the processIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);\n // Register the doClientStuff method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doServerStuff);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistryHandler::onCreateRegistryEvent);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistration::registerSymbols);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new CommonEventHandler());\n MinecraftForge.EVENT_BUS.register(new SymbolSyncer());\n NetworkSync.registerPackets();\n ClickableHandler.registerPackets();\n Registration.init();\n //SymbolRegistration.init();\n\n }\n\n private void setup(final FMLCommonSetupEvent event)\n {\n SymbolHandlerStorage storage = new SymbolHandlerStorage();\n SymbolHandler.SymbolHandlerFactory factory = new SymbolHandler.SymbolHandlerFactory();\n CapabilityManager.INSTANCE.register(ISymbolHandler.class, storage, factory);\n\n ArcanaHandlerStorage storage2 = new ArcanaHandlerStorage();\n ArcanaHandler.ArcanaHandlerFactory factory2 = new ArcanaHandler.ArcanaHandlerFactory();\n CapabilityManager.INSTANCE.register(IArcanaHandler.class, storage2, factory2);\n\n //TODO: register packets somewhere reasonable\n registerPackets();\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n proxy = new ClientProxy();\n KeyEventHandler.registerKeyBindings();\n }\n\n private void doServerStuff(final FMLDedicatedServerSetupEvent event) {\n proxy = new ServerProxy();\n }\n\n private void enqueueIMC(final InterModEnqueueEvent event)\n {\n // some example code to dispatch IMC to another mod\n// InterModComms.sendTo(\"examplemod\", \"helloworld\", () -> { LOGGER.info(\"Hello world from the MDK\"); return \"Hello world\";});\n InterModComms.sendTo(\"curios\", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage(\"ring\").setSize(2));\n InterModComms.sendTo(\"curios\", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage(\"trinket\").setSize(2));\n\n }\n\n private void processIMC(final InterModProcessEvent event)\n {\n // some example code to receive and process InterModComms from other mods\n// LOGGER.info(\"Got IMC {}\", event.getIMCStream().\n// map(m->m.getMessageSupplier().get()).\n// collect(Collectors.toList()));\n }\n\n private void onSetupComplete(final FMLLoadCompleteEvent event)\n {\n PrincipicArmorEventHandler.onSetup(event);\n SymbolCategory.generateCategories(); //TODO remove this when static initialization is working\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(FMLServerStartingEvent event) {\n // do something when the server starts\n// LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD\n // Event bus for receiving Registry Events)\n @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)\n public static class RegistryEvents {\n @SubscribeEvent\n public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {\n // register a new block here\n// LOGGER.info(\"HELLO from Register Block\");\n }\n }\n}", "public class ChalkItem extends Item {\n\n public static AtomicReference<HashableTuple<String, DataType>> selectedFunction;\n\n public ChalkItem() {\n super(new Properties().maxStackSize(1).group(ModSetup.ITEM_GROUP));\n }\n\n private static final int DIRTY_RANGE = 20;\n\n\n @Override\n public ActionResultType onItemUse(ItemUseContext context) {\n\n LazyOptional<ISymbolHandler> symbolOp = context.getWorld().getChunkAt(context.getPos()).getCapability(RunicArcana.SYMBOL_CAP);\n symbolOp.ifPresent(symbols -> {\n\n if (!context.getWorld().isRemote)\n {\n //TODO this will not work if shift+right clicking on a non-symbol functional object\n Chunk chunk = context.getWorld().getChunkAt(context.getPos());\n Symbol symbolToDraw = null;\n symbolToDraw = RegistryManager.ACTIVE.getRegistry(Symbol.class)\n .getValue(new ResourceLocation(context.getItem().getOrCreateTag().contains(\"selected_symbol\")\n ? context.getItem().getOrCreateTag().getString(\"selected_symbol\") : Symbols.DEBUG.getRegistryName().toString()));\n\n symbols.addSymbol(new DrawnSymbol(symbolToDraw, context.getPos(), context.getFace(),chunk), chunk);\n\n for(PlayerEntity player : context.getWorld().getPlayers())\n {\n if(player.chunkCoordX > chunk.getPos().x - DIRTY_RANGE && player.chunkCoordX < chunk.getPos().x + DIRTY_RANGE &&\n player.chunkCoordZ > chunk.getPos().z - DIRTY_RANGE && player.chunkCoordZ < chunk.getPos().z + DIRTY_RANGE)\n {\n SymbolSyncer.SymbolDirtyMessage msg = new SymbolSyncer.SymbolDirtyMessage(chunk.getPos());\n SymbolSyncer.INSTANCE.sendTo( msg, ((ServerPlayerEntity)(player)).connection.netManager, NetworkDirection.PLAY_TO_CLIENT);\n }\n }\n }\n else if(context.getWorld().isRemote && context.getPlayer().isSteppingCarefully())\n {\n IFunctionalObject symbol = SymbolUtil.getLookedFunctionalObject();\n if(symbol !=null) {\n\n ItemStack chalk = context.getItem();\n Chunk chunk = context.getWorld().getChunkAt(context.getPos());\n\n if (!chalk.getOrCreateTag().contains(\"linking_from\") && selectedFunction!=null && selectedFunction.get()!=null) {\n CompoundNBT nbt = symbol.basicSerializeNBT();\n nbt.putString(\"func\",selectedFunction.get().getA());\n nbt.putString(\"type\",selectedFunction.get().getB().name);\n chalk.getTag().put(\"linking_from\",nbt);\n }else\n {\n sendNBTToServer(symbol,chalk,chunk);\n }\n }\n\n\n }\n });\n\n return ActionResultType.SUCCESS;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void sendNBTToServer(IFunctionalObject symbol, ItemStack chalk, Chunk chunk)\n {\n if(OverlayPopup.selectedFunction.get()==null) return;\n IFunctionalObject object = null;\n try {\n object = symbol.getClass().newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n if(object==null)return;\n if(!chalk.getOrCreateTag().contains(\"linking_from\"))return;\n if (chalk.getTag() != null) {\n object.deserializeNBT(chalk.getTag().getCompound(\"linking_from\"));\n }\n object = object.findReal(chunk);\n if(object==null)return;\n\n SymbolSyncer.INSTANCE.sendToServer(new SymbolSyncer.SymbolLinkMessage(object,symbol,\n new HashableTuple<>(chalk.getTag().getCompound(\"linking_from\").getString(\"func\"),DataType.getDataType(chalk.getTag().getCompound(\"linking_from\").getString(\"type\"))),\n OverlayPopup.selectedFunction.get().getA(),OverlayPopup.selectedFunction.get().getB().name));\n\n chalk.getTag().remove(\"linking_from\");\n OverlayPopup.funcObject.set(null);\n OverlayPopup.selectedFunction.set(null);\n OverlayPopup.updateRenderList(chalk,null);\n }\n\n @Override\n public void onCreated(ItemStack stack, World worldIn, PlayerEntity playerIn) {\n CompoundNBT nbt = stack.getOrCreateTag();\n nbt.putString(\"selected_symbol\",Symbols.DEBUG.getRegistryName().toString());\n super.onCreated(stack, worldIn, playerIn);\n }\n\n public static class ChalkSyncMessage\n {\n public Symbol selectedSymbol;\n public Hand hand;\n\n public ChalkSyncMessage(Symbol selectedSymbol, Hand hand)\n {\n this.selectedSymbol = selectedSymbol;\n this.hand = hand;\n }\n\n public static void encode(final ChalkSyncMessage msg, final PacketBuffer buf)\n {\n buf.writeString(msg.selectedSymbol.getRegistryName().toString());\n buf.writeBoolean(msg.hand.equals(Hand.MAIN_HAND));\n }\n\n public static ChalkSyncMessage decode(final PacketBuffer buf)\n {\n Symbol symbol = RegistryManager.ACTIVE.getRegistry(Symbol.class).getValue(new ResourceLocation(buf.readString(128)));\n Hand hand = buf.readBoolean() ? Hand.MAIN_HAND : Hand.OFF_HAND;\n\n return new ChalkSyncMessage(symbol, hand);\n }\n\n public static void handle(final ChalkSyncMessage msg, final Supplier<NetworkEvent.Context> contextSupplier)\n {\n final NetworkEvent.Context context = contextSupplier.get();\n if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT))\n {\n\n context.setPacketHandled(true);\n }\n else if (context.getDirection().equals(NetworkDirection.PLAY_TO_SERVER))\n {\n if(context.getSender()==null)return;\n ItemStack chalk = context.getSender().getHeldItem(msg.hand);\n chalk.getOrCreateTag().putString(\"selected_symbol\", msg.selectedSymbol.getRegistryName().toString());\n\n context.setPacketHandled(true);\n }\n }\n\n }\n\n\n\n\n\n}", "public class Symbols {\n\n @ObjectHolder(\"runicarcana:symbol_debug\")\n public static final Symbol DEBUG = null;\n\n @ObjectHolder(\"runicarcana:symbol_expulsion\")\n public static final Symbol EXPULSION = null;\n\n}", "public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> {\n\n protected String name;\n protected ResourceLocation texture;\n protected int id = -1;\n protected final SymbolCategory category;\n\n protected List<IFunctional> functions = new ArrayList<IFunctional>();\n protected List<HashableTuple<String,DataType>> inputs = new ArrayList<HashableTuple<String,DataType>>();\n protected List<IFunctional> outputs = new ArrayList<IFunctional>();\n protected List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> triggers = new ArrayList<HashableTuple<HashableTuple<String, DataType>, IFunctional>>();\n\n public Symbol(String name, ResourceLocation texture, SymbolCategory category) {\n this.name = name;\n this.texture = texture;\n this.category = category;\n this.setRegistryName(new ResourceLocation(MODID, this.name));\n\n this.registerFunctions();\n\n //roll up the functions into the functional object fields\n for (IFunctional function : functions)\n {\n //synchronize the inputs from all the functions\n for(HashableTuple<String,DataType> input : inputs) {\n //check to see if inputs already has the same DataType and String registered\n if(function.getRequiredInputs()==null)return;\n function.getRequiredInputs().removeIf(finput ->\n {\n if (function.getRequiredInputs().contains(finput)) return false;\n if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) {\n //if we do, remove the input from the function and replace it with the already registered input\n function.getRequiredInputs().add(input);\n return true;\n }\n return false;\n });\n }\n\n //add each input into the object inputs\n if(function.getRequiredInputs()!=null)\n function.getRequiredInputs().forEach(finput->{\n if(!inputs.contains(finput))\n inputs.add(finput);\n });\n }\n\n //repeat for outputs\n for (IFunctional function : outputs)\n {\n //synchronize the inputs from all the functions\n for(HashableTuple<String,DataType> input : inputs) {\n //check to see if inputs already has the same DataType and String registered\n if(function.getRequiredInputs()==null)return;\n function.getRequiredInputs().removeIf(finput ->\n {\n if (function.getRequiredInputs().contains(finput)) return false;\n if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) {\n //if we do, remove the input from the function and replace it with the already registered input\n function.getRequiredInputs().add(input);\n return true;\n }\n return false;\n });\n }\n\n //add each input into the object inputs\n if(function.getRequiredInputs()!=null)\n function.getRequiredInputs().forEach(finput->{\n if(!inputs.contains(finput))\n inputs.add(finput);\n });\n }\n }\n\n public Symbol(String name)\n {\n this(name, SymbolTextures.DEBUG, SymbolCategory.DEFAULT);\n }\n\n public String getName()\n {\n return name;\n }\n\n public ResourceLocation getTexture() {\n return texture;\n }\n\n //we really shouldn't be using this\n public void onTick(DrawnSymbol symbol, World world, Chunk chunk, BlockPos drawnOn, Direction blockFace) {\n\n }\n\n protected abstract void registerFunctions();\n\n public List<IFunctional> getFunctions() {\n return functions;\n }\n\n public List<HashableTuple<String,DataType>> getInputs(){\n return inputs;\n }\n\n public List<IFunctional> getOutputs() {\n return outputs;\n }\n\n public List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> getTriggers()\n {\n return triggers;\n }\n\n public static class DummySymbol extends Symbol{\n public DummySymbol(String name) {\n super(name);\n }\n\n @Override\n protected void registerFunctions() {\n\n }\n }\n\n public SymbolCategory getCategory()\n {\n return category;\n }\n\n public int getId() {\n return id;\n }\n\n //put DrawnSymbol data into contents of packet buffer\n public void encode(final DrawnSymbol symbol, final PacketBuffer buf)\n {\n buf.writeInt(symbol.blockFace.getIndex());\n buf.writeInt(symbol.drawnOn.getX());\n buf.writeInt(symbol.drawnOn.getY());\n buf.writeInt(symbol.drawnOn.getZ());\n }\n\n //take contents of packet buffer and put into DrawnSymbol\n public void decode(final DrawnSymbol symbol, final PacketBuffer buf)\n {\n symbol.blockFace = Direction.byIndex(buf.readInt());\n symbol.drawnOn = new BlockPos(buf.readInt(),buf.readInt(),buf.readInt());\n }\n\n\n\n}", "public class SymbolSyncer\n{\n\n private static final int DIRTY_RANGE = 15;\n\n private static final String PROTOCOL_VERSION = \"1\";\n private static final int MESSAGE_QUEUE_SIZE = 100;\n private static final int PACKETS_PER_TICK = 20;\n public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(\n new ResourceLocation(MODID, \"symbol_synchronization\"),\n () -> PROTOCOL_VERSION,\n PROTOCOL_VERSION::equals,\n PROTOCOL_VERSION::equals\n );\n private static final Queue<SymbolSyncMessage> messageQueue = new LinkedList<SymbolSyncMessage>();\n\n public static boolean canAddMessage()\n {\n return messageQueue.size()<MESSAGE_QUEUE_SIZE;\n }\n\n public static void addMessageToQueue(SymbolSyncMessage msg)\n {\n if(messageQueue.size()<MESSAGE_QUEUE_SIZE) {\n boolean found = false;\n for(SymbolSyncMessage message : messageQueue)\n {\n if(msg.chunkPos.equals(message.chunkPos)) {\n found = true;\n break;\n }\n }\n if(!found)\n messageQueue.add(msg);\n }\n }\n\n @SubscribeEvent\n @OnlyIn(Dist.CLIENT)\n public void onChunkTickEvent(TickEvent.ClientTickEvent evt) {\n int packets_per_tick = PACKETS_PER_TICK;\n while(messageQueue.size()>0 && packets_per_tick-->0)\n SymbolSyncer.INSTANCE.sendToServer(messageQueue.poll());\n }\n\n public static void registerPackets()\n {\n int ind = 0;\n INSTANCE.registerMessage(ind++, SymbolSyncMessage.class,\n SymbolSyncMessage::encode,\n SymbolSyncMessage::decode,\n SymbolSyncMessage::handle);\n\n INSTANCE.registerMessage(ind++, SymbolDirtyMessage.class,\n SymbolDirtyMessage::encode,\n SymbolDirtyMessage::decode,\n SymbolDirtyMessage::handle);\n\n INSTANCE.registerMessage(ind++, ChalkItem.ChalkSyncMessage.class,\n ChalkItem.ChalkSyncMessage::encode,\n ChalkItem.ChalkSyncMessage::decode,\n ChalkItem.ChalkSyncMessage::handle);\n\n INSTANCE.registerMessage(ind++, AddWorkMessage.class,\n AddWorkMessage::encode,\n AddWorkMessage::decode,\n AddWorkMessage::handle);\n\n INSTANCE.registerMessage(ind++, SymbolLinkMessage.class,\n SymbolLinkMessage::encode,\n SymbolLinkMessage::decode,\n SymbolLinkMessage::handle);\n\n }\n\n public static class AddWorkMessage\n {\n public int work;\n public DrawnSymbol symbol;\n public ChunkPos chunkPos;\n\n public AddWorkMessage(int work, DrawnSymbol symbol, ChunkPos chunkPos)\n {\n this.work = work;\n this.symbol = symbol;\n this.chunkPos = chunkPos;\n }\n\n public static void encode(final AddWorkMessage msg, final PacketBuffer buf)\n {\n buf.writeInt(msg.work);\n buf.writeInt(msg.chunkPos.x);\n buf.writeInt(msg.chunkPos.z);\n buf.writeBlockPos(msg.symbol.getDrawnOn());\n buf.writeInt(msg.symbol.getBlockFace().getIndex());\n }\n\n public static AddWorkMessage decode(final PacketBuffer buf)\n {\n int work = buf.readInt();\n ChunkPos chunkPos = new ChunkPos(buf.readInt(),buf.readInt());\n DrawnSymbol symbol = null;\n if(RunicArcana.proxy.getWorld()!=null)\n symbol = new DrawnSymbol(Symbols.DEBUG, buf.readBlockPos(), Direction.byIndex(buf.readInt()),RunicArcana.proxy.getWorld().getChunk(chunkPos.x, chunkPos.z));\n\n return new AddWorkMessage(work, symbol, chunkPos);\n }\n\n public static void handle(final AddWorkMessage msg, final Supplier<NetworkEvent.Context> contextSupplier) {\n final NetworkEvent.Context context = contextSupplier.get();\n if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT)) {\n context.enqueueWork(() -> {\n World world = RunicArcana.proxy.getWorld();\n Chunk chunk = world.getChunkProvider().getChunk(msg.chunkPos.x, msg.chunkPos.z, true);\n\n chunk.getCapability(RunicArcana.SYMBOL_CAP).ifPresent(symbolHandler -> {\n DrawnSymbol symbol = symbolHandler.getSymbolAt(msg.symbol.getDrawnOn(),msg.symbol.getBlockFace());\n if(symbol!=null)\n symbol.applyWork(msg.work);\n });\n });\n context.setPacketHandled(true);\n }\n }\n }\n\n public static class SymbolDirtyMessage\n {\n public ChunkPos chunkPos;\n\n public SymbolDirtyMessage(ChunkPos chunkPos)\n {\n this.chunkPos = chunkPos;\n }\n\n public SymbolDirtyMessage(Chunk chunk)\n {\n this.chunkPos = chunk.getPos();\n }\n\n public static void encode(final SymbolDirtyMessage msg, final PacketBuffer buf)\n {\n buf.writeInt(msg.chunkPos.x);\n buf.writeInt(msg.chunkPos.z);\n }\n\n public static SymbolDirtyMessage decode(final PacketBuffer buf)\n {\n ChunkPos chunkPos = new ChunkPos(buf.readInt(),buf.readInt());\n return new SymbolDirtyMessage(chunkPos);\n }\n\n public static void handle(final SymbolDirtyMessage msg, final Supplier<NetworkEvent.Context> contextSupplier)\n {\n final NetworkEvent.Context context = contextSupplier.get();\n if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT))\n {\n context.enqueueWork(() -> {\n World world = RunicArcana.proxy.getWorld();\n Chunk chunk = world.getChunkProvider().getChunk(msg.chunkPos.x, msg.chunkPos.z, true);\n\n chunk.getCapability(RunicArcana.SYMBOL_CAP).ifPresent(symbolHandler ->{\n symbolHandler.markDirty();\n });\n });\n context.setPacketHandled(true);\n }\n else if (context.getDirection().equals(NetworkDirection.PLAY_TO_SERVER))\n {\n context.setPacketHandled(true);\n }\n }\n\n }\n\n public static class SymbolLinkMessage\n {\n public IFunctionalObject linkingFrom;\n public IFunctionalObject linkingTo;\n public HashableTuple<String, DataType> input;\n public String outputName;\n public String outputType;\n\n public SymbolLinkMessage(IFunctionalObject linkingFrom, IFunctionalObject linkingTo, HashableTuple<String, DataType> input, String outputName, String outputType) {\n this.linkingFrom = linkingFrom;\n this.linkingTo = linkingTo;\n this.input = input;\n this.outputName = outputName;\n this.outputType = outputType;\n }\n\n public SymbolLinkMessage(IFunctionalObject linkingFrom, IFunctionalObject linkingTo, HashableTuple<String, DataType> input, IFunctional output) {\n this.linkingFrom = linkingFrom;\n this.linkingTo = linkingTo;\n this.input = input;\n this.outputName = output.getName();\n this.outputType = output.getOutputType().name;\n }\n\n public static void encode(final SymbolLinkMessage msg, final PacketBuffer buf)\n {\n buf.writeString(msg.linkingFrom.getObjectType());\n buf.writeCompoundTag(msg.linkingFrom.basicSerializeNBT());\n buf.writeString(msg.linkingFrom.getObjectType());\n buf.writeCompoundTag(msg.linkingTo.basicSerializeNBT());\n buf.writeString(msg.input.getA());\n buf.writeString(msg.input.getB().name);\n buf.writeString(msg.outputName);\n buf.writeString(msg.outputType);\n }\n\n public static SymbolLinkMessage decode(final PacketBuffer buf)\n {\n IFunctionalObject linkingFrom = FunctionalTypeRegister.getFunctionalObject(buf.readString(100));\n linkingFrom.deserializeNBT(buf.readCompoundTag());\n IFunctionalObject linkingTo = FunctionalTypeRegister.getFunctionalObject(buf.readString(100));\n linkingTo.deserializeNBT(buf.readCompoundTag());\n\n HashableTuple<String, DataType> input = new HashableTuple<>(buf.readString(100),DataType.getDataType(buf.readString(100)));\n String outputName = buf.readString(100);\n String outputType = buf.readString(100);\n\n return new SymbolLinkMessage(linkingFrom,linkingTo,input,outputName,outputType);\n }\n\n public static void handle(final SymbolLinkMessage msg, final Supplier<NetworkEvent.Context> contextSupplier) {\n final NetworkEvent.Context context = contextSupplier.get();\n if (context.getDirection().equals(NetworkDirection.PLAY_TO_SERVER)) {\n\n context.setPacketHandled(true);\n ServerPlayerEntity sender = context.getSender();\n\n IFunctionalObject realLinkingFrom = null;\n IFunctionalObject realLinkingTo = null;\n IChunk chunk = sender.world.getChunk(msg.linkingFrom.getBlockPos());\n if (chunk instanceof Chunk)\n realLinkingFrom = msg.linkingFrom.findReal((Chunk) chunk);\n chunk = sender.world.getChunk(msg.linkingTo.getBlockPos());\n if (chunk instanceof Chunk)\n realLinkingTo = msg.linkingTo.findReal((Chunk) chunk);\n\n if (realLinkingFrom == null || realLinkingTo == null) return;\n\n HashableTuple<String, DataType> realInput = null;\n for (HashableTuple<String, DataType> input : realLinkingFrom.getInputs()) {\n if (input.getA().equals(msg.input.getA()) && input.getB() == msg.input.getB()) {\n realInput = input;\n break;\n }\n }\n\n IFunctional realOutput = null;\n for (IFunctional output : realLinkingTo.getOutputs()) {\n if (output.getName().equals(msg.outputName) && output.getOutputType().name.equals(msg.outputType)) {\n realOutput = output;\n break;\n }\n }\n\n if (realInput == null || realOutput == null) return;\n\n //TODO inputs not linking properly with this\n realLinkingFrom.getInputLinks().put(realInput, new HashableTuple<>(realLinkingTo, realOutput));\n\n for(PlayerEntity player : ((Chunk)chunk).getWorld().getPlayers())\n {\n if(player.chunkCoordX > chunk.getPos().x - DIRTY_RANGE && player.chunkCoordX < chunk.getPos().x + DIRTY_RANGE &&\n player.chunkCoordZ > chunk.getPos().z - DIRTY_RANGE && player.chunkCoordZ < chunk.getPos().z + DIRTY_RANGE)\n {\n SymbolSyncer.INSTANCE.sendTo( msg, ((ServerPlayerEntity)(player)).connection.netManager, NetworkDirection.PLAY_TO_CLIENT);\n }\n }\n\n }\n else if(context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT))\n {\n context.setPacketHandled(true);\n PlayerEntity sender = RunicArcana.proxy.getPlayer();\n\n IFunctionalObject realLinkingFrom = null;\n IFunctionalObject realLinkingTo = null;\n IChunk chunk = sender.world.getChunk(msg.linkingFrom.getBlockPos());\n if (chunk instanceof Chunk)\n realLinkingFrom = msg.linkingFrom.findReal((Chunk) chunk);\n chunk = sender.world.getChunk(msg.linkingTo.getBlockPos());\n if (chunk instanceof Chunk)\n realLinkingFrom = msg.linkingTo.findReal((Chunk) chunk);\n\n if (realLinkingFrom == null || realLinkingTo == null) return;\n\n HashableTuple<String, DataType> realInput = null;\n for (HashableTuple<String, DataType> input : realLinkingFrom.getInputs()) {\n if (input.getA().equals(msg.input.getA()) && input.getB() == msg.input.getB()) {\n realInput = input;\n }\n }\n\n IFunctional realOutput = null;\n for (IFunctional output : realLinkingTo.getOutputs()) {\n if (output.getName().equals(msg.outputName) && output.getOutputType().name.equals(msg.outputType))\n realOutput = output;\n }\n\n if (realInput == null || realOutput == null) return;\n\n realLinkingFrom.getInputLinks().put(realInput, new HashableTuple<>(realLinkingTo, realOutput));\n }\n }\n }\n\n public static class SymbolSyncMessage\n {\n public ChunkPos chunkPos;\n public ArrayList<DrawnSymbol> symbols;\n\n public SymbolSyncMessage(Chunk chunk, ArrayList<DrawnSymbol> symbols) {\n this.chunkPos = chunk.getPos();\n this.symbols = symbols;\n }\n public SymbolSyncMessage(ChunkPos chunkPos, ArrayList<DrawnSymbol> symbols) {\n this.chunkPos = chunkPos;\n this.symbols = symbols;\n }\n\n public static void encode(final SymbolSyncMessage msg, final PacketBuffer buf)\n {\n buf.writeInt(msg.chunkPos.x);\n buf.writeInt(msg.chunkPos.z);\n buf.writeInt(msg.symbols.size());\n\n ArrayList<String> symbolDict = new ArrayList<String>();\n\n for(DrawnSymbol symbol : msg.symbols)\n {\n if(!symbolDict.contains(symbol.getSymbol().getRegistryName().toString())){\n symbolDict.add(symbol.getSymbol().getRegistryName().toString());\n }\n }\n\n buf.writeInt(symbolDict.size());\n for(int i=0; i<symbolDict.size(); i++)\n {\n buf.writeString(symbolDict.get(i));\n }\n\n for(DrawnSymbol symbol : msg.symbols)\n {\n buf.writeInt(symbolDict.indexOf(symbol.getSymbol().getRegistryName().toString()));\n symbol.encode(buf);\n }\n\n }\n\n public static SymbolSyncMessage decode(final PacketBuffer buf)\n {\n ArrayList<DrawnSymbol> symbols = new ArrayList<DrawnSymbol>();\n ChunkPos chunkPos = new ChunkPos(buf.readInt(),buf.readInt());\n\n int size = buf.readInt();\n\n ArrayList<String> symbolDict = new ArrayList<String>();\n int dictSize = buf.readInt();\n\n for (int i=0; i<dictSize; i++)\n {\n symbolDict.add(buf.readString(100));\n }\n\n for(int i=0; i<size; i++)\n {\n Symbol symbol = RegistryManager.ACTIVE.getRegistry(Symbol.class).getValue(new ResourceLocation(symbolDict.get(buf.readInt())));\n symbols.add(new DrawnSymbol(buf, symbol));\n\n }\n\n return new SymbolSyncMessage(chunkPos, symbols);\n }\n\n public static void handle(final SymbolSyncMessage msg, final Supplier<NetworkEvent.Context> contextSupplier)\n {\n final NetworkEvent.Context context = contextSupplier.get();\n if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT))\n {\n context.enqueueWork(() -> {\n\n //Chunk chunk = sender.getEntityWorld().getChunk(msg.chunkPos.x, msg.chunkPos.z);\n World world = RunicArcana.proxy.getWorld();\n Chunk chunk = world.getChunkProvider().getChunk(msg.chunkPos.x, msg.chunkPos.z, true);\n\n chunk.getCapability(RunicArcana.SYMBOL_CAP).ifPresent(symbolHandler ->{\n symbolHandler.synchronizeSymbols(msg.symbols);\n ((SymbolHandler)symbolHandler).setSynced();\n });\n });\n context.setPacketHandled(true);\n }\n else if (context.getDirection().equals(NetworkDirection.PLAY_TO_SERVER))\n {\n context.enqueueWork(() -> {\n final ServerPlayerEntity sender = context.getSender();\n if (sender == null) {\n return;\n }\n// Chunk chunk = sender.world.getChunk(msg.chunkPos.x, msg.chunkPos.z);\n Chunk chunk = sender.world.getChunkProvider().getChunk(msg.chunkPos.x, msg.chunkPos.z,true);\n chunk.getCapability(RunicArcana.SYMBOL_CAP).ifPresent(symbolHandler -> {\n ArrayList<DrawnSymbol> symbols_ = null;\n symbols_ = symbolHandler.getSymbols();\n if(symbols_ == null)\n symbols_ = new ArrayList<DrawnSymbol>();\n SymbolSyncMessage reply_msg = new SymbolSyncMessage(chunk, symbols_);\n\n INSTANCE.reply(reply_msg, context);\n });\n\n\n });\n context.setPacketHandled(true);\n }\n }\n\n }\n}", "public class SymbolCategory {\n\n public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+\".symbol.category.default\");\n\n private Symbol displaySymbol;\n private final String unlocalizedName;\n\n public static void generateCategories()\n {\n //TODO figure out why static initialization isn't working\n DEFAULT.setDisplaySymbol(Symbols.EXPULSION);\n }\n\n public SymbolCategory(Symbol displaySymbol, String unlocalizedName) {\n this.displaySymbol = displaySymbol;\n this.unlocalizedName = unlocalizedName;\n }\n\n public Symbol getDisplaySymbol() {\n return displaySymbol;\n }\n\n public void setDisplaySymbol(Symbol displaySymbol) {\n this.displaySymbol = displaySymbol;\n }\n\n public String getUnlocalizedName() {\n return unlocalizedName;\n }\n}" ]
import com.latenighters.runicarcana.RunicArcana; import com.latenighters.runicarcana.common.items.ChalkItem; import com.latenighters.runicarcana.common.symbols.Symbols; import com.latenighters.runicarcana.common.symbols.backend.Symbol; import com.latenighters.runicarcana.common.symbols.backend.capability.SymbolSyncer; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.renderer.texture.AtlasTexture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraft.util.text.ITextComponent; import net.minecraftforge.registries.RegistryManager; import java.util.ArrayList;
package com.latenighters.runicarcana.client.gui; public class ScreenChalk extends Screen { private boolean shifting = false; private int categorySelected = 0; private final int guiHeight = 140; private final int guiWidth = 200; public ScreenChalk(ITextComponent titleIn) { super(titleIn); } @Override public void render(int mouseX, int mouseY, float partialTicks) { RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); Minecraft.getInstance().getRenderManager().textureManager.bindTexture(GuiTextures.CHALK_BACKGROUND); TextureAtlasSprite sprite = Minecraft.getInstance().getAtlasSpriteGetter(AtlasTexture.LOCATION_BLOCKS_TEXTURE).apply(GuiTextures.CHALK_BACKGROUND); int xStart = (width-guiWidth)/30; int yStart = (int)((height-guiHeight)*0.95); //drawTexturedModalRect(xStart,yStart,0,0,guiWidth,guiHeight); this.blit(xStart,yStart,0,0,guiWidth,guiHeight); super.render(mouseX, mouseY, partialTicks); } @Override public void init(){ buttons.clear(); PlayerEntity playerEntity = RunicArcana.proxy.getPlayer();
if(playerEntity.getHeldItem(Hand.MAIN_HAND)!=null&&playerEntity.getHeldItem(Hand.MAIN_HAND).getItem() instanceof ChalkItem)
1
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/PrismojiView.java
[ "public interface EmojiCategory {\n /**\n * returns all of the emojis it can display\n *\n * @since 0.4.0\n */\n @NonNull\n Emoji[] getEmojis();\n\n /**\n * returns the icon of the category that should be displayed\n *\n * @since 0.4.0\n */\n @DrawableRes\n int getIcon();\n}", "public interface OnEmojiBackspaceClickListener {\n void onEmojiBackspaceClicked(final View v);\n}", "public interface OnEmojiClickedListener {\n void onEmojiClicked(final Emoji emoji);\n}", "public interface OnEmojiLongClickedListener {\n void onEmojiLongClicked(final View view, final Emoji emoji);\n}", "public final class RepeatListener implements View.OnTouchListener {\n final long normalInterval;\n final View.OnClickListener clickListener;\n\n final Handler handler = new Handler();\n private final long initialInterval;\n View downView;\n\n private final Runnable handlerRunnable = new Runnable() {\n @Override\n public void run() {\n if (downView != null) {\n handler.removeCallbacksAndMessages(downView);\n handler.postAtTime(this, downView, SystemClock.uptimeMillis() + normalInterval);\n clickListener.onClick(downView);\n }\n }\n };\n\n public RepeatListener(final long initialInterval, final long normalInterval,\n final View.OnClickListener clickListener) {\n if (clickListener == null) {\n throw new IllegalArgumentException(\"null runnable\");\n }\n\n if (initialInterval < 0 || normalInterval < 0) {\n throw new IllegalArgumentException(\"negative interval\");\n }\n\n this.initialInterval = initialInterval;\n this.normalInterval = normalInterval;\n this.clickListener = clickListener;\n }\n\n @Override\n @SuppressLint(\"ClickableViewAccessibility\")\n public boolean onTouch(final View view, final MotionEvent motionEvent) {\n switch (motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n handler.removeCallbacks(handlerRunnable);\n handler.postAtTime(handlerRunnable, downView, SystemClock.uptimeMillis() + initialInterval);\n downView = view;\n downView.setPressed(true);\n clickListener.onClick(view);\n return true;\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_OUTSIDE:\n handler.removeCallbacksAndMessages(downView);\n downView.setPressed(false);\n downView = null;\n return true;\n default:\n break;\n }\n\n return false;\n }\n}" ]
import android.annotation.SuppressLint; import android.content.Context; import android.graphics.PorterDuff; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.content.res.AppCompatResources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.apradanas.prismoji.emoji.EmojiCategory; import com.apradanas.prismoji.listeners.OnEmojiBackspaceClickListener; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import com.apradanas.prismoji.listeners.RepeatListener; import java.util.concurrent.TimeUnit;
package com.apradanas.prismoji; @SuppressLint("ViewConstructor") final class PrismojiView extends LinearLayout implements ViewPager.OnPageChangeListener { private static final long INITIAL_INTERVAL = TimeUnit.SECONDS.toMillis(1) / 2; private static final int NORMAL_INTERVAL = 50; @ColorInt private final int themeAccentColor; @ColorInt private final int themeIconColor; private final View[] emojiTabs; private final PrismojiPagerAdapter prismojiPagerAdapter; @Nullable OnEmojiBackspaceClickListener onEmojiBackspaceClickListener; private int emojiTabLastSelectedIndex = -1; PrismojiView(final Context context, final OnEmojiClickedListener onEmojiClickedListener,
final OnEmojiLongClickedListener onEmojiLongClickedListener,
3
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/ExpandedView.java
[ "public interface OverlayCallback {\n\n /**\n * Called to close phial debug window\n */\n void finish();\n\n\n /**\n * Finds view in application view hierarchy\n *\n * @param id view id.\n * @return view or null if view is missing\n */\n @Nullable\n View findViewById(int id);\n}", "public final class Page {\n\n /**\n * Factory that is used to create views when page is selected\n *\n * @param <T> view to display\n */\n public interface PageViewFactory<T extends View & PageView> {\n\n /**\n * @param context android application context\n * @param overlayCallback interface for communication with Phial\n * @return view to display\n */\n T createPageView(Context context, OverlayCallback overlayCallback);\n\n }\n\n private final String id;\n private final int iconResourceId;\n private final CharSequence title;\n private final PageViewFactory pageViewFactory;\n private final Set<TargetScreen> targetScreens;\n\n /**\n * @param id unique pageId\n * @param iconResourceId page icon\n * @param title page title\n * @param pageViewFactory factory that will create view when page is selected\n */\n public Page(\n String id,\n int iconResourceId,\n CharSequence title,\n PageViewFactory pageViewFactory\n ) {\n this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet());\n }\n\n /**\n * @param id unique pageId\n * @param iconResourceId page icon\n * @param title page title\n * @param pageViewFactory factory that will create view when page is selected\n * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty.\n */\n public Page(\n String id,\n int iconResourceId,\n CharSequence title,\n PageViewFactory pageViewFactory,\n Set<TargetScreen> targetScreens\n ) {\n this.id = id;\n this.iconResourceId = iconResourceId;\n this.title = title;\n this.pageViewFactory = pageViewFactory;\n this.targetScreens = Collections.unmodifiableSet(targetScreens);\n }\n\n public String getId() {\n return id;\n }\n\n public int getIconResourceId() {\n return iconResourceId;\n }\n\n public CharSequence getTitle() {\n return title;\n }\n\n public PageViewFactory getPageViewFactory() {\n return pageViewFactory;\n }\n\n public Set<TargetScreen> getTargetScreens() {\n return targetScreens;\n }\n\n}", "public interface PageView {\n\n /**\n * Called when device back button has been pressed\n * @return true if the event was consumed; false otherwise.\n */\n boolean onBackPressed();\n\n}", "public abstract class AnimatorFactory {\n final int x;\n final int y;\n final int startRadius;\n\n AnimatorFactory(View startView) {\n final int width = startView.getWidth();\n final int height = startView.getHeight();\n startRadius = Math.min(width, height) / 2;\n\n int[] location = new int[2];\n startView.getLocationOnScreen(location);\n x = location[0] + width / 2;\n y = location[1] + height / 2;\n }\n\n public static AnimatorFactory createFactory(View startView) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n return new RevealAnimatorFactory(startView);\n } else {\n return new FadeAnimatorFactory(startView);\n }\n }\n\n public abstract Animator createAppearAnimator(View targetView);\n\n public abstract Animator createDisappearAnimator(View targetView);\n\n static int calcRadius(int width, int height) {\n return (int) Math.round(Math.sqrt((float) width * width + height * height));\n }\n}", "public class ArgbEvaluator implements TypeEvaluator {\n private static final ArgbEvaluator INSTANCE = new ArgbEvaluator();\n\n /**\n * Returns an instance of <code>ArgbEvaluator</code> that may be used in\n * {@link android.animation.ValueAnimator#setEvaluator(TypeEvaluator)}. The same instance may\n * be used in multiple <code>Animator</code>s because it holds no state.\n *\n * @return An instance of <code>ArgbEvalutor</code>.\n * @hide\n */\n public static ArgbEvaluator getInstance() {\n return INSTANCE;\n }\n\n /**\n * This function returns the calculated in-between value for a color\n * given integers that represent the start and end values in the four\n * bytes of the 32-bit int. Each channel is separately linearly interpolated\n * and the resulting calculated values are recombined into the return value.\n *\n * @param fraction The fraction from the starting to the ending values\n * @param startValue A 32-bit int value representing colors in the\n * separate bytes of the parameter\n * @param endValue A 32-bit int value representing colors in the\n * separate bytes of the parameter\n * @return A value that is calculated to be the linearly interpolated\n * result, derived by separating the start and end values into separate\n * color channels and interpolating each one separately, recombining the\n * resulting values in the same way.\n */\n public Object evaluate(float fraction, Object startValue, Object endValue) {\n int startInt = (Integer) startValue;\n int startA = (startInt >> 24) & 0xff;\n int startR = (startInt >> 16) & 0xff;\n int startG = (startInt >> 8) & 0xff;\n int startB = startInt & 0xff;\n\n int endInt = (Integer) endValue;\n int endA = (endInt >> 24) & 0xff;\n int endR = (endInt >> 16) & 0xff;\n int endG = (endInt >> 8) & 0xff;\n int endB = endInt & 0xff;\n\n return ((startA + (int) (fraction * (endA - startA))) << 24)\n | ((startR + (int) (fraction * (endR - startR))) << 16)\n | ((startG + (int) (fraction * (endG - startG))) << 8)\n | ((startB + (int) (fraction * (endB - startB))));\n }\n}", "public final class ObjectUtil {\n private ObjectUtil() {\n //to hide\n }\n\n public static <T> boolean equals(T a, T b) {\n return (a == b) || (a != null && a.equals(b));\n }\n}", "public class SimpleAnimatorListener implements Animator.AnimatorListener {\n\n @Override\n public void onAnimationStart(Animator animation) {\n //optional\n }\n\n @Override\n public void onAnimationEnd(Animator animation) {\n //optional\n }\n\n @Override\n public void onAnimationCancel(Animator animation) {\n //optional\n }\n\n @Override\n public void onAnimationRepeat(Animator animation) {\n //optional\n }\n\n public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) {\n return new SimpleAnimatorListener() {\n @Override\n public void onAnimationEnd(Animator animation) {\n runnable.run();\n }\n };\n }\n\n}", "public final class ResourcesCompat {\n private ResourcesCompat() {\n //to hide\n }\n\n @ColorInt\n @SuppressWarnings(\"deprecation\")\n public static int getColor(@NonNull Resources res, @ColorRes int id, @Nullable Resources.Theme theme)\n throws Resources.NotFoundException {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n return res.getColor(id, theme);\n } else {\n return res.getColor(id);\n }\n }\n\n\n @SuppressWarnings(\"deprecation\")\n public static ColorStateList getColorStateList(@NonNull Resources res, @ColorRes int id, @Nullable Resources.Theme theme) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n return res.getColorStateList(id, theme);\n }\n return res.getColorStateList(id);\n }\n}" ]
import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.AnimatorFactory; import com.mindcoders.phial.internal.util.support.ArgbEvaluator; import com.mindcoders.phial.internal.util.ObjectUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.support.ResourcesCompat; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
.setDuration(ANIMATION_DURATION); animator.addListener(SimpleAnimatorListener.createEndListener(() -> { destroyContent(); if (runnable != null) { runnable.run(); } })); animator.start(); } public void destroyContent() { animator.cancel(); setVisibility(INVISIBLE); content = null; contentContainer.removeAllViews(); disposable.dispose(); } private void setupIcons(List<Page> pages, Page selected, boolean animated) { // - 1 in order to not remove settings button iconsHolder.removeViews(0, iconsHolder.getChildCount() - 1); PhialButton selectedButton = null; for (int i = 0; i < pages.size(); i++) { final Page page = pages.get(i); final PhialButton button = new PhialButton(getContext()); button.setTag(page.getId()); button.setIcon(page.getIconResourceId()); final boolean isSelected = ObjectUtil.equals(selected, page); button.setSelected(isSelected); button.setOnClickListener(v -> onTabClicked(button, page)); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); iconsHolder.addView(button, 0, lp); if (isSelected) { selectedButton = button; } } if (selectedButton != null) { final PhialButton finalSelectedButton = selectedButton; disposable.dispose(); disposable = LayoutHelper.onLayout(() -> { setupArrowPosition(finalSelectedButton); if (animated) { animateAppear(); } }, finalSelectedButton, arrow); } } private void setupPage(Page selectedPage) { if (content == null || !ObjectUtil.equals(selectedPage.getId(), content.getTag())) { contentContainer.removeAllViews(); final View view = selectedPage.getPageViewFactory().createPageView(getContext(), callback); content = view; content.setTag(selectedPage.getId()); LayoutParams lp = new LayoutParams(MATCH_PARENT, MATCH_PARENT, Gravity.CENTER); contentContainer.addView(view, lp); } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (!isBackClicked(event)) { return super.dispatchKeyEvent(event); } if (content instanceof PageView) { final PageView pageView = (PageView) content; if (pageView.onBackPressed()) { return true; } } callback.finish(); return true; } private void setupArrowPosition(View target) { float cX = (target.getLeft() + target.getRight()) / 2f; arrow.setX(cX - arrow.getWidth() / 2f); } private void onTabClicked(PhialButton button, Page page) { if (button.isSelected()) { callback.finish(); } else { callback.onPageSelected(page); } } private boolean isBackClicked(KeyEvent event) { return event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_BACK; } private void animateAppear() { setBackgroundResource(BACGROUND_TRANSPARENT_COLOR_RES); final AnimatorSet animator = new AnimatorSet(); animator.playTogether( createRevelAnimator(), createAppearBackgroundAnimator() ); animator.start(); } private Animator createRevelAnimator() { return AnimatorFactory .createFactory(settingsButton) .createAppearAnimator(this) .setDuration(ANIMATION_DURATION); } private Animator createAppearBackgroundAnimator() {
int startColor = ResourcesCompat.getColor(getResources(),
7
bodar/yatspec
src/com/googlecode/yatspec/rendering/html/index/HtmlIndexRenderer.java
[ "public interface SpecResultListener {\n void complete(File yatspecOutputDir, Result result) throws Exception;\n}", "public interface Content {\n String toString();\n}", "public class ContentAtUrl implements Content {\n private final URL url;\n\n public ContentAtUrl(URL url) {\n this.url = url;\n }\n\n @Override\n public String toString() {\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n return Strings.toString(inputStream);\n } catch (IOException e) {\n return e.toString();\n } finally {\n closeQuietly(inputStream);\n }\n }\n\n private static void closeQuietly(InputStream inputStream) {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}", "public class Index {\n private final List<Result> files = new CopyOnWriteArrayList<Result>();\n\n public Index add(Result result) {\n files.add(result);\n return this;\n }\n\n public Sequence<Result> entries() {\n return sequence(files);\n }\n}", "public class HtmlResultRenderer implements SpecResultListener {\n private final List<Pair<Predicate, Renderer>> customRenderers = new ArrayList<Pair<Predicate, Renderer>>();\n\n private List<Content> customScripts = Collections.emptyList();\n private List<Content> customHeaderContents = Collections.emptyList();\n\n @Override\n public void complete(File yatspecOutputDir, Result result) throws Exception {\n overwrite(htmlResultFile(yatspecOutputDir, result.getTestClass()), render(result));\n }\n\n public String render(Result result) throws Exception {\n final EnhancedStringTemplateGroup group = new EnhancedStringTemplateGroup(getClass());\n group.registerRenderer(always().and(not(instanceOf(Number.class))), Xml.escape());\n group.registerRenderer(instanceOf(ScenarioTableHeader.class), callable(new ScenarioTableHeaderRenderer()));\n group.registerRenderer(instanceOf(JavaSource.class), callable(new JavaSourceRenderer()));\n group.registerRenderer(instanceOf(Notes.class), callable(new NotesRenderer()));\n group.registerRenderer(instanceOf(LinkingNote.class), callable(new LinkingNoteRenderer(result.getTestClass())));\n group.registerRenderer(instanceOf(ContentAtUrl.class), asString());\n sequence(customRenderers).fold(group, registerRenderer());\n for (Class document : Creator.optionalClass(\"org.jdom.Document\")) {\n group.registerRenderer(instanceOf(document), callable(Creator.<Renderer>create(Class.forName(\"com.googlecode.yatspec.plugin.jdom.DocumentRenderer\"))));\n }\n\n final StringTemplate template = group.getInstanceOf(\"yatspec\");\n template.setAttribute(\"script\", loadContent(\"xregexp.js\"));\n template.setAttribute(\"script\", loadContent(\"yatspec.js\"));\n for (Content customScript : customScripts) {\n template.setAttribute(\"script\", customScript);\n }\n for (Content customHeaderContent : customHeaderContents) {\n template.setAttribute(\"customHeaderContent\", customHeaderContent);\n }\n template.setAttribute(\"stylesheet\", loadContent(\"yatspec.css\"));\n template.setAttribute(\"cssClass\", getCssMap());\n template.setAttribute(\"testResult\", result);\n StringWriter writer = new StringWriter();\n template.write(new NoIndentWriter(writer));\n return writer.toString();\n }\n\n public <T> HtmlResultRenderer withCustomRenderer(Class<T> klazz, Renderer<T> renderer) {\n return withCustomRenderer((Predicate) instanceOf(klazz), renderer);\n }\n\n public <T> HtmlResultRenderer withCustomRenderer(Predicate<T> predicate, Renderer<T> renderer) {\n customRenderers.add(Pair.<Predicate, Renderer>pair(predicate, renderer));\n return this;\n }\n\n public static <T> Callable1<T, String> callable(final Renderer<T> value) {\n return new Callable1<T, String>() {\n @Override\n public String call(T o) throws Exception {\n return value.render(o);\n }\n };\n }\n\n public static Content loadContent(final String resource) throws IOException {\n return new ContentAtUrl(HtmlResultRenderer.class.getResource(resource));\n }\n\n public static Map<Status, String> getCssMap() {\n return new HashMap<Status, String>() {{\n put(Status.Passed, \"test-passed\");\n put(Status.Failed, \"test-failed\");\n put(Status.NotRun, \"test-not-run\");\n }};\n }\n\n public static String htmlResultRelativePath(Class resultClass) {\n return Files.toPath(resultClass) + \".html\";\n }\n\n public static File htmlResultFile(File outputDirectory, Class resultClass) {\n return new File(outputDirectory, htmlResultRelativePath(resultClass));\n }\n\n public static String testMethodRelativePath(TestMethod testMethod) {\n return format(\"%s#%s\",\n htmlResultRelativePath(testMethod.getTestClass()),\n testMethod.getName());\n }\n\n public HtmlResultRenderer withCustomHeaderContent(Content... content) {\n this.customHeaderContents = Arrays.asList(content);\n return this;\n }\n\n public HtmlResultRenderer withCustomScripts(Content... scripts) {\n this.customScripts = Arrays.asList(scripts);\n return this;\n }\n}", "public interface Result {\n\n List<TestMethod> getTestMethods() throws Exception;\n\n Class<?> getTestClass();\n\n Scenario getScenario(String name) throws Exception;\n\n String getName();\n\n String getPackageName();\n\n}", "public static void overwrite(File output, String content) throws Exception {\n output.delete();\n output.getParentFile().mkdirs();\n write(content.getBytes(\"UTF-8\"), output);\n System.out.println(\"Yatspec output:\\n\" + output);\n}", "public static Map<Status, String> getCssMap() {\n return new HashMap<Status, String>() {{\n put(Status.Passed, \"test-passed\");\n put(Status.Failed, \"test-failed\");\n put(Status.NotRun, \"test-not-run\");\n }};\n}" ]
import com.googlecode.funclate.stringtemplate.EnhancedStringTemplateGroup; import com.googlecode.yatspec.junit.SpecResultListener; import com.googlecode.yatspec.rendering.Content; import com.googlecode.yatspec.rendering.ContentAtUrl; import com.googlecode.yatspec.rendering.Index; import com.googlecode.yatspec.rendering.html.HtmlResultRenderer; import com.googlecode.yatspec.state.Result; import org.antlr.stringtemplate.StringTemplate; import java.io.File; import static com.googlecode.funclate.Model.mutable.model; import static com.googlecode.yatspec.parsing.Files.overwrite; import static com.googlecode.yatspec.rendering.html.HtmlResultRenderer.getCssMap;
package com.googlecode.yatspec.rendering.html.index; public class HtmlIndexRenderer implements SpecResultListener { private final static Index index = new Index(); @Override public void complete(File yatspecOutputDir, Result result) throws Exception { index.add(result);
overwrite(outputFile(yatspecOutputDir), render(yatspecOutputDir, index));
6
Techjar/VivecraftForgeExtensions
src/main/java/com/techjar/vivecraftforge/network/packet/PacketVRSettings.java
[ "@Mod(modid = \"VivecraftForge\", name = \"Vivecraft Forge Extensions\", version = \"@VERSION@\", dependencies = \"required-after:Forge@[10.13.4.1558,)\", acceptableRemoteVersions = \"@RAW_VERSION@.*\")\npublic class VivecraftForge {\n\t@Instance(\"VivecraftForge\")\n\tpublic static VivecraftForge instance;\n\t\n\t@SidedProxy(clientSide = \"com.techjar.vivecraftforge.proxy.ProxyClient\", serverSide = \"com.techjar.vivecraftforge.proxy.ProxyServer\")\n\tpublic static ProxyCommon proxy;\n\n\tpublic static SimpleNetworkWrapper networkVersion;\n\t//public static SimpleNetworkWrapper networkFreeMove; // currently not used\n\tpublic static SimpleNetworkWrapper networkLegacy;\n\tpublic static SimpleNetworkWrapper networkOK;\n\t\n\tpublic static VivecraftForgeChannelHandler packetPipeline;\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event) {\n\t\tConfiguration config = new Configuration(event.getSuggestedConfigurationFile());\n\t\tconfig.load();\n\t\tConfig.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, \"vrCreeperSwellDistance\", 1.75, \"Distance at which creepers swell and explode for VR players. Default: 1.75\").getDouble(1.75D);\n\t\tif (config.hasChanged()) config.save();\n\t}\n\n\t@EventHandler\n\tpublic void load(FMLInitializationEvent event) {\n\t\tpacketPipeline = VivecraftForgeChannelHandler.init();\n\t\tproxy.registerNetworkChannels();\n\t\tproxy.registerEventHandlers();\n\t\tproxy.registerEntities();\n\t\tproxy.registerRenderers();\n\t}\n\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event) {\n\t\t// Stub Method\n\t}\n}", "public abstract class EntityVRObject extends Entity implements IEntityAdditionalSpawnData {\n\tpublic Vec3 position = Vec3.createVectorHelper(0, 0, 0);\n\tpublic Vec3 positionLast = Vec3.createVectorHelper(0, 0, 0);\n\tpublic float rotW = 1, rotX, rotY, rotZ;\n\tpublic float rotWLast = 1, rotXLast, rotYLast, rotZLast;\n\tprotected int associatedEntityId;\n\tprotected EntityPlayer entityPlayer;\n\tprivate boolean spawned;\n\t\n\tpublic EntityVRObject(World world) {\n\t\tthis(world, -1);\n\t}\n\t\n\tpublic EntityVRObject(World world, int associatedEntityId) {\n\t\tsuper(world);\n\t\tthis.associatedEntityId = associatedEntityId;\n\t\tthis.ignoreFrustumCheck = true;\n\t\tthis.renderDistanceWeight = 10.0D;\n\t}\n\n\t@Override\n\tprotected void entityInit() {\n\t\tdataWatcher.addObject(2, 0F);\n\t\tdataWatcher.addObject(3, 0F);\n\t\tdataWatcher.addObject(4, 0F);\n\t\tdataWatcher.addObject(5, 0F);\n\t\tdataWatcher.addObject(6, 0F);\n\t\tdataWatcher.addObject(7, 0F);\n\t\tdataWatcher.addObject(8, 0F);\n\t}\n\t\n\t@Override\n\tpublic void onUpdate() {\n\t\tif (!worldObj.isRemote) {\n\t\t\tif (getEntityPlayer() == null || getEntityPlayer().isDead) {\n\t\t\t\tthis.setDead();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdataWatcher.updateObject(2, (float)position.xCoord);\n\t\t\tdataWatcher.updateObject(3, (float)position.yCoord);\n\t\t\tdataWatcher.updateObject(4, (float)position.zCoord);\n\t\t\tdataWatcher.updateObject(5, (float)rotW);\n\t\t\tdataWatcher.updateObject(6, (float)rotX);\n\t\t\tdataWatcher.updateObject(7, (float)rotY);\n\t\t\tdataWatcher.updateObject(8, (float)rotZ);\n\t\t}\n\t\telse {\n\t\t\tpositionLast.xCoord = position.xCoord;\n\t\t\tpositionLast.yCoord = position.yCoord;\n\t\t\tpositionLast.zCoord = position.zCoord;\n\t\t\trotWLast = rotW;\n\t\t\trotXLast = rotX;\n\t\t\trotYLast = rotY;\n\t\t\trotZLast = rotZ;\n\t\t\tposition.xCoord = dataWatcher.getWatchableObjectFloat(2);\n\t\t\tposition.yCoord = dataWatcher.getWatchableObjectFloat(3);\n\t\t\tposition.zCoord = dataWatcher.getWatchableObjectFloat(4);\n\t\t\trotW = dataWatcher.getWatchableObjectFloat(5);\n\t\t\trotX = dataWatcher.getWatchableObjectFloat(6);\n\t\t\trotY = dataWatcher.getWatchableObjectFloat(7);\n\t\t\trotZ = dataWatcher.getWatchableObjectFloat(8);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void readEntityFromNBT(NBTTagCompound p_70037_1_) {\n\t}\n\n\t@Override\n\tprotected void writeEntityToNBT(NBTTagCompound p_70014_1_) {\n\t}\n\t\n\t@Override\n\tpublic void writeSpawnData(ByteBuf buf) {\n\t\tbuf.writeInt(associatedEntityId);\n\t\tbuf.writeFloat((float)position.xCoord);\n\t\tbuf.writeFloat((float)position.yCoord);\n\t\tbuf.writeFloat((float)position.zCoord);\n\t\tbuf.writeFloat((float)rotW);\n\t\tbuf.writeFloat((float)rotX);\n\t\tbuf.writeFloat((float)rotY);\n\t\tbuf.writeFloat((float)rotZ);\n\t}\n\n\t@Override\n\tpublic void readSpawnData(ByteBuf buf) {\n\t\tassociatedEntityId = buf.readInt();\n\t\tposition.xCoord = positionLast.xCoord = buf.readFloat();\n\t\tposition.yCoord = positionLast.yCoord = buf.readFloat();\n\t\tposition.zCoord = positionLast.zCoord = buf.readFloat();\n\t\trotW = rotWLast = buf.readFloat();\n\t\trotX = rotXLast = buf.readFloat();\n\t\trotY = rotYLast = buf.readFloat();\n\t\trotZ = rotZLast = buf.readFloat();\n\t}\n\t\n\t@Override\n\tpublic void setPosition(double x, double y, double z) {\n\t\tthis.posX = x;\n\t\tthis.posY = y;\n\t\tthis.posZ = z;\n\t}\n\n\t@SideOnly(Side.CLIENT)\n\tpublic boolean isInRangeToRenderDist(double dist) {\n\t\treturn true;\n\t}\n\n\tpublic EntityPlayer getEntityPlayer() {\n\t\tif (entityPlayer == null) {\n\t\t\tentityPlayer = (EntityPlayer)worldObj.getEntityByID(associatedEntityId);\n\t\t}\n\t\treturn entityPlayer;\n\t}\n\t\n\tpublic boolean isSpawned() {\n\t\treturn spawned;\n\t}\n\t\n\tpublic void setSpawned() {\n\t\tspawned = true;\n\t}\n\t\n\t@SideOnly(Side.CLIENT)\n\tpublic Quaternion getRotation() {\n\t\treturn new Quaternion(rotW, rotX, rotY, rotZ);\n\t}\n\t\n\t@SideOnly(Side.CLIENT)\n\tpublic Quaternion getRotationLast() {\n\t\treturn new Quaternion(rotWLast, rotXLast, rotYLast, rotZLast);\n\t}\n}", "public interface IPacket {\n\tpublic void encodePacket(ChannelHandlerContext context, ByteBuf buffer);\n\n\tpublic void decodePacket(ChannelHandlerContext context, ByteBuf buffer);\n\n\tpublic void handleClient(EntityPlayer player);\n\n\tpublic void handleServer(EntityPlayer player);\n}", "public class ProxyClient extends ProxyCommon {\n\tpublic static boolean isVFEServer;\n\tpublic static boolean reverseHandsLast;\n\tpublic static float worldScaleLast;\n\tpublic static boolean seatedLast;\n\tpublic static Map<Integer, VRPlayerData> vrPlayerIds = new HashMap<Integer, VRPlayerData>();\n\n\t@Override\n\tpublic void registerRenderers() {\n\t\tthis.registerEntityRenderers();\n\t}\n\n\t@Override\n\tpublic void registerEventHandlers() {\n\t\tsuper.registerEventHandlers();\n\t\tMinecraftForge.EVENT_BUS.register(new HandlerRenderEvent());\n\t\tFMLCommonHandler.instance().bus().register(new HandlerClientTick());\n\t}\n\n\t@Override\n\tpublic EntityPlayer getPlayerFromNetHandler(INetHandler netHandler) {\n\t\tif (netHandler instanceof NetHandlerPlayServer) {\n\t\t\treturn ((NetHandlerPlayServer)netHandler).playerEntity;\n\t\t}\n\t\treturn FMLClientHandler.instance().getClientPlayerEntity();\n\t}\n\n\tprivate void registerEntityRenderers() {\n\t\tRenderingRegistry.registerEntityRenderingHandler(EntityVRHead.class, new RenderEntityVRHead());\n\t\tRenderingRegistry.registerEntityRenderingHandler(EntityVRMainArm.class, new RenderEntityVRMainArm());\n\t\tRenderingRegistry.registerEntityRenderingHandler(EntityVROffHandArm.class, new RenderEntityVROffHandArm());\n\t}\n\n\tpublic static boolean isVRPlayer(EntityPlayer entity) {\n\t\treturn entity != Minecraft.getMinecraft().thePlayer && ProxyClient.vrPlayerIds.containsKey(entity.getEntityId());\n\t}\n\n\tpublic static float getVRPlayerHeadHeight(EntityPlayer entity) {\n\t\tVRPlayerData data = ProxyClient.vrPlayerIds.get(entity.getEntityId());\n\t\tif (data != null && data.entityIds.size() > 0) {\n\t\t\tEntityVRObject entityVR = (EntityVRObject)entity.worldObj.getEntityByID(data.entityIds.get(0));\n\t\t\tif (entityVR != null) {\n\t\t\t\treturn (float)entityVR.position.yCoord;\n\t\t\t}\n\t\t}\n\t\treturn (float)entity.posY + 1.62F;\n\t}\n\n\tpublic static float getVRPlayerScale(EntityPlayer entity) {\n\t\tfloat height = getVRPlayerHeadHeight((EntityPlayer)entity) - 0.125F;\n\t\treturn Math.max((height - (float)entity.posY) / 1.62F, 0.1F);\n\t}\n\n\tpublic static float getVRPlayerWorldScale(EntityPlayer entity) {\n\t\tVRPlayerData data = ProxyClient.vrPlayerIds.get(entity.getEntityId());\n\t\tif (data != null) {\n\t\t\treturn data.worldScale;\n\t\t}\n\t\treturn 1;\n\t}\n\n\tpublic static boolean getVRPlayerSeated(EntityPlayer entity) {\n\t\tVRPlayerData data = ProxyClient.vrPlayerIds.get(entity.getEntityId());\n\t\tif (data != null) {\n\t\t\treturn data.seated;\n\t\t}\n\t\treturn false;\n\t}\n}", "public class ProxyServer extends ProxyCommon {\n\tpublic static Map<EntityPlayer, VRPlayerData> vrPlayers = new HashMap<EntityPlayer, VRPlayerData>();\n\t\n\t@Override\n\tpublic void registerNetworkChannels() {\n\t\tsuper.registerNetworkChannels();\n\t\tVivecraftForge.networkVersion = NetworkRegistry.INSTANCE.newSimpleChannel(\"MC|Vive|Version\");\n\t\t//VivecraftForge.networkFreeMove = NetworkRegistry.INSTANCE.newSimpleChannel(\"MC|Vive|FreeMove\"); // currently not used\n\t\tVivecraftForge.networkLegacy = NetworkRegistry.INSTANCE.newSimpleChannel(\"MC|Vive\");\n\t\tVivecraftForge.networkOK = NetworkRegistry.INSTANCE.newSimpleChannel(\"MC|ViveOK\");\n\t\tVivecraftForge.networkVersion.registerMessage(ViveMessage.Handle.class, ViveMessage.class, 86, Side.SERVER);\n\t\tVivecraftForge.networkLegacy.registerMessage(ViveMessage.Handle.class, ViveMessage.class, 112, Side.SERVER);\n\t}\n\n\tpublic static boolean isVRPlayer(EntityPlayer entity) {\n\t\treturn ProxyServer.vrPlayers.containsKey(entity);\n\t}\n\t\n\tpublic static boolean getVRPlayerSeated(EntityPlayer entity) {\n\t\tVRPlayerData data = ProxyServer.vrPlayers.get(entity);\n\t\tif (data != null) {\n\t\t\treturn data.seated;\n\t\t}\n\t\treturn false;\n\t}\n}", "public class VRPlayerData {\n\t/**\n\t * Only on server\n\t */\n\tpublic List<EntityVRObject> entities = new ArrayList<EntityVRObject>(3);\n\tpublic List<Integer> entityIds = new ArrayList<Integer>(3);\n\tpublic boolean newAPI;\n\tpublic boolean reverseHands;\n\tpublic float worldScale = 1;\n\tpublic boolean seated;\n\n\tpublic VRPlayerData copy() {\n\t\tVRPlayerData data = new VRPlayerData();\n\t\tdata.newAPI = newAPI;\n\t\tdata.reverseHands = reverseHands;\n\t\tdata.worldScale = worldScale;\n\t\tdata.seated = seated;\n\t\tdata.entities = new ArrayList<EntityVRObject>(entities);\n\t\tdata.entityIds = new ArrayList<Integer>(entityIds);\n\t\treturn data;\n\t}\n}", "public class VivecraftForgeLog {\n\tpublic static void info(String message, Object... data) {\n\t\tFMLRelaunchLog.log(\"Vivecraft Forge Extensions\", Level.INFO, message, data);\n\t}\n\n\tpublic static void warning(String message, Object... data) {\n\t\tFMLRelaunchLog.log(\"Vivecraft Forge Extensions\", Level.WARN, message, data);\n\t}\n\n\tpublic static void severe(String message, Object... data) {\n\t\tFMLRelaunchLog.log(\"Vivecraft Forge Extensions\", Level.ERROR, message, data);\n\t}\n\n\tpublic static void debug(String message, Object... data) {\n\t\tFMLRelaunchLog.log(\"Vivecraft Forge Extensions\", Level.DEBUG, message, data);\n\t}\n}", "@SideOnly(Side.CLIENT)\npublic class VivecraftReflector {\n\tprivate VivecraftReflector() {\n\t}\n\n\t// Stupid JRift Matrix4f\n\tprivate static Field field_M;\n\t// New API\n\tprivate static Method method_getHMDPos_World;\n\tprivate static Method method_getHMDMatrix_World;\n\tprivate static Method method_getControllerPos_World;\n\tprivate static Method method_getControllerMatrix_World;\n\tprivate static Field field_vrPlayer;\n\t// Old API\n\tprivate static Method method_getCameraLocation;\n\tprivate static Method method_getAimSource;\n\tprivate static Method method_getAimRotation;\n\tprivate static Field field_lookaimController;\n\tprivate static Field field_hmdPose;\n\t// Other stuff\n\tprivate static Field field_vrSettings;\n\tprivate static Field field_vrReverseHands;\n\tprivate static Field field_vrWorldScale;\n\tprivate static Field field_seated;\n\tprivate static boolean field_seated_exists = true;\n\tprivate static boolean installed;\n\tprivate static boolean newAPI;\n\tstatic {\n\t\ttry {\n\t\t\tClass.forName(\"com.mtbs3d.minecrift.provider.MCOpenVR\");\n\t\t\tinstalled = true;\n\t\t\tVivecraftForgeLog.debug(\"Vivecraft is installed.\");\n\t\t} catch (ClassNotFoundException ex) {\n\t\t\tinstalled = false;\n\t\t\tVivecraftForgeLog.debug(\"Vivecraft is not installed.\");\n\t\t}\n\t\tif (installed) {\n\t\t\ttry {\n\t\t\t\tClass.forName(\"com.mtbs3d.minecrift.api.IRoomscaleAdapter\");\n\t\t\t\tnewAPI = true;\n\t\t\t\tVivecraftForgeLog.debug(\"Vivecraft is new API.\");\n\t\t\t} catch (ClassNotFoundException ex) {\n\t\t\t\tnewAPI = false;\n\t\t\t\tVivecraftForgeLog.debug(\"Vivecraft is old API.\");\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean isInstalled() {\n\t\treturn installed;\n\t}\n\n\tpublic static boolean isNewAPI() {\n\t\treturn newAPI;\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static boolean getReverseHands() {\n\t\tif (field_vrReverseHands == null) {\n\t\t\tfield_vrReverseHands = Class.forName(\"com.mtbs3d.minecrift.settings.VRSettings\").getDeclaredField(\"vrReverseHands\");\n\t\t}\n\t\treturn field_vrReverseHands.getBoolean(getVRSettings());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static float getWorldScale() {\n\t\tif (field_vrWorldScale == null) {\n\t\t\tfield_vrWorldScale = Class.forName(\"com.mtbs3d.minecrift.settings.VRSettings\").getDeclaredField(\"vrWorldScale\");\n\t\t}\n\t\treturn field_vrWorldScale.getFloat(getVRSettings());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static boolean getSeated() {\n\t\tif (!field_seated_exists) return false;\n\t\tif (field_seated == null) {\n\t\t\ttry {\n\t\t\t\tfield_seated = Class.forName(\"com.mtbs3d.minecrift.settings.VRSettings\").getDeclaredField(\"seated\");\n\t\t\t} catch (NoSuchFieldException ex) {\n\t\t\t\tfield_seated_exists = false;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn field_seated.getBoolean(getVRSettings());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static Object getVRSettings() {\n\t\tif (field_vrSettings == null) {\n\t\t\tfield_vrSettings = Minecraft.class.getDeclaredField(\"vrSettings\");\n\t\t}\n\t\treturn field_vrSettings.get(Minecraft.getMinecraft());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static Vec3 getHeadPosition() {\n\t\tif (newAPI) {\n\t\t\tif (method_getHMDPos_World == null) {\n\t\t\t\tmethod_getHMDPos_World = Class.forName(\"com.mtbs3d.minecrift.api.IRoomscaleAdapter\").getMethod(\"getHMDPos_World\");\n\t\t\t}\n\t\t\treturn (Vec3)method_getHMDPos_World.invoke(getVRPlayer());\n\t\t} else {\n\t\t\tif (method_getCameraLocation == null) {\n\t\t\t\tmethod_getCameraLocation = EntityRenderer.class.getDeclaredMethod(\"getCameraLocation\");\n\t\t\t}\n\t\t\treturn (Vec3)method_getCameraLocation.invoke(Minecraft.getMinecraft().entityRenderer);\n\t\t}\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tpublic static Matrix4f getHeadRotation() {\n\t\tif (newAPI) {\n\t\t\tif (method_getHMDMatrix_World == null) {\n\t\t\t\tmethod_getHMDMatrix_World = Class.forName(\"com.mtbs3d.minecrift.api.IRoomscaleAdapter\").getMethod(\"getHMDMatrix_World\");\n\t\t\t}\n\t\t\tFloatBuffer buffer = (FloatBuffer)method_getHMDMatrix_World.invoke(getVRPlayer());\n\t\t\tbuffer.rewind();\n\t\t\tMatrix4f matrix = new Matrix4f();\n\t\t\tmatrix.load(buffer);\n\t\t\treturn matrix;\n\t\t} else {\n\t\t\tif (field_hmdPose == null) {\n\t\t\t\tfield_hmdPose = Class.forName(\"com.mtbs3d.minecrift.provider.MCOpenVR\").getDeclaredField(\"hmdPose\");\n\t\t\t\tfield_hmdPose.setAccessible(true);\n\t\t\t}\n\t\t\treturn convertMatrix(field_hmdPose.get(null));\n\t\t}\n\t}\n\n\t/**\n\t * 0 for main, 1 for off-hand\n\t */\n\t@SneakyThrows(Exception.class)\n\tpublic static Vec3 getControllerPositon(int controller) {\n\t\tif (newAPI) {\n\t\t\tif (method_getControllerPos_World == null) {\n\t\t\t\tmethod_getControllerPos_World = Class.forName(\"com.mtbs3d.minecrift.api.IRoomscaleAdapter\").getMethod(\"getControllerPos_World\", Integer.TYPE);\n\t\t\t}\n\t\t\treturn (Vec3)method_getControllerPos_World.invoke(getVRPlayer(), controller);\n\t\t} else {\n\t\t\tif (method_getAimSource == null) {\n\t\t\t\tmethod_getAimSource = Class.forName(\"com.mtbs3d.minecrift.api.IBodyAimController\").getDeclaredMethod(\"getAimSource\", Integer.TYPE);\n\t\t\t}\n\t\t\treturn (Vec3)method_getAimSource.invoke(getAimController(), controller);\n\t\t}\n\t}\n\n\t/**\n\t * 0 for main, 1 for off-hand\n\t */\n\t@SneakyThrows(Exception.class)\n\tpublic static Matrix4f getControllerRotation(int controller) {\n\t\tif (newAPI) {\n\t\t\tif (method_getControllerMatrix_World == null) {\n\t\t\t\tmethod_getControllerMatrix_World = Class.forName(\"com.mtbs3d.minecrift.api.IRoomscaleAdapter\").getMethod(\"getControllerMatrix_World\", Integer.TYPE);\n\t\t\t}\n\t\t\tFloatBuffer buffer = (FloatBuffer)method_getControllerMatrix_World.invoke(getVRPlayer(), controller);\n\t\t\tbuffer.rewind();\n\t\t\tMatrix4f matrix = new Matrix4f();\n\t\t\tmatrix.load(buffer);\n\t\t\tmatrix.transpose();\n\t\t\treturn matrix;\n\t\t} else {\n\t\t\tif (method_getAimRotation == null) {\n\t\t\t\tmethod_getAimRotation = Class.forName(\"com.mtbs3d.minecrift.api.IBodyAimController\").getDeclaredMethod(\"getAimRotation\", Integer.TYPE);\n\t\t\t}\n\t\t\treturn convertMatrix(method_getAimRotation.invoke(getAimController(), controller));\n\t\t}\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tprivate static Object getAimController() {\n\t\tif (field_lookaimController == null) {\n\t\t\tfield_lookaimController = Minecraft.class.getDeclaredField(\"lookaimController\");\n\t\t}\n\t\treturn field_lookaimController.get(Minecraft.getMinecraft());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tprivate static Object getVRPlayer() {\n\t\tif (field_vrPlayer == null) {\n\t\t\tfield_vrPlayer = Minecraft.class.getDeclaredField(\"vrPlayer\");\n\t\t}\n\t\treturn field_vrPlayer.get(Minecraft.getMinecraft());\n\t}\n\n\t@SneakyThrows(Exception.class)\n\tprivate static Matrix4f convertMatrix(Object object) {\n\t\tif (field_M == null) {\n\t\t\tfield_M = Class.forName(\"de.fruitfly.ovr.structs.Matrix4f\").getDeclaredField(\"M\");\n\t\t\tfield_M.setAccessible(true);\n\t\t}\n\t\tfloat[][] array = (float[][])field_M.get(object);\n\t\tMatrix4f matrix = new Matrix4f();\n\t\tmatrix.m00 = array[0][0];\n\t\tmatrix.m01 = array[0][1];\n\t\tmatrix.m02 = array[0][2];\n\t\tmatrix.m03 = array[0][3];\n\t\tmatrix.m10 = array[1][0];\n\t\tmatrix.m11 = array[1][1];\n\t\tmatrix.m12 = array[1][2];\n\t\tmatrix.m13 = array[1][3];\n\t\tmatrix.m20 = array[2][0];\n\t\tmatrix.m21 = array[2][1];\n\t\tmatrix.m22 = array[2][2];\n\t\tmatrix.m23 = array[2][3];\n\t\tmatrix.m30 = array[3][0];\n\t\tmatrix.m31 = array[3][1];\n\t\tmatrix.m32 = array[3][2];\n\t\tmatrix.m33 = array[3][3];\n\t\treturn Matrix4f.transpose(matrix, matrix);\n\t}\n}" ]
import java.util.ArrayList; import com.techjar.vivecraftforge.VivecraftForge; import com.techjar.vivecraftforge.entity.EntityVRObject; import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.proxy.ProxyClient; import com.techjar.vivecraftforge.proxy.ProxyServer; import com.techjar.vivecraftforge.util.VRPlayerData; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import com.techjar.vivecraftforge.util.VivecraftReflector; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.network.ByteBufUtils;
package com.techjar.vivecraftforge.network.packet; public class PacketVRSettings implements IPacket { public boolean reverseHands; public float scale; public boolean seated; public PacketVRSettings() { } public PacketVRSettings(boolean reverseHands, float scale, boolean seated) { this.reverseHands = reverseHands; this.scale = scale; this.seated = seated; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(this.reverseHands); buffer.writeFloat(this.scale); buffer.writeBoolean(this.seated); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { this.reverseHands = buffer.readBoolean(); this.scale = buffer.readFloat(); this.seated = buffer.readBoolean(); } @Override public void handleClient(EntityPlayer player) { } @Override public void handleServer(EntityPlayer player) { if (ProxyServer.vrPlayers.containsKey(player)) { VRPlayerData data = ProxyServer.vrPlayers.get(player); data.reverseHands = reverseHands; data.worldScale = scale; data.seated = seated;
VivecraftForge.packetPipeline.sendToAll(new PacketVRPlayerList(ProxyServer.vrPlayers));
0
mru00/cutlet
CutletLib/src/main/java/com/cutlet/lib/optimizer/SAOptimizationStrategy.java
[ "@ToString(exclude = \"sheet\")\r\npublic class PanelInstance implements Serializable {\r\n\r\n private final String title;\r\n private final StockSheet sheet;\r\n private final Dimension dimension;\r\n private final boolean canRotate;\r\n private final int instanceId;\r\n\r\n public String getTitle() {\r\n return title;\r\n }\r\n\r\n public PanelInstance(@NonNull final StockSheet sheet,\r\n @NonNull final Dimension dimension,\r\n @NonNull final String title,\r\n final int instanceId,\r\n final boolean canRotate) {\r\n\r\n this.sheet = sheet;\r\n this.title = title;\r\n this.dimension = dimension;\r\n this.canRotate = canRotate;\r\n this.instanceId = instanceId;\r\n\r\n if (dimension.getWidth() > sheet.getDimension().getWidth() || dimension.getLength() > sheet.getDimension().getLength()) {\r\n throw new RuntimeException(\"panel too large for sheet\");\r\n }\r\n }\r\n\r\n public StockSheet getSheet() {\r\n return sheet;\r\n }\r\n\r\n public Dimension getDimension() {\r\n return dimension;\r\n }\r\n\r\n public int getInstanceId() {\r\n return instanceId;\r\n }\r\n}\r", "public class Project implements Serializable {\r\n\r\n private List<Panel> panels = new ArrayList<>();\r\n private double bladeWidth = 3;\r\n private Optional<OptimizationResult> optimizationResult;\r\n\r\n public List<Panel> getPanels() {\r\n return panels;\r\n }\r\n\r\n public void setPanels(@NonNull final List<Panel> inputs) {\r\n this.panels = inputs;\r\n }\r\n\r\n public double getBladeWidth() {\r\n return bladeWidth;\r\n }\r\n\r\n public void setBladeWidth(final double bladeWidth) {\r\n checkArgument(bladeWidth >= 0, \"bladeWidth can't be negative\");\r\n this.bladeWidth = bladeWidth;\r\n }\r\n\r\n public Optional<OptimizationResult> getOptimizationResult() {\r\n return optimizationResult;\r\n }\r\n\r\n public void setOptimizationResult(@NonNull final Optional<OptimizationResult> optimizationResult) {\r\n this.optimizationResult = optimizationResult;\r\n }\r\n\r\n public void setOptimizationResult(java.util.Optional<OptimizationResult> newValue) {\r\n if (newValue.isPresent()) {\r\n this.optimizationResult = Optional.of(newValue.get());\r\n\r\n } else {\r\n this.optimizationResult = Optional.absent();\r\n\r\n }\r\n }\r\n\r\n public List<PanelInstance> getPanelInstances() {\r\n List<PanelInstance> pis = new ArrayList<>();\r\n for (Panel p : panels) {\r\n for (int i = 0; i < p.getCount(); i++) {\r\n pis.add(new PanelInstance(p.getSheet(), p.getDimension(), p.getTitle(), i, p.canRotate()));\r\n }\r\n }\r\n return pis;\r\n }\r\n}\r", "public class FreeNode extends AbstractCutTreeNode {\r\n\r\n public FreeNode(@NonNull CutTreeNode parent, @NonNull Position position, @NonNull Dimension dimension) {\r\n super(parent, position, dimension);\r\n }\r\n\r\n @Override\r\n public void replaceChild(@NonNull CutTreeNode from, @NonNull CutTreeNode to) {\r\n throw new UnsupportedOperationException(\"Not supported: Freepanel.replace.\");\r\n }\r\n\r\n public CutNode cut(double bladeWidth, double cutPosition, @NonNull CutNode.Direction direction) {\r\n final CutTreeNode parent = this.getParent();\r\n final CutNode cut = new CutNode(parent,\r\n bladeWidth, cutPosition, direction,\r\n getPosition(),\r\n getDimension());\r\n\r\n parent.replaceChild(this, cut);\r\n\r\n return cut;\r\n }\r\n\r\n public PanelNode setPanel(@NonNull PanelInstance panel) {\r\n final CutTreeNode parent = this.getParent();\r\n final PanelNode pn = new PanelNode(parent, panel, getPosition(), getDimension());\r\n parent.replaceChild(this, pn);\r\n return pn;\r\n }\r\n}\r", "public class SimulatedAnnealer {\n private static java.util.Random random = new java.util.Random();\n private State state;\n private double energy;\n private State minState;\n private double minEnergy;\n private double initTemp;\n private double decayRate;\n\n public SimulatedAnnealer(State initState, double initTemp, double decayRate) {\n state = initState;\n energy = initState.energy();\n minState = (State) state.clone();\n minEnergy = energy;\n\tthis.initTemp = initTemp;\n\tthis.decayRate = decayRate;\n }\n \n public State search(int iterations) \n {\n\tdouble temperature = initTemp; // ***\n\tfor (int i = 0; i < iterations; i++) {\n// if (i % 100000 == 0) \n// System.out.println(minEnergy \n// + \"\\t\" + energy);\n state.step();\n double nextEnergy = state.energy();\n\t if (nextEnergy <= energy \n\t\t|| random.nextDouble() // ***\n\t\t< Math.exp((energy - nextEnergy)\n\t\t\t / temperature)) {\n energy = nextEnergy;\n if (nextEnergy < minEnergy) {\n minState \n\t\t\t= (State) state.clone();\n minEnergy = nextEnergy;\n }\n\t }\n\t else\n\t\tstate.undo();\n\t temperature = temperature*decayRate; // ***\n\t}\t \n\treturn minState;\n\t// *** indicates change from HillDescender\n }\n}", "public interface State extends Cloneable { \n void step();\n void undo();\n double energy();\n Object clone();\n}" ]
import com.cutlet.lib.model.PanelInstance; import com.cutlet.lib.model.Project; import com.cutlet.lib.data.cuttree.FreeNode; import com.cutlet.lib.tneller.SimulatedAnnealer; import com.cutlet.lib.tneller.State; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import lombok.NonNull;
/* * Copyright (C) 2017 rudolf.muehlbauer@gmail.com */ package com.cutlet.lib.optimizer; // uses http://cs.gettysburg.edu/~tneller/resources/sls/index.html /** * * @author rmuehlba */ public class SAOptimizationStrategy extends AbstractOptimizationStrategy { private final Logger log = Logger.getLogger(SAOptimizationStrategy.class.getName()); public static java.util.Random random = new java.util.Random(); @Override
public OptimizationResult optimize(@NonNull Project project, @NonNull FitnessFunction fitness) {
1
AdoptOpenJDK/mjprof
src/main/java/com/performizeit/mjprof/plugins/output/ThreadDumpGuiViewer.java
[ "public class Profile {\n public boolean color = false;\n SFNode root = new SFNode();\n\n public Profile() {\n root.setColor(color);\n root.sf = null;\n }\n \n public String test(){\n \treturn root.sf;\n }\n public Profile(String parseString) {\n this();\n if (parseString.contains(\"]\\\\ \")) {\n parseMulti(parseString);\n } else {\n parseSingle(parseString);\n }\n } \n\n\tpublic void parseSingle(String stackTrace) {\n addSingle(stackTrace);\n }\n\n\n public void addSingle(String stackTrace) {\n if (stackTrace.trim().length()==0) return; // I am not sure that this is the correct\n //// decision but when no stack trace then the profile should be nullified as well\n String[] sf = stackTrace.split(\"\\n\");\n HashMap<String,SFNode> c = root.children;\n root.count ++;\n for (int i=sf.length-1;i>=0;i--) {\n\n String sfi = sf[i].trim();\n if (sfi.isEmpty()) continue;\n SFNode node = c.get(sfi);\n if (node == null) {\n node = new SFNode();\n\n node.sf = sfi;\n c.put(sfi, node);\n }\n node.count++;\n c = node.children;\n }\n }\n public void addSingle(StackTraceElement[] elements) {\n if (elements.length==0) return; // I am not sure that this is the correct\n //// decision but when no stack trace then the profile should be nullified as well\n HashMap<String,SFNode> c = root.children;\n root.count ++;\n for (int i=elements.length-1;i>=0;i--) {\n\n String sfi = \"at \"+ elements[i].getClassName() + \".\" +elements[i].getMethodName() +\"(\"+elements[i].getFileName()+\":\"+elements[i].getLineNumber()+\")\";\n if (sfi.isEmpty()) continue;\n SFNode node = c.get(sfi);\n if (node == null) {\n node = new SFNode();\n\n node.sf = sfi;\n c.put(sfi, node);\n }\n node.count++;\n c = node.children;\n }\n }\n\n public void parseMulti(String treeString) {\n String[] lines = treeString.split( \"\\n\");\n nextFrame(-1,root, lines, 0);\n\n }\n\n\n\n private int nextFrame(int parentPehIndent,SFNode parent, String[] lines, int curLine) {\n while (curLine < lines.length) {\n String line = lines[curLine];\n\n ProfileEntryHelper peh = new ProfileEntryHelper(line);\n if (peh.indentation <= parentPehIndent) {\n return curLine;\n } else if (peh.indentation > parentPehIndent) {\n SFNode node;\n node = parent.children.get(peh.description);\n if (node == null) {\n node = new SFNode();\n node.sf = peh.description;\n parent.children.put(peh.description, node);\n }\n node.count += peh.count;\n if (peh.indentation ==0) parent.count += peh.count;\n curLine = nextFrame(peh.indentation, node, lines, curLine + 1);\n }\n }\n return curLine;\n\n }\n \n public void addMulti(Profile p) {\n root.mergeToNode(p.root);\n }\n \n @Override\n public String toString() {\n return root.toString();\n\n }\n\n public void visit(ProfileVisitor pv) {\n root.visitChildren(pv,0);\n }\n\n public void filter(ProfileNodeFilter pnf,Object context) {\n root.filterChildren(pnf,0,context);\n }\n public int getCount() {\n return root.getCount();\n }\n\n\tpublic void filterDown(ProfileNodeFilter profileNodeFilter, Object context) {\n\t\t root.filterDownChildren(profileNodeFilter,0,context);\t\t\n\t}\n\t\n\tpublic void filterUp(ProfileNodeFilter profileNodeFilter, Object context) {\t\n\t\t root.filterUpChildren(profileNodeFilter,0,context);\t\t\n\t}\n\n}", "public interface ProfileVisitor {\n void visit(SFNode stackframe, int level);\n}", "public class SFNode {\n boolean color = false;\n int count;\n String sf;\n HashMap<String, SFNode> children = new HashMap<>();\n\n @Override\n public String toString() {\n if (count == 0) return \"\";\n if (count == 1) return toStringSingle();\n return toStringMulti(-1, new HashSet<>(), count);\n }\n\n private String toStringSingle() {\n String indent = \" \";\n if (sf == null && children.size() > 0) return children.values().iterator().next().toStringSingle();\n if (children.size() == 0) return indent + sf;\n\n return children.values().iterator().next().toStringSingle() + \"\\n\" + indent + sf;\n }\n\n private String CSI() {\n return (char) 0x1b + \"[\";\n }\n\n private String GREEN() {\n if (!color) return \"\";\n return CSI() + \"1;32m\";\n }\n\n private String NC() {\n if (!color) return \"\";\n return CSI() + \"0m\";\n }\n\n public boolean isColor() {\n return color;\n }\n\n public void setColor(boolean color) {\n this.color = color;\n }\n\n public String toStringMulti(int lvl, HashSet<Integer> brkPts, int countall) {\n\n String a = \"\";\n if (sf != null) { // we do not want to print the root node\n for (int i = 0; i < lvl; i++) {\n if (brkPts.contains(i)) {\n\n a += GREEN() + \"|\" + NC();\n } else\n a += \" \";\n }\n String ch = \"\\\\\";\n if (children.size() > 1) {\n ch = \"X\";\n brkPts.add(lvl);\n }\n if (children.size() == 0) {\n ch = \"V\";\n }\n String bb = String.format(\"[%d/%d]\", count, countall);\n a = String.format(\"%6.2f%%%10s\", 100f * (float) count / countall, bb) + a + GREEN() + ch + NC() + \" \" + sf;\n a += \"\\n\";\n\n }\n int t = 0;\n for (SFNode n : children.values()) {\n if (t == children.size() - 1) {\n brkPts.remove(lvl);\n }\n t++;\n a += n.toStringMulti(lvl + 1, brkPts, countall);\n }\n\n return a;\n }\n\n // Visit all chlidren of a node recursively with a ProfileVisitor\n public void visitChildren(ProfileVisitor pv, int level) {\n pv.visit(this, level);\n HashMap<String, SFNode> newChildren = new HashMap<>();\n for (SFNode child : children.values()) { // visit all childred\n child.visitChildren(pv, level + 1);\n newChildren.put(child.getStackFrame(), child);\n }\n children = newChildren;\n }\n\n // filter out children which do not match filter\n public void filterChildren(ProfileNodeFilter pnf, int level, Object context) {\n ArrayList<String> keysToRemove = new ArrayList<String>();\n\n for (String childKey : children.keySet()) {\n SFNode child = children.get(childKey);\n boolean acceptNode = pnf.accept(child, level, context);\n child.filterChildren(pnf, level + 1, context); // first filter out the children\n if (!acceptNode) {\n keysToRemove.add(childKey);\n }\n }\n // if we are about to remove this child then we take all its children and fuse them to this node....\n for (String key : keysToRemove) {\n SFNode child = children.get(key);\n children.remove(key);\n for (String grandchildKey : child.children.keySet()) {\n if (children.get(grandchildKey) == null) {/// there is no child with grandchildKey\n children.put(grandchildKey, child.children.get(grandchildKey));\n } else {\n SFNode newChild = children.get(grandchildKey);\n newChild.mergeToNode(child.children.get(grandchildKey));\n }\n\n }\n\n\n }\n }\n\n public void filterUpChildren(ProfileNodeFilter pnf, int level, Object context) {\n ArrayList<String> keysToRemove = new ArrayList<>();\n\n for (String childKey : children.keySet()) {\n SFNode child = children.get(childKey);\n\n boolean acceptNode = pnf.accept(child, level, context);\n if (acceptNode) {\n //\tchild.filterUpChildren(pnf, level+1,context); // first filter out the children\n } else {\n keysToRemove.add(childKey);\n }\n child.filterUpChildren(pnf, level + 1, context);\n\n\n }\n\n\n // if we are about to remove this child then we take all its children and fuse them to this node....\n for (String key : keysToRemove) {\n SFNode child = children.get(key);\n children.remove(key);\n for (String grandchildKey : child.children.keySet()) {\n if (children.get(grandchildKey) == null) {/// there is no child with grandchildKey\n children.put(grandchildKey, child.children.get(grandchildKey));\n } else {\n SFNode newChild = children.get(grandchildKey);\n newChild.mergeToNode(child.children.get(grandchildKey));\n }\n\n }\n }\n }\n\n public void filterDownChildren(ProfileNodeFilter pnf, int level, Object context) {\n ArrayList<String> keysToRemove = new ArrayList<String>();\n\n for (String childKey : children.keySet()) {\n SFNode child = children.get(childKey);\n boolean acceptNode = pnf.accept(child, level, context);\n //if acceptNode==true we want to save it and all childern\n if (!acceptNode) {\n keysToRemove.add(childKey);\n child.filterDownChildren(pnf, level + 1, context); // first filter out the children\n }\n }\n // if we are about to remove this child then we take all its children and fuse them to this node....\n for (String key : keysToRemove) {\n SFNode child = children.get(key);\n children.remove(key);\n for (String grandchildKey : child.children.keySet()) {\n if (children.get(grandchildKey) == null) {/// there is no child with grandchildKey\n children.put(grandchildKey, child.children.get(grandchildKey));\n } else {\n SFNode newChild = children.get(grandchildKey);\n newChild.mergeToNode(child.children.get(grandchildKey));\n }\n\n }\n\n\n }\n }\n\n\n public void mergeToNode(SFNode that) {\n this.count += that.count;\n //merge children\n for (String key : that.children.keySet()) {\n SFNode thisChild = this.children.get(key);\n SFNode thatChild = that.children.get(key);\n if (thisChild != null) {\n thisChild.mergeToNode(thatChild);\n\n } else {\n children.put(key, thatChild.deepClone());\n }\n }\n }\n\n public SFNode deepClone() {\n SFNode clone = new SFNode();\n clone.count = this.count;\n clone.sf = this.sf;\n for (String key : children.keySet()) {\n clone.children.put(key, children.get(key).deepClone());\n }\n return clone;\n }\n\n public String getStackFrame() {\n return sf;\n }\n\n public void setStackFrame(String sf) {\n this.sf = sf;\n }\n\n public int getNumChildren() {\n return children.size();\n }\n\n public int getCount() {\n return count;\n }\n\n\n public boolean isNull() {\n return sf == null;\n }\n\n public boolean contains(String exp) {\n if (sf.contains(exp))\n return true;\n for (String key : children.keySet()) {\n SFNode thisChild = this.children.get(key);\n if (thisChild.sf.contains(exp))\n return true;\n else\n return thisChild.contains(exp);\n }\n return false;\n }\n\n public int depthBelow() {\n int depthB = Integer.MAX_VALUE;\n for (SFNode child : children.values()) {\n int depthBnew = child.depthBelow() + 1;\n if (depthBnew < depthB) depthB = depthBnew;\n\n }\n if (depthB == Integer.MAX_VALUE) depthB = 0;\n return depthB;\n }\n\n}", "public class ThreadDump {\n protected JStackHeader header;\n ArrayList<ThreadInfo> stacks = new ArrayList<>();\n int JNIglobalReferences = -1;\n\n public static String JNI_GLOBAL_REFS = \"JNI global references:\";\n\n public JStackHeader getHeader() {\n return header;\n }\n\n public ThreadDump(String stringRep) {\n String[] splitTraces = stringRep.split(\"\\n\\\"\"); // Assuming that thread stack trace starts with a new line followed by \"\n\n header = new JStackHeader(splitTraces[0]);\n for (int i = 1; i < splitTraces.length; i++) {\n if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) {\n try {\n JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(\":\") + 2).trim());\n } catch (NumberFormatException e) {\n // do nothing so we missed the JNI global references I do not know what to do with it.\n }\n\n } else {\n stacks.add(new ThreadInfo(\"\\\"\" + splitTraces[i]));\n }\n }\n }\n\n public ThreadDump() {\n super();\n }\n\n public ArrayList<ThreadInfo> getStacks() {\n return stacks;\n }\n\n public void addThreadInfo(ThreadInfo ti) {\n stacks.add(ti);\n }\n\n public void setStacks(ArrayList<ThreadInfo> stacks) {\n this.stacks = stacks;\n }\n\n @Override\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(header).append(\"\\n\\n\");\n\n for (ThreadInfo stack : stacks) {\n s.append(stack.toString()).append(\"\\n\");\n }\n\n return s.toString();\n }\n\n\n public void setHeader(String header) {\n this.header = new JStackHeader(header);\n }\n\n public void setHeader(JStackHeader header) {\n this.header = header;\n }\n\n public ArrayList<ThreadInfo> cloneStacks() {\n ArrayList<ThreadInfo> newStcks = new ArrayList<>();\n for (ThreadInfo stk : getStacks()) {\n newStcks.add(stk);\n }\n return newStcks;\n }\n\n public int getJNIglobalReferences() {\n return JNIglobalReferences;\n }\n\n public void setJNIglobalReferences(int JNIglobalReferences) {\n this.JNIglobalReferences = JNIglobalReferences;\n }\n}", "public class ThreadInfo extends Props {\n\n public static final String LOCKED_OWNABLE_SYNCHRONIZERS = \"Locked ownable synchronizers\";\n public static final String JAVA_LANG_THREAD_STATE = \"java.lang.Thread.State\";\n\n public ThreadInfo(String stackTrace) {\n BufferedReader reader = new BufferedReader(new StringReader(stackTrace));\n try {\n String metaLine = reader.readLine();\n if (metaLine != null) {\n parseMetaLine(metaLine);\n\n String threadState = reader.readLine();\n if (threadState != null) {\n parseThreadState(threadState);\n }\n String linesOfStack = \"\";\n String s;\n while ((s = reader.readLine()) != null) {\n if (s.trim().length() == 0) break;\n linesOfStack += s + \"\\n\";\n }\n props.put(STACK, new Profile(linesOfStack));\n while ((s = reader.readLine()) != null) {\n if (s.contains(LOCKED_OWNABLE_SYNCHRONIZERS)) break;\n }\n String linesOfLOS = \"\";\n while ((s = reader.readLine()) != null) {\n if (s.trim().length() == 0) break;\n linesOfLOS += s + \"\\n\";\n }\n if (linesOfLOS.trim().length() > 0)\n props.put(LOS, new ThreadLockedOwnableSynchronizers(linesOfLOS));\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public ThreadInfo(HashMap<String, Object> mtd) {\n super(mtd);\n }\n\n private void parseThreadState(String threadState) {\n Pattern p = Pattern.compile(\"^[\\\\s]*\" + JAVA_LANG_THREAD_STATE + \": (.*)$\");\n Matcher m = p.matcher(threadState);\n if (m.find()) {\n props.put(STATE, m.group(1));\n }\n }\n\n\n protected String metadataProperty(String metaLine, String propertyName) {\n Pattern p = Pattern.compile(\".* \" + propertyName + \"=([0-9a-fx]*) .*\");\n Matcher m = p.matcher(metaLine);\n\n if (m.find()) {\n return m.group(1);\n\n }\n return null;\n }\n\n protected void metadataKeyValProperties(String metaLine) {\n Pattern p = Pattern.compile(\"(\\\\S+)=(\\\\S+)\"); // a nonspace string then = and then a non space string\n Matcher m = p.matcher(metaLine);\n while (m.find()) {\n props.put(m.group(1), m.group(2));\n }\n if (props.get(TID) != null && !props.get(TID).equals(\"*\")) {\n props.put(TID + \"Long\", new HexaLong((String) props.get(TID)));\n }\n if (props.get(NID) != null && !props.get(NID).equals(\"*\")) {\n props.put(NID + \"Long\", new HexaLong((String) props.get(NID)));\n }\n }\n\n private void parseMetaLine(String metaLine) {\n Pattern p = Pattern.compile(\"^\\\"(.*)\\\".*\");\n Matcher m = p.matcher(metaLine);\n\n if (m.find()) {\n props.put(NAME, m.group(1));\n }\n\n extractStatus(metaLine);\n metadataKeyValProperties(metaLine);\n\n if (metaLine.contains(\"\\\" \" + DAEMON + \" \")) {\n props.put(DAEMON, true);\n }\n\n }\n\n private void extractStatus(String metaLine) {\n int idx = metaLine.lastIndexOf('=');\n if (idx != -1) {\n String lastParam = metaLine.substring(idx);\n idx = lastParam.indexOf(' ');\n if (idx != -1) {\n\n lastParam = lastParam.substring(idx + 1);\n\n if (lastParam.length() > 0) {\n props.put(STATUS, lastParam.trim());\n }\n }\n }\n }\n\n @Override\n public String toString() {\n\n StringBuilder mdStr = new StringBuilder();\n\n if (props.get(NAME) != null) {\n mdStr.append(\"\\\"\").append(props.get(NAME)).append(\"\\\"\");\n }\n if (props.get(COUNT) != null) {\n mdStr.append(\" \" + COUNT + \"=\").append(props.get(COUNT));\n }\n if (props.get(DAEMON) != null) {\n mdStr.append(\" \" + DAEMON);\n }\n if (props.get(PRIO) != null) {\n mdStr.append(\" \" + PRIO + \"=\").append(props.get(PRIO));\n }\n if (props.get(TID) != null) {\n mdStr.append(\" \" + TID + \"=\" + props.get(TID));\n }\n if (props.get(NID) != null) {\n mdStr.append(\" \" + NID + \"=\" + props.get(NID));\n }\n if (props.get(STATUS) != null) {\n mdStr.append(\" \" + props.get(STATUS));\n }\n if (props.get(CPUNS) != null) {\n mdStr.append(\" \" + CPUNS + \"=\").append(props.get(CPUNS));\n }\n if (props.get(WALL) != null) {\n mdStr.append(\" \" + WALL + \"=\").append(props.get(WALL));\n }\n if (props.get(CPU_PREC) != null) {\n mdStr.append(\" \" + CPU_PREC + \"=\").append(props.get(CPU_PREC));\n }\n\n\n if (props.get(STATE) != null) {\n mdStr.append(\"\\n \" + JAVA_LANG_THREAD_STATE + \": \").append(props.get(STATE));\n }\n\n if (props.get(STACK) != null) {\n mdStr.append(\"\\n\").append(props.get(STACK).toString());\n }\n mdStr.append(\"\\n\");\n if (props.get(LOS) != null) {\n mdStr.append(\"\\n \" + LOCKED_OWNABLE_SYNCHRONIZERS + \":\\n\").append(\n props.get(LOS).toString());\n }\n\n return mdStr.toString();\n\n }\n\n}", "public interface ThreadInfoProps {\n public static final String NAME = \"name\"; // the name of the thread\n public static final String PRIO = \"prio\"; //priority\n public static final String CPUNS = \"cpu_ns\"; // amount of cpu consumed by thread\n public static final String WALL = \"wall_ms\"; // amount of cpu consumed by thread\n public static final String CPU_PREC = \"%cpu\";\n public static final String TID = \"tid\"; // java thread id\n public static final String NID = \"nid\"; // native thread id\n public static final String STACK = \"stack\"; // the stack of the thread or the profile of more than one thread\n public static final String STATUS = \"status\";\n public static final String STATE = \"state\";\n public static final String LOS = \"los\"; //locked ownable synchronizers\n public static final String DAEMON = \"daemon\"; // daemon true / false\n public static final String COUNT = \"count\"; // number of actual stacks this profile represent\n}" ]
import com.performizeit.mjprof.model.Profile; import com.performizeit.mjprof.model.ProfileVisitor; import com.performizeit.mjprof.model.SFNode; import com.performizeit.mjprof.parser.ThreadDump; import com.performizeit.mjprof.parser.ThreadInfo; import com.performizeit.mjprof.parser.ThreadInfoProps; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.util.HashMap;
package com.performizeit.mjprof.plugins.output; /** * Created by life on 27/10/14. */ public class ThreadDumpGuiViewer extends JPanel implements TreeSelectionListener { ThreadDump toDisplay; private JTree tree; //Optionally play with line styles. Possible values are //"Angled" (the default), "Horizontal", and "None". private static boolean playWithLineStyle = false; private static String lineStyle = "Horizontal"; //Optionally set the look and feel. private static boolean useSystemLookAndFeel = false; public ThreadDumpGuiViewer(ThreadDump toDisplay) { super(new GridLayout(1, 0)); this.toDisplay = toDisplay; //Create the nodes. DefaultMutableTreeNode top = new DefaultMutableTreeNode("Thread Dump"); createNodes(top); //Create a tree that allows one selection at a time. tree = new JTree(top); tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); //Listen for when the selection changes. tree.addTreeSelectionListener(this); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } if (playWithLineStyle) { System.out.println("line style = " + lineStyle); tree.putClientProperty("JTree.lineStyle", lineStyle); } //Create the scroll pane and add the tree to it. JScrollPane treeView = new JScrollPane(tree); Dimension minimumSize = new Dimension(1000, 800); this.setMinimumSize(minimumSize); this.setSize(minimumSize); treeView.setMaximumSize(minimumSize); treeView.setSize(minimumSize); //Add the split pane to this panel. add(treeView); } /** * Required by TreeSelectionListener interface. */ public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); } private void createNodes(DefaultMutableTreeNode top) { for (ThreadInfo ti : toDisplay.getStacks()) { DefaultMutableTreeNode tgui = createThreadProfile(ti); top.add(tgui); } } class Vis implements ProfileVisitor { HashMap<Integer, DefaultMutableTreeNode> parents = new HashMap<>(); public Vis(DefaultMutableTreeNode thread) { parents.put(0, thread); } @Override public void visit(SFNode stackframe, int level) { if (level == 0) return; DefaultMutableTreeNode parent = parents.get(level - 1); DefaultMutableTreeNode me = new DefaultMutableTreeNode("[" + stackframe.getCount() + "] " + stackframe.getStackFrame()); parent.add(me); parents.put(level, me); } } private DefaultMutableTreeNode createThreadProfile(ThreadInfo ti) {
Profile p = (Profile) ti.getVal(ThreadInfoProps.STACK);
5
Tubitv/TubiPlayer
lib/src/main/java/com/tubitv/media/fsm/concrete/ReceiveAdState.java
[ "public abstract class BaseState implements State {\n\n protected PlayerUIController controller;\n\n protected PlayerAdLogicController componentController;\n\n protected MediaModel movieMedia;\n\n protected AdMediaModel adMedia;\n\n /**\n * for testing purpose,\n *\n * @param fsmPlayer\n * @return\n */\n protected boolean isNull(@NonNull FsmPlayer fsmPlayer) {\n if (fsmPlayer == null) {\n throw new IllegalStateException(\"FsmPlayer can not be null\");\n }\n\n if (controller == null || componentController == null || movieMedia == null) {\n ExoPlayerLogger.e(Constants.FSMPLAYER_TESTING, \"components are null\");\n return true;\n }\n\n return false;\n }\n\n @Override\n public void performWorkAndUpdatePlayerUI(@NonNull FsmPlayer fsmPlayer) {\n /**\n * need to get the reference of the UI and Business logic components first.\n */\n controller = fsmPlayer.getController();\n componentController = fsmPlayer.getPlayerComponentController();\n movieMedia = fsmPlayer.getMovieMedia();\n adMedia = fsmPlayer.getAdMedia();\n }\n}", "public enum Input {\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.FetchCuePointState}\n */\n HAS_PREROLL_AD,\n NO_PREROLL_AD,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.MakingPrerollAdCallState}\n */\n PRE_ROLL_AD_RECEIVED,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.MakingAdCallState}\n */\n AD_RECEIVED,\n EMPTY_AD,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.ReceiveAdState}\n */\n SHOW_ADS,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.AdPlayingState}\n */\n NEXT_AD,\n AD_CLICK,\n AD_FINISH,\n VPAID_MANIFEST,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.VpaidState}\n */\n VPAID_FINISH,\n\n /**\n * Only expect inputs of {@link VastAdInteractionSandBoxState}\n */\n BACK_TO_PLAYER_FROM_VAST_AD,\n\n /**\n * Only expect inputs of {@link com.tubitv.media.fsm.concrete.MoviePlayingState}\n */\n MAKE_AD_CALL,\n MOVIE_FINISH,\n\n /**\n * ERROR INPUT\n */\n ERROR,\n\n INITIALIZE,\n}", "public interface State {\n\n /**\n * let the state to examine itself in a constant time line to detects any input that can change the state.\n */\n @Nullable\n State transformToState(@NonNull Input input, @NonNull StateFactory factory);\n\n /**\n * once the fsm changes states, update player's UI components.\n *\n * @param fsmPlayer the state machine itself that contains the UI and Business logic parts.\n */\n void performWorkAndUpdatePlayerUI(@NonNull FsmPlayer fsmPlayer);\n\n}", "public final class StateFactory {\n\n /**\n * map store singleton instance of every types of {@link State},\n */\n private final Map<Class, State> stateInstance = new HashMap<>();\n\n /**\n * the key is the default state, and value is the custom state.\n */\n private final Map<Class, Class> customStateType = new HashMap<>();\n\n @Nullable\n private synchronized State getCacheInstance(@NonNull Class type) {\n return stateInstance.get(type);\n }\n\n private synchronized void setCacheInstance(@NonNull Class type, @NonNull State instance) {\n stateInstance.put(type, instance);\n }\n\n /**\n * convert the default {@link State} into custom State\n *\n * @param cla default state type\n * @return the custom state type\n */\n @Nullable\n private Class convertToCustomClass(@NonNull Class cla) {\n return customStateType.get(cla);\n }\n\n /**\n * Method should only be called right after initialization, before {@link #createState} ever been called for max state predictability.\n *\n * @param subClass must be the subclass of {@link com.tubitv.media.fsm.BaseState} to swap original to subclass\n * Must be called before any createState method being called.\n */\n public void overrideStateCreation(@NonNull Class subClass) {\n\n if (MakingAdCallState.class.isAssignableFrom(subClass)) {\n customStateType.put(MakingAdCallState.class, subClass);\n\n } else if (MoviePlayingState.class.isAssignableFrom(subClass)) {\n customStateType.put(MoviePlayingState.class, subClass);\n\n } else if (FinishState.class.isAssignableFrom(subClass)) {\n customStateType.put(FinishState.class, subClass);\n\n } else if (ReceiveAdState.class.isAssignableFrom(subClass)) {\n customStateType.put(ReceiveAdState.class, subClass);\n\n } else if (AdPlayingState.class.isAssignableFrom(subClass)) {\n customStateType.put(AdPlayingState.class, subClass);\n\n } else if (VpaidState.class.isAssignableFrom(subClass)) {\n customStateType.put(VpaidState.class, subClass);\n\n } else if (VastAdInteractionSandBoxState.class.isAssignableFrom(subClass)) {\n customStateType.put(VastAdInteractionSandBoxState.class, subClass);\n\n } else if (FetchCuePointState.class.isAssignableFrom(subClass)) {\n customStateType.put(FetchCuePointState.class, subClass);\n\n } else if (MakingPrerollAdCallState.class.isAssignableFrom(subClass)) {\n customStateType.put(MakingPrerollAdCallState.class, subClass);\n\n } else {\n throw new IllegalStateException(\n String.valueOf(subClass.getName() + \"is not a base class of default State class \"));\n }\n }\n\n @NonNull\n public State createState(@NonNull Class classType) {\n\n if (!State.class.isAssignableFrom(classType)) {\n throw new IllegalStateException(\n String.valueOf(classType.getName() + \"is not a base class of default State class \"));\n }\n\n // null check if there is any custom state class. if there is,\n Class finalClassType = convertToCustomClass(classType);\n\n if (finalClassType == null) {\n finalClassType = classType;\n }\n\n State buildState = getCacheInstance(finalClassType);\n\n if (buildState == null) {\n try {\n\n Constructor<?> ctor = finalClassType.getConstructor();\n buildState = (State) ctor.newInstance();\n\n setCacheInstance(finalClassType, buildState);\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n return buildState;\n }\n}", "public abstract class FsmPlayer implements Fsm, RetrieveAdCallback, FsmAdController {\n\n /**\n * a wrapper class for player logic related component objects.\n */\n protected PlayerAdLogicController playerComponentController;\n /**\n * a wrapper class for player UI related objects\n */\n private PlayerUIController controller;\n /**\n * a generic call ad network class\n */\n private AdInterface adServerInterface;\n\n /**\n * information to use when retrieve ad from server\n */\n private AdRetriever adRetriever;\n\n /**\n * information to use when retrieve cuePoint from server.\n */\n private CuePointsRetriever cuePointsRetriever;\n\n /**\n * the main content media\n */\n private MediaModel movieMedia;\n\n /**\n * the content of ad being playing\n */\n private AdMediaModel adMedia;\n\n /**\n * the central state representing {@link com.google.android.exoplayer2.ExoPlayer} state at any given time.\n */\n private State currentState = null;\n\n /**\n * a factory class to create different state when fsm change to a different state.\n */\n private StateFactory factory;\n\n //this is a example url, you should use your own vpaid url instead.\n private String VPAID_END_POINT = \"http://tubitv.com/\";\n\n /**\n * only initialize the fsmPlay onc\n */\n private boolean isInitialized = false;\n\n private Lifecycle mLifecycle;\n\n public FsmPlayer(StateFactory factory) {\n this.factory = factory;\n }\n\n /**\n * update the resume position of the main video\n *\n * @param controller\n */\n public static void updateMovieResumePosition(PlayerUIController controller) {\n\n if (controller == null) {\n return;\n }\n\n SimpleExoPlayer moviePlayer = controller.getContentPlayer();\n\n if (moviePlayer != null && moviePlayer.getPlaybackState() != Player.STATE_IDLE) {\n int resumeWindow = moviePlayer.getCurrentWindowIndex();\n long resumePosition = moviePlayer.isCurrentWindowSeekable() ? Math.max(0, moviePlayer.getCurrentPosition())\n : C.TIME_UNSET;\n controller.setMovieResumeInfo(resumeWindow, resumePosition);\n\n ExoPlayerLogger.i(Constants.FSMPLAYER_TESTING, resumePosition + \"\");\n }\n }\n\n public boolean isInitialized() {\n return isInitialized;\n }\n\n public MediaModel getMovieMedia() {\n return movieMedia;\n }\n\n public void setMovieMedia(MediaModel movieMedia) {\n this.movieMedia = movieMedia;\n }\n\n public AdMediaModel getAdMedia() {\n return adMedia;\n }\n\n public void setAdMedia(AdMediaModel adMedia) {\n this.adMedia = adMedia;\n }\n\n public AdInterface getAdServerInterface() {\n return adServerInterface;\n }\n\n public void setAdServerInterface(@NonNull AdInterface adServerInterface) {\n this.adServerInterface = adServerInterface;\n }\n\n public AdRetriever getAdRetriever() {\n return adRetriever;\n }\n\n public void setAdRetriever(@NonNull AdRetriever adRetriever) {\n this.adRetriever = adRetriever;\n }\n\n public Lifecycle getLifecycle() {\n return mLifecycle;\n }\n\n public void setLifecycle(Lifecycle mLifecycle) {\n this.mLifecycle = mLifecycle;\n }\n\n public boolean hasAdToPlay() {\n return adMedia != null && adMedia.getListOfAds() != null && adMedia.getListOfAds().size() > 0;\n }\n\n public String getVPAID_END_POINT() {\n return VPAID_END_POINT;\n }\n\n public void setVPAID_END_POINT(String VPAID_END_POINT) {\n this.VPAID_END_POINT = VPAID_END_POINT;\n }\n\n /**\n * delete the add at the first of the itme in list, which have been played already.\n */\n private void popPlayedAd() {\n if (adMedia != null) {\n adMedia.popFirstAd();\n }\n }\n\n public MediaModel getNextAdd() {\n return adMedia.nextAD();\n }\n\n public PlayerUIController getController() {\n return controller;\n }\n\n public void setController(@NonNull PlayerUIController controller) {\n this.controller = controller;\n }\n\n public PlayerAdLogicController getPlayerComponentController() {\n return playerComponentController;\n }\n\n public void setPlayerComponentController(PlayerAdLogicController playerComponentController) {\n this.playerComponentController = playerComponentController;\n }\n\n public CuePointsRetriever getCuePointsRetriever() {\n return cuePointsRetriever;\n }\n\n public void setCuePointsRetriever(CuePointsRetriever cuePointsRetriever) {\n this.cuePointsRetriever = cuePointsRetriever;\n }\n\n public void updateCuePointForRetriever(long cuepoint) {\n if (adRetriever != null) {\n adRetriever.setCubPoint(cuepoint);\n }\n }\n\n @Override\n public State getCurrentState() {\n return currentState;\n }\n\n @Override\n public void restart() {\n getController().getContentPlayer().stop();\n getController().getContentPlayer().setPlayWhenReady(false);\n currentState = null;\n getController().clearMovieResumeInfo();\n\n getController().getContentPlayer().prepare(movieMedia.getMediaSource(), true, true);\n transit(Input.INITIALIZE);\n }\n\n @Override\n public void transit(Input input) {\n\n // if the current lifecycle of activity is after on_stop, omit the transition\n if (getLifecycle() != null) {\n if (!getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {\n ExoPlayerLogger.e(Constants.FSMPLAYER_TESTING, \"Activity out of lifecycle\");\n return;\n }\n }\n\n State transitToState;\n\n /**\n * make state transition.\n */\n if (currentState != null) {\n transitToState = currentState.transformToState(input, factory);\n } else {\n\n isInitialized = true;\n transitToState = factory.createState(initializeState());\n\n ExoPlayerLogger.i(Constants.FSMPLAYER_TESTING, \"initialize fsmPlayer\");\n }\n\n /**\n * check if the transition flow is correct, if not then handle the error case.\n */\n if (transitToState != null) {\n /**\n * when transition is not null, state change is successful, and transit to a new state\n */\n currentState = transitToState;\n\n } else {\n\n /**\n * when transition is null, state change is error, transit to default {@link MoviePlayingState}\n */\n if (currentState instanceof MoviePlayingState) { // if player is current in moviePlayingstate when transition error happen, doesn't nothing.\n ExoPlayerLogger.e(Constants.FSMPLAYER_TESTING, \"FSM flow error: remain in MoviePlayingState\");\n return;\n }\n\n ExoPlayerLogger\n .e(Constants.FSMPLAYER_TESTING, \"FSM flow error:\" + \"prepare transition to MoviePlayingState\");\n currentState = factory.createState(MoviePlayingState.class);\n }\n\n if (controller != null) {\n if (!PlayerDeviceUtils.useSinglePlayer() || !controller.isPlayingAds) {\n updateMovieResumePosition(controller);\n }\n }\n\n ExoPlayerLogger.d(Constants.FSMPLAYER_TESTING, \"transit to: \" + currentState.getClass().getSimpleName());\n\n currentState.performWorkAndUpdatePlayerUI(this);\n\n }\n\n @Override\n public void removePlayedAdAndTransitToNextState() {\n\n // need to remove the already played ad first.\n popPlayedAd();\n\n //then check if there are any ad need to be played.\n if (hasAdToPlay()) {\n\n if (getNextAdd().isVpaid()) {\n transit(Input.VPAID_MANIFEST);\n } else {\n transit(Input.NEXT_AD);\n }\n\n } else {\n //depends on current state, to transit to MoviePlayingState.\n if (currentState != null && currentState instanceof VpaidState) {\n transit(Input.VPAID_FINISH);\n } else {\n transit(Input.AD_FINISH);\n }\n }\n\n }\n\n @Override\n public void adPlayerError() {\n transit(Input.ERROR);\n }\n\n @Override\n public void updateSelf() {\n if (currentState != null) {\n ExoPlayerLogger\n .i(Constants.FSMPLAYER_TESTING,\n \"Fsm updates self : \" + currentState.getClass().getSimpleName());\n currentState.performWorkAndUpdatePlayerUI(this);\n }\n }\n\n @Override\n public void onReceiveAd(AdMediaModel mediaModels) {\n ExoPlayerLogger.i(Constants.FSMPLAYER_TESTING, \"AdBreak received\");\n\n adMedia = mediaModels;\n // prepare and build the adMediaModel\n playerComponentController.getDoublePlayerInterface().onPrepareAds(adMedia);\n\n transitToStateBaseOnCurrentState(currentState);\n }\n\n @Override\n public void onError() {\n ExoPlayerLogger.w(Constants.FSMPLAYER_TESTING, \"Fetch Ad fail\");\n transit(Input.ERROR);\n }\n\n @Override\n public void onEmptyAdReceived() {\n ExoPlayerLogger.w(Constants.FSMPLAYER_TESTING, \"Fetch ad succeed, but empty ad\");\n transit(Input.EMPTY_AD);\n }\n\n /**\n * transit to different state, when current state is {@link MakingAdCallState}, then when Ad comes back from server, transit to AD_RECEIVED,which transit current state to {@link com.tubitv.media.fsm.concrete.ReceiveAdState}\n * if current state is {@link MakingPrerollAdCallState}, then when Ad comes back, transit to PRE_ROLL_AD_RECEIVED, which then transit state to {@link com.tubitv.media.fsm.concrete.AdPlayingState}.\n *\n * @param currentState\n */\n private void transitToStateBaseOnCurrentState(State currentState) {\n\n if (currentState == null) {\n return;\n }\n\n if (currentState instanceof MakingPrerollAdCallState) {\n transit(Input.PRE_ROLL_AD_RECEIVED);\n } else if (currentState instanceof MakingAdCallState) {\n transit(Input.AD_RECEIVED);\n }\n }\n}" ]
import android.support.annotation.NonNull; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.SimpleExoPlayer; import com.tubitv.media.fsm.BaseState; import com.tubitv.media.fsm.Input; import com.tubitv.media.fsm.State; import com.tubitv.media.fsm.concrete.factory.StateFactory; import com.tubitv.media.fsm.state_machine.FsmPlayer;
package com.tubitv.media.fsm.concrete; /** * Created by allensun on 7/31/17. */ public class ReceiveAdState extends BaseState { @Override
public State transformToState(Input input, StateFactory factory) {
2
OfficeDev/Property-Inspection-Code-Sample
AndroidRepairApp/app/src/main/java/com/canviz/repairapp/utility/ListHelper.java
[ "public final class Constants {;\n \n\tpublic static final String AAD_CLIENT_ID = \"YOUR CLIENT ID\";\n public static final String AAD_REDIRECT_URL = \"http://PropertyManagementRepairApp\";\n public static final String AAD_AUTHORITY = \"https://login.microsoftonline.com/common\";\n\t \n public static final String GRAPH_RESOURCE_ID = \"https://graph.microsoft.com/\";\n public static final String GRAPH_RESOURCE_URL = \"https://graph.microsoft.com/v1.0/\";\n public static final String GRAPH_BETA_RESOURCE_URL = \"https://graph.microsoft.com/beta/\";\n\t \n public static final String SHAREPOINT_URL = \"https://TENANCY.sharepoint.com\";\n public static final String SHAREPOINT_SITE_PATH = \"/sites/SuiteLevelAppDemo\";\n public static final String SHAREPOINT_RESOURCE_ID = SHAREPOINT_URL;\n\t \n public static final String OUTLOOK_RESOURCE_ID = \"https://outlook.office365.com/\";\n public static final String ONENOTE_RESOURCE_ID = \"https://onenote.com/\";\n public static final String ONENOTE_NAME = \"Contoso Property Management\";\n public static final String VIDEO_RESOURCE_URL = SHAREPOINT_URL + \"/portals/hub\";\n public static final String VIDEO_CHANNEL_NAME = \"Incidents\";\n\t\n public static final String DISPATCHEREMAIL = \"katiej@TENANCY.onmicrosoft.com\";\n\n public static final String LIST_NAME_INCIDENTS = \"Incidents\";\n public static final String LIST_NAME_INSPECTIONS = \"Inspections\";\n public static final String LIST_NAME_INCIDENTWORKFLOWTASKS = \"Incident Workflow Tasks\";\n public static final String LIST_NAME_PROPERTYPHOTOS = \"Property Photos\";\n public static final String LIST_NAME_ROOMINSPECTIONPHOTOS = \"Room Inspection Photos\";\n public static final String LIST_NAME_REPAIRPHOTOS = \"Repair Photos\";\n public static final String LOCALIMAGE_SAVEPATH=\"/mnt/sdcard/repair/images/\";\n\n public static final int SUCCESS = 0x111;\n public static final int FAILED = 0x112;\n}", "public class IncidentModel {\n public static final String[] SELECT = {\n \"ID\",\"Title\",\"sl_inspectorIncidentComments\",\n \"sl_dispatcherComments\",\"sl_repairComments\",\"sl_status\",\n \"sl_type\",\"sl_date\",\"sl_repairCompleted\",\"sl_propertyIDId\",\"sl_inspectionIDId\",\"sl_roomIDId\",\"sl_taskId\",\n \"sl_inspectionID/ID\",\n \"sl_inspectionID/sl_datetime\",\n \"sl_inspectionID/sl_finalized\",\n \"sl_propertyID/ID\",\n \"sl_propertyID/Title\",\n \"sl_propertyID/sl_emailaddress\",\n \"sl_propertyID/sl_owner\",\n \"sl_propertyID/sl_address1\",\n \"sl_propertyID/sl_address2\",\n \"sl_propertyID/sl_city\",\n \"sl_propertyID/sl_state\",\n \"sl_propertyID/sl_postalCode\",\n \"sl_propertyID/sl_group\",\n \"sl_roomID/ID\",\n \"sl_roomID/Title\",\n };\n\n public static final String[] EXPAND = {\n \"sl_inspectionID\",\"sl_propertyID\",\"sl_roomID\"\n };\n\n private final SPListItemWrapper mData;\n\n public IncidentModel() {\n this(new SPListItem());\n }\n\n public IncidentModel(SPListItem listItem) {\n mData = new SPListItemWrapper(listItem);\n }\n\n public int getId() {\n return mData.getInt(\"ID\");\n }\n\n public String getTitle() {\n return mData.getString(\"Title\");\n }\n\n public String getInspectorIncidentComments(){\n return mData.getString(\"sl_inspectorIncidentComments\");\n }\n\n public String getDispatcherComments()\n {\n return mData.getString(\"sl_dispatcherComments\");\n }\n\n public String getRepairComments()\n {\n return mData.getString(\"sl_repairComments\");\n }\n\n public void setRepairComments(String value){\n mData.setString(\"sl_repairComments\",value);\n }\n\n public String getStatus()\n {\n return mData.getString(\"sl_status\");\n }\n\n public void setStatus(String value)\n {\n mData.setString(\"sl_status\",value);\n }\n\n public String getType()\n {\n return mData.getString(\"sl_type\");\n }\n\n public String getDate()\n {\n return mData.getString(\"sl_date\");\n }\n\n public String getRepairCompleted()\n {\n return mData.getString(\"sl_repairCompleted\");\n }\n\n public void setRepairCompleted(String value)\n {\n mData.setString(\"sl_repairCompleted\",value);\n }\n\n public int getPropertyId()\n {\n return mData.getInt(\"sl_propertyIDId\");\n }\n\n public int getInspectionId()\n {\n return mData.getInt(\"sl_inspectionIDId\");\n }\n\n public int getRoomId()\n {\n return mData.getInt(\"sl_roomIDId\");\n }\n\n public int getTaskId()\n {\n return mData.getInt(\"sl_taskId\");\n }\n\n public SPListItem getData(){\n return mData.getInner();\n }\n\n public InspectionModel getInspection(){\n JSONObject data = mData.getObject(\"sl_inspectionID\");\n return new InspectionModel(data);\n }\n\n public PropertyModel getProperty(){\n JSONObject data = mData.getObject(\"sl_propertyID\");\n return new PropertyModel(data);\n }\n\n public RoomModel getRoom(){\n JSONObject data = mData.getObject(\"sl_roomID\");\n return new RoomModel(data);\n }\n\n private Boolean IsChanged;\n\n public void setIsChanged(Boolean value){\n IsChanged = value;\n }\n\n public Boolean getIsChanged(){\n return IsChanged;\n }\n\n private String Token;\n\n public void setToken(String value){\n Token = value;\n }\n\n public String getToken(){\n return Token;\n }\n\n private Bitmap Image;\n\n public void setImage(Bitmap bitmap){\n Image = bitmap;\n }\n\n public Bitmap getImage(){\n return Image;\n }\n}", "public class IncidentWorkflowTaskModel {\n public static final String[] SELECT = {\n \"Id\",\"PercentComplete\",\"Status\"\n };\n\n public static final String[] EXPAND = {\n\n };\n\n private final SPListItemWrapper mData;\n\n public IncidentWorkflowTaskModel() {\n this(new SPListItem());\n }\n\n public IncidentWorkflowTaskModel(SPListItem listItem) {\n mData = new SPListItemWrapper(listItem);\n }\n\n public int getId(){\n return mData.getInt(\"Id\");\n }\n\n public void setId(int id){\n mData.setInt(\"Id\",id);\n }\n\n public String getPercentComplete(){\n return mData.getString(\"PercentComplete\");\n }\n\n public void setPercentComplete(String value){\n mData.setString(\"PercentComplete\",value);\n }\n\n public String getStatus(){\n return mData.getString(\"Status\");\n }\n\n public void setStatus(String value){\n mData.setString(\"Status\",value);\n }\n\n public SPListItem getData(){\n return mData.getInner();\n }\n}", "public class InspectionInspectorModel {\n public static final String[] SELECT = {\n \"Id\",\"sl_datetime\",\"sl_finalized\",\n \"sl_inspector\",\n \"sl_emailaddress\"\n };\n\n public static final String[] EXPAND = {\n\n };\n\n private final SPListItemWrapper mData;\n\n public InspectionInspectorModel() {\n this(new SPListItem());\n }\n\n public InspectionInspectorModel(SPListItem listItem) {\n mData = new SPListItemWrapper(listItem);\n }\n\n public int getId(){\n return mData.getInt(\"ID\");\n }\n\n public String getDateTime(){\n return mData.getString(\"sl_datetime\");\n }\n\n public String getFinalized(){\n return mData.getString(\"sl_finalized\");\n }\n\n public String getInspector(){ return mData.getString(\"sl_inspector\"); }\n\n public String getEmailAddress(){ return mData.getString(\"sl_emailaddress\"); }\n}", "public class RepairPhotoModel {\n\n public static final String[] SELECT = {\n \"Id\",\"sl_inspectionIDId\",\"sl_incidentIDId\",\"sl_roomIDId\"\n };\n\n public static final String[] EXPAND = {\n\n };\n\n private final SPListItemWrapper mData;\n\n public RepairPhotoModel() {\n this(new SPListItem());\n }\n\n public RepairPhotoModel(SPListItem listItem) {\n mData = new SPListItemWrapper(listItem);\n }\n\n public int getId(){\n return mData.getInt(\"Id\");\n }\n\n public void setId(int id){\n mData.setInt(\"Id\",id);\n }\n\n public int getInspectionIDId(){\n return mData.getInt(\"sl_inspectionIDId\");\n }\n\n public void setInspectionIDId(int value){\n mData.setInt(\"sl_inspectionIDId\",value);\n }\n\n public int getIncidentIDId(){\n return mData.getInt(\"sl_incidentIDId\");\n }\n\n public void setIncidentIDId(int value){\n mData.setInt(\"sl_incidentIDId\",value);\n }\n\n public int getRoomIDId(){\n return mData.getInt(\"sl_roomIDId\");\n }\n\n public void setRoomIDId(int value){\n mData.setInt(\"sl_roomIDId\",value);\n }\n\n\n public SPListItem getData(){\n return mData.getInner();\n }\n}" ]
import com.canviz.repairapp.Constants; import com.canviz.repairapp.data.IncidentModel; import com.canviz.repairapp.data.IncidentWorkflowTaskModel; import com.canviz.repairapp.data.InspectionInspectorModel; import com.canviz.repairapp.data.RepairPhotoModel; import com.microsoft.services.sharepoint.Query; import com.microsoft.services.sharepoint.QueryOrder; import com.microsoft.services.sharepoint.SPList; import com.microsoft.services.sharepoint.SPListItem; import com.microsoft.services.sharepoint.ListClient; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException;
public List<IncidentModel> getIncidents(String propertyId) throws ExecutionException, InterruptedException{ Query query = new Query().select(IncidentModel.SELECT) .expand(IncidentModel.EXPAND) .orderBy("sl_date", QueryOrder.Descending) .field("sl_propertyIDId").eq(propertyId) .and() .field("sl_inspectionIDId").gt(0) .and() .field("sl_roomIDId").gt(0); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_INCIDENTS, query).get(); List<IncidentModel> models = new ArrayList<IncidentModel>(); for (SPListItem item : items) { IncidentModel model = new IncidentModel(item); if(model.getPropertyId() > 0 && model.getInspectionId() > 0 && model.getRoomId() > 0) { models.add(new IncidentModel(item)); } } return models; } public InspectionInspectorModel getInspection(int inspectionId) throws ExecutionException, InterruptedException { Query query = new Query().select(InspectionInspectorModel.SELECT) .field("Id").eq(inspectionId) .top(1) .orderBy("sl_datetime", QueryOrder.Descending); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_INSPECTIONS, query).get(); if(items!= null && items.size() > 0){ return new InspectionInspectorModel(items.get(0)); } return null; } public void updateIncidentRepairCompleted(IncidentModel incidentModel) throws ExecutionException, InterruptedException { SPList list = mClient.getList(Constants.LIST_NAME_INCIDENTS).get(); mClient.updateListItem(incidentModel.getData(), list); } public void updateIncidentWorkflowTask(IncidentWorkflowTaskModel incidentWorkflowTaskModel) throws ExecutionException, InterruptedException { SPList list = mClient.getList(Constants.LIST_NAME_INCIDENTWORKFLOWTASKS).get(); mClient.updateListItem(incidentWorkflowTaskModel.getData(), list); } public void updateIncidentRepairComments(IncidentModel incidentModel) throws ExecutionException, InterruptedException { SPList list = mClient.getList(Constants.LIST_NAME_INCIDENTS).get(); mClient.updateListItem(incidentModel.getData(), list); } public int getPropertyPhotoId(int propertyId) throws ExecutionException, InterruptedException { String[] select = {"Id"}; Query query = new Query().select(select) .field("sl_propertyIDId").eq(propertyId) .top(1) .orderBy("Modified", QueryOrder.Descending); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_PROPERTYPHOTOS, query).get(); if(items != null && items.size() > 0){ return items.get(0).getId(); } return 0; } public int getInspectionPhotoId(int incidentId,int roomId, int inspectionId,int top) throws ExecutionException, InterruptedException { String[] select = {"Id"}; Query query = new Query().select(select) .field("sl_inspectionIDId").eq(inspectionId) .and() .field("sl_incidentIDId").eq(incidentId) .and() .field("sl_roomIDId").eq(roomId) .top(top) .orderBy("Modified", QueryOrder.Descending); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_ROOMINSPECTIONPHOTOS, query).get(); if(items != null && items.size() > 0){ return items.get(0).getId(); } return 0; } public List<Integer> getInspectionPhotoIds(int incidentId,int roomId, int inspectionId) throws ExecutionException, InterruptedException { List<Integer> results = new ArrayList<Integer>(); String[] select = {"Id"}; Query query = new Query().select(select) .field("sl_inspectionIDId").eq(inspectionId) .and() .field("sl_incidentIDId").eq(incidentId) .and() .field("sl_roomIDId").eq(roomId) .orderBy("Modified", QueryOrder.Descending); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_ROOMINSPECTIONPHOTOS, query).get(); if(items != null && items.size() > 0){ for(int i =0; i < items.size(); i++){ results.add(items.get(i).getId()); } } return results; } public List<Integer> getRepairPhotoIds(int incidentId,int roomId, int inspectionId) throws ExecutionException, InterruptedException { List<Integer> results = new ArrayList<Integer>(); String[] select = {"Id"}; Query query = new Query().select(select) .field("sl_inspectionIDId").eq(inspectionId) .and() .field("sl_incidentIDId").eq(incidentId) .and() .field("sl_roomIDId").eq(roomId) .orderBy("Modified", QueryOrder.Descending); List<SPListItem> items = mClient.getListItems(Constants.LIST_NAME_REPAIRPHOTOS, query).get(); if(items != null && items.size() > 0){ for(int i =0; i < items.size(); i++){ results.add(items.get(i).getId()); } } return results; }
public void updateRepairPhotoProperty(RepairPhotoModel repairPhotoModel) throws ExecutionException, InterruptedException {
4
FedUni/caliko
caliko-visualisation/src/main/java/au/edu/federation/caliko/visualisation/FabrikLine2D.java
[ "public class FabrikBone2D implements FabrikBone<Vec2f,FabrikJoint2D>\r\n{\r\n\t/**\r\n\t * mJoint\tThe joint attached to this FabrikBone2D.\r\n\t * <p>\r\n\t * Each bone has a single FabrikJoint2D which controls the angle to which the bone is\r\n\t * constrained with regard to the previous (i.e. earlier / closer to the base) bone in its chain.\r\n\t * <p>\r\n\t * By default, a joint is not constrained (that is, it is free to rotate up to 180\r\n\t * degrees in a clockwise or anticlockwise direction), however a joint may be\r\n\t * constrained by specifying constraint angles via the\r\n\t * {@link #setClockwiseConstraintDegs(float)} and {@link #setAnticlockwiseConstraintDegs(float)}\r\n\t * methods.\r\n\t * <p>\r\n\t * You might think that surely a bone has two joints, one at the beginning and one at\r\n\t * the end - however, consider an empty chain to which you add a single bone: It has\r\n\t * a joint at its start, around which the bone may rotate (and which it may optionally\r\n\t * be constrained). In this way the single joint which can be considered to be at the\r\n\t * start location of each bone controls the allowable range of motion for that bone alone.\r\n\t */\r\n\tprivate FabrikJoint2D mJoint = new FabrikJoint2D();\r\n\r\n\t/**\r\n\t * mStartLocation\tThe start location of this FabrikBone2D object.\r\n\t * <p>\r\n\t * The start location of a bone may only be set through a constructor or via an 'addBone'\r\n\t * or 'addConsecutiveBone' method provided by the {@link FabrikChain2D} class.\r\n\t */\r\n\tprivate Vec2f mStartLocation = new Vec2f();\r\n\r\n\t/**\r\n\t * mEndLocation\tThe end location of this FabrikBone2D object.\r\n\t * <p>\r\n\t * The end location of a bone may only be set through a constructor or indirectly via an\r\n\t * 'addBone' method provided by the {@link FabrikChain2D} class.\r\n\t */\r\n\tprivate Vec2f mEndLocation = new Vec2f();\r\n\r\n\t/**\r\n\t * mName\tThe name of this FabrikBone2D object.\r\n\t * <p>\r\n\t * It is not necessary to use this property, but it is provided to allow for easy identification\r\n\t * of a bone, such as when used in a map or such.\r\n\t * <p>\r\n\t * Names exceeding 100 characters will be truncated.\r\n\t */\r\n\tprivate String mName;\r\n\r\n\t/**\r\n\t * mLength\tThe length of this bone from its start location to its end location.\r\n\t * <p>\r\n\t * In the typical usage scenario of a FabrikBone2D the length of the bone remains constant.\r\n\t * <p>\r\n\t * The length may be set explicitly through a value provided to a constructor, or implicitly\r\n\t * when it is calculated as the distance between the {@link #mStartLocation} and {@link mEndLocation}\r\n\t * of a bone.\r\n\t * <p>\r\n\t * Attempting to set a bone length of less than zero, either explicitly or implicitly, will result\r\n\t * in an IllegalArgumentException or\r\n\t */\r\n\tprivate float mLength;\r\n\r\n /**\r\n\t * mGlobalConstraintUV\tThe world-space constraint unit-vector of this 2D bone.\r\n\t */\r\n\tprivate Vec2f mGlobalConstraintUV = new Vec2f(1.0f, 0.0f);\r\n\r\n\t/**\r\n\t * The colour used to draw the bone.\r\n\t * <p>\r\n\t * The default colour is white at full opacity.\r\n\t * <p>\r\n\t * This colour property does not have to be used, for example when using solved IK chains for purposes\r\n\t * other than drawing the solutions to screen.\r\n\t */\r\n\tprivate Colour4f mColour = new Colour4f();\r\n\r\n\t/**\r\n\t * mLineWidth\tThe width of the line drawn to represent this bone, specified in pixels.\r\n\t * <p>\r\n\t * This property can be changed via the {@link #setLineWidth(float)} method, or alternatively, line widths\r\n\t * can be specified as arguments to the {@link #draw(float, Mat4f)} or {@link #draw(Colour4f, float, Mat4f) methods.\r\n\t * <p>\r\n\t * The default line width is 1.0f, which is the only value guaranteed to render correctly for any given\r\n\t * hardware/driver combination. The maximum line width that can be drawn depends on the graphics hardware and drivers\r\n\t * on the host machine, but is typically up to 64.0f on modern hardware.\r\n\t * @see\t\t#setLineWidth(float)\r\n\t * @see\t\t<a href=\"https://www.opengl.org/sdk/docs/man3/xhtml/glLineWidth.xml\">glLineWidth(float)</a>\r\n\t */\r\n\tprivate float mLineWidth = 1.0f;\r\n\r\n\t// ---------- Constructors ----------\r\n\r\n\t/** Default constructor */\r\n\tFabrikBone2D() { }\r\n\r\n\t/**\r\n\t * Constructor to create a new FabrikBone2D from a start and end location as provided by a pair of Vec2fs.\r\n\t * <p>\r\n\t * The {@link #mLength} property is calculated and set from the provided locations. All other properties\r\n\t * are set to their default values.\r\n\t * <p>\r\n\t * Instantiating a FabrikBone2D with the exact same start and end location, and hence a length of zero,\r\n\t * may result in undefined behaviour.\r\n\t *\r\n\t * @param\tstartLocation\tThe start location of the bone in world space.\r\n\t * @param\tendLocation\t\tThe end location of the bone in world space.\r\n\t */\r\n\tpublic FabrikBone2D(Vec2f startLocation, Vec2f endLocation)\r\n\t{\r\n\t\tmStartLocation.set(startLocation);\r\n\t\tmEndLocation.set(endLocation);\r\n\t\tsetLength( Vec2f.distanceBetween(startLocation, endLocation) );\r\n\t}\r\n\r\n\t/**\r\n\t * Constructor to create a new FabrikBone2D from a start and end location as provided by a four floats.\r\n\t * <p>\r\n\t * The {@link #mLength} property is calculated and set from the provided locations. All other properties\r\n\t * are set to their default values.\r\n\t * <p>\r\n\t * Instantiating a FabrikBone2D with the exact same start and end location, and hence a length of zero,\r\n\t * may result in undefined behaviour.\r\n\t *\r\n\t * @param\tstartX\tThe horizontal start location of the bone in world space.\r\n\t * @param\tstartY\tThe vertical start location of the bone in world space.\r\n\t * @param\tendX\tThe horizontal end location of the bone in world space.\r\n\t * @param\tendY\tThe vertical end location of the bone in world space.\r\n\t */\r\n\tpublic FabrikBone2D(float startX, float startY, float endX, float endY)\r\n\t{\r\n\t\tthis( new Vec2f(startX, startY), new Vec2f(endX, endY) );\r\n\t}\r\n\r\n\t/**\r\n\t * Constructor to create a new FabrikBone2D from a start location, a direction unit vector and a length.\r\n\t * <p>\r\n\t * A normalised version of the direction unit vector is used to calculate the end location.\r\n\t * <p>\r\n\t * If the provided direction unit vector is zero then an IllegalArgumentException is thrown.\r\n\t * If the provided length argument is less than zero then an IllegalArgumentException is thrown.\r\n\t * <p>\r\n\t * Instantiating a FabrikBone3D with a length of precisely zero may result in undefined behaviour.\r\n\t *\r\n\t * @param\tstartLocation\tThe start location of the bone in world-space.\r\n\t * @param\tdirectionUV\t\tThe direction unit vector of the bone in world-space.\r\n\t * @param\tlength\t\t\tThe length of the bone in world-space units.\r\n\t */\r\n\tpublic FabrikBone2D(Vec2f startLocation, Vec2f directionUV, float length)\r\n\t{\r\n\t\t// Sanity checking\r\n\t\tUtils.validateDirectionUV(directionUV);\r\n\r\n\t\t// Set the start and end locations\r\n\t\tmStartLocation.set(startLocation);\r\n\t\tmEndLocation.set( mStartLocation.plus( Vec2f.normalised(directionUV).times(length) ) );\r\n\r\n\t\t// Set the bone length via the setLength method rather than directly on the mLength property so that validation is performed\r\n\t\tsetLength(length);\r\n\t}\r\n\r\n\t/**\r\n\t * Constructor to create a new FabrikBone2D from a start location, a direction unit vector, a length and\r\n\t * a pair of constraint angles specified in degrees.\r\n\t * <p>\r\n\t * The clockwise and anticlockwise constraint angles can be considered to be relative to the previous bone\r\n\t * in the chain which this bone exists in UNLESS the bone is a basebone (i.e. the first bone in a chain)\r\n\t * in which case, the constraint angles can optionally be made relative to either a world-space direction,\r\n\t * the direction of the bone to which this bone may be connected, or to a direction relative to the coordinate\r\n\t * space of the bone to which this bone may be connected.\r\n\t * <p>\r\n\t * If the direction unit vector argument is zero then an IllegalArgumentException is thrown.\r\n\t * If the length argument is less than zero then an IllegalArgumentException is thrown.\r\n\t * If either the clockwise or anticlockwise constraint angles are outside of the range 0.0f degrees\r\n\t * to 180.0f degrees then an IllegalArgumentException is thrown.\r\n\t * <p>\r\n\t * Instantiating a FabrikBone3D with a length of precisely zero may result in undefined behaviour.\r\n\t *\r\n\t * @param\tstartLocation\t\tThe start location of the bone in world-space.\r\n\t * @param\tdirectionUV\t\t\tThe direction unit vector of the bone in world-space.\r\n\t * @param\tlength\t\t\t\tThe length of the bone in world-space units.\r\n\t * @param\tcwConstraintDegs\tThe clockwise constraint angle in degrees.\r\n\t * @param\tacwConstraintDegs\tThe anticlockwise constraint angle in degrees.\r\n\t *\r\n\t * @see FabrikChain2D.BaseboneConstraintType2D\r\n\t */\r\n\tpublic FabrikBone2D(Vec2f startLocation, Vec2f directionUV, float length, float cwConstraintDegs, float acwConstraintDegs)\r\n\t{\r\n\t\t// Set up as per previous constructor - IllegalArgumentExceptions will be thrown for invalid directions or lengths\r\n\t\tthis(startLocation, directionUV, length);\r\n\r\n\t\t// Set the constraint angles - IllegalArgumentExceptions will be thrown for invalid constraint angles\r\n\t\tsetClockwiseConstraintDegs(cwConstraintDegs);\r\n\t\tsetAnticlockwiseConstraintDegs(acwConstraintDegs);\r\n\t}\r\n\r\n\t/**\r\n\t * Constructor to create a new FabrikBone2D from a start location, a direction unit vector, a length, a pair\r\n\t * of constraint angles specified in degrees and a colour.\r\n\t * <p>\r\n\t * The clockwise and anticlockwise constraint angles can be considered to be relative to the previous bone\r\n\t * in the chain which this bone exists in UNLESS the bone is a basebone (i.e. the first bone in a chain)\r\n\t * in which case, the constraint angles can optionally be made relative to either a world-space direction,\r\n\t * the direction of the bone to which this bone may be connected, or to a direction relative to the coordinate\r\n\t * space of the bone to which this bone may be connected.\r\n\t * <p>\r\n\t * If the direction unit vector argument is zero then an IllegalArgumentException is thrown.\r\n\t * If the length argument is less than zero then an IllegalArgumentException is thrown.\r\n\t * If either the clockwise or anticlockwise constraint angles are outside of the range 0.0f degrees\r\n\t * to 180.0f degrees then an IllegalArgumentException is thrown.\r\n\t * <p>\r\n\t * Instantiating a FabrikBone3D with a length of precisely zero may result in undefined behaviour.\r\n\t *\r\n\t * @param\tstartLocation\t\tThe start location of the bone in world-space.\r\n\t * @param\tdirectionUV\t\t\tThe direction unit vector of the bone in world-space.\r\n\t * @param\tlength\t\t\t\tThe length of the bone in world-space units.\r\n\t * @param\tcwConstraintDegs\tThe clockwise constraint angle in degrees.\r\n\t * @param\tacwConstraintDegs\tThe anticlockwise constraint angle in degrees.\r\n\t * @param\tcolour\t\t\t\tThe colour with which to draw the bone.\r\n\t *\r\n\t * @see FabrikChain2D.BaseboneConstraintType2D\r\n\t */\r\n\tpublic FabrikBone2D(Vec2f startLocation, Vec2f directionUV, float length, float cwConstraintDegs, float acwConstraintDegs, Colour4f colour)\r\n\t{\r\n\t\tthis(startLocation, directionUV, length, cwConstraintDegs, acwConstraintDegs);\r\n\t\tmColour.set(colour);\r\n\t}\r\n\r\n\t/**\r\n\t * Copy constructor.\r\n\t * <p>\r\n\t * Takes a source FabrikBone2D object and copies all properties into the new FabrikBone2D by value.\r\n\t * Once this is done, there are no shared references between the source and the new object, and they are\r\n\t * exact copies of each other.\r\n\t *\r\n\t * @param\tsource\tThe FabrikBone2D to clone.\r\n\t */\r\n\tpublic FabrikBone2D(FabrikBone2D source)\r\n\t{\r\n\t\t// Set all custom classes via their set methods to avoid new memory allocations\r\n\t\tmStartLocation.set(source.mStartLocation);\r\n\t\tmEndLocation.set(source.mEndLocation);\r\n\t\tmJoint.set(source.mJoint);\r\n\t\tmColour.set(source.mColour);\r\n\r\n\t\t// Set the remaining properties by value via assignment\r\n\t\tmName = source.mName;\r\n\t\tmLength = source.mLength;\r\n\t\tmLineWidth = source.mLineWidth;\r\n\t\tmGlobalConstraintUV = source.mGlobalConstraintUV;\r\n\t}\r\n\r\n\t// ---------- Methods ----------\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic float length() {\treturn mLength; }\r\n\r\n\t/**\r\n\t * Get the colour of this bone as a Colour4f.\r\n\t *\r\n\t * @return The colour of the bone.\r\n\t */\r\n\tpublic Colour4f getColour() { return mColour; }\r\n\r\n\t/**\r\n\t * Set the colour used to draw this bone.\r\n\t * <p>\r\n\t * Any colour component values outside the valid range of 0.0f to 1.0f inclusive are clamped to that range.\r\n\t *\r\n\t * @param\tcolour\tThe colour with which to draw this bone.\r\n\t */\r\n\tpublic void setColour(Colour4f colour) { mColour.set(colour); }\r\n\r\n\t/**\r\n\t * Get the line width with which to draw this line\r\n\t *\r\n\t * @return The width of the line in pixels which should be used to draw this bone.\r\n\t */\r\n\tpublic float getLineWidth()\t{ return mLineWidth; }\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getStartLocation() { return mStartLocation; }\r\n\r\n\t/**\r\n\t * Get the start location of this bone in world-space as an array of two floats.\r\n\t *\r\n\t * @return The start location of this bone.\r\n\t */\r\n\tpublic float[] getStartLocationAsArray() { return new float[] { mStartLocation.x, mStartLocation.y }; }\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getEndLocation() { return mEndLocation; }\r\n\r\n\t/** Get the end location of the bone in world-space as an array of two floats.\r\n\t *\r\n\t * @return The end location of this bone.\r\n\t */\r\n\tpublic float[] getEndLocationAsArray() { return new float[] { mEndLocation.x, mEndLocation.y }; }\r\n\r\n\t/**\r\n\t * Set the FabrikJoint2D object of this bone.\r\n\t *\r\n\t * @param joint The FabrikJoint2D which this bone should use.\r\n\t */\r\n\tpublic void setJoint(FabrikJoint2D joint) {\tmJoint.set(joint); }\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic FabrikJoint2D getJoint() { return mJoint; }\r\n\r\n\t/**\r\n\t * Set the clockwise constraint angle of this bone's joint in degrees.\r\n\t * <p>\r\n\t * The valid range of constraint angle is 0.0f degrees to 180.0f degrees inclusive, angles outside this range are clamped.\r\n\t *\r\n\t * @param angleDegs The clockwise constraint angle specified in degrees.\r\n\t */\r\n\tpublic void setClockwiseConstraintDegs(float angleDegs) { mJoint.setClockwiseConstraintDegs(angleDegs); }\r\n\r\n\t/**\r\n\t * Get the clockwise constraint angle of this bone's joint in degrees.\r\n\t *\r\n\t * @return the clockwise constraint angle in degrees.\r\n\t */\r\n\tpublic float getClockwiseConstraintDegs() { return mJoint.getClockwiseConstraintDegs(); }\r\n\r\n\t/**\r\n\t * Set the anticlockwise constraint angle of this bone's joint in degrees.\r\n\t * <p>\r\n\t * The valid range of constraint angle is 0.0f degrees to 180.0f degrees inclusive.\r\n\t * <p>\r\n\t * If a constraint angle outside of this range is provided then an IllegalArgumentException is thrown.\r\n\t *\r\n\t * @param angleDegs The anticlockwise constraint angle specified in degrees.\r\n\t */\r\n\tpublic void setAnticlockwiseConstraintDegs(float angleDegs) { mJoint.setAnticlockwiseConstraintDegs(angleDegs); }\r\n\r\n\t/**\r\n\t * Get the anticlockwise constraint angle of this bone's joint in degrees.\r\n\t *\r\n\t * @return the anticlockwise constraint angle in degrees.\r\n\t */\r\n\tpublic float getAnticlockwiseConstraintDegs() { return mJoint.getAnticlockwiseConstraintDegs(); }\r\n\r\n\t/**\r\n\t * Get the direction unit vector between the start location and end location of this bone.\r\n\t * <p>\r\n\t * If the opposite (i.e. end to start) location is required then you can simply negate the provided direction.\r\n\t *\r\n\t * @return The direction unit vector of this bone.\r\n\t * @see\t\tVec2f#negated()\r\n\t */\r\n\tpublic Vec2f getDirectionUV() {\treturn Vec2f.getDirectionUV(mStartLocation, mEndLocation); }\r\n\r\n\t/**\r\n\t * Get the world-space constraint unit-vector of this bone.\r\n\t *\r\n\t * @return The world-space constraint unit-vector of this bone.\r\n\t */\r\n\tpublic Vec2f getGlobalConstraintUV()\r\n\t{\r\n\t\treturn mGlobalConstraintUV;\r\n\t}\r\n\r\n\t/**\r\n\t * Set the world-space constraint unit-vector of this bone.\r\n\t *\r\n\t * @param\tv\tThe world-space constraint unit vector.\r\n\t */\r\n\tpublic void setGlobalConstraintUV(Vec2f v)\r\n\t{\r\n\t\tthis.mGlobalConstraintUV = v;\r\n\t}\r\n\r\n\t/**\r\n\t * Set the line width with which to draw this bone.\r\n\t * <p>\r\n\t * The value set is clamped to be between 1.0f and 64.0f inclusive, if necessary.\r\n\t *\r\n\t * @param\tlineWidth\tThe width of the line to draw this bone in pixels.\r\n\t */\r\n\tpublic void setLineWidth(float lineWidth)\r\n\t{\r\n\t\tif (lineWidth < 1.0f ) {\r\n\t\t mLineWidth = 1.0f;\r\n\t\t} else if (lineWidth > 64.0f) {\r\n\t\t mLineWidth = 64.0f;\r\n\t\t} else {\r\n\t mLineWidth = lineWidth;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Set the name of this bone, capped to 100 characters if required.\r\n\t *\r\n\t * @param\tname\tThe name to set.\r\n\t */\r\n\tpublic void setName(String name) { mName = Utils.getValidatedName(name); }\r\n\r\n\t/**\r\n\t * Return the name of this bone.\r\n\t *\r\n\t * @return\tThe name of this bone.\r\n\t */\r\n\tpublic String getName()\t{ return mName; }\r\n\r\n\r\n\t/**\r\n\t * Return the coordinate system to use for any constraints applied to the joint of this bone.\r\n\t *\r\n\t * @return\tThe coordinate system to use for any constraints applied to the joint of this bone.\r\n\t */\r\n\tpublic FabrikJoint2D.ConstraintCoordinateSystem getJointConstraintCoordinateSystem()\r\n\t{\r\n\t\treturn this.mJoint.getConstraintCoordinateSystem();\r\n\t}\r\n\r\n\t/**\r\n\t * Set the coordinate system to use for any constraints applied to the joint of this bone.\r\n\t *\r\n\t * @param\tcoordSystem\t\tThe coordinate system to use for any constraints applied to the joint of this bone.\r\n\t */\r\n\tpublic void setJointConstraintCoordinateSystem(FabrikJoint2D.ConstraintCoordinateSystem coordSystem)\r\n\t{\r\n\t\tthis.mJoint.setConstraintCoordinateSystem(coordSystem);\r\n\t}\r\n\r\n\t/**\r\n\t * Return a concise, human readable description of this FabrikBone2D as a String.\r\n\t *\r\n\t * The colour and line-width are not included in this output, but can be queried separately\r\n\t * via the getColour and getLineWidth methods.\r\n\t */\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\r\n\t\tsb.append(\"Start joint location : \" + mStartLocation + Utils.NEW_LINE);\r\n\t\tsb.append(\"End joint location : \" + mEndLocation + Utils.NEW_LINE);\r\n\t\tsb.append(\"Bone direction : \" + Vec2f.getDirectionUV(mStartLocation, mEndLocation) + Utils.NEW_LINE);\r\n\t\tsb.append(\"Bone length : \" + mLength + Utils.NEW_LINE);\r\n\t\tsb.append( mJoint.toString() );\r\n\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic void setStartLocation(Vec2f location) { mStartLocation.set(location); }\r\n\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic void setEndLocation(Vec2f location) { mEndLocation.set(location); }\r\n\r\n\t/**\r\n\t * Set the length of the bone.\r\n\t * <p>\r\n\t * If the length argument is not greater then zero an IllegalArgumentException is thrown.\r\n\t * If the length argument is precisely zero then\r\n\t *\r\n\t * @param\tlength\tThe value to set on the {@link #mLength} property.\r\n\t */\r\n\tprivate void setLength(float length)\r\n\t{\r\n\t\tif (length >= 0.0f)\r\n\t\t{\r\n\t\t\tmLength = length;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"Bone length must be a positive value.\");\r\n\t\t}\r\n\t}\r\n\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ((mColour == null) ? 0 : mColour.hashCode());\r\n result = prime * result + ((mEndLocation == null) ? 0 : mEndLocation.hashCode());\r\n result = prime * result + ((mJoint == null) ? 0 : mJoint.hashCode());\r\n result = prime * result + Float.floatToIntBits(mLength);\r\n result = prime * result + Float.floatToIntBits(mLineWidth);\r\n result = prime * result + ((mName == null) ? 0 : mName.hashCode());\r\n result = prime * result + ((mStartLocation == null) ? 0 : mStartLocation.hashCode());\r\n return result;\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 == null) {\r\n return false;\r\n }\r\n if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n FabrikBone2D other = (FabrikBone2D) obj;\r\n if (mColour == null) {\r\n if (other.mColour != null) {\r\n return false;\r\n }\r\n } else if (!mColour.equals(other.mColour)) {\r\n return false;\r\n }\r\n if (mEndLocation == null) {\r\n if (other.mEndLocation != null) {\r\n return false;\r\n }\r\n } else if (!mEndLocation.equals(other.mEndLocation)) {\r\n return false;\r\n }\r\n if (mJoint == null) {\r\n if (other.mJoint != null) {\r\n return false;\r\n }\r\n } else if (!mJoint.equals(other.mJoint)) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mLength) != Float.floatToIntBits(other.mLength)) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mLineWidth) != Float.floatToIntBits(other.mLineWidth)) {\r\n return false;\r\n }\r\n if (mName == null) {\r\n if (other.mName != null) {\r\n return false;\r\n }\r\n } else if (!mName.equals(other.mName)) {\r\n return false;\r\n }\r\n if (mStartLocation == null) {\r\n if (other.mStartLocation != null) {\r\n return false;\r\n }\r\n } else if (!mStartLocation.equals(other.mStartLocation)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n} // End of FabrikBone2D class\r", "public class FabrikChain2D implements FabrikChain<FabrikBone2D,Vec2f,FabrikJoint2D,BaseboneConstraintType2D>, Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\t/**\r\n\t * Basebone constraint types.\r\n\t *\r\n\t * Basebone constraints constrain the basebone (i.e. the first bone in a chain) and may be of the following types:\r\n\t * <ul>\r\n\t * <li>NONE - No constraint.</li>\r\n\t * <li>GLOBAL_ABSOLUTE - Constrained about a world-space direction.</li>\r\n\t * <li>LOCAL_RELATIVE - Constrained about the direction of the connected bone.</li>\r\n\t * <li>LOCAL_ABSOLUTE - Constrained about a direction with relative to the direction of the connected bone.</li>\r\n\t * </ul>\r\n\t * \r\n\t * See {@link #setBaseboneConstraintType(BaseboneConstraintType2D)}\r\n\t */\r\n\tpublic enum BaseboneConstraintType2D\timplements BaseboneConstraintType { NONE, GLOBAL_ABSOLUTE, LOCAL_RELATIVE, LOCAL_ABSOLUTE }\r\n\t\r\n\t// ---------- Private Properties ----------\r\n\r\n\t/**\r\n\t * The core of a FabrikChain2D is a list of FabrikBone2D objects, where each bone contains a start and end location, and a joint\r\n\t * that stores any rotational constraints.\r\n\t */\r\n\tprivate List<FabrikBone2D> mChain = new ArrayList<>();\r\n\r\n\t/** \r\n\t * The name of this FabrikChain2D object.\r\n\t * <p>\r\n\t * Although entirely optional, it may be used to uniquely identify a specific FabrikChain2D in an an array/vector/map\r\n\t * or such.\r\n\t * \r\n\t * See {@link au.edu.federation.caliko.FabrikChain#setName(String)}\r\n\t * See {@link au.edu.federation.caliko.FabrikChain#getName()}\r\n\t */\r\n\tprivate String mName;\r\n\r\n\t/** \r\n\t * The distance threshold we must meet in order to consider this FabrikChain2D to be successfully solved for distance.\r\n\t * <p>\r\n\t * When we solve a chain so that the distance between the end effector and target is less than or equal to the distance\r\n\t * threshold, then we consider the chain to be successfully solved and will dynamically abort any further attempts to solve the chain.\r\n\t * <p>\r\n\t * The minimum valid distance threshold is 0.0f, however a slightly higher value should be used to avoid forcing the IK\r\n\t * chain solve process to run repeatedly when an <strong>acceptable</strong> (but not necessarily <em>perfect</em>)\r\n\t * solution is found.\r\n\t * <p>\t\r\n\t * Although this property is the main criteria used to establish whether or not we have solved a given IK chain, it works\r\n\t * in combination with the {@link #mMaxIterationAttempts} and {@link mMinIterationChange} fields to improve the\r\n\t * performance of the algorithm in situations where we may not be able to solve a given IK chain. Such situations may arise\r\n\t * when bones in the chain are highly constrained, or when the target is further away than the length of a chain which has\r\n\t * a fixed base location.\r\n\t * \r\n\t * The default value is 1.0f.\r\n\t * \r\n\t * See {@link #setSolveDistanceThreshold(float)}\r\n\t */\r\n\tprivate float mSolveDistanceThreshold = 1.0f;\r\n\r\n\t/** \r\n\t * Specifies the maximum number of attempts that will be performed in order to solve this FabrikChain2D.\r\n\t *\r\n\t * As FABRIK is an iterative algorithm, after a single solve attempt we may not be within the solve distance threshold for the chain, so must take\r\n\t * the current chain configuration and perform another solve attempt. With a reasonable value for the solve distance threshold (i.e. the distance which\r\n\t * we must solve the chain for in order to consider it solved), it is common to be able to solve a given IK chain within a small number of attempts.\r\n\t *\r\n\t * However, some IK chains cannot be solved, whether this is due to joint constraints, or (in the case of an IK chain with a fixed base location)\r\n\t * where the distance between the base location and the target is greater than the length of the chain itself. In these cases, we may abort\r\n\t * any further attempts to solve the chain after this number of solve attempts. This decreases the execution time of the algorithm, as there\r\n\t * is no point in repeatedly attempting to solve an IK chain which cannot be solved.\r\n\t * <p>\r\n\t * Further, we may find that we are making unacceptably low progress towards solving the chain, then will also abort solving the chain based on the\r\n\t * {@link mMinIterationChange} threshold.\r\n\t * \r\n\t * The default value is 15.\r\n\t *\r\n\t * See {@link #setMaxIterationAttempts(int)}\r\n\t */\r\n\tprivate int mMaxIterationAttempts = 15;\r\n\r\n\t/** \r\n\t * Specifies the minimum change in the solve distance which must be made from one solve attempt to the next in order for us to believe it\r\n\t * worthwhile to continue making attempts to solve the IK chain.\r\n\t * <p>\r\n\t * As FABRIK is an iterative algorithm, after a single solve attempt we may not be within the solve distance threshold for the chain, so must take\r\n\t * the current chain configuration and perform another solve attempt. With a reasonable value for the solve distance threshold (i.e. the distance which\r\n\t * we must solve the chain for in order to consider it solved), it is common to be able to solve a given IK chain within a small number of attempts.\r\n\t * <p>\r\n\t * However, some IK chains cannot be solved, whether this is due to joint constraints, or (in the case of an IK chain with a fixed base location)\r\n\t * where the distance between the base location and the target is greater than the length of the chain itself. In these cases, we abort attempting\r\n\t * to solve the chain if we are making very little progress towards solving the chain between solve attempts. This decreases the execution time of\r\n\t * the algorithm, as there is no point in repeatedly attempting to solve an IK chain which cannot be solved.\r\n\t * <p> \r\n\t * This property must be greater than or equal to zero.\r\n\t *\r\n\t * The default value is 0.01f.\r\n\t *\r\n\t * See {@link #setMinIterationChange(float)}\r\n\t */\r\n\tprivate float mMinIterationChange = 0.01f;\r\n\r\n\t/**\r\n\t * The chainLength is the combined length of all bones in this FabrikChain2D object.\r\n\t *\r\n\t * When a FabrikBone2D is added or removed from the chain using the addBone/addConsecutiveBone or removeBone methods, then\r\n\t * the chainLength is updated to reflect this. \r\n\t */\r\n\tprivate float mChainLength;\r\n\r\n\t/** \r\n\t * The location of the start joint of the first bone added to the chain.\r\n\t * <p>\r\n\t * By default, FabrikChain2D objects are created with a fixed base location, that is, the start joint of the first bone in the chain is\r\n\t * immovable. As such, the start joint location of the first bone in the chain is stored in this property so that the base of the chain\r\n\t * can be snapped back to this location during the FABRIK solve process.\r\n\t * <p>\r\n\t * Base locations do not <em>have</em> to be fixed - this property can be modified to via the setFixedBaseLocation method.\r\n\t * \r\n\t * See {@link #setFixedBaseMode(boolean)}\r\n\t */\r\n\tprivate Vec2f mBaseLocation = new Vec2f();\r\n\r\n\r\n\t/** mFixedBaseMode\tWhether this FabrikChain2D has a fixed (i.e. immovable) base location.\r\n\t *\r\n\t * By default, the location of the start joint of the first bone added to the IK chain is considered fixed. This\r\n\t * 'anchors' the base of the chain in place. Optionally, a user may call the setFixedBaseMode method to disable\r\n\t * fixing the base bone start location in place.\r\n\t * \r\n\t * The default value is true (i.e. the basebone of the chain is fxied in place).\r\n\t *\r\n\t * See {@link #setFixedBaseMode(boolean)}\r\n\t */\r\n\tprivate boolean mFixedBaseMode = true;\r\n\t\r\n\t/**\r\n\t * The type of constraint applied to the basebone of this chain.\r\n\t * \r\n\t * The default value is BaseboneConstraintType2D.NONE.\r\n\t */\r\n\tprivate BaseboneConstraintType2D mBaseboneConstraintType = BaseboneConstraintType2D.NONE;\r\n\t\r\n\t/**\r\n\t * If this chain is connected to a bone in another chain, then this property controls whether\r\n\t * it should connect to the start end location of the host bone.\r\n\t * \r\n\t * The default value is BoneConnectionPoint.END.\r\n\t *\r\n\t * See {@link #setBoneConnectionPoint(BoneConnectionPoint)}\r\n\t * See {@link FabrikStructure2D#connectChain(FabrikChain2D, int, int, BoneConnectionPoint)}\r\n\t */\r\n\tprivate BoneConnectionPoint mBoneConnectionPoint = BoneConnectionPoint.END;\r\n\t\r\n\t/**\r\n\t * The direction around which we should constrain the base bone, as provided to the setBaseboneConstraintUV method.\r\n\t * \r\n\t * See {@link #setBaseboneConstraintUV(Vec2f)} \r\n\t */\r\n\tprivate Vec2f mBaseboneConstraintUV = new Vec2f();\r\n\t\r\n\t/**\r\n\t * The (internally used) constraint unit vector when this chain is connected to another chain in either\r\n\t * LOCAL_ABSOLUTE or LOCAL_RELATIVE modes.\r\n\t * <p>\r\n\t * This property cannot be accessed by users and is updated in the FabrikStructure2D.solveForTarget() method.\r\n\t */\r\n\tprivate Vec2f mBaseboneRelativeConstraintUV = new Vec2f();\r\n\t\r\n\t/**\r\n\t * mLastTargetLocation\tThe last target location for the end effector of this IK chain.\r\n\t * <p>\r\n\t * The last target location is used during the solve attempt and is specified as a property of the chain to avoid\r\n\t * memory allocation at runtime.\r\n\t */\r\n\tprivate Vec2f mLastTargetLocation = new Vec2f(Float.MAX_VALUE, Float.MAX_VALUE);\r\n\t\r\n\t/** \r\n\t * mLastBaseLocation - The previous base location of the chain from the last solve attempt.\r\n\t * \r\n\t * The default value is Vec2f(Float.MAX_VALUE, Float.MAX_VALUE).\r\n\t */\r\n\tprivate Vec2f mLastBaseLocation = new Vec2f(Float.MAX_VALUE, Float.MAX_VALUE);\r\n\t\r\n\t/**\r\n\t * mEmbeddedTarget\tAn embedded target location which can be used to solve this chain.\r\n\t * <p>\r\n\t * Embedded target locations allow structures to be solved for multiple targets (one per chain in the structure)\r\n\t * rather than all chains being solved for the same target. To use embedded targets, the mUseEmbeddedTargets flag\r\n\t * must be true (which is not the default) - this flag can be set via a call to setEmbeddedTarget(true).\r\n\t * \r\n\t * See {@link #setEmbeddedTargetMode(boolean)}\r\n\t */\r\n\tprivate Vec2f mEmbeddedTarget = new Vec2f();\r\n\t\r\n\t/**\r\n\t * mUseEmbeddedTarget\tWhether or not to use the mEmbeddedTarget location when solving this chain.\r\n\t * <p>\r\n\t * This flag may be toggled by calling the setEmbeddedTargetMode(boolean) method on the chain.\r\n\t * \r\n\t * The default value is false.\r\n\t *\r\n\t * See {@link #setEmbeddedTargetMode(boolean)}\r\n\t */\r\n\tprivate boolean mUseEmbeddedTarget = false;\r\n\t\r\n\t/**\r\n\t * mCurrentSolveDistance\tThe current distance between the end effector and the target location for this IK chain.\r\n\t * <p>\r\n\t * The current solve distance is updated when an attempt is made to solve IK chain as triggered by a call to the\r\n\t * {@link #solveForTarget(Vec2f)} or (@link #solveForTarget(float, float) methods.\r\n\t */\r\n\tprivate float mCurrentSolveDistance = Float.MAX_VALUE;\r\n\t\r\n\t/**\r\n\t * The zero-indexed number of the chain this chain is connected to in a FabrikStructure2D.\r\n\t * <p>\t * \r\n\t * If this value is -1 then this chain is not connected to another chain.\r\n\t * \r\n\t * The default value is -1.\r\n\t */\r\n\tprivate int mConnectedChainNumber = -1;\r\n\t\r\n\t/**\r\n\t * The zero-indexed number of the bone that this chain is connected to, if it's connected to another chain at all.\r\n\t * <p>\r\n\t * If the value is -1 then it's not connected to another bone in another chain.\r\n\t * \r\n\t * The default value is -1.\r\n\t */ \r\n\tprivate int mConnectedBoneNumber = -1;\r\n\r\n\t// ---------- Constructors ----------\r\n\r\n\t/** Default constructor. */\r\n\tpublic FabrikChain2D() { }\r\n\t\r\n\t/**\r\n\t * Naming constructor.\r\n\t * \r\n\t * @param\tname\tThe name of this chain.\r\n\t */\r\n\tpublic FabrikChain2D(String name) {\tmName = name; }\r\n\t\r\n\t/**\r\n\t * Copy constructor.\r\n\t *\r\n\t * @param\tsource\tThe FabrikChain2D to use as the basis for this new FabrikChain2D.\r\n\t */\r\n\tpublic FabrikChain2D(FabrikChain2D source)\r\n\t{\r\n\t\t// Force copy by value\r\n\t\tmChain = source.cloneChainVector();\r\n\t\tmBaseLocation.set(source.mBaseLocation);\r\n\t\tmLastTargetLocation.set(source.mLastTargetLocation);\r\n\t\tmLastBaseLocation.set(source.mLastBaseLocation);\r\n\t\tmBaseboneConstraintUV.set(source.mBaseboneConstraintUV);\r\n\t\tmBaseboneRelativeConstraintUV.set(source.mBaseboneRelativeConstraintUV);\t\r\n\t\tmEmbeddedTarget.set(source.mEmbeddedTarget);\r\n\t\t\r\n\t\t// Native copy by value for primitive members\r\n\t\tmChainLength = source.mChainLength;\r\n\t\tmCurrentSolveDistance = source.mCurrentSolveDistance;\r\n\t\tmConnectedChainNumber = source.mConnectedChainNumber;\r\n\t\tmConnectedBoneNumber = source.mConnectedBoneNumber;\r\n\t\tmBaseboneConstraintType = source.mBaseboneConstraintType;\r\n\t\tmBoneConnectionPoint = source.mBoneConnectionPoint;\r\n\t\tmName = source.mName;\r\n\t\tmUseEmbeddedTarget = source.mUseEmbeddedTarget;\r\n\t}\r\n\r\n\t// ---------- Public Methods ------------\r\n\r\n\t/**\r\n\t * Add a bone to the end of this IK chain of this FabrikChain2D object.\r\n\t * <p>\r\n\t * This chain's {@link mChainLength} property is updated to take into account the length of the\r\n\t * new bone added to the chain.\r\n\t * <p>\r\n\t * In addition, if the bone being added is the very first bone, then this chain's\r\n\t * {@link mBaseLocation} property is set from the start joint location of the bone.\r\n\t * \r\n\t * @param\tbone\tThe FabrikBone2D object to add to this FabrikChain2D.\r\n\t * @see\t\t#mChainLength\r\n\t * @see\t\t#mBaseLocation\r\n\t */\r\n\t@Override\r\n\tpublic void addBone(FabrikBone2D bone)\r\n\t{\r\n\t\t// Add the new bone to the end of the chain\r\n\t\tmChain.add(bone);\r\n\r\n\t\t// If this is the basebone...\r\n\t\tif (this.mChain.size()==1)\r\n\t\t{\r\n\t\t\t// ...then keep a copy of the fixed start location...\r\n\t\t\tmBaseLocation.set( bone.getStartLocation() );\r\n\t\t\t\r\n\t\t\t// ...and set the basebone constraint UV to be around the bone direction\r\n\t\t\tmBaseboneConstraintUV = bone.getDirectionUV();\r\n\t\t}\r\n\r\n\t\t// ...and update the desired length of the chain (i.e. combined length of all bones)\r\n\t\tupdateChainLength();\r\n\t}\r\n\r\n\t/**\r\n\t * Add a constrained bone to the end of this IK chain.\r\n\t * <p>\r\n\t * The constraint angles are relative to the coordinate system of the previous bone in the chain.\r\n\t * <p>\r\n\t * This method can only be used when the IK chain contains a base bone, as without it we do not\r\n\t * have a start location for this bone (i.e. the end location of the previous bone).\r\n\t * <p>\r\n\t * If this method is called on a chain which does not contain a base bone\r\n\t * then a {@link RuntimeException} is thrown.\r\n\t * <p>\r\n\t * Specifying a direction unit vector of zero will result in an IllegalArgumentException being thrown.\r\n\t * \r\n\t * @param\tdirectionUV\t\t\tThe initial direction of the new bone\r\n\t * @param\tlength\t\t\t\tThe length of the new bone\r\n\t * @param\tclockwiseDegs\t\tThe clockwise constraint angle in degrees.\r\n\t * @param\tanticlockwiseDegs\tThe anti-clockwise constraint angle in degrees.\r\n\t */\r\n\tpublic void addConsecutiveConstrainedBone(Vec2f directionUV, float length, float clockwiseDegs, float anticlockwiseDegs)\r\n\t{\r\n\t\taddConsecutiveConstrainedBone( directionUV, length, clockwiseDegs, anticlockwiseDegs, new Colour4f() );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add a constrained bone to the end of this IK chain.\r\n\t * <p>\r\n\t * The constraint angles are relative to the coordinate system of the previous bone in the chain.\r\n\t * <p>\r\n\t * This method can only be used when the IK chain contains a base bone, as without it we do not\r\n\t * have a start location for this bone (i.e. the end location of the previous bone).\r\n\t * <p>\r\n\t * If this method is called on a chain which does not contain a base bone\r\n\t * then a {@link RuntimeException} is thrown.\r\n\t * <p>\r\n\t * Specifying a direction unit vector of zero will result in an IllegalArgumentException being thrown.\r\n\t * \r\n\t * @param\tdirectionUV\t\t\tThe initial direction of the new bone\r\n\t * @param\tlength\t\t\t\tThe length of the new bone\r\n\t * @param\tclockwiseDegs\t\tThe clockwise constraint angle in degrees.\r\n\t * @param\tanticlockwiseDegs\tThe anti-clockwise constraint angle in degrees.\r\n\t * @param\tcolour\t\t\t\tThe colour to draw the bone.\r\n\t */\r\n\tpublic void addConsecutiveConstrainedBone(Vec2f directionUV, float length, float clockwiseDegs, float anticlockwiseDegs, Colour4f colour)\r\n\t{\r\n\t\t// Validate the direction unit vector - throws an IllegalArgumentException if it has a magnitude of zero\r\n\t\tUtils.validateDirectionUV(directionUV);\r\n\t\t\r\n\t\t// Validate the length of the bone - throws an IllegalArgumentException if it is not a positive value\r\n\t\tUtils.validateLength(length);\r\n\t\t\t\t\r\n\t\t// If we have at least one bone already in the chain...\r\n\t\tif (!this.mChain.isEmpty())\r\n\t\t{\t\t\r\n\t\t\t// Get the end location of the last bone, which will be used as the start location of the new bone\r\n\t\t\tVec2f prevBoneEnd = mChain.get(this.mChain.size()-1).getEndLocation();\r\n\t\t\t\t\r\n\t\t\t// Add a bone to the end of this IK chain\r\n\t\t\taddBone( new FabrikBone2D(prevBoneEnd, Vec2f.normalised(directionUV), length, clockwiseDegs, anticlockwiseDegs, colour) );\r\n\t\t}\r\n\t\telse // Attempting to add a relative bone when there is no base bone for it to be relative to?\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"You cannot add the base bone to a chain using this method as it does not provide a start location.\");\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Add a unconstrained bone to the end of this IK chain.\r\n\t * <p>\r\n\t * This method can only be used when the IK chain contains a base bone, as without it we do not\r\n\t * have a start location for this bone (i.e. the end location of the previous bone).\r\n\t * <p>\r\n\t * If this method is called on a chain which does not contain a base bone\r\n\t * then a {@link RuntimeException} is thrown.\r\n\t * <p>\r\n\t * Specifying a direction unit vector of zero will result in an IllegalArgumentException being thrown.\r\n\t * \r\n\t * @param\tdirectionUV\t\t\tThe initial direction of the new bone\r\n\t * @param\tlength\t\t\t\tThe length of the new bone\r\n\t */\r\n\t@Override\r\n\tpublic void addConsecutiveBone(Vec2f directionUV, float length)\r\n\t{\r\n\t\taddConsecutiveConstrainedBone( directionUV, length, 180.0f, 180.0f, new Colour4f() );\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * Add pre-created bone to the end of this IK chain.\r\n\t * <p>\r\n\t * This method can only be used when the IK chain contains a base bone, as without it we do not\r\n\t * have a start location for this bone (i.e. the end location of the previous bone).\r\n\t * <p>\r\n\t * If this method is called on a chain which does not contain a base bone\r\n\t * then a {@link RuntimeException} is thrown.\r\n\t * <p>\r\n\t * Specifying a direction unit vector of zero will result in an IllegalArgumentException being thrown.\r\n\t * \r\n\t * @param\tbone\t\t\tThe bone to add to the end of this chain.\r\n\t */\r\n\t@Override\r\n\tpublic void addConsecutiveBone(FabrikBone2D bone)\r\n\t{\r\n\t\t// Validate the direction unit vector - throws an IllegalArgumentException if it has a magnitude of zero\r\n\t\tVec2f dir = bone.getDirectionUV();\r\n\t\tUtils.validateDirectionUV(dir);\r\n\t\t\r\n\t\t// Validate the length of the bone - throws an IllegalArgumentException if it is not a positive value\r\n\t\tfloat len = bone.length();\r\n\t\tUtils.validateLength(len);\r\n\t\t\t\t\r\n\t\t// If we have at least one bone already in the chain...\r\n\t\tif ( !this.mChain.isEmpty() )\r\n\t\t{\t\t\r\n\t\t\t// Get the end location of the last bone, which will be used as the start location of the new bone\r\n\t\t\tVec2f prevBoneEnd = mChain.get(this.mChain.size()-1).getEndLocation();\r\n\t\t\t\t\r\n\t\t\tbone.setStartLocation(prevBoneEnd);\r\n\t\t\tbone.setEndLocation( prevBoneEnd.plus(dir.times(len)) );\r\n\t\t\t\r\n\t\t\t// Add a bone to the end of this IK chain\r\n\t\t\taddBone(bone);\r\n\t\t}\r\n\t\telse // Attempting to add a relative bone when there is no base bone for it to be relative to?\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"You cannot add the base bone to a chain using this method as it does not provide a start location.\");\r\n\t\t}\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * Return the basebone constraint type of this chain.\r\n\t * \r\n\t * @return The basebone constraint type of this chain.\r\n\t */\r\n\t@Override\r\n\tpublic BaseboneConstraintType2D getBaseboneConstraintType() { return mBaseboneConstraintType; }\r\n\t\r\n\t/**\r\n\t * Return the basebone constraint unit vector.\r\n\t * \r\n\t * @return The basebone constraint unit vector of this FabrikChain2D.\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getBaseboneConstraintUV() { return mBaseboneConstraintUV; }\r\n\t\r\n\t/**\r\n\t * Return \r\n\t * <p>\r\n\t * Regardless of how many bones are contained in the chain, the base location is always the start location of the first bone in the chain.\r\n\t * <p>\r\n\t * If there are no bones in the chain when this method is called then a RuntimeException is thrown.\r\n\t * \r\n\t * @return\tThe base location of this FabrikChain2D.\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getBaseLocation() \r\n\t{\r\n\t\tif (!this.mChain.isEmpty())\r\n\t\t{\r\n\t\t\treturn mChain.get(0).getStartLocation();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"Cannot get base location as there are zero bones in the chain.\");\r\n\t\t}\r\n\t}\t\r\n\r\n\t/**\r\n\t * Return a bone by its location in the IK chain.\r\n\t * <p>\r\n\t * The base bone is always bone 0, each additional bone increases the number by 1.\r\n\t * \r\n\t * @param\tboneNumber\tThe number of the bone to return from the Vector of FabrikBone2D objects.\r\n\t * @return\tThe FabrikBone2D at the given location in this chain. \r\n\t */\r\n\t@Override\r\n\tpublic FabrikBone2D getBone(int boneNumber)\r\n\t{\r\n\t\treturn mChain.get(boneNumber);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Return the bone connection point of this chain.\r\n\t * \r\n\t * The connection point will be either BoneConnectionPoint2D.START or BoneConnectionPoint2D.END.\r\n\t *\r\n\t * @return\tThe bone connection point of this chain.\r\n\t */\r\n\tpublic BoneConnectionPoint getBoneConnectionPoint() { return mBoneConnectionPoint; }\r\n\t\r\n\t/**\r\n\t * Return the actual IK chain of this FabrikChain2D object,\r\n\t * \r\n\t * @return\t\tThe IK chain of this FabrikChain2D as a List of FabrikBone2D objects.\r\n\t */\r\n\t@Override\r\n\tpublic List<FabrikBone2D> getChain() { return mChain; }\r\n\r\n\t/**\r\n\t * Return the current length of this IK chain.\r\n\t * <p>\r\n\t * This method does not dynamically re-calculate the length of the chain - it merely returns the previously\r\n\t * calculated chain length, which gets updated each time a bone is added to the chain.\r\n\t * \r\n\t * @return\tThe length of this IK chain as stored in the mChainLength property.\r\n\t */\r\n\t@Override\r\n\tpublic float getChainLength() { return mChainLength; }\r\n\t\r\n\t/**\r\n\t * Return the number of the bone in another chain that this FabrikChain2D is connected to.\r\n\t *\r\n\t * @return The connected bone number as stored in the mConnectedBoneNumber property.\r\n\t */\r\n\t@Override\r\n\tpublic int getConnectedBoneNumber() { return mConnectedBoneNumber; }\r\n\t\r\n\t/**\r\n\t * Return the number of the chain in the structure containing this FabrikChain2D that this chain is connected to.\r\n\t *\r\n\t * @return The connected chain number as stored in the mConnectedChainNumber property.\r\n\t */\r\n\t@Override\r\n\tpublic int getConnectedChainNumber() { return mConnectedChainNumber; }\r\n\t\r\n\t/**\r\n\t * Return the location of the end effector in the IK chain.\r\n\t * <p>\r\n\t * Regardless of how many bones are contained in the chain, the end effector is always\r\n\t * the end location of the final bone in the chain.\r\n\t * <p>\r\n\t * If there are no bones in the chain when this method is called then a RuntimeException is thrown.\r\n\t * \r\n\t * @return\tVec2f\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getEffectorLocation()\r\n\t{\r\n\t\tif (!this.mChain.isEmpty())\r\n\t\t{\r\n\t\t\treturn mChain.get(this.mChain.size()-1).getEndLocation();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"Cannot get effector location as there are zero bones in the chain.\");\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Return whether or not this chain uses an embedded target.\r\n\t * \r\n\t * Embedded target mode may be enabled or disabled using setEmbeddededTargetMode(boolean).\r\n\t * \r\n\t * @return whether or not this chain uses an embedded target.\r\n\t */\r\n\t@Override\r\n\tpublic boolean getEmbeddedTargetMode() { return mUseEmbeddedTarget; }\r\n\t\r\n\t/**\r\n\t * Return the embedded target location.\r\n\t * \r\n\t * @return the embedded target location.\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getEmbeddedTarget() { return mEmbeddedTarget; }\r\n\t\r\n\t/**\r\n\t * Return the last target location for which we attempted to solve this IK chain.\r\n\t * <p>\r\n\t * The last target location and the current target location may not be the same.\r\n\t * \r\n\t * @return\tThe last target location that we attempted to solve this chain for.\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getLastTargetLocation() { return mLastTargetLocation; }\r\n\t\r\n\t/**\r\n\t * Return the name of this FabrikChain2D.\r\n\t * \r\n\t * @return\tThe name of his chain, or <strong>null</strong> if the name has not been set.\r\n\t * \r\n\t * @see #setName(String)\r\n\t * @see #getName()\r\n\t */\r\n\t@Override\r\n\tpublic String getName() { return mName; }\r\n\t\r\n\t/**\r\n\t * Return the number of bones in the IK chain.\r\n\t * <p>\r\n\t * Bones may be added to the chain via the addBone or addConsecutiveBone methods.\r\n\t * \r\n\t * @return\tThe number of bones in the FabrikChain2D.\r\n\t */\r\n\t@Override\r\n\tpublic int getNumBones() { return this.mChain.size(); }\r\n\t\r\n\t/**\r\n\t * Remove a bone from this IK chain.\r\n\t * <p>\r\n\t * Bone numbers start at 0, so if there were 3 bones in a chain they would be at locations 0, 1 and 2.\r\n\t * <p> \r\n\t * This chain's {@link mChainLength} property is updated to take into account the new chain length.\r\n\t * <p>\r\n\t * If this chain does not contain a bone at the specified location then an IllegalArgumentException is thrown.\r\n\t * \r\n\t * @param\tboneNumber\tThe zero-indexed bone to remove from this IK chain.\r\n\t * @see\t\t#mChainLength\r\n\t * @see\t\t#mBaseLocation\r\n\t */\r\n\t@Override\r\n\tpublic void removeBone(int boneNumber)\r\n\t{\r\n\t\t// If the bone number is a bone which exists...\r\n\t\tif (boneNumber < this.mChain.size())\r\n\t\t{\r\n\t\t\t\r\n\t\t\t// ...then remove the bone, decrease the bone count and update the chain length.\r\n\t\t\tmChain.remove(boneNumber);\r\n\t\t\tupdateChainLength();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"Bone \" + boneNumber + \" does not exist in this chain.\");\r\n\t\t}\r\n\t}\r\n\t\r\n\t/** Set the basebone constraint type on this chain.\r\n\t * \r\n\t * @param type The BaseboneConstraintType2D to set.\r\n\t */\r\n\tpublic void setBaseboneConstraintType(BaseboneConstraintType2D type) { mBaseboneConstraintType = type; }\r\n\r\n\t/**\r\n\t * Set the constraint unit vector for the basebone of this chain..\r\n\t * <p>\r\n\t * The bone will be constrained about the clockwise and anticlockwise constraint angles with regard to this\r\n\t * direction methods on the FabrikBone2D to be constrained.\r\n\t * \r\n\t * @param constraintUV The direction unit vector to constrain the base bone to.\r\n\t * @see #setBaseboneConstraintType(BaseboneConstraintType2D)\r\n\t * @see au.edu.federation.caliko.FabrikJoint2D#setClockwiseConstraintDegs\r\n\t * @see au.edu.federation.caliko.FabrikJoint2D#setAnticlockwiseConstraintDegs\r\n\t */\r\n\t@Override\r\n\tpublic void setBaseboneConstraintUV(Vec2f constraintUV)\r\n\t{\r\n\t\t// Sanity checking\r\n\t\tUtils.validateDirectionUV(constraintUV);\r\n\t\t\r\n\t\t// All good? Then normalise the constraint direction and set it\r\n\t\tmBaseboneConstraintUV.set( Vec2f.normalised(constraintUV) );\r\n\t}\r\n\r\n\t/**\r\n\t * Set the base location of this chain.\r\n\t *\r\n\t * @param\tbaseLocation\tThe location to set the mBaseLocation property.\r\n\t * @see\t\t#mBaseLocation\r\n\t */\r\n\tpublic void setBaseLocation(Vec2f baseLocation) { mBaseLocation.set(baseLocation); }\r\n\t\r\n\t/**\r\n\t * Set the bone connection point of this chain.\r\n\t * <p>\r\n\t * When this chain is connected to another chain, it may either connect to the bone in the other chain at\r\n\t * the start (BoneConnectionPoint.START) or end (BoneConnectionPoint.END) of the bone.\r\n\t * <p>\r\n\t * This property is held per-chain rather than per-bone for efficiency.\r\n\t * \r\n\t * @param\tboneConnectionPoint\tThe BoneConnectionPoint to set on this chain.\r\n\t */\r\n\tpublic void setBoneConnectionPoint(BoneConnectionPoint boneConnectionPoint) { mBoneConnectionPoint = boneConnectionPoint; }\r\n\r\n\t/**\r\n\t * Set the List%lt;FabrikBone2D%gt; of this FabrikChain2D to the provided list by reference.\r\n\t * \r\n\t * @param\tchain\tThe List%lt;FabrikBone2D%gt; of FabrikBone2D objects to assign to this chain.\r\n\t * @see\t\t#mChain\r\n\t */\r\n\tpublic void setChain(List<FabrikBone2D> chain)\r\n\t{\r\n\t\t// Assign this chain to be a reference to the chain provided as an argument to this method\r\n\t\tthis.mChain = chain;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Set the colour of all bones in this chain to the specified colour.\r\n\t * \r\n\t * @param\tcolour\tThe colour to set on all bones in this chain.\r\n\t */\r\n\tpublic void setColour(Colour4f colour)\r\n\t{\t\t\t\r\n\t\tfor (FabrikBone2D aBone : this.mChain)\r\n\t\t{\r\n\t\t\taBone.setColour(colour);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Set which number bone this chain is connected to in another chain in a FabrikStructure2D object.\r\n\t * \r\n\t * @param\tboneNumber\tThe number of the bone this chain is connected to.\r\n\t */\r\n\tvoid setConnectedBoneNumber(int boneNumber)\t{ mConnectedBoneNumber = boneNumber; }\r\n\t\r\n\t/**\r\n\t * Set which number chain this chain is connected to in a FabrikStructure2D object.\r\n\t * \r\n\t * @param\tchainNumber\tThe number of the chain that this chain is connected to.\r\n\t */\r\n\tvoid setConnectedChainNumber(int chainNumber) {\tmConnectedChainNumber = chainNumber; }\r\n\t\r\n\t/**\r\n\t * Set the fixed base bone mode for this chain.\r\n\t * <p>\r\n\t * If the base bone is 'fixed' in place, then its start location cannot move unless it is attached\r\n\t * to another chain (which moves). The bone is still allowed to rotate, with or without constraints.\r\n\t * <p>\r\n\t * Specifying a non-fixed base location while this chain is connected to another chain will result in a\r\n\t * RuntimeException being thrown.\r\n\t * <p>\r\n\t * Fixing the base bone's start location in place and constraining to a global absolute direction are\r\n\t * mutually exclusive. Disabling fixed base mode while the chain's constraint type is\r\n\t * BaseBoneConstraintType2D.GLOBAL_ABSOLUTE will result in a RuntimeException being thrown. \r\n\t * \r\n\t * @param value Whether or not to fix the base bone start location in place.\r\n\t */\r\n\t@Override\r\n\tpublic void setFixedBaseMode(boolean value)\r\n\t{\t\r\n\t\tif (!value && mConnectedChainNumber != -1)\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"This chain is connected to another chain so must remain in fixed base mode.\");\r\n\t\t}\r\n\t\t\r\n\t\t// We cannot have a freely moving base location AND constrain the base bone - so if we have both\r\n\t\t// enabled then we disable the base bone angle constraint here.\r\n\t\tif (mBaseboneConstraintType == BaseboneConstraintType2D.GLOBAL_ABSOLUTE && !value)\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"Cannot set a non-fixed base mode when the chain's constraint type is BaseBoneConstraintType2D.GLOBAL_ABSOLUTE.\");\r\n\t\t}\r\n\t\t\r\n\t\t// Above conditions met? Set the fixedBaseMode\r\n\t\tmFixedBaseMode = value;\r\n\t}\r\n\r\n\t/**\r\n\t * Set the maximum number of attempts that will be made to solve this IK chain.\r\n\t * <p>\r\n\t * The FABRIK algorithm may require more than a single pass in order to solve\r\n\t * a given IK chain for an acceptable distance threshold. If we reach this\r\n\t * iteration limit then we stop attempting to solve the IK chain.\r\n\t * <p>\r\n\t * Specifying a maxIterations value of less than 1 will result in an IllegalArgumentException is thrown.\r\n\t * \r\n\t * @param maxIterations The maximum number of attempts that will be made to solve this IK chain.\r\n\t */\r\n\t@Override\r\n\tpublic void setMaxIterationAttempts(int maxIterations)\r\n\t{\r\n\t\t// Ensure we have a valid maximum number of iteration attempts\r\n\t\tif (maxIterations < 1)\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"The maximum number of attempts to solve this IK chain must be at least 1.\");\r\n\t\t}\r\n\t\t\r\n\t\t// All good? Set the new maximum iteration attempts property\r\n\t\tmMaxIterationAttempts = maxIterations;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Set the minimum iteration change before we dynamically abort any further attempts to solve this IK chain.\r\n\t * <p>\r\n\t * If the current solve distance changes by less than this amount between solve attempt then we consider the\r\n\t * solve process to have stalled and dynamically abort any further attempts to solve the chain to minimise CPU usage.\r\n\t * <p>\r\n\t * If a minIterationChange value of less than zero is provided then an IllegalArgumentException is thrown.\r\n\t * \r\n\t * @param minIterationChange The minimum change in solve distance from one iteration to the next.\r\n\t */\r\n\t@Override\r\n\tpublic void setMinIterationChange(float minIterationChange)\r\n\t{\r\n\t\t// Ensure we have a valid maximum number of iteration attempts\r\n\t\tif (minIterationChange < 0.0f)\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"The minimum iteration change value must be more than or equal to zero.\");\r\n\t\t}\r\n\t\t\r\n\t\t// All good? Set the new minimum iteration change distance\r\n\t\tmMinIterationChange = minIterationChange;\r\n\t}\r\n\t\r\n\t/** \r\n\t * Set the name of this chain, capped to 100 characters if required.\r\n\t * \r\n\t * @param\tname\tThe name to set.\r\n\t */\r\n\t @Override\r\n\tpublic void setName(String name) { mName = Utils.getValidatedName(name); }\r\n\r\n\t/**\r\n\t * Set the distance threshold within which we consider the IK chain to be solved.\r\n\t * <p>\r\n\t * If a solve distance of less than zero is provided then an IllegalArgumentException is thrown.\r\n\t * \r\n\t * @param solveDistance The distance between the end effector of this IK chain and target within which we will accept the solution.\r\n\t */\r\n\t @Override\r\n\tpublic void setSolveDistanceThreshold(float solveDistance)\r\n\t{\r\n\t\t// Ensure we have a valid solve distance\r\n\t\tif (solveDistance < 0.0f)\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"The solve distance threshold must be greater than or equal to zero.\");\r\n\t\t}\r\n\t\t\r\n\t\t// All good? Set the new solve distance threshold\r\n\t\tmSolveDistanceThreshold = solveDistance;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * Solve the Inverse Kinematics (IK) problem using the FABRIK algorithm in two dimensions.\r\n\t * <p>\r\n\t * The FABRIK algorithm itself can be found in the following paper:\r\n\t * Aristidou, A., & Lasenby, J. (2011). FABRIK: a fast, iterative solver for the inverse kinematics problem. Graphical Models, 73(5), 243-260.\r\n\t * <p> \r\n\t * The end result of running this method is that the IK chain configuration is updated (i.e. joint locations for\r\n\t * each bone in the chain are modified in order to solve the chain for the provided target location).\r\n\t * <p>\r\n\t * @param \ttarget\tThe target location to solve the IK chain for.\r\n\t * @return\tfloat\tThe distance between the end effector and the given target location after attempting to solve the IK chain.\r\n\t */\r\n\tprivate float solveIK(Vec2f target)\r\n\t{\t\r\n\t\t// ---------- Step 1 of 2 - Forward pass from end-effector to base -----------\r\n\r\n\t\t// Loop over all bones in the chain, from the end effector (numBones-1) back to the base bone (0)\t\t\r\n\t\tfor (int loop = this.mChain.size()-1; loop >= 0; --loop)\r\n\t\t{\r\n\t\t\t// Get this bone\r\n\t\t\tFabrikBone2D thisBone = mChain.get(loop);\r\n\t\t\t\r\n\t\t\t// Get the length of the bone we're working on\r\n\t\t\tfloat boneLength = thisBone.length();\t\t\t\r\n\t\t\t\r\n\t\t\t// If we are not working on the end effector bone\r\n\t\t\tif (loop != this.mChain.size() - 1)\r\n\t\t\t{\r\n\t\t\t\tFabrikBone2D outerBone = mChain.get(loop+1);\r\n\t\t\t\t\r\n\t\t\t\t// Get the outer-to-inner unit vector of the bone further out\r\n\t\t\t\tVec2f outerBoneOuterToInnerUV = outerBone.getDirectionUV().negated();\r\n\r\n\t\t\t\t// Get the outer-to-inner unit vector of this bone\r\n\t\t\t\tVec2f thisBoneOuterToInnerUV = thisBone.getDirectionUV().negated();\r\n\t\t\t\t\r\n\t\t\t\t// Constrain the angle between the outer bone and this bone.\r\n\t\t\t\t// Note: On the forward pass we constrain to the limits imposed by joint of the outer bone.\r\n\t\t\t\tfloat clockwiseConstraintDegs = outerBone.getJoint().getClockwiseConstraintDegs();\r\n\t\t\t\tfloat antiClockwiseConstraintDegs = outerBone.getJoint().getAnticlockwiseConstraintDegs();\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tVec2f constrainedUV;\r\n\t\t\t\tif (mChain.get(loop).getJointConstraintCoordinateSystem() == FabrikJoint2D.ConstraintCoordinateSystem.LOCAL)\r\n\t\t\t\t{\r\n\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneOuterToInnerUV, outerBoneOuterToInnerUV, clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t}\r\n\t\t\t\telse // Constraint is in global coordinate system\r\n\t\t\t\t{\r\n\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneOuterToInnerUV, thisBone.getGlobalConstraintUV().negated(), clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t// At this stage we have a outer-to-inner unit vector for this bone which is within our constraints,\r\n\t\t\t\t// so we can set the new inner joint location to be the end joint location of this bone plus the\r\n\t\t\t\t// outer-to-inner direction unit vector multiplied by the length of the bone.\r\n\t\t\t\tVec2f newStartLocation = thisBone.getEndLocation().plus( constrainedUV.times(boneLength) );\r\n\r\n\t\t\t\t// Set the new start joint location for this bone\r\n\t\t\t\tthisBone.setStartLocation(newStartLocation);\r\n\r\n\t\t\t\t// If we are not working on the base bone, then we set the end joint location of\r\n\t\t\t\t// the previous bone in the chain (i.e. the bone closer to the base) to be the new\r\n\t\t\t\t// start joint location of this bone also.\r\n\t\t\t\tif (loop > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tmChain.get(loop-1).setEndLocation(newStartLocation);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse // If we are working on the end effector bone ...\r\n\t\t\t{\r\n\t\t\t\t// Snap the end effector's end location to the target\r\n\t\t\t\tthisBone.setEndLocation(target);\r\n\t \r\n\t\t\t\t// Get the UV between the target / end-location (which are now the same) and the start location of this bone\r\n\t\t\t\tVec2f thisBoneOuterToInnerUV = thisBone.getDirectionUV().negated();\r\n\t \r\n\t\t\t\tVec2f constrainedUV;\r\n\t\t\t\tif (loop > 0) {\r\n\t\t\t\t\t// The end-effector bone is NOT the basebone as well\r\n\t\t\t\t\t// Get the outer-to-inner unit vector of the bone further in\r\n\t\t\t\t\tVec2f innerBoneOuterToInnerUV = mChain.get(loop-1).getDirectionUV().negated();\r\n\t \r\n\t\t\t\t\t// Constrain the angle between the this bone and the inner bone\r\n\t\t\t\t\t// Note: On the forward pass we constrain to the limits imposed by the first joint of the inner bone.\r\n\t\t\t\t\tfloat clockwiseConstraintDegs = thisBone.getJoint().getClockwiseConstraintDegs();\r\n\t\t\t\t\tfloat antiClockwiseConstraintDegs = thisBone.getJoint().getAnticlockwiseConstraintDegs();\r\n\t \r\n\t\t\t\t\t// If this bone is locally constrained...\r\n\t\t\t\t\tif (thisBone.getJoint().getConstraintCoordinateSystem() == ConstraintCoordinateSystem.LOCAL)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// Params: directionUV, baselineUV, clockwise, anticlockwise\r\n\t\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV( thisBoneOuterToInnerUV, innerBoneOuterToInnerUV, clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse // End effector bone is globally constrained\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV( thisBoneOuterToInnerUV, thisBone.getGlobalConstraintUV().negated(), clockwiseConstraintDegs, antiClockwiseConstraintDegs);\t\t\t\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t \r\n\t\t\t\t}\r\n\t\t\t\telse // There is only one bone in the chain, and the bone is both the basebone and the end-effector bone.\r\n\t\t\t\t{\r\n\t\t\t\t\t// Don't constraint (nothing to constraint against) if constraint is in local coordinate system\r\n\t\t\t\t\tif (thisBone.getJointConstraintCoordinateSystem() == FabrikJoint2D.ConstraintCoordinateSystem.LOCAL)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconstrainedUV = thisBoneOuterToInnerUV;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse // Can constrain if constraining against global coordinate system\r\n\t\t\t\t\t{\t\r\n\t\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneOuterToInnerUV, thisBone.getGlobalConstraintUV().negated(), thisBone.getClockwiseConstraintDegs(), thisBone.getAnticlockwiseConstraintDegs());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t \r\n\t\t\t\t// Calculate the new start joint location as the end joint location plus the outer-to-inner direction UV\r\n\t\t\t\t// multiplied by the length of the bone.\r\n\t\t\t\tVec2f newStartLocation = thisBone.getEndLocation().plus( constrainedUV.times(boneLength) );\r\n\t \r\n\t\t\t\t// Set the new start joint location for this bone to be new start location...\r\n\t\t\t\tthisBone.setStartLocation(newStartLocation);\r\n\t\r\n\t\t\t\t// ...and set the end joint location of the bone further in to also be at the new start location.\r\n\t\t\t\tif (loop > 0) { \r\n\t\t\t\t\tmChain.get(loop-1).setEndLocation(newStartLocation);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} // End of forward-pass loop over all bones\r\n\r\n\t\t// ---------- Step 2 of 2 - Backward pass from base to end effector -----------\r\n\r\n\t\tfor (int loop = 0; loop < this.mChain.size(); ++loop)\r\n\t\t{\r\n\t\t\t// Get the length of the bone we're working on\r\n\t\t\tfloat boneLength = mChain.get(loop).length();\r\n\r\n\t\t\tFabrikBone2D thisBone = mChain.get(loop);\r\n\t\t\t\r\n\t\t\t// If we are not working on the base bone\r\n\t\t\tif (loop != 0)\r\n\t\t\t{\r\n\t\t\t\tFabrikBone2D previousBone = mChain.get(loop-1);\r\n\t\t\t\t\r\n\t\t\t\t// Get the inner-to-outer direction of this bone as well as the previous bone to use as a baseline\r\n\t\t\t\tVec2f thisBoneInnerToOuterUV = thisBone.getDirectionUV();\r\n\t\t\t\tVec2f prevBoneInnerToOuterUV = previousBone.getDirectionUV();\r\n\t\t\t\t\r\n\t\t\t\t// Constrain the angle between this bone and the inner bone.\r\n\t\t\t\t// Note: On the backward pass we constrain to the limits imposed by the first joint of this bone.\r\n\t\t\t\tfloat clockwiseConstraintDegs = thisBone.getJoint().getClockwiseConstraintDegs();\r\n\t\t\t\tfloat antiClockwiseConstraintDegs = thisBone.getJoint().getAnticlockwiseConstraintDegs();\r\n\t\t\t\t\r\n\t\t\t\tVec2f constrainedUV;\r\n\t\t\t\tif (thisBone.getJointConstraintCoordinateSystem() == ConstraintCoordinateSystem.LOCAL)\r\n\t\t\t\t{\r\n\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneInnerToOuterUV, prevBoneInnerToOuterUV, clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t}\r\n\t\t\t\telse // Bone is constrained in global coordinate system\r\n\t\t\t\t{\r\n\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneInnerToOuterUV, thisBone.getGlobalConstraintUV(), clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// At this stage we have an inner-to-outer unit vector for this bone which is within our constraints,\r\n\t\t\t\t// so we can set the new end location to be the start location of this bone plus the constrained\r\n\t\t\t\t// inner-to-outer direction unit vector multiplied by the length of this bone.\r\n\t\t\t\tVec2f newEndLocation = thisBone.getStartLocation().plus( constrainedUV.times(boneLength) );\r\n\r\n\t\t\t\t// Set the new end joint location for this bone\r\n\t\t\t\tthisBone.setEndLocation(newEndLocation);\r\n\r\n\t\t\t\t// If we are not working on the end bone, then we set the start joint location of\r\n\t\t\t\t// the next bone in the chain (i.e. the bone closer to the end effector) to be the\r\n\t\t\t\t// new end joint location of this bone also.\r\n\t\t\t\tif (loop < this.mChain.size()-1)\r\n\t\t\t\t{\r\n\t\t\t\t\tmChain.get(loop+1).setStartLocation(newEndLocation);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse // If we ARE working on the base bone...\r\n\t\t\t{\t\r\n\t\t\t\t// If the base location is fixed then snap the start location of the base bone back to the fixed base\r\n\t\t\t\tif (mFixedBaseMode)\r\n\t\t\t\t{\r\n\t\t\t\t\tmChain.get(0).setStartLocation(mBaseLocation);\r\n\t\t\t\t}\r\n\t\t\t\telse // If the base location is not fixed...\r\n\t\t\t\t{\r\n\t\t\t\t\t// ...then set the new base bone start location to be its the end location minus the\r\n\t\t\t\t\t// bone direction multiplied by the length of the bone (i.e. projected backwards).\r\n\t\t\t\t\t//float boneZeroLength = mChain.get(0).length();\r\n\t\t\t\t\tVec2f boneZeroUV = mChain.get(0).getDirectionUV();\r\n\t\t\t\t\tVec2f boneZeroEndLocation = mChain.get(0).getEndLocation();\r\n\t\t\t\t\tVec2f newBoneZeroStartLocation = boneZeroEndLocation.minus( boneZeroUV.times(boneLength) );\r\n\t\t\t\t\tmChain.get(0).setStartLocation(newBoneZeroStartLocation);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// If the base bone is unconstrained then process it as usual...\r\n\t\t\t\tif (mBaseboneConstraintType == BaseboneConstraintType2D.NONE)\r\n\t\t\t\t{\r\n\t\t\t\t\t// Get the inner to outer direction of this bone\r\n\t\t\t\t\tVec2f thisBoneInnerToOuterUV = thisBone.getDirectionUV();\r\n\t\r\n\t\t\t\t\t// Calculate the new end location as the start location plus the direction times the length of the bone\r\n\t\t\t\t\tVec2f newEndLocation = thisBone.getStartLocation().plus( thisBoneInnerToOuterUV.times(boneLength) );\r\n\t\r\n\t\t\t\t\t// Set the new end joint location\r\n\t\t\t\t\tmChain.get(0).setEndLocation(newEndLocation);\r\n\t\r\n\t\t\t\t\t// Also, set the start location of the next bone to be the end location of this bone\r\n\t\t\t\t\tif (mChain.size() > 1) { \r\n\t\t\t\t\t mChain.get(1).setStartLocation(newEndLocation);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse // ...otherwise we must constrain it to the basebone constraint unit vector\r\n\t\t\t\t{\t\r\n\t\t\t\t\t// Note: The mBaseBoneConstraintUV is either fixed, or it may be dynamically updated from\r\n\t\t\t\t\t// a FabrikStructure2D if this chain is connected to another chain.\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Get the inner-to-outer direction of this bone\r\n\t\t\t\t\tVec2f thisBoneInnerToOuterUV = thisBone.getDirectionUV();\r\n\r\n\t\t\t\t\t// Get the constrained direction unit vector between the base bone and the base bone constraint unit vector\r\n\t\t\t\t\t// Note: On the backward pass we constrain to the limits imposed by the first joint of this bone.\r\n\t\t\t\t\tfloat clockwiseConstraintDegs = thisBone.getJoint().getClockwiseConstraintDegs();\r\n\t\t\t\t\tfloat antiClockwiseConstraintDegs = thisBone.getJoint().getAnticlockwiseConstraintDegs();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// LOCAL_ABSOLUTE? (i.e. local-space directional constraint) - then we must constraint about the relative basebone constraint UV...\r\n\t\t\t\t\tVec2f constrainedUV;\r\n\t\t\t\t\tif (mBaseboneConstraintType == BaseboneConstraintType2D.LOCAL_ABSOLUTE)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneInnerToOuterUV, mBaseboneRelativeConstraintUV, clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t\t\t\r\n//\t\t\t\t\t\tSystem.out.println(\"----- In LOCAL_ABSOLUTE --------\");\r\n//\t\t\t\t\t\tSystem.out.println(\"This bone UV = \" + thisBoneInnerToOuterUV);\r\n//\t\t\t\t\t\tSystem.out.println(\"Constraint UV = \" + mBaseboneConstraintUV);\r\n//\t\t\t\t\t\tSystem.out.println(\"Relative constraint UV = \" + mBaseboneRelativeConstraintUV);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse // ...otherwise we're free to use the standard basebone constraint UV.\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconstrainedUV = Vec2f.getConstrainedUV(thisBoneInnerToOuterUV, mBaseboneConstraintUV, clockwiseConstraintDegs, antiClockwiseConstraintDegs);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t// At this stage we have an inner-to-outer unit vector for this bone which is within our constraints,\r\n\t\t\t\t\t// so we can set the new end location to be the start location of this bone plus the constrained\r\n\t\t\t\t\t// inner-to-outer direction unit vector multiplied by the length of the bone.\r\n\t\t\t\t\tVec2f newEndLocation = mChain.get(loop).getStartLocation().plus( constrainedUV.times(boneLength) );\r\n\r\n\t\t\t\t\t// Set the new end joint location for this bone\r\n\t\t\t\t\tmChain.get(loop).setEndLocation(newEndLocation);\r\n\r\n\t\t\t\t\t// If we are not working on the end bone, then we set the start joint location of\r\n\t\t\t\t\t// the next bone in the chain (i.e. the bone closer to the end effector) to be the\r\n\t\t\t\t\t// new end joint location of this bone.\r\n\t\t\t\t\tif (loop < this.mChain.size()-1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmChain.get(loop+1).setStartLocation(newEndLocation);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t} // End of basebone constraint enforcement section\t\t\t\r\n\r\n\t\t\t} // End of base bone handling section\r\n\r\n\t\t} // End of backward-pass loop over all bones\r\n\r\n\t\t// Update our last target location\r\n\t\tmLastTargetLocation.set(target);\r\n\t\t\r\n\t\t// Finally, get the current effector location...\r\n\t\tVec2f currentEffectorLocation = mChain.get(this.mChain.size()-1).getEndLocation();\r\n\t\t\t\t\r\n\t\t// ...and calculate and return the distance between the current effector location and the target.\r\n\t\treturn Vec2f.distanceBetween(currentEffectorLocation, target);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Specify whether we should use the embedded target location when solving the IK chain.\r\n\t * \r\n\t * @param\tvalue\tWhether we should use the embedded target location when solving the IK chain.\r\n\t */\r\n\t@Override\r\n\tpublic void setEmbeddedTargetMode(boolean value) { mUseEmbeddedTarget = value; }\r\n\t\r\n\t/**\r\n\t * Return a concise, human-readable of the IK chain.\r\n\t * @return String\r\n\t */\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\t\r\n\t\t\tsb.append(\"----- FabrikChain2D: \" + mName + \" -----\" + Utils.NEW_LINE);\t\t\t\t\r\n\t\t\tsb.append(\"Number of bones: \" + this.mChain.size() + Utils.NEW_LINE);\r\n\t\t\t\r\n\t\t\tsb.append(\"Fixed base mode: \");\r\n\t\t\tif (mFixedBaseMode) { \r\n\t\t\t sb.append(\"Yes.\" + Utils.NEW_LINE); \r\n\t\t\t} else { \r\n\t\t\t sb.append(\"No.\" + Utils.NEW_LINE); \r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tsb.append(\"Base location: \" + getBaseLocation() );\r\n\t\t\r\n\t\treturn sb.toString();\r\n\t} \r\n\r\n\t// ---------- Private Methods ----------\r\n\t\r\n\t/**\r\n\t * Clone and return the IK Chain of this FabrikChain2D, that is, the Vector of FabrikBone2D objects.\r\n\t * <p>\r\n\t * This does not clone the entire FabrikChain2D object, only its IK chain.\r\n\t * \r\n\t * @return\tThe clones list of FabrikBone2D objects\r\n\t */\r\n\tprivate List<FabrikBone2D> cloneChainVector()\r\n\t{\r\n\t\t// How many bones are in this chain?\r\n\t\tint numBones = mChain.size();\r\n\t\t\r\n\t\t// Create a new Vector of FabrikBone2D objects large enough to contain all the bones in this chain\r\n\t\tList<FabrikBone2D> clonedChain = new ArrayList<>(numBones);\r\n\r\n\t\t// For each bone in the chain being cloned...\t\t\r\n\t\tfor (int loop = 0; loop < numBones; ++loop)\r\n\t\t{\r\n\t\t\t// ...use the FabrikBone2D copy constructor to create a new FabrikBone2D with the properties as set from the source bone\r\n\t\t\t// and add it to the cloned chain\r\n\t\t\tclonedChain.add( new FabrikBone2D( mChain.get(loop) ) );\r\n\t\t}\r\n\t\t\r\n\t\treturn clonedChain;\r\n\t}\r\n\t\r\n\t/***\r\n\t * Calculate the length of this IK chain by adding up the lengths of each bone.\r\n\t * <p>\r\n\t * The resulting chain length is stored in the mChainLength property.\r\n\t * <p>\r\n\t * This method is called each time a bone is added to the chain. In addition, the\r\n\t * length of each bone is recalculated during the process to ensure that our chain\r\n\t * length is accurate. As the typical usage of a FabrikChain2D is to add a number\r\n\t * of bones once (during setup) and then use them, this should not have any\r\n\t * performance implication on the typical execution cycle of a FabrikChain2D object,\r\n\t * as this method will not be called in any method which executes regularly. \r\n\t */\r\n\t@Override\r\n\tpublic void updateChainLength()\r\n\t{\r\n\t\tmChainLength = 0.0f;\r\n\t\tfor (FabrikBone2D aBone : this.mChain)\r\n\t\t{\r\n\t\t\tmChainLength += aBone.length();\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Update the embedded target for this chain.\r\n\t * \r\n\t * The internal mEmbeddedTarget object is updated with the location of the provided parameter.\r\n\t * If the chain is not in useEmbeddedTarget mode then a RuntimeException is thrown.\r\n\t * Embedded target mode can be enabled by calling setEmbeddedTargetMode(true) on the chain.\r\n\t * \r\n\t * @param newEmbeddedTarget\tThe location of the embedded target.\r\n\t */\r\n\tpublic void updateEmbeddedTarget(Vec2f newEmbeddedTarget)\r\n\t{\r\n\t\t// Using embedded target mode? Overwrite embedded target with provided location\r\n\t\tif (mUseEmbeddedTarget) { \r\n\t\t mEmbeddedTarget.set(newEmbeddedTarget); \r\n\t\t}\r\n\t\telse { \r\n\t\t throw new RuntimeException(\"This chain does not have embedded targets enabled - enable with setEmbeddedTargetMode(true).\"); \r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Update the embedded target for this chain.\r\n\t * \r\n\t * The internal mEmbeddedTarget object is updated with the location of the provided parameter.\r\n\t * If the chain is not in useEmbeddedTarget mode then a RuntimeException is thrown.\r\n\t * Embedded target mode can be enabled by calling setEmbeddedTargetMode(true) on the chain.\r\n\t * \r\n\t * @param x\tThe x location of the embedded target.\r\n\t * @param y\tThe y location of the embedded target.\r\n\t */\r\n\tpublic void updateEmbeddedTarget(float x, float y)\r\n\t{\r\n\t\t// Using embedded target mode? Overwrite embedded target with provided location\r\n\t\tif (mUseEmbeddedTarget) { \r\n\t\t mEmbeddedTarget.set( new Vec2f(x, y) ); \r\n\t\t}\r\n\t\telse { \r\n\t\t throw new RuntimeException(\"This chain does not have embedded targets enabled - enable with setEmbeddedTargetMode(true).\"); \r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Solve this IK chain for the current embedded target location.\r\n\t * \r\n\t * The embedded target location can be updated by calling updateEmbeddedTarget(Vec2f).\r\n\t * \r\n\t * @return The distance between the end effector and the chain's embedded target location for our best solution.\r\n\t */\r\n\t@Override\r\n\tpublic float solveForEmbeddedTarget()\r\n\t{\r\n\t\tif (mUseEmbeddedTarget) { \r\n\t\t return solveForTarget(mEmbeddedTarget); \r\n\t\t}\r\n\t\telse { \r\n\t\t throw new RuntimeException(\"This chain does not have embedded targets enabled - enable with setEmbeddedTargetMode(true).\"); \r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Solve the IK chain for this target to the best of our ability.\r\n\t * <p>\r\n\t * We will iteratively attempt up to solve the chain up to a maximum of mMaxIterationAttempts.\r\n\t * \r\n\t * This method may return early if any of the following conditions are met:\r\n\t * <ul>\r\n\t * <li>We've already solved for this target location,</li>\r\n\t * <li>We successfully solve for distance, or</li>\r\n\t * <li>We grind to a halt (i.e. low iteration change compared to previous solution).</li>\r\n\t * </ul>\r\n\t * <p>\r\n\t * This method simply constructs a Vec2f from the provided arguments and calls the {@link Vec2f} version of the solveForTarget method.\r\n\t * By making this available, the user does not need to use our custom {@link Vec2f} class in their application.\r\n\t * \r\n\t * @param targetX\t(float)\tThe x location of the target.\r\n\t * @param targetY\t(float) The y location of the target.\r\n\t * @see \tmMaxIterationAttempts\r\n\t * @see \tmSolveDistanceThreshold\r\n\t * @see \tmMinIterationChange\r\n\t * @return\tThe distance between the end effector and the target for our best solution\r\n\t */\r\n\tpublic float solveForTarget(float targetX, float targetY)\r\n\t{\r\n\t\treturn solveForTarget( new Vec2f(targetX, targetY) );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Solve the IK chain for this target to the best of our ability.\r\n\t * <p>\r\n\t * We will iteratively attempt up to solve the chain up to a maximum of mMaxIterationAttempts.\r\n\t * \r\n\t * This method may return early if any of the following conditions are met:\r\n\t * <ul>\r\n\t * <li>We've already solved for this target location,</li>\r\n\t * <li>We successfully solve for distance, or</li>\r\n\t * <li>We grind to a halt (i.e. low iteration change compared to previous solution).</li>\r\n\t * </ul>\r\n\t * \r\n\t * The solution may NOT change we cannot improve upon the calculated distance between the new target location and the existing solution.\r\n\t * \r\n\t * @param newTarget\tThe target location to solve this IK chain for.\r\n\t * \r\n\t * @see \tmMaxIterationAttempts\r\n\t * @see \tmSolveDistanceThreshold\r\n\t * @see \tmMinIterationChange\r\n\t * @return\tThe distance between the end effector and the target for our best solution\r\n\t */\r\n\tpublic float solveForTarget(Vec2f newTarget)\r\n\t{\t\t\r\n\t\t// Same target as before? Abort immediately and save ourselves some cycles\r\n\t\tif ( mLastTargetLocation.approximatelyEquals(newTarget, 0.001f) && mLastBaseLocation.approximatelyEquals(mBaseLocation, 0.001f) )\r\n\t\t{\r\n\t\t\treturn mCurrentSolveDistance;\r\n\t\t}\r\n\t\t\r\n\t\t// Keep starting solutions and distance\r\n\t\tfloat startingDistance;\r\n\t\tList<FabrikBone2D> startingSolution = null;\r\n\t\t\r\n\t\t// If the base location of a chain hasn't moved then we may opt to keep the current solution if our \r\n\t\t// best new solution is worse...\r\n\t\tif (mLastBaseLocation.approximatelyEquals(mBaseLocation, 0.001f))\r\n\t\t{\t\t\t\r\n\t\t\tstartingDistance = Vec2f.distanceBetween(mChain.get(mChain.size() - 1).getEndLocation(), newTarget);\r\n\t\t\tstartingSolution = this.cloneChainVector();\r\n\t\t}\r\n\t\telse // Base has changed? Then we have little choice but to recalc the solution and take that new solution.\r\n\t\t{\r\n\t\t\tstartingDistance = Float.MAX_VALUE;\r\n\t\t}\r\n\t\t\r\n\t\t// Not the same target? Then we must solve the chain for the new target.\r\n\t\t// We'll start by creating a list of bones to store our best solution\r\n\t\tList<FabrikBone2D> bestSolution = new ArrayList<>(this.mChain.size());\r\n\t\t\r\n\t\t// We'll keep track of our best solve distance, starting it at a huge value which will be beaten on first attempt\t\t\t\r\n\t\tfloat bestSolveDistance = Float.MAX_VALUE;\r\n\t\tfloat lastPassSolveDistance = Float.MAX_VALUE;\r\n\t\t\r\n\t\t// Allow up to our iteration limit attempts at solving the chain\r\n\t\tfloat solveDistance;\r\n\t\tfor (int loop = 0; loop < mMaxIterationAttempts; ++loop)\r\n\t\t{\t\r\n\t\t\t// Solve the chain for this target\r\n\t\t\tsolveDistance = solveIK(newTarget);\r\n\t\t\t\r\n\t\t\t// Did we solve it for distance? If so, update our best distance and best solution, and also\r\n\t\t\t// update our last pass solve distance. Note: We will ALWAYS beat our last solve distance on the first run. \r\n\t\t\tif (solveDistance < bestSolveDistance)\r\n\t\t\t{\t\r\n\t\t\t\tbestSolveDistance = solveDistance;\r\n\t\t\t\tbestSolution = this.cloneChainVector();\r\n\t\t\t\t\r\n\t\t\t\t// Did we solve for distance? Great! Break out of the loop.\r\n\t\t\t\tif (solveDistance <= mSolveDistanceThreshold) { \r\n\t\t\t\t break; \r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse // Did not solve to our satisfaction? Okay...\r\n\t\t\t{\r\n\t\t\t\t// Did we grind to a halt? If so then it's time to break out of the loop.\r\n\t\t\t\tif (Math.abs(solveDistance - lastPassSolveDistance) < mMinIterationChange) { \r\n\t\t\t\t break; \r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Update the last pass solve distance\r\n\t\t\tlastPassSolveDistance = solveDistance;\r\n\t\t}\r\n\t\t\r\n\t\t// Did we get a solution that's better than the starting solution's to the new target location?\r\n\t\tif (bestSolveDistance < startingDistance)\r\n\t\t{\r\n\t\t\t// If so, set the newly found solve distance and solution as the best found.\r\n\t\t\tmCurrentSolveDistance = bestSolveDistance;\r\n\t\t\tmChain = bestSolution;\r\n\t\t}\r\n\t\telse // Did we make things worse? Then we keep our starting distance and solution!\r\n\t\t{\r\n\t\t\tmCurrentSolveDistance = startingDistance;\r\n\t\t\tmChain = startingSolution; \r\n\t\t}\t\t\t\t\r\n\t\t\r\n\t\t// Update our last base and target locations so we know whether we need to solve for this start/end configuration next time\r\n\t\tmLastBaseLocation.set(mBaseLocation);\r\n\t\tmLastTargetLocation.set(newTarget);\r\n\t\t\r\n\t\t// Finally, return the solve distance we ended up with\r\n\t\treturn mCurrentSolveDistance;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Return the relative constraint UV about which this bone connects to a bone in another chain.\r\n\t *\r\n\t * @return\tThe relative constraint UV about which this bone connects to a bone in another chain.\r\n\t */\r\n\t@Override\r\n\tpublic Vec2f getBaseboneRelativeConstraintUV() { return mBaseboneRelativeConstraintUV; }\r\n\t\r\n\t/**\r\n\t * Set the constraint UV about which this bone connects to a bone in another chain.\r\n\t *\r\n\t * @param\tconstraintUV\tThe basebone relative constraint unit vector to set.\r\n\t */\r\n\tpublic void setBaseboneRelativeConstraintUV(Vec2f constraintUV) { mBaseboneRelativeConstraintUV.set(constraintUV); }\r\n\t\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic int getMaxIterationAttempts() {\r\n\t\treturn this.mMaxIterationAttempts;\r\n\t}\r\n\t\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic float getMinIterationChange() {\r\n\t\treturn this.mMinIterationChange;\r\n\t}\r\n\t\r\n\t/**\r\n\t * {@inheritDoc}\r\n\t */\r\n\t@Override\r\n\tpublic float getSolveDistanceThreshold() {\r\n\t\treturn this.mSolveDistanceThreshold;\r\n\t}\r\n\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ((mBaseLocation == null) ? 0 : mBaseLocation.hashCode());\r\n result = prime * result + ((mBaseboneConstraintType == null) ? 0 : mBaseboneConstraintType.hashCode());\r\n result = prime * result + ((mBaseboneConstraintUV == null) ? 0 : mBaseboneConstraintUV.hashCode());\r\n result = prime * result + ((mBaseboneRelativeConstraintUV == null) ? 0 : mBaseboneRelativeConstraintUV.hashCode());\r\n result = prime * result + ((mBoneConnectionPoint == null) ? 0 : mBoneConnectionPoint.hashCode());\r\n result = prime * result + ((mChain == null) ? 0 : mChain.hashCode());\r\n result = prime * result + Float.floatToIntBits(mChainLength);\r\n result = prime * result + mConnectedBoneNumber;\r\n result = prime * result + mConnectedChainNumber;\r\n result = prime * result + Float.floatToIntBits(mCurrentSolveDistance);\r\n result = prime * result + ((mEmbeddedTarget == null) ? 0 : mEmbeddedTarget.hashCode());\r\n result = prime * result + (mFixedBaseMode ? 1231 : 1237);\r\n result = prime * result + ((mLastBaseLocation == null) ? 0 : mLastBaseLocation.hashCode());\r\n result = prime * result + ((mLastTargetLocation == null) ? 0 : mLastTargetLocation.hashCode());\r\n result = prime * result + mMaxIterationAttempts;\r\n result = prime * result + Float.floatToIntBits(mMinIterationChange);\r\n result = prime * result + ((mName == null) ? 0 : mName.hashCode());\r\n result = prime * result + Float.floatToIntBits(mSolveDistanceThreshold);\r\n result = prime * result + (mUseEmbeddedTarget ? 1231 : 1237);\r\n return result;\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 == null) {\r\n return false;\r\n }\r\n if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n FabrikChain2D other = (FabrikChain2D) obj;\r\n if (mBaseLocation == null) {\r\n if (other.mBaseLocation != null) {\r\n return false;\r\n }\r\n } else if (!mBaseLocation.equals(other.mBaseLocation)) {\r\n return false;\r\n }\r\n if (mBaseboneConstraintType != other.mBaseboneConstraintType) {\r\n return false;\r\n }\r\n if (mBaseboneConstraintUV == null) {\r\n if (other.mBaseboneConstraintUV != null) {\r\n return false;\r\n }\r\n } else if (!mBaseboneConstraintUV.equals(other.mBaseboneConstraintUV)) {\r\n return false;\r\n }\r\n if (mBaseboneRelativeConstraintUV == null) {\r\n if (other.mBaseboneRelativeConstraintUV != null) {\r\n return false;\r\n }\r\n } else if (!mBaseboneRelativeConstraintUV.equals(other.mBaseboneRelativeConstraintUV)) {\r\n return false;\r\n }\r\n if (mBoneConnectionPoint != other.mBoneConnectionPoint) {\r\n return false;\r\n }\r\n if (mChain == null) {\r\n if (other.mChain != null) {\r\n return false;\r\n }\r\n } else if (!mChain.equals(other.mChain)) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mChainLength) != Float.floatToIntBits(other.mChainLength)) {\r\n return false;\r\n }\r\n if (mConnectedBoneNumber != other.mConnectedBoneNumber) {\r\n return false;\r\n }\r\n if (mConnectedChainNumber != other.mConnectedChainNumber) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mCurrentSolveDistance) != Float.floatToIntBits(other.mCurrentSolveDistance)) {\r\n return false;\r\n }\r\n if (mEmbeddedTarget == null) {\r\n if (other.mEmbeddedTarget != null) {\r\n return false;\r\n }\r\n } else if (!mEmbeddedTarget.equals(other.mEmbeddedTarget)) {\r\n return false;\r\n }\r\n if (mFixedBaseMode != other.mFixedBaseMode) {\r\n return false;\r\n }\r\n if (mLastBaseLocation == null) {\r\n if (other.mLastBaseLocation != null) {\r\n return false;\r\n }\r\n } else if (!mLastBaseLocation.equals(other.mLastBaseLocation)) {\r\n return false;\r\n }\r\n if (mLastTargetLocation == null) {\r\n if (other.mLastTargetLocation != null) {\r\n return false;\r\n }\r\n } else if (!mLastTargetLocation.equals(other.mLastTargetLocation)) {\r\n return false;\r\n }\r\n if (mMaxIterationAttempts != other.mMaxIterationAttempts) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mMinIterationChange) != Float.floatToIntBits(other.mMinIterationChange)) {\r\n return false;\r\n }\r\n if (mName == null) {\r\n if (other.mName != null) {\r\n return false;\r\n }\r\n } else if (!mName.equals(other.mName)) {\r\n return false;\r\n }\r\n if (Float.floatToIntBits(mSolveDistanceThreshold) != Float.floatToIntBits(other.mSolveDistanceThreshold)) {\r\n return false;\r\n }\r\n if (mUseEmbeddedTarget != other.mUseEmbeddedTarget) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\t\r\n\r\n} // End of FabrikChain2D class\r", "public enum BaseboneConstraintType2D\timplements BaseboneConstraintType { NONE, GLOBAL_ABSOLUTE, LOCAL_RELATIVE, LOCAL_ABSOLUTE }\r", "public static enum ConstraintCoordinateSystem { LOCAL, GLOBAL };\r", "public class FabrikStructure2D implements FabrikStructure<FabrikChain2D,Vec2f>, Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\tprivate static final Vec2f UP = new Vec2f(0.0f, 1.0f);\r\n\t\r\n\t// ---------- Private Properties ----------\r\n\t\r\n\t/** The string name of this FabrikStructure2D - can be used for creating Maps, if required. */\r\n\tprivate String mName;\r\n\r\n\t/** The main substance of a FabrikStructure2D is an ArrayList of FabrikChain2D objects. */\r\n\tprivate List<FabrikChain2D> mChains = new ArrayList<>();\r\n\r\n\t/** Property to indicate if the first chain (chain zero) in this structure has its basebone fixed in place or not. */\r\n\tprivate boolean mFixedBaseMode = true;\r\n\r\n\t// --------- Public Methods ----------\r\n\r\n\t/** Default constructor. */\r\n\tpublic FabrikStructure2D() { }\r\n\t\r\n\t/**\r\n\t * Naming constructor.\r\n\t * <p>\r\n\t * Names lengths are limited to 100 characters and are truncated if necessary.\r\n\t * \r\n\t * @param\tname\tThe name you wish to call the structure.\r\n\t */\r\n\tpublic FabrikStructure2D(String name) {\tsetName(name); }\r\n\r\n\t/** \r\n\t * Set the name of this structure, capped to 100 characters if required.\r\n\t * \r\n\t * @param\tname\tThe name to set.\r\n\t */\r\n\t@Override\r\n\tpublic void setName(String name) { mName = Utils.getValidatedName(name); }\r\n\t\r\n\t/**\r\n\t * Solve the structure for the given target location.\r\n\t * <p>\r\n\t * All chains in this structure are solved for the given target location EXCEPT those which have embedded targets enabled, which are\r\n\t * solved for the target location embedded in the chain.\r\n\t * <p>\r\n\t * After this method has been executed, the configuration of all IK chains attached to this structure will have been updated.\r\n\t * \r\n\t * @param newTargetLocation\tThe location of the target for which we will attempt to solve all chains attached to this structure.\r\n\t */\r\n\t@Override\r\n\tpublic void solveForTarget(Vec2f newTargetLocation)\r\n\t{\r\n\t\tint numChains = mChains.size();\r\n\t\tint hostChainNumber;\r\n\t\tFabrikChain2D thisChain;\t\t\r\n\t\t\r\n\t\tfor (int loop = 0; loop < numChains; ++loop)\r\n\t\t{\r\n\t\t\tthisChain = mChains.get(loop);\r\n\t\t\t\r\n\t\t\t// Is this chain connected to another chain?\r\n\t\t\thostChainNumber = thisChain.getConnectedChainNumber();\r\n\t\t\t\r\n\t\t\t// Get the basebone constraint type of the chain we're working on\r\n\t\t\tBaseboneConstraintType2D constraintType = thisChain.getBaseboneConstraintType();\r\n\t\t\t\r\n\t\t\t// If this chain is not connected to another chain and the basebone constraint type of this chain is not global absolute\r\n\t\t\t// then we must update the basebone constraint UV for LOCAL_RELATIVE and the basebone relative constraint UV for LOCAL_ABSOLUTE connection types.\r\n\t\t\t// Note: For NONE or GLOBAL_ABSOLUTE we don't need to update anything before calling updateTarget().\r\n\t\t\tif (hostChainNumber != -1 && constraintType != BaseboneConstraintType2D.GLOBAL_ABSOLUTE)\r\n\t\t\t{\t\r\n\t\t\t\t// Get the bone which this chain is connected to in the 'host' chain\r\n\t\t\t\tFabrikBone2D hostBone = mChains.get(hostChainNumber).getBone( mChains.get(loop).getConnectedBoneNumber() );\r\n\t\t\t\t\r\n\t\t\t\t// If we're connecting this chain to the start location of the bone in the 'host' chain...\r\n\t\t\t\tif (thisChain.getBoneConnectionPoint() == BoneConnectionPoint.START)\r\n\t\t\t\t{\r\n\t\t\t\t\t// ...set the base location of this bone to be the start location of the bone it's connected to.\r\n\t\t\t\t\tthisChain.setBaseLocation( hostBone.getStartLocation() );\r\n\t\t\t\t}\r\n\t\t\t\telse // If the bone connection point is BoneConnectionPoint.END...\r\n\t\t\t\t{\t\r\n\t\t\t\t\t// ...set the base location of the chain to be the end location of the bone we're connecting to.\r\n\t\t\t\t\tthisChain.setBaseLocation( hostBone.getEndLocation() );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// If the basebone is constrained to the direction of the bone it's connected to...\r\n\t\t\t\tVec2f hostBoneUV = hostBone.getDirectionUV();\r\n\t\t\t\tif (constraintType == BaseboneConstraintType2D.LOCAL_RELATIVE)\r\n\t\t\t\t{\t\r\n\t\t\t\t\t// ...then set the basebone constraint UV to be the direction of the bone we're connected to.\r\n\t\t\t\t\tmChains.get(loop).setBaseboneConstraintUV(hostBoneUV);\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t\telse if (constraintType == BaseboneConstraintType2D.LOCAL_ABSOLUTE)\r\n\t\t\t\t{\t\r\n\t\t\t\t\t// Note: LOCAL_ABSOLUTE directions are directions which are in the local coordinate system of the host bone.\r\n\t\t\t\t\t// For example, if the baseboneConstraintUV is Vec2f(-1.0f, 0.0f) [i.e. left], then the baseboneConnectionConstraintUV\r\n\t\t\t\t\t// will be updated to be left with regard to the host bone.\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Get the angle between UP and the hostbone direction\r\n\t\t\t\t\tfloat angleDegs = UP.getSignedAngleDegsTo(hostBoneUV);\r\n\t\t\t\t\t\r\n\t\t\t\t\t// ...then apply that same rotation to this chain's basebone constraint UV to get the relative constraint UV... \r\n\t\t\t\t\tVec2f relativeConstraintUV = Vec2f.rotateDegs( thisChain.getBaseboneConstraintUV(), angleDegs);\r\n\t\t\t\t\t\r\n\t\t\t\t\t// ...which we then update.\r\n\t\t\t\t\tthisChain.setBaseboneRelativeConstraintUV(relativeConstraintUV);\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// NOTE: If the basebone constraint type is NONE then we don't do anything with the basebone constraint of the connected chain.\r\n\t\t\t\t\r\n\t\t\t} // End of if chain is connected to another chain section\r\n\t\t\t\r\n\t\t\t// Update the target and solve the chain\r\n\t\t\tif ( !thisChain.getEmbeddedTargetMode() )\r\n\t\t\t{\r\n\t\t\t\tthisChain.solveForTarget(newTargetLocation);\t\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthisChain.solveForEmbeddedTarget();\r\n\t\t\t}\t\t\t\r\n\t\t\t\r\n\t\t} // End of loop over chains\r\n\t\t\r\n\t} // End of updateTarget method\r\n\r\n\t/**\r\n\t * Add a FabrikChain2D object to a FabrikStructure2D object.\r\n\t * <p>\r\n\t * Adding a chain using this method adds the chain to the structure, but does not connect it to any existing chain in the structure.\r\n\t * However, all chains in a structure share the same target, and all chains in the structure can be solved for the target location\r\n\t * via a single call to updateTarget on this structure.\r\n\t * \r\n\t * @param chain\t(FabrikChain2D)\tThe FabrikChain2D to add to this structure.\r\n\t **/\r\n\t@Override\r\n\tpublic void addChain(FabrikChain2D chain)\r\n\t{\r\n\t\tmChains.add(chain);\t\t\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * Add a chain to this structure which is connected to a specific bone of an existing chain in this structure.\r\n\t * <p>\r\n\t * When connecting a chain to an existing chain in a structure, the multiple chains will all share the same\r\n\t * target location / end effector.\r\n\t * <p>\r\n\t * The location of the bones in the chain to be connected should be specified relative to the origin (0.0f, 0.0f),\r\n\t * not relative to the current location of connection point in the chain being connected to. On connection, all\r\n\t * bones are translated (that is, moved horizontally and vertically) so that they're positioned relative to the\r\n\t * end location of the specified bone in the specified chain.\r\n\t * <p> \r\n\t * Both chains within the structure and bones within a chain are zero. If the chainNumber or boneNumber specified\r\n\t * do not exist then an IllegalArgumentException is thrown.\r\n\t * \r\n\t * @param\tchain\t\tThe chain to connect to this structure\r\n\t * @param\tchainNumber The zero indexed number of the chain to connect the provided chain to.\r\n\t * @param\tboneNumber\tThe zero indexed number of the bone within the specified chain to connect the provided chain to.\r\n\t */\r\n\t@Override\r\n\tpublic void connectChain(FabrikChain2D chain, int chainNumber, int boneNumber)\r\n\t{\t\r\n\t\t// Does this chain exist? If not throw an IllegalArgumentException\r\n\t\tif (chainNumber >= this.mChains.size())\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot connect to chain \" + chainNumber + \" - no such chain (remember that chains are zero indexed).\");\r\n\t\t}\r\n\t\t\r\n\t\t// Do we have this bone in the specified chain? If not throw an IllegalArgumentException\r\n\t\tif ( boneNumber >= mChains.get(chainNumber).getNumBones() )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot connect to bone \" + boneNumber + \" of chain \" + chainNumber + \" - no such bone (remember that bones are zero indexed).\");\r\n\t\t}\r\n\t\t\t\t\r\n\t\t// Note: Any basebone constraint type is fine for a connected chain\r\n\t\t\r\n\t\t// The chain as we were provided should be centred on the origin, so we must now make it\r\n\t\t// relative to the connection point in the given chain.\t\t\r\n\t\tFabrikChain2D relativeChain = new FabrikChain2D(chain);\t\t\r\n\t\trelativeChain.setConnectedChainNumber(chainNumber);\r\n\t\trelativeChain.setConnectedBoneNumber(boneNumber);\r\n\t\t\r\n\t\t// Get the connection point so we know to connect at the start or end location of the bone we're connecting to\r\n\t\tBoneConnectionPoint connectionPoint = chain.getBoneConnectionPoint();\t\t\r\n\t\tVec2f connectionLocation;\r\n\t\tif (connectionPoint == BoneConnectionPoint.START)\r\n\t\t{\r\n\t\t\tconnectionLocation = mChains.get(chainNumber).getBone(boneNumber).getStartLocation();\r\n\t\t}\r\n\t\telse // If it's BoneConnectionPoint.END then we set the connection point to be the end location of the bone we're connecting to\r\n\t\t{\r\n\t\t\tconnectionLocation = mChains.get(chainNumber).getBone(boneNumber).getEndLocation();\r\n\t\t}\t\t\r\n\t\trelativeChain.setBaseLocation(connectionLocation);\r\n\t\t\r\n\t\t// When we have a chain connected to a another 'host' chain, the chain is which is connecting in\r\n\t\t// MUST have a fixed base, even though that means the base location is 'fixed' to the connection\r\n\t\t// point on the host chain, rather than a static location.\r\n\t\trelativeChain.setFixedBaseMode(true);\r\n\t\t\r\n\t\t// Translate the chain we're connecting to the connection point\r\n\t\tfor (int loop = 0; loop < chain.getNumBones(); ++loop)\r\n\t\t{\r\n\t\t\tVec2f origStart = relativeChain.getBone(loop).getStartLocation();\r\n\t\t\tVec2f origEnd = relativeChain.getBone(loop).getEndLocation();\r\n\t\t\t\r\n\t\t\tVec2f translatedStart = origStart.plus(connectionLocation);\r\n\t\t\tVec2f translatedEnd = origEnd.plus(connectionLocation);\r\n\t\t\t\r\n\t\t\trelativeChain.getBone(loop).setStartLocation(translatedStart);\r\n\t\t\trelativeChain.getBone(loop).setEndLocation(translatedEnd);\r\n\t\t}\r\n\t\t\r\n\t\tthis.addChain(relativeChain);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Connect a chain to an existing chain in the structure.\r\n\t * \r\n\t * @param\tchain\t\t\t\tThe chain which we will connect to this structure.\r\n\t * @param\tchainNumber\t\t\tThe zero-indexed number of the pre-existing chain in this structure that the new chain will attach to.\r\n\t * @param\tboneNumber\t\t\tThe zero-indexed number of bone in the pre-existing chain in this structure that the new chain will attach to.\r\n\t * @param\tboneConnectionPoint\tWhether to attach the new chain to the start or end point of the bone we are connecting to.\r\n\t */\r\n\t@Override\r\n\tpublic void connectChain(FabrikChain2D chain, int chainNumber, int boneNumber, BoneConnectionPoint boneConnectionPoint)\r\n\t{\r\n\t\t// Set the bone connection point so we'll connect to the start or the end point of the specified connection bone\r\n\t\tchain.setBoneConnectionPoint(boneConnectionPoint);\r\n\t\t\r\n\t\t// Call the standard addConnectedChain method to perform the connection\r\n\t\tconnectChain(chain, chainNumber, boneNumber);\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Return the number of chains in this structure.\r\n\t * \r\n\t * @return\tThe number of chains in this structure.\r\n\t */\r\n\t@Override\r\n\tpublic int getNumChains() { return this.mChains.size(); }\r\n\t\r\n\t/**\r\n\t * Return a chain which exists in this structure.\r\n\t * <p>\r\n\t * Note: Chains are zero-indexed.\r\n\t * \r\n\t * @param\tchainNumber\tThe zero-indexed chain in this structure to return.\r\n\t * @return\t\t\t\tThe desired chain.\r\n\t */\r\n\t@Override\r\n\tpublic FabrikChain2D getChain(int chainNumber) { return mChains.get(chainNumber); }\r\n\t\r\n\t/**\r\n\t * Set the fixed-base mode on the first chain in this structure.\r\n\t * \r\n\t * If disabling fixed-base mode and the first chain has a BaseBoneConstraintType of GLOBAL_ABSOLUTE\r\n\t * then a RuntimeException will be thrown as this these options are mutually exclusive.\r\n\t * \r\n\t * @param\tfixedBaseMode\tWhether we want this structure to operate in fixed-base mode (true) or not (false).\r\n\t */\r\n\tpublic void setFixedBaseMode(boolean fixedBaseMode)\r\n\t{\r\n\t\t// Update our flag and set the fixed base mode on the first (i.e. 0th) chain in this structure.\r\n\t\tmFixedBaseMode = fixedBaseMode;\t\t\r\n\t\tmChains.get(0).setFixedBaseMode(mFixedBaseMode);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String getName() {\r\n\t\treturn this.mName;\r\n\t}\r\n\r\n\t/**\r\n\t * Return a concise, human readable description of this FabrikStructure2D. \r\n\t * <p>\r\n\t * If further details on a specific chain are required, then you should get and print each chain individually.\r\n\t */\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tsb.append(\"----- FabrikStructure2D: \" + mName + \" -----\" + Utils.NEW_LINE);\t\t\r\n\t\tsb.append(\"Number of chains: \" + this.mChains.size() + Utils.NEW_LINE);\r\n\t\tfor (int loop = 0; loop < this.mChains.size(); ++loop)\r\n\t\t{\r\n\t\t\tsb.append(mChains.get(loop).toString() );\r\n\t\t}\r\n\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ((mChains == null) ? 0 : mChains.hashCode());\r\n result = prime * result + (mFixedBaseMode ? 1231 : 1237);\r\n result = prime * result + ((mName == null) ? 0 : mName.hashCode());\r\n return result;\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 == null) {\r\n return false;\r\n }\r\n if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n FabrikStructure2D other = (FabrikStructure2D) obj;\r\n if (mChains == null) {\r\n if (other.mChains != null) {\r\n return false;\r\n }\r\n } else if (!mChains.equals(other.mChains)) {\r\n return false;\r\n }\r\n if (mFixedBaseMode != other.mFixedBaseMode) {\r\n return false;\r\n }\r\n if (mName == null) {\r\n if (other.mName != null) {\r\n return false;\r\n }\r\n } else if (!mName.equals(other.mName)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n} // End of FabrikStructure2D class\r", "public class Colour4f implements Serializable\n{\n\tprivate static final long serialVersionUID = 1L;\n\n\t// ---------- Properties ----------\n\n\t/** The minimum valid value of any colour component. */\n\tprivate static final float MIN_COMPONENT_VALUE = 0.0f;\n\n\t/** The maximum valid value of any colour component. */\n\tprivate static final float MAX_COMPONENT_VALUE = 1.0f;\n\n\t/** Red component. Publicly accessible. */\n\tpublic float r;\n\n\t/** Green component. Publicly accessible. */\n\tpublic float g;\n\n\t/** Blue component. Publicly accessible. */\n\tpublic float b;\n\n\t/** Alpha (transparency) component. Publicly accessible. */\n\tpublic float a;\n\n\t// ---------- Constructors ----------\n\n\t/**\n\t * Default constructor.\n\t * <p>\n\t * The constructed Colour4f has it's RGBA components set to default values of 1.0f, which equates to white at full opacity.\n\t */\n\tpublic Colour4f() {\tr = g = b = a = 1.0f; }\n\n\t/**\n\t * Copy constructor.\n\t *\n\t * @param\tsource The source Colour4f object to copy the component values from.\n\t */\n\tpublic Colour4f(Colour4f source) { r = source.r; g = source.g; b = source.b; a = source.a; }\n\n\t/**\n\t * Array Constructor.\n\t * <p>\n\t * If the array size is not 4, then an IllegalArgument exception is thrown.\n\t *\n\t * @param\tsourceValues\tThe array of floats to copy the values from.\n\t */\n\tpublic Colour4f(float[] sourceValues)\n\t{\n\t\tif (sourceValues.length == 4)\n\t\t{\n\t\t\tthis.r = Colour4f.clamp( sourceValues[0] );\n\t\t\tthis.g = Colour4f.clamp( sourceValues[1] );\n\t\t\tthis.b = Colour4f.clamp( sourceValues[2] );\n\t\t\tthis.a = Colour4f.clamp( sourceValues[3] );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Colour source array size must be precisely 4 elements.\");\n\t\t}\n\t}\n\n\t/**\n\t * Float Constructor.\n\t * <p>\n\t * The valid range of each component is 0.0f to 1.0f inclusive, any values outside of this range will be clamped.\n\t *\n\t * @param red\t\tThe red component of this colour.\n\t * @param green\tThe green component of this colour.\n\t * @param blue\tThe blue component of this colour.\n\t * @param alpha\tThe alpha component of this colour.\n\t */\n\tpublic Colour4f(float red, float green, float blue, float alpha)\n\t{\n\t\tthis.r = Colour4f.clamp(red);\n\t\tthis.g = Colour4f.clamp(green);\n\t\tthis.b = Colour4f.clamp(blue);\n\t\tthis.a = Colour4f.clamp(alpha);\n\t}\n\n\t// ---------- Public Methods ----------\n\n\t/**\n\t * Set the RGBA values of this Colour4f object from a source Colour4f object.\n\t * <p>\n\t * Source values are clamped to the range 0.0f..1.0f.\n\t *\n\t * @param source \tThe source colour to set the values of this colour to.\n\t */\n\tpublic void set(Colour4f source)\n\t{\n\t\tthis.r = Colour4f.clamp(source.r);\n\t\tthis.g = Colour4f.clamp(source.g);\n\t\tthis.b = Colour4f.clamp(source.b);\n\t\tthis.a = Colour4f.clamp(source.a);\n\t}\n\n\t/**\n\t * Set the RGBA values of this Colour4f object from a red, green, blue and alpha value.\n\t * <p>\n\t * Any values outside the range 0.0f..1.0f are clamped to the nearest valid value.\n\t * <p>\n\t * @param red\t\t(float) The red component to set for this colour.\n\t * @param green\t(float) The green component to set for this colour.\n\t * @param blue\t(float) The blue component to set for this colour.\n\t * @param alpha\t(float) The alpha component to set for this colour.\n\t */\n\tpublic void set(final float red, final float green, final float blue, final float alpha)\n\t{\n\t\tthis.r = Colour4f.clamp(red);\n\t\tthis.g = Colour4f.clamp(green);\n\t\tthis.b = Colour4f.clamp(blue);\n\t\tthis.a = Colour4f.clamp(alpha);\n\t}\n\n\t/**\n\t * Add to the RGB components of this colour by the given amounts and return this modified colour for chaining.\n\t * <p>\n\t * When adding, colour values are clamped to a maximum value of 1.0f.\n\t *\n\t * @param red\t\tThe red component to add to this colour.\n\t * @param green\tThe green component to add to this colour.\n\t * @param blue\tThe blue component to add to this colour.\n\t * @return\t\t\tThis modified colour.\n\t */\n\tpublic Colour4f addRGB(float red, float green, float blue)\n\t{\n\t\tthis.r = Colour4f.clamp(this.r + red);\n\t\tthis.g = Colour4f.clamp(this.g + green);\n\t\tthis.b = Colour4f.clamp(this.b + blue);\n\t\treturn this;\n\t}\n\n\t/** Subtract from the RGB components of this colour by the given amounts and return this modified colour for chaining.\n\t * <p>\n\t * When subtracting, colour values are clamped to a minimum value of 1.0f.\n\t *\n\t * @param red\t\tThe red component to add to this colour.\n\t * @param green\tThe green component to add to this colour.\n\t * @param blue\tThe blue component to add to this colour.\n\t * @return\t\t\tThis modified colour.\n\t */\n\tpublic Colour4f subtractRGB(float red, float green, float blue)\n\t{\n\t\tthis.r = Colour4f.clamp(this.r - red);\n\t\tthis.g = Colour4f.clamp(this.g - green);\n\t\tthis.b = Colour4f.clamp(this.b - blue);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Lighten the RGB components of this colour by a given amount.\n\t * <p>\n\t * Resulting colour components are clamped to the range 0.0f..1.0f.\n\t *\n\t * @param\tamount\tThe value to add to each (RGB only) component of the colour.\n\t * @return\t\t\tThe 'lightened' colour with the amount added to each component.\n\t */\n\tpublic Colour4f lighten(float amount) { return addRGB(amount, amount, amount); }\n\n\t/**\n\t * Darken the RGB components of this colour by a given amount.\n\t * <p>\n\t * Resulting colour components are clamped to the range 0.0f..1.0f.\n\t *\n\t * @param\tamount\tThe value to subtract from each (RGB only) component of the colour.\n\t * @return\t\t\tThe 'darkened' colour with the amount subtracted from each component.\n\t */\n\tpublic Colour4f darken(float amount) { return subtractRGB(amount, amount, amount); }\n\n\t/**\n\t * Return this colour as an array of four floats.\n\t *\n\t * @return\tThis colour as an array of four floats.\n\t */\n\tpublic float[] toArray() { return new float[] { r, g, b, a }; }\n\n\t/** Return a concise, human-readable description of the Colour4f object. */\n\t@Override\n\tpublic String toString() { return \"Red: \" + r + \", Green: \" + g + \", Blue: \" + b + \", Alpha: \" + a; }\n\n\t// ---------- Static Methods -----------\n\n\t/**\n\t * Return a random colour with an alpha value of 1.0f (i.e. fully opaque)\n\t *\n\t * @return\tThe random opaque colour.\n\t */\n\tpublic static Colour4f randomOpaqueColour()\n\t{\n\t\treturn new Colour4f(Utils.random.nextFloat(), Utils.random.nextFloat(), Utils.random.nextFloat(), 1.0f);\n\t}\n\n\t// ---------- Private Methods ----------\n\n\tprivate static float clamp(final float componentValue)\n\t{\n\t\tif (componentValue > MAX_COMPONENT_VALUE) { return MAX_COMPONENT_VALUE; }\n\t\telse if (componentValue < MIN_COMPONENT_VALUE) { return MIN_COMPONENT_VALUE; }\n\t\telse { return componentValue; }\n\t}\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + Float.floatToIntBits(a);\n result = prime * result + Float.floatToIntBits(b);\n result = prime * result + Float.floatToIntBits(g);\n result = prime * result + Float.floatToIntBits(r);\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n Colour4f other = (Colour4f) obj;\n if (Float.floatToIntBits(a) != Float.floatToIntBits(other.a)) {\n return false;\n }\n if (Float.floatToIntBits(b) != Float.floatToIntBits(other.b)) {\n return false;\n }\n if (Float.floatToIntBits(g) != Float.floatToIntBits(other.g)) {\n return false;\n }\n if (Float.floatToIntBits(r) != Float.floatToIntBits(other.r)) {\n return false;\n }\n return true;\n }\n}", "public class Mat4f\n{\n\t/** Get the line separator for this system. */\n\tprivate static final String newLine = System.lineSeparator();\n\t\n\t// Constants to convert angles between degrees and radians\n\tprivate static final float DEGS_TO_RADS = (float)Math.PI / 180.0f;\n\t//private static final float RADS_TO_DEGS = 180.0f / (float)Math.PI;\n\t\n\t/** Constant used to determine if a float is approximately equal to another float value. */\n\tprivate static final float FLOAT_EQUALITY_TOLERANCE = 0.0001f;\n\t\n\t// ---------- Public Properties ---------\n\n\t// These properties are deliberately declared as public for fast access without the need\n\t// to use getters and setters.\n\n\tpublic float m00, m01, m02, m03; // First column - x-axis\n\tpublic float m10, m11, m12, m13; // Second column - y-axis\n\tpublic float m20, m21, m22, m23; // Third column - z-axis\n\tpublic float m30, m31, m32, m33; // Fourth column - origin\n\n\t// ---------- Constructors ----------\n\t\n\t/**\n\t * Default constructor.\n\t * <p>\n\t * All member properties are implicitly set to zero by Java as that is the default value of a float primitive.\n\t */\n\tpublic Mat4f() { }\n\t\n\t/**\n\t * Copy constructor.\n\t * <p>\n\t * Copies all properties from the source matrix into the newly constructed matrix.\n\t * \n\t * @param\tsource\tThe matrix to copy the values from.\n\t */\n\tpublic Mat4f(Mat4f source)\n\t{\n\t\tm00 = source.m00;\n\t\tm01 = source.m01;\n\t\tm02 = source.m02;\n\t\tm03 = source.m03;\n\n\t\tm10 = source.m10;\n\t\tm11 = source.m11;\n\t\tm12 = source.m12;\n\t\tm13 = source.m13;\n\n\t\tm20 = source.m20;\n\t\tm21 = source.m21;\n\t\tm22 = source.m22;\n\t\tm23 = source.m23;\n\n\t\tm30 = source.m30;\n\t\tm31 = source.m31;\n\t\tm32 = source.m32;\n\t\tm33 = source.m33;\n\t}\n\t\n\t/** \n\t * Constructor to create a Mat4f from a Mat3f and an origin.\n\t * \n\t * @param\trotationMatrix\tThe Mat3f to use for the X/Y/Z axes.\n\t * @param\torigin\t\t\tThe Vec3f to use as the origin.\n\t */\n\tpublic Mat4f(Mat3f rotationMatrix, Vec3f origin)\n\t{\n\t\tm00 = rotationMatrix.m00;\n\t\tm01 = rotationMatrix.m01;\n\t\tm02 = rotationMatrix.m02;\n\t\tm03 = 0.0f;\n\n\t\tm10 = rotationMatrix.m10;\n\t\tm11 = rotationMatrix.m11;\n\t\tm12 = rotationMatrix.m12;\n\t\tm13 = 0.0f;\n\n\t\tm20 = rotationMatrix.m20;\n\t\tm21 = rotationMatrix.m21;\n\t\tm22 = rotationMatrix.m22;\n\t\tm23 = 0.0f;\n\n\t\tm30 = origin.x;\n\t\tm31 = origin.y;\n\t\tm32 = origin.z;\n\t\tm33 = 1.0f;\n\t}\n\t\n\t/**\n\t * Float array constructor.\n\t * <p>\n\t * The matrix is set a column at a time, so the first four floats from the source array are set on m0\n\t * to m03, the next four on m10 to m13 and so on.\n\t * <p>\n\t * If the source array is not an array of precisely 16 floats then a IllegalArgumentException is thrown.\n\t * \n\t * @param\tsource\tThe array of 16 floats used as the source values to set on this Mat4f.\n\t */\t\n\tpublic Mat4f(float[] source)\n\t{\n\t\t// If we have an array of precisely 16 floats then proceed with initialisation\n\t\tif (source.length == 16)\n\t\t{\t\t\n\t\t\t// First column (x-axis)\n\t\t\tm00 = source[0 ];\n\t\t\tm01 = source[1 ];\n\t\t\tm02 = source[2 ];\n\t\t\tm03 = source[3 ];\n\t\n\t\t\t// Second column (y-axis)\n\t\t\tm10 = source[4 ];\n\t\t\tm11 = source[5 ];\n\t\t\tm12 = source[6 ];\n\t\t\tm13 = source[7 ];\n\t\n\t\t\t// Third column (z-axis)\n\t\t\tm20 = source[8 ];\n\t\t\tm21 = source[9 ];\n\t\t\tm22 = source[10];\n\t\t\tm23 = source[11];\n\t\n\t\t\t// Fourth column (origin)\n\t\t\tm30 = source[12];\n\t\t\tm31 = source[13];\n\t\t\tm32 = source[14];\n\t\t\tm33 = source[15];\n\t\t}\n\t\telse // Bad array size? Throw an exception.\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Source array must contain precisely 16 floats.\");\n\t\t}\n\t}\n\n\t/**\n\t * One parameter constructor.\n\t * <p>\n\t * Sets the provided value diagonally across the matrix. For example, to create an identity matrix with\n\t * 1.0f across the diagonal then you can call:\n\t * <p>\n\t * {@code Mat4f m = new Mat4f(1.0f)}\n\t * <p>\n\t * Which will result in a matrix with the following properties:\n\t * <p>\n\t * 1.0f 0.0f 0.0f 0.0f\n\t * <p>\n\t * 0.0f 1.0f 0.0f 0.0f\n\t * <p>\n\t * 0.0f 0.0f 1.0f 0.0f\n\t * <p>\n\t * 0.0f 0.0f 0.0f 1.0f\n\t * \n\t * @param\tvalue\tThe value to set across the diagonal of the matrix.\n\t */\n\tpublic Mat4f(float value)\n\t{\n\t\t// Set diagonal\n\t\tm00 = m11 = m22 = m33 = value;\n\n\t\t// All other values are implicitly set to zero by Java as that is the default value of a float primitive.\n\t}\n\t\n\t// ---------- Methods ----------\n\n\t/**\n\t * Zero all properties of a matrix.\n\t */\n\tpublic void zero()\n\t{\n\t\tm00 = m01 = m02 = m03 = m10 = m11 = m12 = m13 = m20 = m21 = m22 = m23 = m30 = m31 = m32 = m33 = 0.0f;\n\t}\n\n\t/**\n\t * Reset a matrix to the identity matrix.\n\t * <p>\n\t * The matrix is set as follows:\n\t * <p>\n\t * 1.0f 0.0f 0.0f 0.0f\n\t * <p>\n\t * 0.0f 1.0f 0.0f 0.0f\n\t * <p>\n\t * 0.0f 0.0f 1.0f 0.0f\n\t * <p>\n\t * 0.0f 0.0f 0.0f 1.0f\n\t */\n\tpublic void setIdentity()\n\t{\n\t\t// Set diagonal\n\t\tm00 = m11 = m22 = m33 = 1.0f;\n\n\t\t// Zero the rest of the matrix\n\t\tm01 = m02 = m03 = m10 = m12 = m13 = m20 = m21 = m23 = m30 = m31 = m32 = 0.0f;\n\t}\n\n\t/**\n\t * Set the details of this Mat4f from an array of 16 floats.\n\t * <p>\n\t * The matrix is set a column at a time, so the first four floats from the source array are set on m0\n\t * to m03, the next four on m10 to m13 and so on.\n\t * <p>\n\t * If the source array is not an array of precisely 16 floats then a IllegalArgumentException is thrown.\n\t * \n\t * @param\tsource\tThe array of 16 floats used as the source values to set on this Mat4f.\n\t */ \n\tpublic void setFromArray(float[] source)\n\t{\n\t\t/// If we have an array of precisely 16 floats then proceed with setting\n\t\tif (source.length == 16)\n\t\t{\t\t\n\t\t\t// First column (x-axis)\n\t\t\tm00 = source[0 ];\n\t\t\tm01 = source[1 ];\n\t\t\tm02 = source[2 ];\n\t\t\tm03 = source[3 ];\n\t\n\t\t\t// Second column (y-axis)\n\t\t\tm10 = source[4 ];\n\t\t\tm11 = source[5 ];\n\t\t\tm12 = source[6 ];\n\t\t\tm13 = source[7 ];\n\t\n\t\t\t// Third column (z-axis)\n\t\t\tm20 = source[8 ];\n\t\t\tm21 = source[9 ];\n\t\t\tm22 = source[10];\n\t\t\tm23 = source[11];\n\t\n\t\t\t// Fourth column (origin)\n\t\t\tm30 = source[12];\n\t\t\tm31 = source[13];\n\t\t\tm32 = source[14];\n\t\t\tm33 = source[15];\n\t\t}\n\t\telse // Bad array size? Throw an exception.\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Source array must contain precisely 16 floats.\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Return the x-basis of this Mat4f as a Vec3f.\n\t * <p>\n\t * The x-basis is the orientation of the x-axis, as held by the m00, m01 and m02 properties.\n\t * \n\t * @return\t\tA Vec3f containing the x-basis of this Mat4f.\n\t */\n\tpublic Vec3f getXBasis()\n\t{\n\t\treturn new Vec3f(m00, m01, m02);\n\t}\n\t\n\t/**\n\t * Return the x-basis of this Mat4f as an array of three floats.\n\t * <p>\n\t * The x-basis is the orientation of the x-axis, as held by the m00, m01 and m02 properties.\n\t * <p>\n\t * This method is provided to allow for interoperability for users who do not want to use the {@link Vec3f} class.\n\t * \n\t * @return\t\tAn array of three floats containing the x-basis of this Mat4f.\n\t */\n\tpublic float[] getXBasisArray()\n\t{\n\t\treturn new float[] { m00, m01, m02 };\n\t}\n\n\t/**\n\t * Set the x-basis of this Mat4f from a provided Vec3f.\n\t * <p>\n\t * The x-basis is the orientation of the x-axis, as held by the m00, m01 and m02 properties.\n\t * <p>\n\t * To ensure the legality of the x-basis, the provided Vec3f is normalised if required before being set.\n\t * <p>\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which accept a float array and do not attempt to enforce\n\t * rotation matrix legality such as {@link #setFromArray(float[])} and {@link #Mat4f(float[])}. \n\t * \n\t * @param\tv\tThe Vec3f holding the x-basis to set.\n\t * @see #setFromArray(float[])\n\t * @see #Mat4f(float[])\n\t */\n\tpublic void setXBasis(Vec3f v)\n\t{\n\t\t// If the provided Vec3f is not normalised then normalise it\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the x-basis\n\t\tm00 = v.x;\n\t\tm01 = v.y;\n\t\tm02 = v.z;\n\t}\n\t\n\t/**\n\t * Set the x-basis of this Mat4f from a provided array of three floats.\n\t * <p>\n\t * The x-basis is the orientation of the x-axis, as held by the m00, m01 and m02 properties.\n\t * <p>\n\t * To ensure the legality of the x-basis, the provided array is converted into a Vec3f and\n\t * normalised (if required) before being set.\n\t * <p>\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which do not enforce normalisation such as the\n\t * {@link #setFromArray(float[])} and {@link #Mat4f(float[])} methods. \n\t * \n\t * @param\tf\tThe array of three floats to set as the x-basis of this Mat4f.\n\t * @see\t\t#setFromArray(float[])\n\t * @see\t\t#Mat4f(float[])\n\t */\n\tpublic void setXBasis(float[] f)\n\t{\n\t\t// Array is correct size? If not then return without setting any values\n\t\tif (f.length != 3)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Construct a Vec3f from the array and normalise it if required\n\t\tVec3f v = new Vec3f(f[0], f[1], f[2]);\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the x-basis\n\t\tm00 = v.x;\n\t\tm01 = v.y;\n\t\tm02 = v.z;\n\t}\n\n\t/**\n\t * Return the y-basis of this Mat4f as a Vec3f.\n\t * <p>\n\t * The y-basis is the orientation of theyx-axis, as held by the m10, m11 and m12 properties.\n\t * \n\t * @return\t\tA Vec3f containing the y-basis of this Mat4f.\n\t */\n\tpublic Vec3f getYBasis()\n\t{\n\t\treturn new Vec3f(m10, m11, m12);\n\t}\n\t\n\n\t/**\n\t * Return the y-basis of this Mat4f as an array of three floats.\n\t * <p>\n\t * The y-basis is the orientation of the y-axis, as held by the m10, m11 and m12 properties.\n\t * <p>\n\t * This method is provided to allow for interoperability for users who do not want to use the {@link Vec3f} class.\n\t * \n\t * @return\t\tAn array of three floats containing the y-basis of this Mat4f.\n\t */\n\tpublic float[] getYBasisArray()\n\t{\n\t\treturn new float[] { m10, m11, m12 };\n\t}\n\n\t/**\n\t * Set the y-basis of this Mat4f from a provided Vec3f.\n\t * <p>\n\t * The y-basis is the orientation of the y-axis, as held by the m10, m11 and m12 properties.\n\t * <p>\n\t * To ensure the legality of the y-basis, the provided Vec3f is normalised if required before being set.\n\t * <p>\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which do not enforce normalisation such as the\n\t * {@link #setFromArray(float[])} and {@link #Mat4f(float[])} methods. \n\t * \n\t * @param\tv\tThe Vec3f holding the y-basis to set.\n\t * @see\t\t#setFromArray(float[])\n\t * @see\t\t#Mat4f(float[])\n\t */\n\tpublic void setYBasis(Vec3f v)\n\t{\n\t\t// If the provided Vec3f is not normalised then normalise it\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the y-basis\n\t\tm10 = v.x;\n\t\tm11 = v.y;\n\t\tm12 = v.z;\n\t}\n\t\n\t/**\n\t * Set the y-basis of this Mat4f from a provided array of three floats.\n\t * <p>\n\t * The y-basis is the orientation of the y-axis, as held by the m10, m11 and m12 properties.\n\t * <p>\n\t * To ensure the legality of the y-basis, the provided array is converted into a Vec3f and\n\t * normalised (if required) before being set.\n\t * <p>\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which do not enforce normalisation such as the\n\t * {@link #setFromArray(float[])} and {@link #Mat4f(float[])} methods. \n\t * \n\t * @param\tf\tThe array of three floats to set as the y-basis of this Mat4f.\n\t * @see\t\t#setFromArray(float[])\n\t * @see\t\t#Mat4f(float[])\n\t */\n\tpublic void setYBasis(float[] f)\n\t{\n\t\t// Array is correct size? If not then return without setting any values\n\t\tif (f.length != 3)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Construct a Vec3f from the array and normalise it if required\n\t\tVec3f v = new Vec3f(f[0], f[1], f[2]);\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the y-basis\n\t\tm10 = v.x;\n\t\tm11 = v.y;\n\t\tm12 = v.z;\n\t}\n\n\t/**\n\t * Return the z-basis of this Mat4f as a Vec3f.\n\t * <p>\n\t * The z-basis is the orientation of the x-axis, as held by the m20, m21 and m22 properties.\n\t * \n\t * @return\t\tA Vec3f containing the z-basis of this Mat4f.\n\t */\n\tpublic Vec3f getZBasis()\n\t{\n\t\treturn new Vec3f(m20, m21, m22);\n\t}\n\t\n\t/**\n\t * Return the z-basis of this Mat4f as an array of three floats.\n\t * <p>\n\t * The z-basis is the orientation of the z-axis, as held by the m20, m21 and m22 properties.\n\t * <p>\n\t * This method is provided to allow for interoperability for users who do not want to use the {@link Vec3f} class.\n\t * \n\t * @return\t\tAn array of three floats containing the y-basis of this Mat4f.\n\t */\n\tpublic float[] getZBasisArray()\n\t{\n\t\treturn new float[] { m20, m21, m22 };\n\t}\n\n\t/**\n\t * Set the z-basis of this Mat4f from a provided Vec3f.\n\t * <p>\n\t * The z-basis is the orientation of the z-axis, as held by the m20, m21 and m22 properties.\n\t * <p>\n\t * To ensure the legality of the z-basis, the provided Vec3f is normalised if required before being set.\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which do not enforce normalisation such as the\n\t * {@link #setFromArray(float[])} and {@link #Mat4f(float[])} methods.\n\t * \n\t * @param\tv\tThe Vec3f holding the z-basis to set.\n\t * @see #setFromArray(float[])\n\t * @see #Mat4f(float[])\n\t */\n\tpublic void setZBasis(Vec3f v)\n\t{\n\t\t// If the provided Vec3f is not normalised then normalise it\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the y-basis\n\t\tm20 = v.x;\n\t\tm21 = v.y;\n\t\tm22 = v.z;\n\t}\n\t\n\t/**\n\t * Set the z-basis of this Mat4f from a provided array of three floats.\n\t * <p>\n\t * The z-basis is the orientation of the z-axis, as held by the m20, m21 and m22 properties.\n\t * <p>\n\t * To ensure the legality of the z-basis, the provided array is converted into a Vec3f and\n\t * normalised (if required) before being set.\n\t * <p>\n\t * If you wish to use this class for storing matrices which do not represent a rotation matrix\n\t * then you should avoid the setXBasis/setYBasis/setZBasis methods and instead set the matrix\n\t * properties via other methods which do not enforce normalisation such as the\n\t * {@link #setFromArray(float[])} and {@link #Mat4f(float[])} methods.\n\t * \n\t * @param\tf\tThe array of three floats to set as the z-basis of this Mat4f.\n\t * @see \t#setFromArray(float[])\n\t * @see \t#Mat4f(float[])\n\t */\n\tpublic void setZBasis(float[] f)\n\t{\n\t\t// Array is correct size? If not then return without setting any values\n\t\tif (f.length != 3)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Construct a Vec3f from the array and normalise it if required\n\t\tVec3f v = new Vec3f(f[0], f[1], f[2]);\n\t\tif ( !v.lengthIsApproximately(1.0f, FLOAT_EQUALITY_TOLERANCE) )\n\t\t{\n\t\t\tv.normalise();\n\t\t}\n\n\t\t// Set the y-basis\n\t\tm20 = v.x;\n\t\tm21 = v.y;\n\t\tm22 = v.z;\n\t}\n\n\t/**\n\t * Return the origin of this Mat4f.\n\t * \n\t * @return\t\tA Vec3f of the origin location of this Mat4f, as stored in the m30, m31 and m32 properties.\n\t */\n\tpublic Vec3f getOrigin()\n\t{\n\t\treturn new Vec3f(m30, m31, m32);\n\t}\n\n\t/**\n\t * Set the origin of this Mat4f.\n\t * <p>\n\t * The origin is stored in the matrix properties m30 (x location), m31 (y location) and m32 (z location).\n\t * <p>\n\t * As the origin may be at any location, as such it is <em>not</em> normalised before being set.\n\t * \n\t * @param\tv\tThe origin of this Mat4f as a Vec3f.\n\t */\n\tpublic void setOrigin(Vec3f v)\n\t{\n\t\t// Set the origin\n\t\tm30 = v.x;\n\t\tm31 = v.y;\n\t\tm32 = v.z;\n\t\tm33 = 1.0f;\n\t}\n\n\t/**\n\t * Return whether or not all three axes of this Mat4f are orthogonal (i.e. at 90 degrees to each other).\n\t * <p>\n\t * Any two axes, such as x/y, x/z or y/z will be orthogonal if their dot product is zero. However, to\n\t * account for floating point precision errors, this method accepts that two axes are orthogonal if\n\t * their dot product is less than or equal to 0.01f.\n\t * <p>\n\t * If you want to find out if any two specific axes are orthogonal, then you can use code similar to the\n\t * following:\n\t * <p>\n\t * {@code boolean xDotYOrthogonal = Math.abs( xAxis.dot(yAxis) ) <= 0.01f;}\n\t * \n\t * @return\t\tA boolean indicating whether this Mat4f is orthogonal or not. \n\t */\n\tpublic boolean isOrthogonal()\n\t{\n\t\t// Get the x, y and z axes of the matrix as Vec3f objects\n\t\tVec3f xAxis = new Vec3f(m00, m01, m02);\n\t\tVec3f yAxis = new Vec3f(m10, m11, m12);\n\t\tVec3f zAxis = new Vec3f(m20, m21, m22);\n\t\t\n\t\t// As exact floating point comparisons are a bad idea, we'll accept that a float is\n\t\t// approximately equal to zero if it is +/- this epsilon.\n\t\tfloat epsilon = 0.01f;\n\n\t\t// Check whether the x/y, x/z and y/z axes are orthogonal.\n\t\t// If two axes are orthogonal then their dot product will be zero (or approximately zero in this case).\n\t\t// Note: We could have picked y/x, z/x, z/y but it's the same thing - they're either orthogonal or they're not.\t\t\n\t\tboolean xDotYOrthogonal = Math.abs( Vec3f.dotProduct(xAxis, yAxis) ) <= epsilon;\n\t\tboolean xDotZOrthogonal = Math.abs( Vec3f.dotProduct(xAxis, zAxis) ) <= epsilon;\n\t\tboolean yDotZOrthogonal = Math.abs( Vec3f.dotProduct(yAxis, zAxis) ) <= epsilon;\n\n\t\t// All three axes are orthogonal? Return true\n\t\treturn (xDotYOrthogonal && xDotZOrthogonal && yDotZOrthogonal);\n\t}\n\n\t/**\n\t * Transpose this Mat4f.\n\t * <p>\n\t * <strong>This</strong> Mat4f is transposed, not a copy.\n\t * <p>\n\t * If you want to return a transposed version of a Mat4f <em>without modifying</em> the source\n\t * then use the {@link #transposed()} method instead.\n\t * \n\t * @return\tReturn this Mat4f for chaining.\n\t * @see\t\t#transposed()\n\t */\n\tpublic Mat4f transpose()\n\t{\n\t\t// Take a copy of this matrix as a series of floats.\n\t\t// Note: We do not need the m00, m11, m22, or m33 values as they do not change places.\n\t\t\n\t\t//float m00copy = m00;\n\t\tfloat m01copy = m01;\n\t\tfloat m02copy = m02;\n\t\tfloat m03copy = m03;\n\n\t\tfloat m10copy = m10;\n\t\t//float m11copy = m11;\n\t\tfloat m12copy = m12;\n\t\tfloat m13copy = m13;\n\n\t\tfloat m20copy = m20;\n\t\tfloat m21copy = m21;\n\t\t//float m22copy = m22;\n\t\tfloat m23copy = m23;\n\n\t\tfloat m30copy = m30;\n\t\tfloat m31copy = m31;\n\t\tfloat m32copy = m32;\n\t\t//float m33copy = m33;\n\t\t\n\t\t// Assign the values back to this matrix in transposed order\n\t\t\n\t\t//this.m00 = m00copy; // No-op!\n\t\tthis.m01 = m10copy;\n\t\tthis.m02 = m20copy;\n\t\tthis.m03 = m30copy;\n\n\t\tthis.m10 = m01copy;\n\t\t//this.m11 = m11copy; // No-op!\n\t\tthis.m12 = m21copy;\n\t\tthis.m13 = m31copy;\n\n\t\tthis.m20 = m02copy;\n\t\tthis.m21 = m12copy;\n\t\t//this.m22 = m22copy; // No-op!\n\t\tthis.m23 = m32copy;\n\n\t\tthis.m30 = m03copy;\n\t\tthis.m31 = m13copy;\n\t\tthis.m32 = m23copy;\n\t\t//this.m33 = m33copy; // No-op!\n\n\t\t// Return this for chaining\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Return a transposed version of this Mat4f.\n\t * <p>\n\t * This Mat4f is <strong>not</strong> modified during the transposing process.\n\t * <p>\n\t * If you want to transpose 'this' Mat4f rather than return a transposed copy then use the\n\t * {@link #transpose()} method instead.\n\t * \n\t * @return\t\tA transposed version of this Mat4f.\n\t */\n\tpublic Mat4f transposed()\n\t{\n\t\t// Create a new Mat4f to hold the transposed version of this matrix\n\t\tMat4f result = new Mat4f();\n\t\t\n\t\t// Assign the values of this matrix to the result matrix in transposed order.\n\t\t// Note: We don't really need to specify 'this.mXX' (the 'this' is implied) but\n\t\t// there's no harm in doing so, and it helps to clarify what's going on.\n\t\tresult.m00 = this.m00;\n\t\tresult.m01 = this.m10;\n\t\tresult.m02 = this.m20;\n\t\tresult.m03 = this.m30;\n\n\t\tresult.m10 = this.m01;\n\t\tresult.m11 = this.m11;\n\t\tresult.m12 = this.m21;\n\t\tresult.m13 = this.m31;\n\n\t\tresult.m20 = this.m02;\n\t\tresult.m21 = this.m12;\n\t\tresult.m22 = this.m22;\n\t\tresult.m23 = this.m32;\n\n\t\tresult.m30 = this.m03;\n\t\tresult.m31 = this.m13;\n\t\tresult.m32 = this.m23;\n\t\tresult.m33 = this.m33;\n\n\t\t// Return the transposed matrix\n\t\treturn result;\n\t}\n\n\t/**\n\t * Method to multiply this Mat4f by another Mat4f and return the result.\n\t * <p>\n\t * Neither this matrix or the provided matrix argument are modified by the multiplication process,\n\t * instead a new Mat4f containing the resulting matrix is returned.\n\t * <p>\n\t * Matrix multiplication is <strong>not commutative</strong> (i.e. {@code AB != BA} - that is, the\n\t * result of multiplying matrix A by matrix B is <em>not</em> the same as multiplying matrix B by\n\t * matrix A). As such, to construct a ModelView or ModelViewProjection matrix you must specify them\n\t * in that precise order <strong>reversed</strong> (because of the order in which the calculations\n\t * take place), for example:\n\t * <p>\n\t * {@code Mat4f modelViewMatrix = viewMatrix.times(modelMatrix); }\n\t * <p>\n\t * {@code Mat4f modelViewProjectionMatrix = projectionMatrix.times(viewMatrix).times(modelMatrix); } \n\t * <p>\n\t * Although matrix multiplication is <strong>not</strong> commutative, it <strong>is</strong>\n\t * associative (i.e. {@code A(BC) == (AB)C}), so you can quite happily combine matrices like this:\n\t * <p>\n\t * {@code Mat4f modelViewMatrix = viewMatrix.times(modelMatrix); }\n\t * <p>\n\t * {@code Mat4f modelViewProjectionMatrix = projectionMatrix.times(modelViewMatrix); }\n\t * \n\t * @param\tm\tThe matrix to multiply this matrix by. \n\t * @return\t\tA Mat4f which is the result of multiplying this matrix by the provided matrix.\n\t */\n\tpublic Mat4f times(Mat4f m)\n\t{\n\t\t// Create a new Mat4f to hold the resulting matrix\n\t\tMat4f result = new Mat4f();\n\t\t\n\t\t// Multiply this matrix by the provided matrix\n\t\t// Note: This multiplication cannot be performed 'inline' on the same object, hence the need to\n\t\t// calculate the and place them into a new matrix which we return.\n\t\tresult.m00 = m00 * m.m00 + m10 * m.m01 + m20 * m.m02 + m30 * m.m03;\n\t\tresult.m01 = m01 * m.m00 + m11 * m.m01 + m21 * m.m02 + m31 * m.m03;\n\t\tresult.m02 = m02 * m.m00 + m12 * m.m01 + m22 * m.m02 + m32 * m.m03;\n\t\tresult.m03 = m03 * m.m00 + m13 * m.m01 + m23 * m.m02 + m33 * m.m03;\n\t\t\n\t\tresult.m10 = m00 * m.m10 + m10 * m.m11 + m20 * m.m12 + m30 * m.m13;\n\t\tresult.m11 = m01 * m.m10 + m11 * m.m11 + m21 * m.m12 + m31 * m.m13;\n\t\tresult.m12 = m02 * m.m10 + m12 * m.m11 + m22 * m.m12 + m32 * m.m13;\n\t\tresult.m13 = m03 * m.m10 + m13 * m.m11 + m23 * m.m12 + m33 * m.m13;\n\t\t\n\t\tresult.m20 = m00 * m.m20 + m10 * m.m21 + m20 * m.m22 + m30 * m.m23;\n\t\tresult.m21 = m01 * m.m20 + m11 * m.m21 + m21 * m.m22 + m31 * m.m23;\n\t\tresult.m22 = m02 * m.m20 + m12 * m.m21 + m22 * m.m22 + m32 * m.m23;\n\t\tresult.m23 = m03 * m.m20 + m13 * m.m21 + m23 * m.m22 + m33 * m.m23;\n\t\t\n\t\tresult.m30 = m00 * m.m30 + m10 * m.m31 + m20 * m.m32 + m30 * m.m33;\n\t\tresult.m31 = m01 * m.m30 + m11 * m.m31 + m21 * m.m32 + m31 * m.m33;\n\t\tresult.m32 = m02 * m.m30 + m12 * m.m31 + m22 * m.m32 + m32 * m.m33;\n\t\tresult.m33 = m03 * m.m30 + m13 * m.m31 + m23 * m.m32 + m33 * m.m33;\t\t\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Transform a point in 3D space.\n\t * <p>\n\t * This method multiplies the provided Vec3f by this matrix. This is commonly used to transform vertices\n\t * between coordinate spaces, for example you might multiply a vertex location by a model matrix to\n\t * transform the vertex from model space into world space.\n\t * <p>\n\t * The difference between this method and the {@link #transformDirection} method is that this method\n\t * takes the origin of this Mat4f into account when performing the transformation, whilst\n\t * transformDirection does not.\n\t * \n\t * @param\tv\tThe Vec3f location to transform.\n\t * @return\t\tThe transformed Vec3f location.\n\t */ \n\tpublic Vec3f transformPoint(Vec3f v)\n\t{\n\t\t// Create a new Vec3f with all properties set to zero\n\t\tVec3f result = new Vec3f();\n\t\t\n\t\t// Apply the transformation of the given point using this matrix\n\t\tresult.x = this.m00 * v.x + this.m10 * v.y + this.m20 * v.z + this.m30; // * 1.0f; - no need as w is 1.0 for a location\n\t\tresult.y = this.m01 * v.x + this.m11 * v.y + this.m21 * v.z + this.m31; // * 1.0f; - no need as w is 1.0 for a location\n\t\tresult.z = this.m02 * v.x + this.m12 * v.y + this.m22 * v.z + this.m32; // * 1.0f; - no need as w is 1.0 for a location\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Transform a direction in 3D space taking into account the orientation of this Mat4fs x/y/z axes.\n\t * <p>\n\t * The difference between this method and the {@link #transformPoint} method is that this method\n\t * does not take the origin of this Mat4f into account when performing the transformation, whilst\n\t * transformPoint does.\n\t * \n\t * @param\tv\tThe Vec3f to transform.\n\t * @return\t\tThe transformed Vec3f.\n\t */ \n\tpublic Vec3f transformDirection(Vec3f v)\n\t{\n\t\tVec3f result = new Vec3f(0.0f);\t\t\n\t\t\n\t\t// NO!\n\t\tresult.x = this.m00 * v.x + this.m10 * v.y + this.m20 * v.z; // + this.m30 * 0.0; - no need as w is 0.0 for a direction\n\t\tresult.y = this.m01 * v.x + this.m11 * v.y + this.m21 * v.z; // + this.m31 * 0.0; - no need as w is 0.0 for a direction\n\t\tresult.z = this.m02 * v.x + this.m12 * v.y + this.m22 * v.z; // + this.m32 * 0.0; - no need as w is 0.0 for a direction\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Calculate and return the inverse of a Mat4f.\n\t * <p>\n\t * Only matrices which do not have a {@link #determinant()} of zero can be inverted. If\n\t * the determinant of the provided matrix is zero then an IllegalArgumentException is thrown.\n\t * \n\t * @param\tm\tThe matrix to invert.\n\t * @return\t\tThe inverted matrix.\n\t */\n\tpublic static Mat4f inverse(Mat4f m)\n\t{\n\t\tMat4f temp = new Mat4f();\n\n\t\ttemp.m00 = m.m12*m.m23*m.m31 - m.m13*m.m22*m.m31 + m.m13*m.m21*m.m32 - m.m11*m.m23*m.m32 - m.m12*m.m21*m.m33 + m.m11*m.m22*m.m33;\n\t\ttemp.m01 = m.m03*m.m22*m.m31 - m.m02*m.m23*m.m31 - m.m03*m.m21*m.m32 + m.m01*m.m23*m.m32 + m.m02*m.m21*m.m33 - m.m01*m.m22*m.m33;\n\t\ttemp.m02 = m.m02*m.m13*m.m31 - m.m03*m.m12*m.m31 + m.m03*m.m11*m.m32 - m.m01*m.m13*m.m32 - m.m02*m.m11*m.m33 + m.m01*m.m12*m.m33;\n\t\ttemp.m03 = m.m03*m.m12*m.m21 - m.m02*m.m13*m.m21 - m.m03*m.m11*m.m22 + m.m01*m.m13*m.m22 + m.m02*m.m11*m.m23 - m.m01*m.m12*m.m23;\n\t\ttemp.m10 = m.m13*m.m22*m.m30 - m.m12*m.m23*m.m30 - m.m13*m.m20*m.m32 + m.m10*m.m23*m.m32 + m.m12*m.m20*m.m33 - m.m10*m.m22*m.m33;\n\t\ttemp.m11 = m.m02*m.m23*m.m30 - m.m03*m.m22*m.m30 + m.m03*m.m20*m.m32 - m.m00*m.m23*m.m32 - m.m02*m.m20*m.m33 + m.m00*m.m22*m.m33;\n\t\ttemp.m12 = m.m03*m.m12*m.m30 - m.m02*m.m13*m.m30 - m.m03*m.m10*m.m32 + m.m00*m.m13*m.m32 + m.m02*m.m10*m.m33 - m.m00*m.m12*m.m33;\n\t\ttemp.m13 = m.m02*m.m13*m.m20 - m.m03*m.m12*m.m20 + m.m03*m.m10*m.m22 - m.m00*m.m13*m.m22 - m.m02*m.m10*m.m23 + m.m00*m.m12*m.m23;\n\t\ttemp.m20 = m.m11*m.m23*m.m30 - m.m13*m.m21*m.m30 + m.m13*m.m20*m.m31 - m.m10*m.m23*m.m31 - m.m11*m.m20*m.m33 + m.m10*m.m21*m.m33;\n\t\ttemp.m21 = m.m03*m.m21*m.m30 - m.m01*m.m23*m.m30 - m.m03*m.m20*m.m31 + m.m00*m.m23*m.m31 + m.m01*m.m20*m.m33 - m.m00*m.m21*m.m33;\n\t\ttemp.m22 = m.m01*m.m13*m.m30 - m.m03*m.m11*m.m30 + m.m03*m.m10*m.m31 - m.m00*m.m13*m.m31 - m.m01*m.m10*m.m33 + m.m00*m.m11*m.m33;\n\t\ttemp.m23 = m.m03*m.m11*m.m20 - m.m01*m.m13*m.m20 - m.m03*m.m10*m.m21 + m.m00*m.m13*m.m21 + m.m01*m.m10*m.m23 - m.m00*m.m11*m.m23;\n\t\ttemp.m30 = m.m12*m.m21*m.m30 - m.m11*m.m22*m.m30 - m.m12*m.m20*m.m31 + m.m10*m.m22*m.m31 + m.m11*m.m20*m.m32 - m.m10*m.m21*m.m32;\n\t\ttemp.m31 = m.m01*m.m22*m.m30 - m.m02*m.m21*m.m30 + m.m02*m.m20*m.m31 - m.m00*m.m22*m.m31 - m.m01*m.m20*m.m32 + m.m00*m.m21*m.m32;\n\t\ttemp.m32 = m.m02*m.m11*m.m30 - m.m01*m.m12*m.m30 - m.m02*m.m10*m.m31 + m.m00*m.m12*m.m31 + m.m01*m.m10*m.m32 - m.m00*m.m11*m.m32;\n\t\ttemp.m33 = m.m01*m.m12*m.m20 - m.m02*m.m11*m.m20 + m.m02*m.m10*m.m21 - m.m00*m.m12*m.m21 - m.m01*m.m10*m.m22 + m.m00*m.m11*m.m22;\n\n\t\t// Get the determinant of this matrix\n\t\tfloat determinant = temp.determinant();\n\n\t\t// Each property of the inverse matrix is multiplied by 1.0f divided by the determinant.\n\t\t// As we cannot divide by zero, we will throw an IllegalArgumentException if the determinant is zero.\n\t\tif (Float.compare(determinant,0.0f)==0)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Cannot invert a matrix with a determinant of zero.\");\n\t\t}\n\n\t\t// Otherwise, calculate the value of one over the determinant and scale the matrix by that value\n\t\tfloat oneOverDeterminant = 1.0f / temp.determinant();\n\n\t\ttemp.m00 *= oneOverDeterminant;\n\t\ttemp.m01 *= oneOverDeterminant;\n\t\ttemp.m02 *= oneOverDeterminant;\n\t\ttemp.m03 *= oneOverDeterminant;\n\t\ttemp.m10 *= oneOverDeterminant;\n\t\ttemp.m11 *= oneOverDeterminant;\n\t\ttemp.m12 *= oneOverDeterminant;\n\t\ttemp.m13 *= oneOverDeterminant;\n\t\ttemp.m20 *= oneOverDeterminant;\n\t\ttemp.m21 *= oneOverDeterminant;\n\t\ttemp.m22 *= oneOverDeterminant;\n\t\ttemp.m23 *= oneOverDeterminant;\n\t\ttemp.m30 *= oneOverDeterminant;\n\t\ttemp.m31 *= oneOverDeterminant;\n\t\ttemp.m32 *= oneOverDeterminant;\n\t\ttemp.m33 *= oneOverDeterminant;\n\n\t\t// Finally, return the inverted matrix\n\t\treturn temp;\n\t}\n\n\t/**\n\t * Calculate the determinant of this matrix.\n\t * \n\t * @return\tThe determinant of this matrix.\n\t */\n\tpublic float determinant()\n\t{\n\t\treturn m03*m12*m21*m30 - m02*m13*m21*m30 - m03*m11*m22*m30 + m01*m13*m22*m30 +\n\t\t\tm02*m11*m23*m30 - m01*m12*m23*m30 - m03*m12*m20*m31 + m02*m13*m20*m31 +\n\t\t\tm03*m10*m22*m31 - m00*m13*m22*m31 - m02*m10*m23*m31 + m00*m12*m23*m31 +\n\t\t\tm03*m11*m20*m32 - m01*m13*m20*m32 - m03*m10*m21*m32 + m00*m13*m21*m32 +\n\t\t\tm01*m10*m23*m32 - m00*m11*m23*m32 - m02*m11*m20*m33 + m01*m12*m20*m33 +\n\t\t\tm02*m10*m21*m33 - m00*m12*m21*m33 - m01*m10*m22*m33 + m00*m11*m22*m33;\n\t}\n\t\n\t/**\n\t * Translate this matrix by a provided Vec3f.\n\t * <p>\n\t * The changes made are to <strong>this</strong> Mat4f, in the coordinate space of this matrix.\n\t * \n\t * @param\tv\tThe vector to translate this matrix by.\n\t * @return\t\tThis Mat4f for chaining. \n\t */ \n\tpublic Mat4f translate(Vec3f v)\n\t{\n\t\t// Unlike in rotation, the translation procedure can be applied 'inline'\n\t\t// so we are able to/ work directly on this Mat4f, rather than a copy.\n\t\tthis.m30 += this.m00 * v.x + this.m10 * v.y + this.m20 * v.z;\n\t\tthis.m31 += this.m01 * v.x + this.m11 * v.y + this.m21 * v.z;\n\t\tthis.m32 += this.m02 * v.x + this.m12 * v.y + this.m22 * v.z;\n\t\tthis.m33 += this.m03 * v.x + this.m13 * v.y + this.m23 * v.z;\n\t\t\n\t\t// Return this for chaining\n\t\treturn this;\n\t}\n\n\t/**\n\t * Translate this matrix by separate x, y and z amounts specified as floats.\n\t * <p>\n\t * The changes made are to <strong>this</strong> Mat4f.\n\t * \n\t * @param\tx\tThe amount to translate on the X-axis.\n\t * @param\ty\tThe amount to translate on the Y-axis.\n\t * @param\tz\tThe amount to translate on the Z-axis.\n\t * @return\t\tThis translated Mat4f for chaining.\n\t */\n\tpublic Mat4f translate(float x, float y, float z)\n\t{\n\t\treturn this.translate( new Vec3f(x, y, z) );\n\t}\n\n\t/*public static Mat4f rotateAroundArbitraryAxisRads(float angleRads, Vec3f axis)\n\t{\n\t\tMat4f result = new Mat4f();\n\t\t\n\t\tfloat sinTheta = (float)Math.sin(angleRads);\n\t\tfloat cosTheta = (float)Math.cos(angleRads);\n\t\tfloat oneMinusCosTheta = 1.0f - cosTheta;\n\t\t\n\t\tresult.m00 = m00 * m00 * oneMinusCosTheta + cosTheta;\n\t\tresult.m01 = \n\t}*/\n\t\n\t/**\n\t * Rotate this matrix about a local axis by an angle specified in radians.\n\t * <p>\n\t * By a 'local' axis we mean that for example, if you rotated this matrix about the positive\n\t * X-axis (1,0,0), then rotation would occur around the positive X-axis of\n\t * <strong>this matrix</strong>, not the <em>global / world-space</em> X-axis.\n\t * \n\t * @param\tangleRads\tThe angle to rotate the matrix in radians.\n\t * @param\tlocalAxis\tThe local axis around which to rotate the matrix.\n\t * @return\t\t\t\tThis rotated matrix\n\t */\n\t// Method to rotate a matrix around an arbitrary axis\n\tpublic Mat4f rotateAboutLocalAxisRads(float angleRads, Vec3f localAxis)\n\t{\n\t\tMat4f dest = new Mat4f();\n\n\t\tfloat cos = (float) Math.cos(angleRads);\n\t\tfloat sin = (float) Math.sin(angleRads);\n\t\tfloat nivCos = 1.0f - cos;\n\n\t\tfloat xy = localAxis.x * localAxis.y;\n\t\tfloat yz = localAxis.y * localAxis.z;\n\t\tfloat xz = localAxis.x * localAxis.z;\n\t\tfloat xs = localAxis.x * sin;\n\t\tfloat ys = localAxis.y * sin;\n\t\tfloat zs = localAxis.z * sin;\n\n\t\t// Rotate the axis\n\t\tfloat f00 = localAxis.x * localAxis.x * nivCos + cos;\n\t\tfloat f01 = xy * nivCos + zs;\n\t\tfloat f02 = xz * nivCos - ys;\n\n\t\tfloat f10 = xy * nivCos - zs;\n\t\tfloat f11 = localAxis.y * localAxis.y * nivCos + cos;\n\t\tfloat f12 = yz * nivCos + xs;\n\n\t\tfloat f20 = xz * nivCos + ys;\n\t\tfloat f21 = yz * nivCos - xs;\n\t\tfloat f22 = localAxis.z * localAxis.z * nivCos + cos;\n\n\t\tfloat t00 = m00 * f00 + m10 * f01 + m20 * f02;\n\t\tfloat t01 = m01 * f00 + m11 * f01 + m21 * f02;\n\t\tfloat t02 = m02 * f00 + m12 * f01 + m22 * f02;\n\t\tfloat t03 = m03 * f00 + m13 * f01 + m23 * f02;\n\t\tfloat t10 = m00 * f10 + m10 * f11 + m20 * f12;\n\t\tfloat t11 = m01 * f10 + m11 * f11 + m21 * f12;\n\t\tfloat t12 = m02 * f10 + m12 * f11 + m22 * f12;\n\t\tfloat t13 = m03 * f10 + m13 * f11 + m23 * f12;\n\n\t\t// Construct rotate matrix\n\t\tdest.m20 = m00 * f20 + m10 * f21 + m20 * f22;\n\t\tdest.m21 = m01 * f20 + m11 * f21 + m21 * f22;\n\t\tdest.m22 = m02 * f20 + m12 * f21 + m22 * f22;\n\t\tdest.m23 = m03 * f20 + m13 * f21 + m23 * f22;\n\t\tdest.m00 = t00;\n\t\tdest.m01 = t01;\n\t\tdest.m02 = t02;\n\t\tdest.m03 = t03;\n\t\tdest.m10 = t10;\n\t\tdest.m11 = t11;\n\t\tdest.m12 = t12;\n\t\tdest.m13 = t13;\n\n\t\tdest.m30 = m30;\n\t\tdest.m31 = m31;\n\t\tdest.m32 = m32;\n\t\tdest.m33 = m33;\n\n\t\t// Update this matrix to be the rotated matrix\n\t\tthis.m00 = dest.m00;\n\t\tthis.m01 = dest.m01;\n\t\tthis.m02 = dest.m02;\n\t\tthis.m03 = dest.m03;\n\n\t\tthis.m10 = dest.m10;\n\t\tthis.m11 = dest.m11;\n\t\tthis.m12 = dest.m12;\n\t\tthis.m13 = dest.m13;\n\n\t\tthis.m20 = dest.m20;\n\t\tthis.m21 = dest.m21;\n\t\tthis.m22 = dest.m22;\n\t\tthis.m23 = dest.m23;\n\n\t\tthis.m30 = dest.m30;\n\t\tthis.m31 = dest.m31;\n\t\tthis.m32 = dest.m32;\n\t\tthis.m33 = dest.m33;\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Rotate this matrix about a local axis by an angle specified in degrees.\n\t * <p>\n\t * By a 'local' axis we mean that for example, if you rotated this matrix about the positive\n\t * X-axis (1,0,0), then rotation would occur around the positive X-axis of\n\t * <strong>this matrix</strong>, not the <em>global / world-space</em> X-axis.\n\t * \n\t * @param\tangleDegs\tThe angle to rotate the matrix in degrees.\n\t * @param\tlocalAxis\tThe local axis around which to rotate the matrix.\n\t * @return\t\t\t\tThis rotated matrix\n\t */\n\tpublic Mat4f rotateAboutLocalAxisDegs(float angleDegs, Vec3f localAxis) { return rotateAboutLocalAxisRads(angleDegs * DEGS_TO_RADS, localAxis); }\n\t\n\t/**\n\t * Rotate this matrix about a world-space axis by an angle specified in radians.\n\t * <p>\n\t * The cardinal 'world-space' axes are defined so that the +X axis runs to the right,\n\t * the +Y axis runs upwards, and the +Z axis runs directly outwards from the screen.\n\t *\n\t * @param\tangleRads\tThe angle to rotate the matrix in radians.\n\t * @param\tworldAxis\tThe world-space axis around which to rotate the matrix.\n\t * @return\t\t\tThis rotated matrix.\n\t */\n\tpublic Mat4f rotateAboutWorldAxisRads(float angleRads, Vec3f worldAxis)\n\t{\n\t\t// Extract the x/y/z axes from this matrix\n\t\tVec3f xAxis = new Vec3f(m00, m01, m02);\n\t\tVec3f yAxis = new Vec3f(m10, m11, m12);\n\t\tVec3f zAxis = new Vec3f(m20, m21, m22);\n\t\t\n\t\t// Rotate them around the global axis\n\t\tVec3f rotatedXAxis = Vec3f.rotateAboutAxisRads(xAxis, angleRads, worldAxis);\n\t\tVec3f rotatedYAxis = Vec3f.rotateAboutAxisRads(yAxis, angleRads, worldAxis);\n\t\tVec3f rotatedZAxis = Vec3f.rotateAboutAxisRads(zAxis, angleRads, worldAxis);\n\t\t\n\t\t\n\t\t// Assign the rotated axes back to the this matrix\n\t\t\n\t\t// Set rotated X-axis\n\t\tthis.m00 = rotatedXAxis.x;\n\t\tthis.m01 = rotatedXAxis.y;\n\t\tthis.m02 = rotatedXAxis.z;\n\t\t//this.m03 = this.m03; // No change to w\n\t\t\n\t\t// Set rotated Y-axis\n\t\tthis.m10 = rotatedYAxis.x;\n\t\tthis.m11 = rotatedYAxis.y;\n\t\tthis.m12 = rotatedYAxis.z;\n\t\t//this.m13 = matrix.m13; // No change to w\n\t\t\n\t\t// Set rotated Z-axis\n\t\tthis.m20 = rotatedZAxis.x;\n\t\tthis.m21 = rotatedZAxis.y;\n\t\tthis.m22 = rotatedZAxis.z;\n\t\t// this.m23 = matrix.m23; No change to w\n\t\t\n\t\t// The origin does not change\n\t\t//this.m30 = matrix.m30;\n\t\t//this.m31 = matrix.m31;\n\t\t//this.m32 = matrix.m32;\n\t\t//this.m33 = matrix.m33;\n\t\t\n\t\t// Return the rotated matrix\n\t\treturn this;\n\t}\n\n\t/**\n\t * Rotate a matrix about a given global axis by an angle in radians.\n\t * <p>\n\t * The matrix provided is NOT modified - a rotated version is returned.\n\t * <p>\n\t * The axis specified to rotate the matrix about is <strong>not</strong>\n\t * specified in the coordinate space of the matrix being rotated - it is\n\t * specified in global coordinates, such as used in OpenGL world space. In\n\t * this coordinate system:\n\t * <ul>\n\t * <li>The positive X-axis runs to the right (1,0,0),\n\t * <li>The positive Y-axis runs vertically upwards (0,1,0), and</li>\n\t * <li>The positive Z-axis runs outwards from the screen (0,0,1).</li>\n\t * </ul>\n\t * \n\t * @param\tmatrix\t\tThe matrix to rotate.\n\t * @param\tangleRads\tThe angle to rotate the matrix in radians.\n\t * @param\tworldAxis\tThe world-space axis to rotate around.\n\t * @return\t\t\tThe rotated matrix.\n\t */\t\n\tpublic static Mat4f rotateAboutWorldAxisRads(Mat4f matrix, float angleRads, Vec3f worldAxis)\n\t{\n\t\t// Extract the x/y/z axes from the matrix\n\t\tVec3f xAxis = new Vec3f(matrix.m00, matrix.m01, matrix.m02);\n\t\tVec3f yAxis = new Vec3f(matrix.m10, matrix.m11, matrix.m12);\n\t\tVec3f zAxis = new Vec3f(matrix.m20, matrix.m21, matrix.m22);\n\t\t\n\t\t//System.out.println(\"In rotMat, xAxis is: \" + xAxis);\n\t\t\n\t\t// Rotate them around the global axis\n\t\tVec3f rotatedXAxis = Vec3f.rotateAboutAxisRads(xAxis, angleRads, worldAxis);\n\t\tVec3f rotatedYAxis = Vec3f.rotateAboutAxisRads(yAxis, angleRads, worldAxis);\n\t\tVec3f rotatedZAxis = Vec3f.rotateAboutAxisRads(zAxis, angleRads, worldAxis);\n\t\t\n\t\t//System.out.println(\"In rotMat, rotated xAxis is: \" + rotatedXAxis);\n\t\t\n\t\t// Assign them back to the result matrix\n\t\tMat4f result = new Mat4f();\n\t\t\n\t\t// Set rotated X-axis\n\t\tresult.m00 = rotatedXAxis.x;\n\t\tresult.m01 = rotatedXAxis.y;\n\t\tresult.m02 = rotatedXAxis.z;\n\t\tresult.m03 = matrix.m03;\n\t\t\n\t\t// Set rotated Y-axis\n\t\tresult.m10 = rotatedYAxis.x;\n\t\tresult.m11 = rotatedYAxis.y;\n\t\tresult.m12 = rotatedYAxis.z;\n\t\tresult.m13 = matrix.m13;\n\t\t\n\t\t// Set rotated Z-axis\n\t\tresult.m20 = rotatedZAxis.x;\n\t\tresult.m21 = rotatedZAxis.y;\n\t\tresult.m22 = rotatedZAxis.z;\n\t\tresult.m23 = matrix.m23;\n\t\t\n\t\t// The origin does not change\n\t\tresult.m30 = matrix.m30;\n\t\tresult.m31 = matrix.m31;\n\t\tresult.m32 = matrix.m32;\n\t\tresult.m33 = matrix.m33;\n\t\t\n\t\t// Return the rotated matrix\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Rotate a matrix about a given global axis by an angle in radians.\n\t * <p>\n\t * The matrix provided is NOT modified - a rotated version is returned.\n\t * <p>\n\t * The axis specified to rotate the matrix about is <strong>not</strong>\n\t * specified in the coordinate space of the matrix being rotated - it is\n\t * specified in global coordinates, such as used in OpenGL world space. In\n\t * this coordinate system:\n\t * <ul>\n\t * <li>The positive X-axis runs to the right (1,0,0),\n\t * <li>The positive Y-axis runs vertically upwards (0,1,0), and</li>\n\t * <li>The positive Z-axis runs outwards from the screen (0,0,1).</li>\n\t * </ul>\n\t * \n\t * @param\tmatrix\t\tThe matrix to rotate.\n\t * @param\tangleDegs\tThe angle to rotate the matrix in degrees.\n\t * @param\tworldAxis\tThe world-space axis to rotate around.\n\t * @return\t\t\tA rotated version of the provided matrix.\n\t */\t\n\tpublic static Mat4f rotateAboutWorldAxisDegs(Mat4f matrix, float angleDegs, Vec3f worldAxis)\n\t{\n\t\treturn rotateAboutWorldAxisRads(matrix, angleDegs * DEGS_TO_RADS, worldAxis);\n\t}\n\t\n\t/**\n\t * Rotate matrix about a relative axis.\n\t * <p>\n\t * The matrix is rotated about the provided axis in the coordinate system of the provided matrix.\n\t * \n\t * @param\tmatrix\t\tThe matrix to rotate.\n\t * @param\tangleRads\tThe angle to rotate the matrix about in radians.\n\t * @param\tlocalAxis\tThe relative axis to rotate about.\n\t * @return\t\t\tA rotated matrix.\n\t */\n\tpublic static Mat4f rotateMatrixAboutLocalAxisRads(Mat4f matrix, float angleRads, Vec3f localAxis)\n\t{\t\t\n\t\t// Transform the local rotation axis into world space\n\t\tVec3f worldSpaceAxis = matrix.transformDirection(localAxis);\n\t\t\n\t\t// With that done, we can now use the world-space axis method to perform the matrix rotation\n\t\treturn Mat4f.rotateAboutWorldAxisRads(matrix, angleRads, worldSpaceAxis);\n\t}\n\t\n\t/**\n\t * Rotate matrix about a relative axis.\n\t * <p>\n\t * The matrix is rotated about the provided axis in the coordinate system of the provided matrix.\n\t * \n\t * @param\tmatrix\t\tThe matrix to rotate.\n\t * @param\tangleDegs\tThe angle to rotate the matrix about in degrees.\n\t * @param\tlocalAxis\tThe relative axis to rotate about.\n\t * @return\t\t\tA rotated matrix.\n\t */\n\tpublic static Mat4f rotateMatrixAboutLocalAxisDegs(Mat4f matrix, float angleDegs, Vec3f localAxis)\n\t{\n\t\treturn Mat4f.rotateMatrixAboutLocalAxisDegs(matrix, angleDegs * DEGS_TO_RADS, localAxis);\n\t}\n\n\t/**\n\t * Return a Mat3f version of this Mat4f.\n\t * <p>\n\t * The x, y and z axes are returned in the Mat3f, while the w component of each axis\n\t * and the origin plus it's w component are discarded.\n\t * <p>\n\t * In effect, we are extracting the orientation of this Mat4f into a Mat3f.\n\t * \n\t * @return\tA Mat3f version of this Mat4f.\n\t */\n\tpublic Mat3f toMat3f()\n\t{\n\t\tMat3f rotationMatrix = new Mat3f();\n\n\t\trotationMatrix.m00 = this.m00;\n\t\trotationMatrix.m01 = this.m01;\n\t\trotationMatrix.m02 = this.m02;\n\n\t\trotationMatrix.m10 = this.m10;\n\t\trotationMatrix.m11 = this.m11;\n\t\trotationMatrix.m12 = this.m12;\n\n\t\trotationMatrix.m20 = this.m20;\n\t\trotationMatrix.m21 = this.m21;\n\t\trotationMatrix.m22 = this.m22;\n\n\t\treturn rotationMatrix;\n\t}\n\n\t/**\n\t * Return this Mat4f as an array of 16 floats.\n\t * \n\t * @return\tThis Mat4f as an array of 16 floats.\n\t */\n\tpublic float[] toArray() { return new float[] { m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 }; }\n\t\n\t/**\n\t * Overridden toString method.\n\t * <p>\n\t * The matrix values are formatted to three decimal places. If you require the exact unformatted\n\t * m<em>XY</em> values then they may be accessed directly.\n\t * \n\t * @return\tA concise, human-readable description of a Mat4f.\n\t */\n\t@Override\n\tpublic String toString()\n\t{\n\t\t// Note: '0' means put a 0 there if it's zero, '#' means omit if zero\n\t\tDecimalFormat df = new DecimalFormat(\"0.000\");\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\t\n\t\tsb.append(\"X-axis: (\" + df.format(m00) + \", \" + df.format(m01) + \", \" + df.format(m02) + \", \" + df.format(m03) + \")\" + newLine);\n\t\tsb.append(\"Y-axis: (\" + df.format(m10) + \", \" + df.format(m11) + \", \" + df.format(m12) + \", \" + df.format(m13) + \")\" + newLine);\n\t\tsb.append(\"Z-axis: (\" + df.format(m20) + \", \" + df.format(m21) + \", \" + df.format(m22) + \", \" + df.format(m23) + \")\" + newLine);\n\t\tsb.append(\"Origin: (\" + df.format(m30) + \", \" + df.format(m31) + \", \" + df.format(m32) + \", \" + df.format(m33) + \")\" + newLine);\n\t\t\n\t\treturn sb.toString();\n\t}\n\n\t// ---------- Static methods ----------\n\n\t/**\n\t * Construct an orthographic projection matrix.\n\t * <p>\n\t * Orthographic projections are commonly used when working in 2D or CAD scenarios. As orthographic projection\n\t * does not perform foreshortening on any projected geometry, objects are drawn the same size regardless of\n\t * their distance from the camera.\n\t * <p>\n\t * By specifying the bottom clipping plane to be 0.0f and the top clipping plane to be the height of the window,\n\t * the origin of the coordinate space is at the bottom-left of the window and the positive y-axis runs upwards.\n\t * To place the origin at the top left of the window and have the y-axis run downwards, simply swap the top and\n\t * bottom values.\n\t * <p>\n\t * Once you have an orthographic projection matrix, if you are not using any separate Model or View matrices\n\t * then you may simply use the orthographic matrix as a ModelViewProjection matrix.\n\t * <p>\n\t * If values are passed so that (right - left), (top - bottom) or (far - near) are zero then an\n\t * IllegalArgumentException is thrown.\n\t * \n\t * @param\tleft\tThe left clipping plane, typically 0.0f.\t\n\t * @param\tright\tThe right clipping plane, typically the width of the window.\n\t * @param\ttop\t\tThe top clipping plane, typically the height of the window.\n\t * @param\tbottom The bottom clipping plane, typically 0.0f.\n\t * @param\tnear\tThe near clipping plane, typically -1.0f.\n\t * @param\tfar The far clipping plane, typically 1.0f.\n\t * @return\t\t\tThe constructed orthographic matrix\n\t * @see\t\t\t\t<a href=\"http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho\">http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho</a>\n\t */\n\tpublic static Mat4f createOrthographicProjectionMatrix(float left, float right, float top, float bottom, float near, float far)\n\t{\n\t\t// Perform sanity checking to avoid divide by zero errors\n\t\tif (Float.compare(right - left,0.0f)==0) { throw new IllegalArgumentException(\"(right - left) cannot be zero.\"); }\n\t\tif (Float.compare(top - bottom,0.0f)==0) {\tthrow new IllegalArgumentException(\"(top - bottom) cannot be zero.\"); }\t\t\n\t\tif (Float.compare(far - near,0.0f)==0) { throw new IllegalArgumentException(\"(far - near) cannot be zero.\"); }\n\t\t\n\t\t// Got legal arguments? Construct the orthographic matrix\t\t\n\t\tMat4f m = new Mat4f();\n\t\t\n\t\tm.m00 = 2.0f / (right - left);\n\t\tm.m01 = 0.0f;\n\t\tm.m02 = 0.0f;\n\t\tm.m03 = 0.0f;\n\n\t\tm.m10 = 0.0f;\n\t\tm.m11 = 2.0f / (top - bottom);\n\t\tm.m12 = 0.0f;\n\t\tm.m13 = 0.0f;\n\n\t\tm.m20 = 0.0f;\n\t\tm.m21 = 0.0f;\n\t\tm.m22 = -2.0f / (far - near);\n\t\tm.m23 = 0.0f;\n\n\t\tm.m30 = -(right + left ) / (right - left );\n\t\tm.m31 = -(top + bottom) / (top - bottom);\n\t\tm.m32 = -(far + near ) / (far - near );\n\t\tm.m33 = 1.0f;\n\n\t\treturn m;\n\t}\n\n\t/**\n\t * Construct a perspective projection matrix.\n\t * <p>\n\t * The parameters provided are the locations of the left/right/top/bottom/near/far clipping planes.\n\t * <p>\n\t * There is rarely any need to specify the bounds of a projection matrix in this manner, and you\n\t * are likely to be better served by using the\n\t * {@link #createPerspectiveProjectionMatrix(float, float, float, float)} method instead.\n\t * <p>\n\t * Once you have a Projection matrix, then it can be combined with a ModelView or separate Model and\n\t * View matrices in the following manner (be careful: multiplication order is important) to create a\n\t * ModelViewProjection matrix:\n\t * <p>\n\t * {@code Mat4f mvpMatrix = projectionMatrix.times(modelViewMatrix);}\n\t * <p>\n\t * or\n\t * <p>\n\t * {@code Mat4f mvpMatrix = projectionMatrix.times(viewMatrix).times(modelMatrix);}\n\t * \n\t * @param\tleft\tThe left clipping plane, typically 0.0f.\t\n\t * @param\tright\tThe right clipping plane, typically the width of the window.\n\t * @param\ttop\t\tThe top clipping plane, typically the height of the window.\n\t * @param\tbottom The bottom clipping plane, typically 0.0f.\n\t * @param\tnear\tThe near clipping plane, typically -1.0f.\n\t * @param\tfar The far clipping plane, typically 1.0f.\n\t * @return\t\t\tThe constructed orthographic matrix\n\t * @see\t\t\t\t<a href=\"http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho\">http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho</a>\n\t */\n\tpublic static Mat4f createPerspectiveProjectionMatrix(float left, float right, float top, float bottom, float near, float far)\n\t{\n\t\t// Instantiate a new matrix, initialised to identity\n\t\tMat4f p = new Mat4f(1.0f);\n\n\t\t// Set matrix values\n\t\tp.m00 = (2.0f * near) / (right - left);\n\n\t\tp.m11 = (2.0f * near) / (top - bottom);\n\n\t\tp.m20 = (right + left) / (right - left);\n\t\tp.m21 = (top + bottom) / (top - bottom);\n\t\tp.m22 = -(far + near) / (far - near);\n\t\tp.m23 = -1.0f;\n\n\t\tp.m32 = (-2.0f * far * near) / (far - near);\n\t\tp.m33 = 0.0f;\n\n\t\treturn p;\n\t}\n\n\t/***\n\t * Construct a perspective projection matrix.\n\t * <p>\n\t * The vertical and horizontal field of view (FoV) values are related in such a way that if you know one\n\t * then you can calculate the other. This method takes the vertical FoV and allows the horizontal FoV to\n\t * adapt to it based on the aspect ratio of the screen in a technique called 'Hor+' (horizontal plus) scaling.\n\t * <p>\n\t * If required, the horizontal and vertical FoVs can be calculated via the following process (note: all angles\n\t * are specified in <strong>radians</strong>):\n\t * <p>\n\t * {@code float horizFoVRads = 2.0f * (float)Math.atan( Math.tan(vertFoVRads / 2.0f) * aspectRatio);}\n\t * <p>\n\t * {@code float vertFoVRads = 2.0f * (float)Math.atan( Math.tan(horizFoVRads / 2.0f) * (1.0f / aspectRatio) ); }\n\t * <p>\n\t * The aspect ratio can be calculated as: {@code (float)windowWidth / (float)windowHeight} - if the size of the\n\t * window changes then a new projection matrix should be created with the new aspect ratio of the window.\n\t * <p>\n\t * {@code zNear} and {@code zFar} represent the near and far clipping distances outside of which any geometry\n\t * will be clipped (i.e. not rendered). An acceptable value for zNear is <strong>1.0f</strong> (0.0f should be\n\t * avoided), however, specifying a zNear value of <strong>2.0f</strong> will essentially double the precision\n\t * of your depth buffer due to the way in which floating point values distribute bits between the significand\n\t * (i.e. the value before the decimal point) and the exponent (the value to raise or lower the significand to).\n\t * Choosing good values for your near and far clipping planes can often eliminate any z-fighting in your scenes.\n\t * <p>\n\t * An {@link IllegalArgumentException} is thrown is any of the parameters are specified with illegal values.\n\t * \n\t * @param\tvertFoVDegs\tThe vertical Field of View angle - must be a positive value between 1.0f and 179.0f. For good\n\t * choices, see <a href=\"http://en.wikipedia.org/wiki/Field_of_view_in_video_games#Choice_of_field_of_view\">choice of\n\t * field of view</a>.\n\t * @param\taspectRatio\tThe aspect ratio of the window in which drawing will occur - must be a positive value.\n\t * @param\tzNear\t\tThe near clipping distance - must be a positive value which is less than zFar.\n\t * @param\tzFar\t\tThe far clipping distance - must be a positive value which is greater than zNear.\n\t * @return\t\t\t\tA projection matrix as a Mat4f.\n\t * @see\t\t<a href=\"http://en.wikipedia.org/wiki/Field_of_view_in_video_games\">http://en.wikipedia.org/wiki/Field_of_view_in_video_games</a>\n\t * @see\t\t<a href=\"http://www.songho.ca/opengl/gl_projectionmatrix.html\">http://www.songho.ca/opengl/gl_projectionmatrix.html</a>\n\t * @see\t\t<a href=\"https://www.opengl.org/archives/resources/faq/technical/depthbuffer.htm\">https://www.opengl.org/archives/resources/faq/technical/depthbuffer.htm</a>\n\t * @see\t\t<a href=\"http://en.wikipedia.org/wiki/Floating_point\">http://en.wikipedia.org/wiki/Floating_point</a>\n\t * @see\t\t<a href=\"http://en.wikipedia.org/wiki/Z-fighting\">http://en.wikipedia.org/wiki/Z-fighting</a>\n\t */ \n\tpublic static Mat4f createPerspectiveProjectionMatrix(float vertFoVDegs, float aspectRatio, float zNear, float zFar)\n\t{\n\t\t// Sanity checking\n\t\tif (aspectRatio < 0.0f ) { throw new IllegalArgumentException(\"Aspect ratio cannot be negative.\"); }\n\t\tif (zNear <= 0.0f || zFar <= 0.0f ) { throw new IllegalArgumentException(\"The values of zNear and zFar must be positive.\"); }\n\t\tif (zNear >= zFar ) { throw new IllegalArgumentException(\"zNear must be less than than zFar.\"); }\n\t\tif (vertFoVDegs < 1.0f || vertFoVDegs > 179.0f) {throw new IllegalArgumentException(\"Vertical FoV must be within 1 and 179 degrees inclusive.\"); }\n\t\t\n\t\tfloat frustumLength = zFar - zNear;\n\t\t\n\t\t// Calculate half the vertical field of view in radians\n\t\tfloat halfVertFoVRads = (vertFoVDegs / 2.0f) * DEGS_TO_RADS;\n\n\t\t// There is no built in Math.cot() in Java, but co-tangent is simply 1 over tangent\n\t\tfloat cotangent = 1.0f / (float)Math.tan(halfVertFoVRads);\n\t\t\n\t\t// Instantiate a new matrix, initialised to identity\n\t\tMat4f p = new Mat4f(1.0f);\n\n\t\t// Set matrix values and return the constructed projection matrix\n\t\tp.m00 = cotangent / aspectRatio;\n\n\t\tp.m11 = cotangent;\n\n\t\tp.m22 = -(zFar + zNear) / frustumLength;\n\t\tp.m23 = -1.0f;\n\n\t\tp.m32 = (-2.0f * zNear * zFar) / frustumLength;\n\t\tp.m33 = 0.0f;\n\n\t\treturn p;\n\t}\n\n} // End of Mat4f class", "public final class Utils\n{\n\t// Constants to translate values from degrees to radians and vice versa\n\tprivate static final float DEGS_TO_RADS = (float)Math.PI / 180.0f;\n\tprivate static final float RADS_TO_DEGS = 180.0f / (float)Math.PI;\n\n\t// Define a private static DecimalFormat to be used by our toString() method.\n\t// Note: '0' means put a 0 there if it's zero, '#' means omit if zero.\n\tpublic static final DecimalFormat df = new DecimalFormat(\"0.000\");\n\t\n\t/** Newline character for this system. */\n\tpublic static final String NEW_LINE = System.lineSeparator();\n\t\n\t/**\n\t * Some colours with which to draw things.\n\t * <p>\n\t * These colours are neither final nor 'constant', so they can be user modified at runtime if desired.\n\t */\n\tpublic static final Colour4f RED = new Colour4f(1.0f, 0.0f, 0.0f, 1.0f);\n\tpublic static final Colour4f GREEN = new Colour4f(0.0f, 1.0f, 0.0f, 1.0f);\n\tpublic static final Colour4f BLUE = new Colour4f(0.0f, 0.0f, 1.0f, 1.0f);\n\tpublic static final Colour4f MID_RED = new Colour4f(0.6f, 0.0f, 0.0f, 1.0f);\n\tpublic static final Colour4f MID_GREEN = new Colour4f(0.0f, 0.6f, 0.0f, 1.0f);\n\tpublic static final Colour4f MID_BLUE = new Colour4f(0.0f, 0.0f, 0.6f, 1.0f);\n\tpublic static final Colour4f BLACK = new Colour4f(0.0f, 0.0f, 0.0f, 1.0f);\n\tpublic static final Colour4f GREY = new Colour4f(0.5f, 0.5f, 0.5f, 1.0f);\n\tpublic static final Colour4f WHITE = new Colour4f(1.0f, 1.0f, 1.0f, 1.0f);\n\tpublic static final Colour4f YELLOW = new Colour4f(1.0f, 1.0f, 0.0f, 1.0f);\n\tpublic static final Colour4f CYAN = new Colour4f(0.0f, 1.0f, 1.0f, 1.0f);\n\tpublic static final Colour4f MAGENTA = new Colour4f(1.0f, 0.0f, 1.0f, 1.0f);\n\t\n\t/**\n\t * A Random object used to generate random numbers in the randRange methods.\n\t * <p>\n\t * If you want a reproducable sequence of events, then set a seed value using Utils.setRandomSeed(someValue).\n\t * \n\t * @see #setRandomSeed(int)\n\t * @see #randRange(float, float)\n\t * @see #randRange(int, int)\n\t */ \n\tpublic static Random random = new Random();\n\t\n\t/** The maximum length in characters of any names which may be used for bones, chains or structures. */\n\tpublic static final int MAX_NAME_LENGTH = 100;\n\t\n\tprivate Utils() {}\n\n\t/**\n\t * Set a fixed seed value - call this with any value before starting the inverse kinematics runs to get a repeatable sequence of events.\n\t * \n\t * @param\tseedValue\tThe seed value to set.\n\t */\n\tpublic static void setRandomSeed(int seedValue)\n\t{\n\t\trandom = new Random(seedValue);\n\t}\n\t\n\t/**\n\t * Return a random floating point value between the half-open range [min..max).\n\t * <p>\n\t * This means that, for example, a call to {@code randRange(-5.0f, 5.0f)} may return a value between -5.0f up to a maximum of 4.999999f.\n\t * \n\t * @param\tmin\tThe minimum value\n\t * @param\tmax The maximum value\n\t * @return\t\tA random float within the specified half-open range.\n\t */\n\tpublic static float randRange(float min, float max) { return random.nextFloat() * (max - min) + min; }\n\t\n\t/**\n\t * Return a random integer value between the half-open range (min..max]\n\t * <p>\n\t * This means that, for example, a call to {@code randRange(-5, 5)} will return a value between -5 up to a maximum of 4.\n\t * \n\t * @param\tmin\tThe minimum value\n\t * @param\tmax The maximum value\n\t * @return\t\tA random int within the specified half-open range.\n\t */\n\tpublic static int randRange(int min, int max) {\treturn random.nextInt(max - min) + min; }\n\n\t/**\n\t * Return the co-tangent of an angle specified in radians.\n\t * \n\t * @param\tangleRads\tThe angle specified in radians to return the co-tangent of.\n\t * @return\t\t\t\tThe co-tangent of the specified angle.\n\t */ \n\tpublic static float cot(float angleRads) { return (float)( 1.0f / Math.tan(angleRads) ); }\n\t\t\n\t/**\n\t * Convert an radians to degrees.\n\t * \n\t * @param\tangleRads\tThe angle in radians.\n\t * @return\t\t\t\tThe converted angle in degrees.\n\t */\n\tpublic static float radiansToDegrees(float angleRads) { return angleRads * RADS_TO_DEGS; }\n\n\t/**\n\t * Convert an angle from degrees to radians.\n\t * \n\t * @param\tangleDegs\tThe angle in degrees.\n\t * @return\t\t\t\tThe converted angle in radians.\n\t */\n\tpublic static float degreesToRadians(float angleDegs) { return angleDegs * DEGS_TO_RADS; }\t\n\n\t/**\n\t * Return a FloatBuffer which can hold the specified number of floats.\n\t *\n\t * @param\tnumFloats\tThe number of floats this FloatBuffer should hold.\n\t * @return\t\t\t\tA float buffer which can hold the specified number of floats.\n\t */\n\tpublic static FloatBuffer createFloatBuffer(int numFloats)\n\t{\t\n\t\treturn ByteBuffer.allocateDirect(numFloats * Float.BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();\n\t}\n\t\n\t/**\n\t * Determine the sign of a float value.\n\t * \n\t * @param\tvalue\tThe value to return the sign of.\n\t * @return\t\t\t1.0f if the provided float value is positive, -1.0f otherwise.\n\t */ \n\tpublic static float sign(float value)\n\t{\n\t\tif (value >= 0.0f) { \n\t\t return 1.0f; \n\t\t}\t\t\n\t\treturn -1.0f;\n\t}\n\t\n\t/**\n\t * Method to set a provided seed value to be used for random number generation.\n\t * <p>\n\t * This allows you to have a repoducable sequence of pseudo-random numbers which are used by\n\t * the visualisation MovingTarget class.\n\t * \n\t * @param\tseed\tThe seed value\n\t */\n\tpublic static void setSeed(int seed) { random = new Random(seed); }\n\t\n\t/**\n\t * Validate a direction unit vector (Vec2f) to ensure that it does not have a magnitude of zero.\n\t * <p>\n\t * If the direction unit vector has a magnitude of zero then an IllegalArgumentException is thrown.\n\t * @param\tdirectionUV\tThe direction unit vector to validate\n\t */\n\tpublic static void validateDirectionUV(Vec2f directionUV)\n\t{\n\t\t// Ensure that the magnitude of this direction unit vector is greater than zero\n\t\tif ( directionUV.length() <= 0.0f )\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Vec2f direction unit vector cannot be zero.\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Validate a direction unit vector (Vec3f) to ensure that it does not have a magnitude of zero.\n\t * <p>\n\t * If the direction unit vector has a magnitude of zero then an IllegalArgumentException is thrown.\n\t * @param\tdirectionUV\tThe direction unit vector to validate\n\t */\n\tpublic static void validateDirectionUV(Vec3f directionUV)\n\t{\n\t\t// Ensure that the magnitude of this direction unit vector is greater than zero\n\t\tif ( directionUV.length() <= 0.0f )\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Vec3f direction unit vector cannot be zero.\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Validate the length of a bone to ensure that it's a positive value.\n\t * <p>\n\t * If the provided bone length is not greater than zero then an IllegalArgumentException is thrown.\n\t * @param\tlength\tThe length value to validate.\n\t */\n\tpublic static void validateLength(float length)\n\t{\n\t\t// Ensure that the magnitude of this direction unit vector is not zero\n\t\tif (length < 0.0f)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Length must be a greater than or equal to zero.\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Convert a value in one range into a value in another range.\n\t * <p>\n\t * If the original range is approximately zero then the returned value is the\n\t * average value of the new range, that is: (newMin + newMax) / 2.0f\n\t * \n\t * @param\torigValue\tThe original value in the original range.\n\t * @param\torigMin\t\tThe minimum value in the original range.\n\t * @param\torigMax\t\tThe maximum value in the original range.\n\t * @param\tnewMin\t\tThe new range's minimum value.\n\t * @param\tnewMax\t\tThe new range's maximum value.\n\t * @return\t\t\t\tThe original value converted into the new range.\n\t */\n\tpublic static float convertRange(float origValue, float origMin, float origMax, float newMin, float newMax)\n\t{\t\n\t\tfloat origRange = origMax - origMin;\n\t\tfloat newRange = newMax - newMin;\n\t\t\n\t\tfloat newValue;\n\t\tif (origRange > -0.000001f && origRange < 0.000001f)\n\t\t{\n\t\t newValue = (newMin + newMax) / 2.0f;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewValue = (((origValue - origMin) * newRange) / origRange) + newMin;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn newValue;\n\t}\n\t\n\t/**\n\t * Return a boolean indicating whether a float approximately equals another to within a given tolerance.\n\t * \n\t * @param\ta\t\tThe first value\n\t * @param\tb\t\tThe second value\n\t * @param\ttolerance\tThe difference within the <strong>a</strong> and <strong>b</strong> values must be within to be considered approximately equal.\n\t * @return\t\t\tWhether the a and b values are approximately equal or not.\n\t */\n\tpublic static boolean approximatelyEquals(float a, float b, float tolerance)\n\t{\n\t\treturn (Math.abs(a - b) <= tolerance) ? true : false; \n\t}\n\t\n\t/** Ensure we have a legal line width with which to draw.\n\t * <p>\n\t * Valid line widths are between 1.0f and 32.0f pixels inclusive.\n\t * <p>\n\t * Line widths outside this range will cause an IllegalArgumentException to be thrown.\n\t * \n\t * @param\tlineWidth\tThe width of the line we are validating. \n\t */\n\tpublic static void validateLineWidth(float lineWidth)\n\t{\n\t\tif (lineWidth < 1.0f || lineWidth > 32.0f)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Line widths must be within the range 1.0f to 32.0f - but only 1.0f is guaranteed to be supported.\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Return the given name capped at 100 characters, if necessary.\n\t * \n\t * @param\tname\tThe name to validate.\n\t * @return\t\t\tThe given name capped at 100 characters, if necessary.\n\t */\n\tpublic static String getValidatedName(String name)\n\t{\n\t\tif (name.length() >= Utils.MAX_NAME_LENGTH)\n\t\t{\n\t\t\treturn name.substring(0, Utils.MAX_NAME_LENGTH);\n\t\t} \n\t\telse\n\t\t{\t\n\t\t\treturn name;\n\t\t}\n\t}\n\n} // End of Utils clas", "public class Vec2f implements Vectorf<Vec2f>\n{\n\t// Conversion constants to/from degrees and radians\n\tprivate static final float DEGS_TO_RADS = (float)Math.PI / 180.0f;\n\tprivate static final float RADS_TO_DEGS = 180.0f / (float)Math.PI;\n\n\t/** Decimal format which prints values to three decimal places, used in the toString method. */\n\t// Note: '0' means put a 0 there if it's zero, '#' means omit if zero.\n\tprivate static DecimalFormat df = new DecimalFormat(\"0.000\");\n\n\tpublic float x, y;\n\n\t// ---------- Constructors ----------\n\n\t/**\n\t * Default constructor.\n\t * <p>\n\t * The x and y properties of the Vec2f are implicitly set to 0.0f by Java as that's the default value for\n\t * primitives of type float. This allows for fast creation of large numbers of Vec2f objects without the\n\t * need to have the x and y properties explicitly set to zero.\n\t */\n\tpublic Vec2f() { }\n\n\t/**\n\t * Copy-constructor.\n\t * <p>\n\t * @param\tsource\tThe source Vec2f to copy the x and y values from.\n\t */\n\tpublic Vec2f(Vec2f source) { x = source.x; y = source.y; }\n\n\t/**\n\t * Two parameter constructor which allows for creation of a Vec2f from two separate float values.\n\t * <p>\n\t * @param x\tThe x value of this Vec2f.\n\t * @param y\tThe y value of this Vec2f.\n\t */\n\tpublic Vec2f(float x, float y) { this.x = x; this.y = y; }\n\n\t// ---------- Methods ----------\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic boolean approximatelyEquals(Vec2f v, float tolerance)\n\t{\n\t\tif (tolerance < 0.0f) {\tthrow new IllegalArgumentException(\"Equality threshold must be greater than or equal to 0.0f\");\t}\n\t\treturn (Math.abs(this.x - v.x) < tolerance && Math.abs(this.y - v.y) < tolerance);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f plus(Vec2f v) { return new Vec2f(x + v.x, y + v.y); }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f minus(Vec2f v) { return new Vec2f(x - v.x, y - v.y); }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f times(float value) { return new Vec2f(x * value, y * value); }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f dividedBy(float value) { return new Vec2f(x / value, y / value); }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f negated() { return new Vec2f(-x, -y); }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void set(Vec2f source) { x = source.x; y = source.y; }\n\n\t/**\n\t * Set the x and y values of a given Vec2f object from two floats.\n\t * <p>\n\t * This method isn't necessarily required as the x and y properties are public, but it doesn't hurt either.\n\t *\n\t * @param x\tThe x value to set.\n\t * @param y\tThe y value to set.\n\t */\n\tpublic void set(float x, float y) { this.x = x; this.y = y; }\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic float length() { return (float)Math.sqrt(x * x + y * y);\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Vec2f normalise()\n\t{\n\t\tfloat magnitude = (float)Math.sqrt(this.x * this.x + this.y * this.y);\n\n\t\t// If the magnitude is greater than zero then normalise the vector, otherwise simply return it as it is\n\t\tif (magnitude > 0.0f)\n\t\t{\n\t\t\tthis.x /= magnitude;\n\t\t\tthis.y /= magnitude;\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Return a normalised version of the provided vector. The provided vector argument itself remains unchanged.\n\t * <p>\n\t * If the magnitude of the vector is zero then the original vector is returned.\n\t *\n\t * @param\tsource\tThe vector to normalise.\n\t * @return\t\tA normalised version of this vector.\n\t */\n\tpublic static Vec2f normalised(Vec2f source) { return new Vec2f(source).normalise(); }\n\n\t/**\n\t * Calculate and return the direction between two points as a unit vector.\n\t * <p>\n\t * The direction returned is the direction <strong>from</strong> {@code a} <strong>to</strong> {@code b}. If the\n\t * opposite direction is required then the result can simply be negated.\n\t * @param\ta\tThe first location.\n\t * @param\tb\tThe second location.\n\t * @return\t\tFIX THIS\n\t * @see\t\tVec2f#negated()\n\t */\n\tpublic static Vec2f getDirectionUV(Vec2f a, Vec2f b) { return b.minus(a).normalise(); }\n\n\t/**\n\t * Calculate and return the distance between two Vec2f objects.\n\t * <p>\n\t * The distance is calculated as the square root of the horizontal distance squared plus the vertical distance squared.\n\t *\n\t * @param\tv1\tThe first vector location.\n\t * @param\tv2\tThe second vector location.\n\t * @return\t\tThe distance between the two vector arguments.\n\t */\n\tpublic static float distanceBetween(Vec2f v1, Vec2f v2)\t{ return (float)Math.sqrt( (v2.x - v1.x) * (v2.x - v1.x) + (v2.y - v1.y) * (v2.y - v1.y) ); }\n\n\t/**\n\t * Calculate and return the dot product (i.e. scalar product) of this Vec2f and another Vec2f.\n\t *\n\t * @param\tv1\tThe first Vec2f with which to calculate the dot product.\n\t * @param\tv2\tThe second Vec2f with which to calculate the dot product.\n\t * @return\t\tThe dot product (i.e. scalar product) of v1 and v2.\n\t */\n\tpublic static float dot(Vec2f v1, Vec2f v2) { return v1.x * v2.x + v1.y * v2.y;\t}\n\n\t/**\n\t * Calculate and return the dot product (i.e. scalar product) of this Vec2f and another Vec2f.\n\t *\n\t * @param\tv\tThe Vec2f with which to calculate the dot product.\n\t * @return\t\tThe dot product (i.e. scalar product) of this Vec2f and the 'v' Vec2f.\n\t */\n\tpublic float dot(Vec2f v) { return x * v.x + y * v.y; }\n\n\t/**\n\t * Calculate and return the unsigned angle between two Vec2f objects.\n\t * <p>\n\t * The returned angle will be within the half-open range [0.0f..180.0f)\n\t * @param\tv1\tThe first Vec2f\n\t * @param\tv2\tThe second Vec2f\n\t * @return\tfloat\n\t */\n\tpublic static float getUnsignedAngleBetweenVectorsDegs(Vec2f v1, Vec2f v2)\n\t{\n\t\treturn (float)Math.acos( Vec2f.normalised(v1).dot( Vec2f.normalised(v2) ) ) * RADS_TO_DEGS;\n\t}\n\n\t/**\n\t * Method to determine the sign of the angle between two Vec2f objects.\n\t * <p>\n\t * @param\tu\tThe first vector.\n\t * @param\tv\tThe second vector.\n\t * @return\t\tAn indication of whether the angle is positive (1), negative (-1) or that the vectors are parallel (0).\n\t * @see <a href=\"https://stackoverflow.com/questions/7785601/detecting-if-angle-is-more-than-180-degrees\">https://stackoverflow.com/questions/7785601/detecting-if-angle-is-more-than-180-degrees</a>\n\t */\n\tpublic static int zcross(Vec2f u, Vec2f v)\n\t{\n\t\tfloat p = u.x * v.y - v.x * u.y;\n\n\t\tif (p > 0.0f) { return 1; }\n\t\telse if (p < 0.0f) { return -1;\t}\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Get the signed angle in degrees between this vector and another vector.\n\t * <p>\n\t * The signed angle, if not zero (i.e. vectors are parallel), will be either positive or negative:\n\t * - If positive (between 0.0f and 180.0f), then to rotate this vector to the other vector requires a rotation in\n\t * an anti-clockwise direction,\n\t * - If negative (between 0.0f and -180.0f), then to rotate this vector to the other vector requires a rotation in\n\t * a clockwise direction.\n\t * <p>\n\t * Internally, once the unsigned angle between the vectors is calculated via the arc-cosine of the dot-product of\n\t * the vectors, the {@link Vec2f#zcross(Vec2f, Vec2f)} method is used to determine if the angle is positive or negative.\n\t * @param\totherVector The Vec2f that we are looking to find the angle we must rotate this vector about to reach.\n\t * @return\tfloat\n\t */\n\tpublic float getSignedAngleDegsTo(Vec2f otherVector)\n\t{\n\t\t// Normalise the vectors that we're going to use\n\t\tVec2f thisVectorUV = Vec2f.normalised(this);\n\t\tVec2f otherVectorUV = Vec2f.normalised(otherVector);\n\n\t\t// Calculate the unsigned angle between the vectors as the arc-cosine of their dot product\n\t\tfloat unsignedAngleDegs = (float)Math.acos( thisVectorUV.dot(otherVectorUV) ) * RADS_TO_DEGS;\n\n\t\t// Calculate and return the signed angle between the two vectors using the zcross method\n\t\tif ( Vec2f.zcross(thisVectorUV, otherVectorUV) == 1)\n\t\t{\n\t\t\treturn unsignedAngleDegs;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn -unsignedAngleDegs;\n\t\t}\n\t}\n\n\t/**\n\t * Constrain a direction unit vector to be within the clockwise and anti-clockwise rotational constraints of a baseline unit vector.\n\t * <p>\n\t * By default, the FABRIK algorithm solves an IK chain without constraints being applied between adjacent bones in the IK chain.\n\t * However, when simulating real-world objects, such angles between bones would be unrealistic - and we should constrain the bones\n\t * to (in this case, in 2D) specified clockwise and anti-clockwise rotational limits with regard to adjacent bones in the chain.\n\t * <p>\n\t * This method takes a direction unit vector and a baseline unit vector, and should the difference between those vectors be\n\t * greater than the allowable clockwise or anti-clockwise constraint angles, then it clamps the returned direction unit vector\n\t * so that it cannot exceed the clockwise or anti-clockwise rotational limits.\n\t * @param\tdirectionUV\tThe direction unit vector to constrain\n\t * @param\tbaselineUV\tThe baseline unit vector with which to constrain the direction\n\t * @param\tclockwiseConstraintDegs\tThe maximum clockwise rotation that may be applied to the direction unit vector\n\t * @param\tantiClockwiseConstraintDegs\tThe maximum anti-clockwise rotation that may be applied to the direction unit vector\n\t * @return\tVec2f\n\t */\n\tpublic static Vec2f getConstrainedUV(Vec2f directionUV, Vec2f baselineUV, float clockwiseConstraintDegs, float antiClockwiseConstraintDegs)\n\t{\n\t\t// Get the signed angle from the baseline UV to the direction UV.\n\t\t// Note: In our signed angle ranges:\n\t\t// 0...180 degrees represents anti-clockwise rotation, and\n\t\t// 0..-180 degrees represents clockwise rotation\n\t\tfloat signedAngleDegs = baselineUV.getSignedAngleDegsTo(directionUV);\n\n\t\t// If we've exceeded the anti-clockwise (positive) constraint angle...\n\t\tif (signedAngleDegs > antiClockwiseConstraintDegs)\n\t\t{\n\t\t\t// ...then our constrained unit vector is the baseline rotated by the anti-clockwise constraint angle.\n\t\t\t// Note: We could do this by calculating a correction angle to apply to the directionUV, but it's simpler to work from the baseline.\n\t\t\treturn Vec2f.rotateDegs(baselineUV, antiClockwiseConstraintDegs);\n\t\t}\n\n\t\t// If we've exceeded the clockwise (negative) constraint angle...\n\t\tif (signedAngleDegs < -clockwiseConstraintDegs)\n\t\t{\n\t\t\t// ...then our constrained unit vector is the baseline rotated by the clockwise constraint angle.\n\t\t\t// Note: Again, we could do this by calculating a correction angle to apply to the directionUV, but it's simpler to work from the baseline.\n\t\t\treturn Vec2f.rotateDegs(baselineUV, -clockwiseConstraintDegs);\n\t\t}\n\n\t\t// If we have not exceeded any constraint then we simply return the original direction unit vector\n\t\treturn directionUV;\n\t}\n\n\t/**\n\t * Method to rotate this Vec2f by a given angle as specified in radians.\n\t * <p>\n\t * Positive values rotate this Vec2f in an anti-clockwise direction.\n\t * Negative values rotate this Vec2f in a clockwise direction.\n\t * <p>\n\t * The changes are applied to 'this' vector, and 'this' is returned for chaining.\n\t * @param angleRads\tThe angle to rotate this vector specified in radians.\n\t * @return\tVec2f\n\t */\n\tpublic Vec2f rotateRads(float angleRads)\n\t{\n\t\t// Rotation about the z-axis:\n\t\t// x' = x*cos q - y*sin q\n\t\t// y' = x*sin q + y*cos q\n\t\t// z' = z\n\n\t\t// Pre-calc any expensive calculations we use more than once\n\t\tfloat cosTheta = (float)Math.cos(angleRads);\n\t\tfloat sinTheta = (float)Math.sin(angleRads);\n\n\t\t// Create a new vector which is the rotated vector\n\t\t// Note: This calculation cannot be performed 'inline' because each aspect (x and y) depends on\n\t\t// the other aspect to get the correct result. As such, we must create a new rotated vector, and\n\t\t// then assign it back to the original vector.\n\t\tVec2f rotatedVector = new Vec2f(x * cosTheta - y * sinTheta, // x\n\t\t\t\t x * sinTheta + y * cosTheta); // y\n\n\t\t// Set the rotated vector coords on this Vec2f\n\t\tx = rotatedVector.x;\n\t\ty = rotatedVector.y;\n\n\t\t// Return this Vec2f for chaining\n\t\treturn this;\n\t}\n\n\t/**\n\t * Method to rotate this Vec2f by a given angle as specified in degrees.\n\t * <p>\n\t * This static method does not modify the source Vec2f - it returns a new Vec2f rotated by the specified angle.\n\t * Positive values rotate the source Vec2f in an anti-clockwise direction.\n\t * Negative values rotate the source Vec2f in a clockwise direction.\n\t * <p>\n\t * This method does not convert degrees to radians and call rotateRads() - instead it performs a degrees to radians\n\t * conversion and then uses identical code from the rotateRads() method to rotate the vector whilst avoiding the\n\t * additional function call overhead.\n\t *\n\t * @param\tsource\t\tThe vector to rotate.\n\t * @param\tangleDegs\tThe angle to rotate the source vector specified in degrees.\n\t * @return\tVec2f\n\t */\n\tpublic static Vec2f rotateDegs(Vec2f source, float angleDegs)\n\t{\n\t\t// Rotation about the z-axis:\n\t\t// x' = x*cos q - y*sin q\n\t\t// y' = x*sin q + y*cos q\n\t\t// z' = z\n\n\t\t// Convert the rotation angle from degrees to radians\n\t\tfloat angleRads = angleDegs * DEGS_TO_RADS;\n\n\t\t// Pre-calc any expensive calculations we use more than once\n\t\tfloat cosTheta = (float)Math.cos(angleRads);\n\t\tfloat sinTheta = (float)Math.sin(angleRads);\n\n\t\t// Create a new vector which is the rotated vector\n\t\t// Note: This calculation cannot be performed 'inline' because each aspect (x and y) depends on\n\t\t// the other aspect to get the correct result. As such, we must create a new rotated vector, and\n\t\t// then assign it back to the original vector.\n\t\treturn new Vec2f(source.x * cosTheta - source.y * sinTheta, // x\n\t\t\t\t source.x * sinTheta + source.y * cosTheta); // y\n\t}\n\n\t/**\n\t * Return a concise, human-readable description of this Vec2f as a String.\n\t * <p>\n\t * The x and y values are formatted to three decimal places - if you want the exact values with no\n\t * formatting applied then you can access and print them manually (they're declared as public).\n\t * @return String\n\t */\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn df.format(x) + \", \" + df.format(y);\n\t}\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + Float.floatToIntBits(x);\n result = prime * result + Float.floatToIntBits(y);\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n Vec2f other = (Vec2f) obj;\n if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) {\n return false;\n }\n if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) {\n return false;\n }\n return true;\n }\n\n} // End of Vec2f class" ]
import au.edu.federation.caliko.FabrikBone2D; import au.edu.federation.caliko.FabrikChain2D; import au.edu.federation.caliko.FabrikChain2D.BaseboneConstraintType2D; import au.edu.federation.caliko.FabrikJoint2D.ConstraintCoordinateSystem; import au.edu.federation.caliko.FabrikStructure2D; import au.edu.federation.utils.Colour4f; import au.edu.federation.utils.Mat4f; import au.edu.federation.utils.Utils; import au.edu.federation.utils.Vec2f;
package au.edu.federation.caliko.visualisation; /** * A static class used to draw a 2D lines to represent FabrikBone2D, FabrikChain2D or FabrickStructure2D objects. * <p> * These draw methods are only provided to assist with prototyping and debugging. * <p> * The GLSL shaders used to draw the lines require a minimum OpenGL version of 3.3 (i.e. GLSL #version 330). * * @author Al Lansley * @version 0.6 - 02/08/2016 */ public class FabrikLine2D { /** Anticlockwise constraint lines will be drawn in red at full opacity. */ private static final Colour4f ANTICLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(1.0f, 0.0f, 0.0f, 1.0f); /** Clockwise constraint lines will be drawn in blue at full opacity. */ private static final Colour4f CLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(0.0f, 0.0f, 1.0f, 1.0f); /** A static Line2D object used to draw all lines. */ private static Line2D line = new Line2D(); /** A point to draw the 2D target if chains use embedded targets. */ private static Point2D point = new Point2D(); // ---------- FabrikBone2D Drawing Methods ---------- /** * Draw this bone as a line. * <p> * The line will be drawn in the colour and line width as taken from the bone. * * @param bone The bone to draw. * @param mvpMatrix The ModelViewProjection matrix with which to draw the line * @see FabrikBone2D#setColour(Colour4f) * @see FabrikBone2D#setLineWidth(float) * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */
public static void draw(FabrikBone2D bone, Mat4f mvpMatrix)
0
desht/ScrollingMenuSign
src/main/java/me/desht/scrollingmenusign/commandlets/PopupCommandlet.java
[ "public class SMSValidate {\n public static void isTrue(boolean cond, String err) {\n if (!cond) throw new SMSException(err);\n }\n\n public static void isFalse(boolean cond, String err) {\n if (cond) throw new SMSException(err);\n }\n\n public static void notNull(Object o, String err) {\n if (o == null) throw new SMSException(err);\n }\n}", "public class ScrollingMenuSign extends JavaPlugin implements ConfigurationListener {\n\n public static final int BLOCK_TARGET_DIST = 4;\n public static final String CONSOLE_OWNER = \"[console]\";\n public static final UUID CONSOLE_UUID = new UUID(0, 0);\n\n private static ScrollingMenuSign instance = null;\n\n public static Economy economy = null;\n public static Permission permission = null;\n\n private final CommandManager cmds = new CommandManager(this);\n private final CommandletManager cmdlets = new CommandletManager(this);\n private final ViewManager viewManager = new ViewManager(this);\n private final LocationManager locationManager = new LocationManager();\n private final VariablesManager variablesManager = new VariablesManager(this);\n private final MenuManager menuManager = new MenuManager(this);\n private final SMSHandlerImpl handler = new SMSHandlerImpl(this);\n private final ConfigCache configCache = new ConfigCache();\n\n private boolean spoutEnabled = false;\n\n private ConfigurationManager configManager;\n\n public final ResponseHandler responseHandler = new ResponseHandler(this);\n private boolean protocolLibEnabled = false;\n private MetaFaker faker;\n private boolean vaultLegacyMode = false;\n private boolean holoAPIEnabled;\n\n @Override\n public void onLoad() {\n ConfigurationSerialization.registerClass(PersistableLocation.class);\n }\n\n @Override\n public void onEnable() {\n setInstance(this);\n\n LogUtils.init(this);\n\n DirectoryStructure.setupDirectoryStructure();\n\n configManager = new ConfigurationManager(this, this);\n configManager.setPrefix(\"sms\");\n\n configCleanup();\n\n configCache.processConfig(getConfig());\n\n MiscUtil.init(this);\n MiscUtil.setColouredConsole(getConfig().getBoolean(\"sms.coloured_console\"));\n\n Debugger.getInstance().setPrefix(\"[SMS] \");\n Debugger.getInstance().setLevel(getConfig().getInt(\"sms.debug_level\"));\n Debugger.getInstance().setTarget(getServer().getConsoleSender());\n\n PluginManager pm = getServer().getPluginManager();\n setupSpout(pm);\n setupVault(pm);\n setupProtocolLib(pm);\n setupHoloAPI(pm);\n if (protocolLibEnabled) {\n ItemGlow.init(this);\n setupItemMetaFaker();\n }\n\n setupCustomFonts();\n\n new SMSPlayerListener(this);\n new SMSBlockListener(this);\n new SMSEntityListener(this);\n new SMSWorldListener(this);\n if (spoutEnabled) {\n new SMSSpoutKeyListener(this);\n }\n\n registerCommands();\n registerCommandlets();\n\n MessagePager.setPageCmd(\"/sms page [#|n|p]\");\n MessagePager.setDefaultPageSize(getConfig().getInt(\"sms.pager.lines\", 0));\n\n SMSScrollableView.setDefaultScrollType(SMSScrollableView.ScrollType.valueOf(getConfig().getString(\"sms.scroll_type\").toUpperCase()));\n\n loadPersistedData();\n variablesManager.checkForUUIDMigration();\n\n if (spoutEnabled) {\n SpoutUtils.precacheTextures();\n }\n\n setupMetrics();\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is enabled!\");\n\n UUIDMigration.migrateToUUID(this);\n }\n\n @Override\n public void onDisable() {\n SMSPersistence.saveMenusAndViews();\n SMSPersistence.saveMacros();\n SMSPersistence.saveVariables();\n for (SMSMenu menu : getMenuManager().listMenus()) {\n // this also deletes all the menu's views...\n menu.deleteTemporary();\n }\n for (SMSMacro macro : SMSMacro.listMacros()) {\n macro.deleteTemporary();\n }\n\n if (faker != null) {\n faker.shutdown();\n }\n\n economy = null;\n permission = null;\n setInstance(null);\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is disabled!\");\n }\n\n @Override\n public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {\n return cmds.dispatch(sender, command, label, args);\n }\n\n @Override\n public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {\n return cmds.onTabComplete(sender, command, label, args);\n }\n\n public SMSHandler getHandler() {\n return handler;\n }\n\n public boolean isSpoutEnabled() {\n return spoutEnabled;\n }\n\n public boolean isProtocolLibEnabled() {\n return protocolLibEnabled;\n }\n\n public boolean isHoloAPIEnabled() {\n return holoAPIEnabled;\n }\n\n public static ScrollingMenuSign getInstance() {\n return instance;\n }\n\n public CommandletManager getCommandletManager() {\n return cmdlets;\n }\n\n public ConfigurationManager getConfigManager() {\n return configManager;\n }\n\n /**\n * @return the viewManager\n */\n public ViewManager getViewManager() {\n return viewManager;\n }\n\n /**\n * @return the locationManager\n */\n public LocationManager getLocationManager() {\n return locationManager;\n }\n\n private void setupMetrics() {\n if (!getConfig().getBoolean(\"sms.mcstats\")) {\n return;\n }\n\n try {\n Metrics metrics = new Metrics(this);\n\n Graph graphM = metrics.createGraph(\"Menu/View/Macro count\");\n graphM.addPlotter(new Plotter(\"Menus\") {\n @Override\n public int getValue() {\n return getMenuManager().listMenus().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Views\") {\n @Override\n public int getValue() {\n return viewManager.listViews().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Macros\") {\n @Override\n public int getValue() {\n return SMSMacro.listMacros().size();\n }\n });\n\n Graph graphV = metrics.createGraph(\"View Types\");\n for (final Entry<String, Integer> e : viewManager.getViewCounts().entrySet()) {\n graphV.addPlotter(new Plotter(e.getKey()) {\n @Override\n public int getValue() {\n return e.getValue();\n }\n });\n }\n metrics.start();\n } catch (IOException e) {\n LogUtils.warning(\"Can't submit metrics data: \" + e.getMessage());\n }\n }\n\n private static void setInstance(ScrollingMenuSign plugin) {\n instance = plugin;\n }\n\n private void setupHoloAPI(PluginManager pm) {\n Plugin holoAPI = pm.getPlugin(\"HoloAPI\");\n if (holoAPI != null && holoAPI.isEnabled()) {\n holoAPIEnabled = true;\n Debugger.getInstance().debug(\"Hooked HoloAPI v\" + holoAPI.getDescription().getVersion());\n }\n }\n\n private void setupSpout(PluginManager pm) {\n Plugin spout = pm.getPlugin(\"Spout\");\n if (spout != null && spout.isEnabled()) {\n spoutEnabled = true;\n Debugger.getInstance().debug(\"Hooked Spout v\" + spout.getDescription().getVersion());\n }\n }\n\n private void setupVault(PluginManager pm) {\n Plugin vault = pm.getPlugin(\"Vault\");\n if (vault != null && vault.isEnabled()) {\n int ver = PluginVersionChecker.getRelease(vault.getDescription().getVersion());\n Debugger.getInstance().debug(\"Hooked Vault v\" + vault.getDescription().getVersion());\n vaultLegacyMode = ver < 1003000; // Vault 1.3.0\n if (vaultLegacyMode) {\n LogUtils.warning(\"Detected an older version of Vault. Proper UUID functionality requires Vault 1.4.1 or later.\");\n }\n setupEconomy();\n setupPermission();\n } else {\n LogUtils.warning(\"Vault not loaded: no economy command costs & no permission group support\");\n }\n }\n\n private void setupEconomy() {\n RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(Economy.class);\n economy = economyProvider.getProvider();\n if (economyProvider == null) {\n LogUtils.warning(\"No economy plugin detected - economy command costs not available\");\n }\n }\n\n private void setupPermission() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n permission = permissionProvider.getProvider();\n if (permission == null) {\n LogUtils.warning(\"No permissions plugin detected - no permission group support\");\n }\n }\n\n public boolean isVaultLegacyMode() {\n return vaultLegacyMode;\n }\n\n private void setupProtocolLib(PluginManager pm) {\n Plugin pLib = pm.getPlugin(\"ProtocolLib\");\n if (pLib != null && pLib instanceof ProtocolLibrary && pLib.isEnabled()) {\n protocolLibEnabled = true;\n Debugger.getInstance().debug(\"Hooked ProtocolLib v\" + pLib.getDescription().getVersion());\n }\n }\n\n private void setupItemMetaFaker() {\n faker = new MetaFaker(this, new MetadataFilter() {\n @Override\n public ItemMeta filter(ItemMeta itemMeta, Player player) {\n if (player.getGameMode() == GameMode.CREATIVE) {\n // messing with item meta in creative mode can have unwanted consequences\n return null;\n }\n if (!ActiveItem.isActiveItem(itemMeta)) {\n String[] f = PopupItem.getPopupItemFields(itemMeta);\n if (f == null) {\n return null;\n }\n }\n // strip the last line from the lore for active items & popup items\n List<String> newLore = new ArrayList<String>(itemMeta.getLore());\n newLore.remove(newLore.size() - 1);\n ItemMeta newMeta = itemMeta.clone();\n newMeta.setLore(newLore);\n return newMeta;\n }\n });\n }\n\n private void registerCommands() {\n cmds.registerCommand(new AddItemCommand());\n cmds.registerCommand(new AddMacroCommand());\n cmds.registerCommand(new AddViewCommand());\n cmds.registerCommand(new CreateMenuCommand());\n cmds.registerCommand(new DeleteMenuCommand());\n cmds.registerCommand(new EditMenuCommand());\n cmds.registerCommand(new FontCommand());\n cmds.registerCommand(new GetConfigCommand());\n cmds.registerCommand(new GiveCommand());\n cmds.registerCommand(new ItemUseCommand());\n cmds.registerCommand(new ListMacroCommand());\n cmds.registerCommand(new ListMenusCommand());\n cmds.registerCommand(new MenuCommand());\n cmds.registerCommand(new PageCommand());\n cmds.registerCommand(new ReloadCommand());\n cmds.registerCommand(new RemoveItemCommand());\n cmds.registerCommand(new RemoveMacroCommand());\n cmds.registerCommand(new RemoveViewCommand());\n cmds.registerCommand(new RepaintCommand());\n cmds.registerCommand(new SaveCommand());\n cmds.registerCommand(new SetConfigCommand());\n cmds.registerCommand(new UndeleteMenuCommand());\n cmds.registerCommand(new VarCommand());\n cmds.registerCommand(new ViewCommand());\n }\n\n private void registerCommandlets() {\n cmdlets.registerCommandlet(new AfterCommandlet());\n cmdlets.registerCommandlet(new CooldownCommandlet());\n cmdlets.registerCommandlet(new PopupCommandlet());\n cmdlets.registerCommandlet(new SubmenuCommandlet());\n cmdlets.registerCommandlet(new CloseSubmenuCommandlet());\n cmdlets.registerCommandlet(new ScriptCommandlet());\n cmdlets.registerCommandlet(new QuickMessageCommandlet());\n }\n\n private void loadPersistedData() {\n SMSPersistence.loadMacros();\n SMSPersistence.loadVariables();\n SMSPersistence.loadMenus();\n SMSPersistence.loadViews();\n }\n\n public static URL makeImageURL(String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n\n return makeImageURL(ScrollingMenuSign.getInstance().getConfig().getString(\"sms.resource_base_url\"), path);\n }\n\n public static URL makeImageURL(String base, String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n if ((base == null || base.isEmpty()) && !path.startsWith(\"http:\")) {\n throw new MalformedURLException(\"base URL must be set (use /sms setcfg resource_base_url ...\");\n }\n if (path.startsWith(\"http:\") || base == null) {\n return new URL(path);\n } else {\n return new URL(new URL(base), path);\n }\n }\n\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(\"scroll_type\")) {\n try {\n SMSScrollableView.ScrollType t = SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase());\n DHValidate.isTrue(t != SMSGlobalScrollableView.ScrollType.DEFAULT, \"Scroll type must be one of SCROLL/PAGE\");\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Scroll type must be one of SCROLL/PAGE\");\n }\n } else if (key.equals(\"debug_level\")) {\n DHValidate.isTrue((Integer) newVal >= 0, \"Debug level must be >= 0\");\n } else if (key.equals(\"submenus.back_item.material\") || key.equals(\"inv_view.default_icon\")) {\n try {\n SMSUtil.parseMaterialSpec(newVal.toString());\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Invalid material specification: \" + newVal.toString());\n }\n }\n return newVal;\n }\n\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.startsWith(\"actions.spout\") && isSpoutEnabled()) {\n // reload & re-cache spout key definitions\n SpoutUtils.loadKeyDefinitions();\n } else if (key.startsWith(\"spout.\") && isSpoutEnabled()) {\n // settings which affects how spout views are drawn\n repaintViews(\"spout\");\n } else if (key.equalsIgnoreCase(\"command_log_file\")) {\n CommandParser.setLogFile(newVal.toString());\n } else if (key.equalsIgnoreCase(\"debug_level\")) {\n Debugger.getInstance().setLevel((Integer) newVal);\n } else if (key.startsWith(\"item_prefix.\") || key.endsWith(\"_justify\") || key.equals(\"max_title_lines\") || key.startsWith(\"submenus.\")) {\n // settings which affect how all views are drawn\n if (key.equals(\"item_prefix.selected\")) {\n configCache.setPrefixSelected(newVal.toString());\n } else if (key.equals(\"item_prefix.not_selected\")) {\n configCache.setPrefixNotSelected(newVal.toString());\n } else if (key.equals(\"submenus.back_item.label\")) {\n configCache.setSubmenuBackLabel(newVal.toString());\n } else if (key.equals(\"submenus.back_item.material\")) {\n configCache.setSubmenuBackIcon(newVal.toString());\n } else if (key.equals(\"submenus.title_prefix\")) {\n configCache.setSubmenuTitlePrefix(newVal.toString());\n }\n repaintViews(null);\n } else if (key.equals(\"coloured_console\")) {\n MiscUtil.setColouredConsole((Boolean) newVal);\n } else if (key.equals(\"scroll_type\")) {\n SMSScrollableView.setDefaultScrollType(SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase()));\n repaintViews(null);\n } else if (key.equals(\"no_physics\")) {\n configCache.setPhysicsProtected((Boolean) newVal);\n } else if (key.equals(\"no_break_signs\")) {\n configCache.setBreakProtected((Boolean) newVal);\n } else if (key.equals(\"inv_view.default_icon\")) {\n configCache.setDefaultInventoryViewIcon(newVal.toString());\n } else if (key.equals(\"user_variables.fallback_sub\")) {\n configCache.setFallbackUserVarSub(newVal.toString());\n }\n }\n\n public ConfigCache getConfigCache() {\n return configCache;\n }\n\n private void repaintViews(String type) {\n for (SMSView v : viewManager.listViews()) {\n if (type == null || v.getType().equals(type)) {\n v.update(null, new RepaintAction());\n }\n }\n }\n\n public void setupCustomFonts() {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n\n //noinspection ConstantConditions\n for (File f : DirectoryStructure.getFontsFolder().listFiles()) {\n String n = f.getName().toLowerCase();\n int type;\n if (n.endsWith(\".ttf\")) {\n type = Font.TRUETYPE_FONT;\n } else if (n.endsWith(\".pfa\") || n.endsWith(\".pfb\") || n.endsWith(\".pfm\") || n.endsWith(\".afm\")) {\n type = Font.TYPE1_FONT;\n } else {\n continue;\n }\n try {\n ge.registerFont(Font.createFont(type, f));\n Debugger.getInstance().debug(\"registered font: \" + f.getName());\n } catch (Exception e) {\n LogUtils.warning(\"can't load custom font \" + f + \": \" + e.getMessage());\n }\n }\n }\n\n private void configCleanup() {\n String[] obsolete = new String[]{\n \"sms.maps.break_block_id\", \"sms.autosave\", \"sms.menuitem_separator\",\n \"sms.persistent_user_vars\", \"uservar\",\n };\n\n boolean changed = false;\n Configuration config = getConfig();\n for (String k : obsolete) {\n if (config.contains(k)) {\n config.set(k, null);\n LogUtils.info(\"removed obsolete config item: \" + k);\n changed = true;\n }\n }\n if (changed) {\n saveConfig();\n }\n }\n\n public VariablesManager getVariablesManager() {\n return variablesManager;\n }\n\n public MenuManager getMenuManager() {\n return menuManager;\n }\n}", "public abstract class CommandTrigger implements Comparable<CommandTrigger> {\n public static final UUID GLOBAL_PLAYER_UUID = UUID.fromString(\"90e73940-ba41-11e3-a5e2-0800200c9a66\");\n\n public abstract void pushMenu(Player player, SMSMenu newActive);\n\n public abstract SMSMenu popMenu(Player player);\n\n public abstract SMSMenu getNativeMenu();\n\n public abstract SMSMenu getActiveMenu(Player player);\n\n public abstract String getName();\n\n /**\n * Get the player context for operations such as view scrolling, active submenu etc. For\n * views which have a per-player context (e.g. maps), this is just the player's UUID. For views\n * with a global context (e.g. signs), a global pseudo-player handle is used.\n *\n * @param player the player to check for\n * @return the player context ID\n */\n protected UUID getPlayerContext(Player player) {\n return player == null? GLOBAL_PLAYER_UUID : player.getUniqueId();\n }\n\n /**\n * Get the title for the given player's currently active menu.\n *\n * @param player the player to check\n * @return title of the active menu\n */\n public String getActiveMenuTitle(Player player) {\n SMSMenu activeMenu = getActiveMenu(player);\n String prefix = activeMenu == getNativeMenu() ? \"\" : ScrollingMenuSign.getInstance().getConfigCache().getSubmenuTitlePrefix();\n return prefix + activeMenu.getTitle();\n }\n\n /**\n * Get the number of items in the given player's currently active menu. Note that for non-native menus,\n * this will be one greater than the actual menu size, because a synthetic \"BACK\" button is added.\n *\n * @param player the player to check\n * @return the number of items in the active menu\n */\n public int getActiveMenuItemCount(Player player) {\n SMSMenu activeMenu = getActiveMenu(player);\n int count = activeMenu.getItemCount();\n if (activeMenu != getNativeMenu())\n count++; // adding a synthetic entry for the BACK item\n return count;\n }\n\n /**\n * Get the menu item at the given position for the given player's currently active menu.\n *\n * @param player the player to check\n * @param pos position in the active menu\n * @return the active menu item\n */\n public SMSMenuItem getActiveMenuItemAt(Player player, int pos) {\n SMSMenu activeMenu = getActiveMenu(player);\n if (activeMenu != getNativeMenu() && pos == activeMenu.getItemCount() + 1) {\n return makeSpecialBackItem(activeMenu);\n } else {\n return activeMenu.getItemAt(pos);\n }\n }\n\n /**\n * Get the menu item of the given label for the given player's currently active menu.\n *\n * @param player the player to check\n * @param label label of the desired item\n * @return the active menu item\n */\n public SMSMenuItem getActiveMenuItemByLabel(Player player, String label) {\n SMSMenu activeMenu = getActiveMenu(player);\n if (label.equals(ScrollingMenuSign.getInstance().getConfigCache().getSubmenuBackLabel())) {\n return makeSpecialBackItem(activeMenu);\n } else {\n return activeMenu.getItem(label);\n }\n }\n\n private SMSMenuItem makeSpecialBackItem(SMSMenu menu) {\n String label = ScrollingMenuSign.getInstance().getConfigCache().getSubmenuBackLabel();\n ItemStack backIcon = ScrollingMenuSign.getInstance().getConfigCache().getSubmenuBackIcon();\n return new SMSMenuItem.Builder(menu, label)\n .withCommand(\"BACK\")\n .withIcon(backIcon)\n .build();\n }\n\n /**\n * Get the label for the menu item at the given position for the given player's currently active menu. View variable\n * substitution will have been performed on the returned label.\n *\n * @param player the player to check\n * @param pos position in the active menu\n * @return the label of the active menu item\n */\n public String getActiveItemLabel(Player player, int pos) {\n SMSMenuItem item = getActiveMenuItemAt(player, pos);\n if (!item.hasPermission(player)) {\n return MiscUtil.parseColourSpec(ScrollingMenuSign.getInstance().getConfig().getString(\"sms.hidden_menuitem_text\", \"???\"));\n }\n return item.getLabel();\n }\n\n @Override\n public int compareTo(CommandTrigger other) {\n return this.getName().compareTo(other.getName());\n }\n}", "public interface PoppableView {\n public void showGUI(Player player);\n\n public void hideGUI(Player player);\n\n public void toggleGUI(Player player);\n\n public boolean hasActiveGUI(Player player);\n\n public SMSPopup getActiveGUI(Player player);\n}", "public abstract class SMSView extends CommandTrigger implements Observer, SMSPersistable, ConfigurationListener, SMSInteractableBlock {\n // operations which were player-specific (active submenu, scroll position...)\n // need to be handled with a single global \"player\" here...\n protected static final String GLOBAL_PSEUDO_PLAYER = \"&&global\";\n\n // view attribute names\n public static final String OWNER = \"owner\";\n public static final String GROUP = \"group\";\n public static final String ITEM_JUSTIFY = \"item_justify\";\n public static final String TITLE_JUSTIFY = \"title_justify\";\n public static final String ACCESS = \"access\";\n\n private final SMSMenu menu;\n private final Set<PersistableLocation> locations = new HashSet<PersistableLocation>();\n private final String name;\n private final AttributeCollection attributes; // view attributes to be displayed and/or edited by players\n private final Map<String, String> variables; // view variables\n private final Map<UUID, MenuStack> menuStack; // map player ID to menu stack (submenu support)\n\n private boolean autosave;\n private boolean dirty;\n private int maxLocations;\n private UUID ownerId;\n private boolean inThaw;\n\n // we can't use a Set here, since there are three possible values: 1) dirty, 2) clean, 3) unknown\n private final Map<UUID, Boolean> dirtyPlayers = new HashMap<UUID, Boolean>();\n // map a world name (for a world which hasn't been loaded yet) to a list of x,y,z positions\n private final Map<String, List<Vector>> deferredLocations = new HashMap<String, List<Vector>>();\n\n /**\n * Get a user-friendly string representing the type of this view.\n *\n * @return The type of view this is.\n */\n public abstract String getType();\n\n public SMSView(SMSMenu menu) {\n this(null, menu);\n }\n\n public SMSView(String name, SMSMenu menu) {\n if (name == null) {\n name = makeUniqueName(menu.getName());\n }\n this.name = name;\n this.menu = menu;\n this.dirty = true;\n this.autosave = true;\n this.attributes = new AttributeCollection(this);\n this.variables = new HashMap<String, String>();\n this.maxLocations = 1;\n this.menuStack = new HashMap<UUID, MenuStack>();\n\n attributes.registerAttribute(OWNER, ScrollingMenuSign.CONSOLE_OWNER, \"Player who owns this view\");\n attributes.registerAttribute(GROUP, \"\", \"Permission group for this view\");\n attributes.registerAttribute(TITLE_JUSTIFY, ViewJustification.DEFAULT, \"Horizontal title positioning\");\n attributes.registerAttribute(ITEM_JUSTIFY, ViewJustification.DEFAULT, \"Horizontal item positioning\");\n attributes.registerAttribute(ACCESS, SMSAccessRights.ANY, \"Who may use this view\");\n }\n\n private String makeUniqueName(String base) {\n int idx = 1;\n String s = String.format(\"%s-%d\", base, idx);\n while (ScrollingMenuSign.getInstance().getViewManager().checkForView(s)) {\n idx++;\n s = String.format(\"%s-%d\", base, idx);\n }\n return s;\n }\n\n /**\n * Get the view's autosave status - will the view be automatically saved to disk when modified?\n *\n * @return true if the view will be autosaved, false otherwise\n */\n public boolean isAutosave() {\n return autosave;\n }\n\n /**\n * Set the view's autosave status - will the view be automatically saved to disk when modified?\n *\n * @param autosave true if the view will be autosaved, false otherwise\n */\n public void setAutosave(boolean autosave) {\n this.autosave = autosave;\n }\n\n /* (non-Javadoc)\n * @see java.util.Observer#update(java.util.Observable, java.lang.Object)\n */\n @Override\n public void update(Observable o, Object arg1) {\n if (o == null) {\n return;\n }\n SMSMenu m = (SMSMenu) o;\n ViewUpdateAction vu = ViewUpdateAction.getAction(arg1);\n Debugger.getInstance().debug(\"update: view=\" + getName() + \" action=\" + vu.getClass().getSimpleName()\n + \" player=\" + vu.getSender() + \" menu=\" + m.getName() + \", nativemenu=\" + getNativeMenu().getName());\n if (m == getNativeMenu()) {\n if (vu instanceof MenuDeleteAction) {\n ScrollingMenuSign.getInstance().getViewManager().deleteView(this, ((MenuDeleteAction) vu).isPermanent());\n }\n }\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.Freezable#getName()\n */\n /* (non-Javadoc)\n\t * @see me.desht.scrollingmenusign.views.CommandTrigger#getName()\n\t */\n @Override\n public String getName() {\n return name;\n }\n\n /**\n * Get the native menu associated with the view. The native menu is the menu that\n * the view was originally created for.\n *\n * @return The native SMSMenu object for this view.\n */\n public SMSMenu getNativeMenu() {\n return menu;\n }\n\n public UUID getOwnerId() {\n return ownerId;\n }\n\n public void setOwnerId(UUID ownerId) {\n this.ownerId = ownerId;\n if (ownerId == null || ownerId.equals(ScrollingMenuSign.CONSOLE_UUID)) {\n setAttribute(OWNER, ScrollingMenuSign.CONSOLE_OWNER);\n } else {\n String name = Bukkit.getOfflinePlayer(ownerId).getName();\n setAttribute(OWNER, name == null ? \"???\" : name);\n }\n autosave();\n }\n\n /**\n * Get the currently active menu for this view for the given player. This is not necessarily the\n * same as the view's native menu, if the player has a submenu open in this view.\n *\n * @return the active SMSMenu object for this view\n */\n public SMSMenu getActiveMenu(Player player) {\n UUID key = getPlayerContext(player);\n\n if (!menuStack.containsKey(key)) {\n menuStack.put(key, new MenuStack());\n }\n MenuStack mst = menuStack.get(key);\n return mst.isEmpty() ? getNativeMenu() : mst.peek();\n }\n\n /**\n * Push the given menu onto the view, making it the active menu as returned by {@link #getActiveMenu(Player)}\n *\n * @param player player to push the menu for\n * @param newActive the menu to make active\n */\n public void pushMenu(Player player, SMSMenu newActive) {\n UUID key = getPlayerContext(player);\n\n getActiveMenu(player).deleteObserver(this);\n if (!menuStack.containsKey(key)) {\n menuStack.put(key, new MenuStack());\n }\n menuStack.get(key).pushMenu(newActive);\n newActive.addObserver(this);\n Debugger.getInstance().debug(\"pushed menu \" + newActive.getName() + \" onto \" + getName()\n + \" player=\" + player.getName() + \" player-context = \" + key);\n update(newActive, new RepaintAction());\n }\n\n /**\n * Pop the active menu off the view, making the previously active menu the new active menu.\n *\n * @param player player to pop the menu for\n * @return the active menu that has just been popped off\n */\n public SMSMenu popMenu(Player player) {\n UUID key = getPlayerContext(player);\n\n if (!menuStack.containsKey(key)) {\n menuStack.put(key, new MenuStack());\n }\n MenuStack mst = menuStack.get(key);\n SMSMenu oldActive = mst.popMenu();\n if (oldActive == null) {\n return null;\n }\n oldActive.deleteObserver(this);\n SMSMenu newActive = getActiveMenu(player);\n newActive.addObserver(this);\n Debugger.getInstance().debug(\"popped menu \" + oldActive.getName() + \" off \" + getName() + \" new active = \" + newActive.getName()\n + \" player=\" + player.getName() + \" player-context = \" + key);\n update(newActive, new RepaintAction());\n return oldActive;\n }\n\n /**\n * Get the set of player IDs who have a submenu open for this view.\n *\n * @return a set of player IDs who have a submenu open for this view\n */\n public Set<UUID> getSubmenuPlayers() {\n return menuStack.keySet();\n }\n\n MenuStack getMenuStack(UUID playerId) {\n return menuStack.get(playerId);\n }\n\n @Override\n public String getActiveItemLabel(Player player, int pos) {\n String label = super.getActiveItemLabel(player, pos);\n return label == null ? null : doVariableSubstitutions(player, label);\n }\n\n /**\n * Set an arbitrary string of tagged data on this view.\n *\n * @param key the variable name (must contain only alphanumeric or underscore)\n * @param val the variable value (may contain any character)\n */\n public void setVariable(String key, String val) {\n SMSValidate.isTrue(key.matches(\"[A-Za-z0-9_]+\"), \"Invalid variable name: \" + key);\n if (val == null) {\n variables.remove(key);\n } else {\n variables.put(key, val);\n }\n }\n\n /**\n * Get an arbitrary string of tagged data from this view\n *\n * @param key the variable name (must contain only alphanumeric or underscore)\n * @return the variable value\n */\n public String getVariable(String key) {\n SMSValidate.isTrue(key.matches(\"[A-Za-z0-9_]+\"), \"Invalid variable name: \" + key);\n SMSValidate.isTrue(variables.containsKey(key), \"View \" + getName() + \" has no variable: \" + key);\n return variables.get(key);\n }\n\n /**\n * Check if the given view variable exists in this view.\n *\n * @param key the variable name (must contain only alphanumeric or underscore)\n * @return true if the variable exists, false otherwise\n */\n public boolean checkVariable(String key) {\n return variables.containsKey(key);\n }\n\n /**\n * Get a list of all variable names for this view.\n *\n * @return a list of variable names for this view\n */\n public Set<String> listVariables() {\n return variables.keySet();\n }\n\n /**\n * Get the justification for menu items in this view\n *\n * @return the justification for menu items in this view\n */\n public ViewJustification getItemJustification() {\n return getJustification(\"sms.item_justify\", ITEM_JUSTIFY, ViewJustification.LEFT);\n }\n\n /**\n * Get the justification for the menu title in this view\n *\n * @return the justification for the menu title in this view\n */\n public ViewJustification getTitleJustification() {\n return getJustification(\"sms.title_justify\", TITLE_JUSTIFY, ViewJustification.CENTER);\n }\n\n private ViewJustification getJustification(String configItem, String attrName, ViewJustification fallback) {\n ViewJustification viewJust = (ViewJustification) getAttribute(attrName);\n if (viewJust != ViewJustification.DEFAULT) {\n return viewJust;\n }\n\n String j = ScrollingMenuSign.getInstance().getConfig().getString(configItem, fallback.toString());\n try {\n return ViewJustification.valueOf(j.toUpperCase());\n } catch (IllegalArgumentException e) {\n return fallback;\n }\n }\n\n public String doVariableSubstitutions(Player player, String text) {\n String s = Substitutions.viewVariableSubs(this, text);\n s = Substitutions.userVariableSubs(player, s, null);\n return s;\n }\n\n public List<String> doVariableSubstitutions(Player player, List<String> l) {\n List<String> res = new ArrayList<String>(l.size());\n for (String s : l) {\n res.add(doVariableSubstitutions(player, s));\n }\n return res;\n }\n\n public Map<String, Object> freeze() {\n Map<String, Object> map = new HashMap<String, Object>();\n Map<String, String> vars = new HashMap<String, String>();\n\n map.put(\"name\", name);\n map.put(\"menu\", menu.getName());\n map.put(\"class\", getClass().getName());\n map.put(\"owner_id\", getOwnerId() == null ? \"\" : getOwnerId().toString());\n for (String key : listAttributeKeys(false)) {\n map.put(key, attributes.get(key).toString());\n }\n List<PersistableLocation> locs = new ArrayList<PersistableLocation>();\n for (Location l : getLocations()) {\n PersistableLocation pl = new PersistableLocation(l);\n pl.setSavePitchAndYaw(false);\n locs.add(pl);\n }\n map.put(\"locations\", locs);\n for (String key : listVariables()) {\n vars.put(key, getVariable(key));\n }\n map.put(\"vars\", vars);\n return map;\n }\n\n @SuppressWarnings(\"unchecked\")\n protected void thaw(ConfigurationSection node) throws SMSException {\n inThaw = true;\n\n List<Object> locs = (List<Object>) node.getList(\"locations\");\n for (Object o : locs) {\n if (o instanceof PersistableLocation) {\n PersistableLocation pl = (PersistableLocation) o;\n try {\n addLocation(pl.getLocation());\n } catch (IllegalStateException e) {\n // world not loaded? we'll defer adding this location to the view for now\n // perhaps the world will get loaded later\n addDeferredLocation(pl.getWorldName(), new Vector(pl.getX(), pl.getY(), pl.getZ()));\n }\n } else {\n throw new SMSException(\"invalid location in view \" + getName() + \" (corrupted file?)\");\n }\n }\n\n String id = node.getString(\"owner_id\");\n if (id != null && !id.isEmpty()) {\n setOwnerId(UUID.fromString(id));\n }\n\n // temporarily disable validation while attributes are loaded from saved data\n attributes.setValidate(false);\n for (String key : node.getKeys(false)) {\n if (!node.isConfigurationSection(key) && attributes.hasAttribute(key)) {\n String val = node.getString(key);\n try {\n setAttribute(key, val);\n } catch (SMSException e) {\n LogUtils.warning(\"View \" + getName() + \": can't set \" + key + \"='\" + val + \"': \" + e.getMessage());\n }\n }\n }\n // ensure view has an owner (pre-2.0, views did not)\n String owner = getAttributeAsString(OWNER);\n if (owner.isEmpty()) {\n setAttribute(OWNER, getNativeMenu().getOwner());\n }\n\n ConfigurationSection vars = node.getConfigurationSection(\"vars\");\n if (vars != null) {\n for (String k : vars.getKeys(false)) {\n setVariable(k, vars.getString(k));\n }\n }\n attributes.setValidate(true);\n inThaw = false;\n }\n\n /**\n * Mark a location (actually a world name and a x,y,z vector) as deferred - the world isn't\n * currently available.\n *\n * @param worldName name of the world\n * @param v a vector describing the location\n */\n private void addDeferredLocation(String worldName, Vector v) {\n List<Vector> l = deferredLocations.get(worldName);\n if (l == null) {\n l = new ArrayList<Vector>();\n deferredLocations.put(worldName, l);\n }\n l.add(v);\n }\n\n /**\n * Get a list of the locations (x,y,z vectors) that have been deferred for the given world name.\n *\n * @param worldName the name of the world to check for\n * @return a list of vectors; the locations that have been deferred\n */\n public List<Vector> getDeferredLocations(String worldName) {\n return deferredLocations.get(worldName);\n }\n\n /**\n * Get the \"dirty\" status for this view - whether or not a repaint is needed for all players.\n *\n * @return true if a repaint is needed, false otherwise\n */\n public boolean isDirty() {\n return dirty;\n }\n\n /**\n * Get the \"dirty\" status for this view - whether or not a repaint is needed for the given player.\n *\n * @param player The player to check for\n * @return true if a repaint is needed, false otherwise\n */\n public boolean isDirty(Player player) {\n UUID key = getPlayerContext(player);\n return dirtyPlayers.containsKey(key) ? dirtyPlayers.get(key) : dirty;\n }\n\n /**\n * Set the global \"dirty\" status for this view - whether or not a repaint is needed for all players.\n *\n * @param dirty true if a repaint is needed, false otherwise\n */\n public void setDirty(boolean dirty) {\n setDirty(null, dirty);\n }\n\n /**\n * Set the per-player \"dirty\" status for this view - whether or not a repaint is needed for the given player.\n * If a null player is passed, the view is marked as dirty for all players.\n *\n * @param player The player to check for, may be null\n * @param dirty Whether or not a repaint is needed\n */\n public void setDirty(Player player, boolean dirty) {\n if (player == null) {\n this.dirty = dirty;\n if (dirty) {\n dirtyPlayers.clear();\n }\n } else {\n dirtyPlayers.put(getPlayerContext(player), dirty);\n }\n }\n\n /**\n * Get a set of all locations for this view. Views may have zero or more locations (e.g. a sign\n * view has one location, a map view has zero locations, a multisign view has several locations...)\n *\n * @return A Set of all locations for this view object\n * @throws IllegalStateException if the world for this view has become unloaded\n */\n public Set<Location> getLocations() {\n Set<Location> res = new HashSet<Location>();\n for (PersistableLocation l : locations) {\n res.add(l.getLocation());\n }\n return res;\n }\n\n /**\n * Get a list of all locations for this view as a Java array.\n *\n * @return An array of all locations for this view object\n */\n public Location[] getLocationsArray() {\n Set<Location> locs = getLocations();\n return locs.toArray(new Location[locs.size()]);\n }\n\n /**\n * Set the maximum number of locations which are allowed. Subclass constructors should call this\n * as appropriate.\n *\n * @param maxLocations the maximum number of locations to be allowed\n */\n protected void setMaxLocations(int maxLocations) {\n this.maxLocations = maxLocations;\n }\n\n /**\n * Get the maximum number of locations that this view may occupy.\n *\n * @return The maximum number of locations\n */\n public int getMaxLocations() {\n return maxLocations;\n }\n\n /**\n * Build the name of the player (or possibly the console) which owns this view.\n *\n * @param sender the command sender object\n * @return the name of the command sender\n */\n String makeOwnerName(CommandSender sender) {\n return sender != null && sender instanceof Player ? sender.getName() : ScrollingMenuSign.CONSOLE_OWNER;\n }\n\n /**\n * Register a new location as being part of this view object\n *\n * @param loc The location to register\n * @throws SMSException if the location is not suitable for adding to this view\n */\n public void addLocation(Location loc) throws SMSException {\n SMSValidate.isTrue(getLocations().size() < getMaxLocations(),\n \"View \" + getName() + \" already occupies the maximum number of locations (\" + getMaxLocations() + \")\");\n\n ViewManager viewManager = ScrollingMenuSign.getInstance().getViewManager();\n SMSView v = viewManager.getViewForLocation(loc);\n if (v != null) {\n throw new SMSException(\"Location \" + MiscUtil.formatLocation(loc) + \" already contains a view on menu: \" + v.getNativeMenu().getName());\n }\n locations.add(new PersistableLocation(loc));\n if (viewManager.checkForView(getName())) {\n viewManager.registerLocation(loc, this);\n }\n autosave();\n }\n\n /**\n * Unregister a location from the given view.\n *\n * @param loc The location to unregister.\n */\n public void removeLocation(Location loc) {\n ViewManager viewManager = ScrollingMenuSign.getInstance().getViewManager();\n locations.remove(new PersistableLocation(loc));\n viewManager.unregisterLocation(loc);\n\n autosave();\n }\n\n /**\n * Save this view's contents to disk (if autosaving is enabled, and the view\n * is registered).\n */\n public void autosave() {\n if (isAutosave() && ScrollingMenuSign.getInstance().getViewManager().checkForView(getName()))\n SMSPersistence.save(this);\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.SMSPersistable#getSaveFolder()\n */\n public File getSaveFolder() {\n return DirectoryStructure.getViewsFolder();\n }\n\n /**\n * Check if the given player has access rights for this view.\n *\n * @param player The player to check\n * @return True if the player may use this view, false if not\n */\n public boolean hasOwnerPermission(Player player) {\n if (!getActiveMenu(player).hasOwnerPermission(player)) {\n return false;\n }\n SMSAccessRights access = (SMSAccessRights) getAttribute(ACCESS);\n return access.isAllowedToUse(player, ownerId, getAttributeAsString(OWNER), getAttributeAsString(GROUP));\n }\n\n /**\n * Check if this view is owned by the given player.\n *\n * @param player the player to check\n * @return true if the view is owned by the player, false otherwise\n */\n public boolean isOwnedBy(Player player) {\n return player.getUniqueId().equals(ownerId);\n }\n\n /**\n * Require that the given command sender is allowed to use this view, and throw a SMSException if not.\n *\n * @param sender the command sender to check\n * @throws SMSException if the command sender is not allowed to use this view\n */\n public void ensureAllowedToUse(CommandSender sender) {\n if (sender instanceof Player) {\n Player player = (Player) sender;\n if (!hasOwnerPermission(player)) {\n throw new SMSException(\"That menu view is private to someone else.\");\n }\n if (!isTypeUsable(player)) {\n throw new SMSException(\"You don't have permission to use \" + getType() + \" menu views.\");\n }\n }\n }\n\n protected boolean isTypeUsable(Player player) {\n return PermissionUtils.isAllowedTo(player, \"scrollingmenusign.use.\" + getType());\n }\n\n /**\n * Require that the given command sender is allowed to modify this view, and throw a SMSException if not.\n *\n * @param sender the command sender to check\n * @throws SMSException if the command sender is not allowed to modify this view\n */\n public void ensureAllowedToModify(CommandSender sender) {\n if (sender instanceof Player) {\n Player player = (Player) sender;\n if (!PermissionUtils.isAllowedTo(player, \"scrollingmenusign.edit.any\") && !isOwnedBy(player)) {\n throw new SMSException(\"That view is owned by someone else.\");\n }\n }\n }\n\n protected void registerAttribute(String attr, Object def, String desc) {\n attributes.registerAttribute(attr, def, desc);\n }\n\n protected void registerAttribute(String attr, Object def) {\n attributes.registerAttribute(attr, def);\n }\n\n public AttributeCollection getAttributes() {\n return attributes;\n }\n\n public Object getAttribute(String k) {\n return attributes.get(k);\n }\n\n public String getAttributeAsString(String k, String def) {\n Object o = getAttribute(k);\n return o == null || o.toString().isEmpty() ? def : o.toString();\n }\n\n public String getAttributeAsString(String k) {\n return getAttributeAsString(k, \"\");\n }\n\n public void setAttribute(String k, String val) throws SMSException {\n SMSValidate.isTrue(attributes.contains(k), \"No such view attribute: \" + k);\n attributes.set(k, val);\n }\n\n public Set<String> listAttributeKeys(boolean isSorted) {\n return attributes.listAttributeKeys(isSorted);\n }\n\n /* (non-Javadoc)\n * @see me.desht.dhutils.ConfigurationListener#onConfigurationChanged(me.desht.dhutils.ConfigurationManager, java.lang.String, java.lang.Object, java.lang.Object)\n */\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(OWNER) && !inThaw) {\n // try to get the owner UUID matching the owner name if possible\n final String owner = newVal.toString();\n if (owner.isEmpty() || owner.equals(ScrollingMenuSign.CONSOLE_OWNER)) {\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n } else if (MiscUtil.looksLikeUUID(owner)) {\n ownerId = UUID.fromString(owner);\n String name = Bukkit.getOfflinePlayer(ownerId).getName();\n setAttribute(OWNER, name == null ? \"?\" : name);\n } else if (!owner.equals(\"?\")) {\n @SuppressWarnings(\"deprecation\") Player p = Bukkit.getPlayer(owner);\n if (p != null) {\n ownerId = p.getUniqueId();\n } else {\n updateOwnerAsync(owner);\n }\n }\n }\n\n // Don't do updates on views that haven't been registered yet (which will be the case\n // when restoring saved views from disk)\n if (ScrollingMenuSign.getInstance().getViewManager().checkForView(getName())) {\n update(null, new RepaintAction());\n }\n }\n\n private void updateOwnerAsync(final String owner) {\n final UUIDFetcher uf = new UUIDFetcher(Arrays.asList(owner));\n Bukkit.getScheduler().runTaskAsynchronously(ScrollingMenuSign.getInstance(), new Runnable() {\n @Override\n public void run() {\n try {\n Map<String,UUID> res = uf.call();\n if (res.containsKey(owner)) {\n ownerId = res.get(owner);\n } else {\n LogUtils.warning(\"View [\" + getName() + \"]: no known UUID for player: \" + owner);\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n }\n } catch (Exception e) {\n LogUtils.warning(\"View [\" + getName() + \"]: can't retrieve UUID for player: \" + owner + \": \" + e.getMessage());\n }\n }\n });\n }\n\n /* (non-Javadoc)\n * @see me.desht.dhutils.ConfigurationListener#onConfigurationValidate(me.desht.dhutils.ConfigurationManager, java.lang.String, java.lang.String)\n */\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(ACCESS)) {\n SMSAccessRights access = (SMSAccessRights) newVal;\n if (access != SMSAccessRights.ANY && ownerId == null) {\n throw new SMSException(\"View must be owned by a player to change access control to \" + access);\n } else if (access == SMSAccessRights.GROUP && ScrollingMenuSign.permission == null) {\n throw new SMSException(\"Cannot use GROUP access control (no permission group support available)\");\n }\n }\n return newVal;\n }\n\n /**\n * Erase the view's contents and perform any housekeeping; called when it's about to be deleted.\n */\n public void onDeleted(boolean permanent) {\n // does nothing by default: override in subclasses\n }\n\n /**\n * Called automatically when the view is used to execute a menu item. Override and extend this\n * in subclasses.\n *\n * @param player The player who did the execution\n */\n public void onExecuted(Player player) {\n // does nothing by default: override in subclasses\n }\n\n /**\n * Called automatically when the view is scrolled. Override and extend this\n * in subclasses.\n *\n * @param player The player who did the scrolling\n * @param action The scroll direction: SCROLLDOWN or SCROLLUP\n */\n public void onScrolled(Player player, SMSUserAction action) {\n // does nothing by default: override in subclasses\n }\n\n /**\n * Called automatically when a player logs out. Perform any cleardown work to remove player\n * records from the view. Override and extend this in subclasses.\n *\n * @param player The player who logged out\n */\n public void clearPlayerForView(Player player) {\n // does nothing by default: override in subclasses\n }\n\n public void processEvent(ScrollingMenuSign plugin, BlockDamageEvent event) {\n Block b = event.getBlock();\n Player player = event.getPlayer();\n\n SMSMenu menu = getNativeMenu();\n if (Debugger.getInstance().getLevel() > 0) {\n Debugger.getInstance().debug(\"block damage event @ \" + MiscUtil.formatLocation(b.getLocation()) + \", view = \" + getName() + \", menu=\" + menu.getName());\n }\n if (plugin.getConfigCache().isBreakProtected() ||\n !menu.isOwnedBy(player) && !PermissionUtils.isAllowedTo(player, \"scrollingmenusign.edit.any\")) {\n event.setCancelled(true);\n }\n }\n\n public void processEvent(ScrollingMenuSign plugin, BlockBreakEvent event) {\n Player player = event.getPlayer();\n Block b = event.getBlock();\n\n if (Debugger.getInstance().getLevel() > 0) {\n Debugger.getInstance().debug(\"block break event @ \" + b.getLocation() + \", view = \" + getName() + \", menu=\" + getNativeMenu().getName());\n }\n\n if (plugin.getConfigCache().isBreakProtected()) {\n event.setCancelled(true);\n update(getActiveMenu(player), new RepaintAction());\n } else {\n removeLocation(b.getLocation());\n if (getLocations().isEmpty()) {\n plugin.getViewManager().deleteView(this, true);\n }\n MiscUtil.statusMessage(player,\n String.format(\"%s block @ &f%s&- was removed from view &e%s&- (menu &e%s&-).\",\n b.getType(), MiscUtil.formatLocation(b.getLocation()), getName(), getNativeMenu().getName()));\n }\n }\n\n public void processEvent(ScrollingMenuSign plugin, BlockPhysicsEvent event) {\n Block b = event.getBlock();\n\n if (Debugger.getInstance().getLevel() > 0) {\n Debugger.getInstance().debug(\"block physics event @ \" + b.getLocation() + \", view = \" + getName() + \", menu=\" + getNativeMenu().getName());\n }\n if (plugin.getConfigCache().isPhysicsProtected()) {\n event.setCancelled(true);\n } else if (BlockUtil.isAttachableDetached(b)) {\n // attached to air? looks like the sign (or other attachable) has become detached\n // NOTE: for multi-block views, the loss of *any* block due to physics causes the view to be removed\n LogUtils.info(\"Attachable view block \" + getName() + \" @ \" + b.getLocation() + \" has become detached: deleting\");\n plugin.getViewManager().deleteView(this, true);\n }\n }\n\n public void processEvent(ScrollingMenuSign plugin, BlockRedstoneEvent event) {\n Block b = event.getBlock();\n\n if (Debugger.getInstance().getLevel() > 0) {\n Debugger.getInstance().debug(\"block redstone event @ \" + b.getLocation() + \", view = \"\n + getName() + \", menu = \" + getNativeMenu().getName()\n + \", current = \" + event.getOldCurrent() + \"->\" + event.getNewCurrent());\n }\n }\n\n /**\n * Get a view by name. Backwards-compatibility for other plugins which need it.\n *\n * @param viewName name of the view to get\n * @return the view object\n * @throws SMSException if there is no such view\n * @deprecated use ViewManager#getView(String)\n */\n @Deprecated\n public static SMSView getView(String viewName) {\n return ScrollingMenuSign.getInstance().getViewManager().getView(viewName);\n }\n\n /**\n * Register a view with the view manager. Backwards-compatibility for other plugins which need it.\n *\n * @deprecated use ViewManager#registerView(SMSView)\n */\n @Deprecated\n public void register() {\n ScrollingMenuSign.getInstance().getViewManager().registerView(this);\n }\n\n /**\n * Check if this view responds to player clicks to scroll/execute it.\n *\n * @return true if the view is responsive to clicks, false otherwise\n */\n public boolean isClickable() {\n return true;\n }\n\n /**\n * Represents a stack of menus, for submenu support. The currently-active\n * menu is at the top of the stack.\n */\n public class MenuStack {\n final Deque<WeakReference<SMSMenu>> stack;\n\n public MenuStack() {\n stack = new ArrayDeque<WeakReference<SMSMenu>>();\n }\n\n public void pushMenu(SMSMenu menu) {\n stack.push(new WeakReference<SMSMenu>(menu));\n }\n\n public SMSMenu popMenu() {\n return stack.pop().get();\n }\n\n public SMSMenu peek() {\n return stack.peek().get();\n }\n\n public boolean isEmpty() {\n return stack.isEmpty();\n }\n }\n}" ]
import me.desht.scrollingmenusign.SMSValidate; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.views.CommandTrigger; import me.desht.scrollingmenusign.views.PoppableView; import me.desht.scrollingmenusign.views.SMSView; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player;
package me.desht.scrollingmenusign.commandlets; public class PopupCommandlet extends BaseCommandlet { public PopupCommandlet() { super("POPUP"); } @Override
public boolean execute(ScrollingMenuSign plugin, CommandSender sender, CommandTrigger trigger, String cmd, String[] args) {
1
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/internal_metric_collectors/linux/ProcessStatus/ProcessStatusCollector.java
[ "public abstract class InternalCollectorFramework {\n \n private static final Logger logger = LoggerFactory.getLogger(InternalCollectorFramework.class.getName());\n \n protected final int NUM_FILE_WRITE_RETRIES = 3;\n protected final int DELAY_BETWEEN_WRITE_RETRIES_IN_MS = 100;\n \n private final boolean isEnabled_;\n private final long collectionInterval_;\n private final String internalCollectorMetricPrefix_;\n private final String outputFilePathAndFilename_;\n private final boolean writeOutputFiles_;\n \n private final String linuxProcFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxProcLocation());\n private final String linuxSysFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxSysLocation());\n\n private String fullInternalCollectorMetricPrefix_ = null;\n private String finalOutputFilePathAndFilename_ = null;\n \n public InternalCollectorFramework(boolean isEnabled, long collectionInterval, String internalCollectorMetricPrefix, \n String outputFilePathAndFilename, boolean writeOutputFiles) {\n this.isEnabled_ = isEnabled;\n this.collectionInterval_ = collectionInterval;\n this.internalCollectorMetricPrefix_ = internalCollectorMetricPrefix;\n this.outputFilePathAndFilename_ = outputFilePathAndFilename;\n this.writeOutputFiles_ = writeOutputFiles;\n \n createFullInternalCollectorMetricPrefix();\n this.finalOutputFilePathAndFilename_ = this.outputFilePathAndFilename_;\n }\n \n public void outputGraphiteMetrics(List<GraphiteMetric> graphiteMetrics) {\n \n if (graphiteMetrics == null) return;\n \n for (GraphiteMetric graphiteMetric : graphiteMetrics) {\n try {\n if (graphiteMetric == null) continue;\n\n String graphiteMetricPathWithPrefix = fullInternalCollectorMetricPrefix_ + graphiteMetric.getMetricPath();\n GraphiteMetric outputGraphiteMetric = new GraphiteMetric(graphiteMetricPathWithPrefix, graphiteMetric.getMetricValue(), graphiteMetric.getMetricTimestampInSeconds());\n\n outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());\n GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric);\n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n if (writeOutputFiles_) {\n String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_);\n writeGraphiteMetricsToFile(outputString);\n }\n \n }\n \n public void outputOpentsdbMetricsAsGraphiteMetrics(List<OpenTsdbMetric> openTsdbMetrics) {\n\n if (openTsdbMetrics == null) return;\n \n for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {\n try {\n if (openTsdbMetric == null) continue;\n\n String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric();\n GraphiteMetric outputGraphiteMetric = new GraphiteMetric(metricNameWithPrefix, openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds());\n\n outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());\n GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric);\n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n if (writeOutputFiles_) {\n List<GraphiteMetric> graphiteMetrics = new ArrayList<>();\n \n for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {\n try {\n if (openTsdbMetric == null) continue;\n GraphiteMetric graphiteMetric = new GraphiteMetric(openTsdbMetric.getMetric(), openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds());\n graphiteMetrics.add(graphiteMetric);\n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_);\n writeGraphiteMetricsToFile(outputString);\n }\n \n }\n \n public void outputOpenTsdbMetrics(List<OpenTsdbMetric> openTsdbMetrics) {\n \n if (openTsdbMetrics == null) return;\n \n for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {\n try {\n if (openTsdbMetric == null) continue;\n\n String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric();\n OpenTsdbMetric outputOpenTsdbMetric = new OpenTsdbMetric(metricNameWithPrefix, openTsdbMetric.getMetricTimestampInMilliseconds(), \n openTsdbMetric.getMetricValue(), openTsdbMetric.getTags());\n\n outputOpenTsdbMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());\n GlobalVariables.openTsdbMetrics.put(outputOpenTsdbMetric.getHashKey(), outputOpenTsdbMetric);\n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n if (writeOutputFiles_) {\n String outputString = buildOpenTsdbMetricsFile(openTsdbMetrics, true, fullInternalCollectorMetricPrefix_);\n writeGraphiteMetricsToFile(outputString);\n }\n \n }\n \n private void writeGraphiteMetricsToFile(String output) {\n \n if ((output == null) || output.isEmpty()) {\n return;\n }\n \n boolean isSuccessfulWrite;\n \n try {\n for (int i = 0; i <= NUM_FILE_WRITE_RETRIES; i++) {\n isSuccessfulWrite = FileIo.saveStringToFile(finalOutputFilePathAndFilename_, output);\n\n if (isSuccessfulWrite) break;\n else Threads.sleepMilliseconds(DELAY_BETWEEN_WRITE_RETRIES_IN_MS);\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n private String buildGraphiteMetricsFile(List<GraphiteMetric> graphiteMetrics, boolean stripPrefix, String metricPrefix) {\n \n if ((graphiteMetrics == null) || graphiteMetrics.isEmpty()) {\n return null;\n }\n \n StringBuilder stringBuilder = new StringBuilder();\n \n for (GraphiteMetric graphiteMetric : graphiteMetrics) {\n try {\n if (graphiteMetric == null) continue;\n\n GraphiteMetric outputGraphiteMetric = graphiteMetric;\n\n if (stripPrefix && (metricPrefix != null)) {\n String graphiteMetricPathNoPrefix = StringUtils.removeStart(graphiteMetric.getMetricPath(), metricPrefix);\n outputGraphiteMetric = new GraphiteMetric(graphiteMetricPathNoPrefix, graphiteMetric.getMetricValue(), graphiteMetric.getMetricTimestampInSeconds());\n }\n\n stringBuilder.append(outputGraphiteMetric.getGraphiteFormatString(true, true)).append(\"\\n\");\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return stringBuilder.toString();\n }\n \n private String buildOpenTsdbMetricsFile(List<OpenTsdbMetric> openTsdbMetrics, boolean stripPrefix, String metricPrefix) {\n \n if ((openTsdbMetrics == null) || openTsdbMetrics.isEmpty()) {\n return null;\n }\n \n StringBuilder stringBuilder = new StringBuilder();\n \n for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {\n try {\n if (openTsdbMetric == null) continue;\n\n OpenTsdbMetric outputOpenTsdbMetric = openTsdbMetric;\n\n if (stripPrefix && (metricPrefix != null)) {\n String openTsdbMetricNameNoPrefix = StringUtils.removeStart(openTsdbMetric.getMetric(), metricPrefix);\n outputOpenTsdbMetric = new OpenTsdbMetric(openTsdbMetricNameNoPrefix, openTsdbMetric.getMetricTimestampInMilliseconds(), \n openTsdbMetric.getMetricValue(), openTsdbMetric.getTags());\n }\n\n stringBuilder.append(outputOpenTsdbMetric.getOpenTsdbTelnetFormatString(true)).append(\"\\n\");\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return stringBuilder.toString();\n }\n \n /*\n returns GlobalMetricPrefix.CollectorMetricPrefix.\n */\n protected final void createFullInternalCollectorMetricPrefix() {\n createAndUpdateFullInternalCollectorMetricPrefix(null, null);\n }\n \n protected void createAndUpdateFullInternalCollectorMetricPrefix(String textToReplace, String replacement) {\n \n String metricPrefix = \"\";\n \n if (ApplicationConfiguration.isGlobalMetricNamePrefixEnabled() && (ApplicationConfiguration.getGlobalMetricNamePrefix() != null)) metricPrefix += ApplicationConfiguration.getGlobalMetricNamePrefix();\n \n if (!metricPrefix.isEmpty() && !metricPrefix.endsWith(\".\")) metricPrefix += \".\";\n \n if (internalCollectorMetricPrefix_ != null) {\n String localInternalCollectorMetricPrefix = internalCollectorMetricPrefix_;\n if ((textToReplace != null) && localInternalCollectorMetricPrefix.contains(textToReplace)) {\n if (replacement == null) localInternalCollectorMetricPrefix = localInternalCollectorMetricPrefix.replace(textToReplace, \"\");\n else localInternalCollectorMetricPrefix = localInternalCollectorMetricPrefix.replace(textToReplace, replacement);\n metricPrefix += localInternalCollectorMetricPrefix;\n }\n else metricPrefix += internalCollectorMetricPrefix_;\n }\n \n if (!metricPrefix.isEmpty() && !metricPrefix.endsWith(\".\")) metricPrefix += \".\";\n \n fullInternalCollectorMetricPrefix_ = metricPrefix;\n }\n \n protected void updateOutputFilePathAndFilename(String textToReplace, String replacement) {\n String localOutputFilePathAndFilename = outputFilePathAndFilename_;\n\n try {\n if ((localOutputFilePathAndFilename != null) && (textToReplace != null) && localOutputFilePathAndFilename.contains(textToReplace)) {\n if (replacement == null) {\n localOutputFilePathAndFilename = localOutputFilePathAndFilename.replace(textToReplace, \"\");\n }\n else {\n localOutputFilePathAndFilename = localOutputFilePathAndFilename.replace(textToReplace, replacement);\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n finalOutputFilePathAndFilename_ = localOutputFilePathAndFilename;\n }\n \n private static String removeTrailingSlash(String input) {\n if ((input == null) || input.isEmpty()) return input;\n \n while(input.endsWith(\"/\")) input = StringUtils.removeEnd(input, \"/\");\n return input;\n }\n \n public boolean isEnabled() {\n return isEnabled_;\n }\n\n public long getCollectionInterval() {\n return collectionInterval_;\n }\n \n public String getInternalCollectorMetricPrefix() {\n return internalCollectorMetricPrefix_;\n }\n \n public boolean isWriteOutputFiles() {\n return writeOutputFiles_;\n }\n\n protected String getLinuxProcFileSystemLocation() {\n return linuxProcFileSystemLocation_;\n }\n\n protected String getLinuxSysFileSystemLocation() {\n return linuxSysFileSystemLocation_;\n }\n \n}", "public class GraphiteMetric implements GraphiteMetricFormat, OpenTsdbMetricFormat, GenericMetricFormat, InfluxdbMetricFormat_v1 {\n \n private static final Logger logger = LoggerFactory.getLogger(GraphiteMetric.class.getName());\n \n private long hashKey_ = -1;\n \n private final String metricPath_;\n private final BigDecimal metricValue_;\n private final long metricTimestamp_;\n private final long metricReceivedTimestampInMilliseconds_;\n \n private final boolean isMetricTimestampInSeconds_;\n \n // metricTimestamp is assumed to be in seconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, int metricTimestamp) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = ((long) metricTimestamp) * 1000;\n \n this.isMetricTimestampInSeconds_ = true;\n }\n \n // metricTimestamp is assumed to be in seconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, int metricTimestamp, long metricReceivedTimestampInMilliseconds) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = metricReceivedTimestampInMilliseconds;\n \n this.isMetricTimestampInSeconds_ = true;\n }\n \n // metricTimestamp is assumed to be in milliseconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, long metricTimestamp, long metricReceivedTimestampInMilliseconds) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = metricReceivedTimestampInMilliseconds;\n \n this.isMetricTimestampInSeconds_ = false;\n }\n \n @Override\n public int hashCode() {\n return new HashCodeBuilder(11, 13)\n .append(metricPath_)\n .append(metricValue_)\n .append(metricTimestamp_)\n .append(metricReceivedTimestampInMilliseconds_)\n .append(isMetricTimestampInSeconds_)\n .toHashCode();\n }\n \n @Override\n public boolean equals(Object obj) {\n if (obj == null) return false;\n if (obj == this) return true;\n if (obj.getClass() != getClass()) return false;\n \n GraphiteMetric graphiteMetric = (GraphiteMetric) obj;\n \n boolean isMetricValueEqual = false;\n if ((metricValue_ != null) && (graphiteMetric.getMetricValue() != null)) {\n isMetricValueEqual = metricValue_.compareTo(graphiteMetric.getMetricValue()) == 0;\n }\n else if (metricValue_ == null) {\n isMetricValueEqual = graphiteMetric.getMetricValue() == null;\n }\n \n return new EqualsBuilder()\n .append(metricPath_, graphiteMetric.getMetricPath())\n .append(isMetricValueEqual, true)\n .append(metricTimestamp_, graphiteMetric.getMetricTimestamp())\n .append(metricReceivedTimestampInMilliseconds_, graphiteMetric.getMetricReceivedTimestampInMilliseconds())\n .append(isMetricTimestampInSeconds_, isMetricTimestampInSeconds())\n .isEquals();\n }\n \n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n \n stringBuilder.append(metricPath_).append(\" \")\n .append(getMetricValueString()).append(\" \") \n .append(metricTimestamp_)\n .append(\" @ \").append(metricReceivedTimestampInMilliseconds_);\n \n return stringBuilder.toString();\n }\n\n @Override\n public String getGraphiteFormatString(boolean sanitizeMetric, boolean substituteCharacters) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metricPath = GraphiteMetric.getGraphiteSanitizedString(metricPath_, sanitizeMetric, substituteCharacters);\n \n stringBuilder.append(metricPath).append(\" \").append(getMetricValueString()).append(\" \").append(getMetricTimestampInSeconds());\n\n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric) {\n return getOpenTsdbTelnetFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metric = sanitizeMetric ? OpenTsdbMetric.getOpenTsdbSanitizedString(metricPath_) : metricPath_;\n \n String tag = (defaultOpenTsdbTagKey == null) ? \"Format=Graphite\" : (defaultOpenTsdbTagKey + \"=\" + defaultOpenTsdbTagValue);\n \n stringBuilder.append(metric).append(\" \").append(getMetricTimestampInSeconds()).append(\" \").append(getMetricValueString()).append(\" \").append(tag);\n\n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric) {\n return getOpenTsdbJsonFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n \n if ((metricPath_ == null) || metricPath_.isEmpty()) return null;\n if (getMetricTimestampInSeconds() < 0) return null;\n if ((getMetricValue() == null)) return null;\n \n StringBuilder openTsdbJson = new StringBuilder();\n\n openTsdbJson.append(\"{\");\n\n if (sanitizeMetric) openTsdbJson.append(\"\\\"metric\\\":\\\"\").append(StringEscapeUtils.escapeJson(OpenTsdbMetric.getOpenTsdbSanitizedString(metricPath_))).append(\"\\\",\");\n else openTsdbJson.append(\"\\\"metric\\\":\\\"\").append(StringEscapeUtils.escapeJson(metricPath_)).append(\"\\\",\");\n \n openTsdbJson.append(\"\\\"timestamp\\\":\").append(getMetricTimestampInSeconds()).append(\",\");\n openTsdbJson.append(\"\\\"value\\\":\").append(getMetricValueString()).append(\",\");\n\n openTsdbJson.append(\"\\\"tags\\\":{\");\n if ((defaultOpenTsdbTagKey == null) || (defaultOpenTsdbTagValue == null)) openTsdbJson.append(\"\\\"Format\\\":\\\"Graphite\\\"\");\n else openTsdbJson.append(\"\\\"\").append(defaultOpenTsdbTagKey).append(\"\\\":\\\"\").append(defaultOpenTsdbTagValue).append(\"\\\"\");\n openTsdbJson.append(\"}\");\n\n openTsdbJson.append(\"}\");\n \n return openTsdbJson.toString();\n }\n \n @Override\n public String getInfluxdbV1JsonFormatString() {\n\n if ((metricPath_ == null) || metricPath_.isEmpty()) return null;\n if (metricTimestamp_ < 0) return null;\n if ((getMetricValue() == null)) return null;\n\n StringBuilder influxdbJson = new StringBuilder();\n\n influxdbJson.append(\"{\");\n\n // the metric name, with the prefix already built-in\n influxdbJson.append(\"\\\"name\\\":\\\"\").append(StringEscapeUtils.escapeJson(metricPath_)).append(\"\\\",\");\n\n // column order: value, time, tag(s)\n influxdbJson.append(\"\\\"columns\\\":[\\\"value\\\",\\\"time\\\"],\");\n\n // only include one point in the points array. note-- timestamp will always be sent to influxdb in milliseconds\n influxdbJson.append(\"\\\"points\\\":[[\");\n influxdbJson.append(getMetricValueString()).append(\",\");\n influxdbJson.append(getMetricTimestampInMilliseconds());\n \n influxdbJson.append(\"]]}\");\n\n return influxdbJson.toString();\n }\n \n /*\n @param unsanitizedInput The input is expected to be a Graphite 'metric path'.\n \n @param sanitizeMetric When set to true, all input will have back-to-back '.' characters merged into a single '.'.\n Example: \"lol...lol\" -> \"lol.lol\"\n \n @param 'substituteCharacters' When set to true: a few special characters will be turned into characters that Graphite can handle. \n % -> Pct\n (){}[]/\\ -> |\n */\n public static String getGraphiteSanitizedString(String unsanitizedInput, boolean sanitizeMetric, boolean substituteCharacters) {\n\n if (unsanitizedInput == null) return null;\n if (!sanitizeMetric && !substituteCharacters) return unsanitizedInput;\n \n StringBuilder sanitizedInput = new StringBuilder();\n\n for (int i = 0; i < unsanitizedInput.length(); i++) {\n char character = unsanitizedInput.charAt(i);\n\n if (substituteCharacters && Character.isLetterOrDigit(character)) {\n sanitizedInput.append(character);\n continue;\n }\n\n if (sanitizeMetric && (character == '.')) {\n int iPlusOne = i + 1;\n \n if (((iPlusOne < unsanitizedInput.length()) && (unsanitizedInput.charAt(iPlusOne) != '.')) || (iPlusOne == unsanitizedInput.length())) {\n sanitizedInput.append(character);\n continue;\n }\n }\n\n if (substituteCharacters) {\n if (character == '%') {\n sanitizedInput.append(\"Pct\");\n continue;\n }\n \n if (character == ' ') {\n sanitizedInput.append(\"_\");\n continue;\n }\n \n if ((character == '\\\\') || (character == '/') || \n (character == '[') || (character == ']') || \n (character == '{') || (character == '}') ||\n (character == '(') || (character == ')')) {\n sanitizedInput.append(\"|\");\n continue;\n }\n\n }\n \n if (sanitizeMetric && (character != '.')) sanitizedInput.append(character);\n else if (!sanitizeMetric) sanitizedInput.append(character);\n }\n \n return sanitizedInput.toString();\n }\n \n public static GraphiteMetric parseGraphiteMetric(String unparsedMetric, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if (unparsedMetric == null) {\n return null;\n }\n \n try {\n int metricPathIndexRange = unparsedMetric.indexOf(' ', 0);\n String metricPath = null;\n if (metricPathIndexRange > 0) {\n if ((metricPrefix != null) && !metricPrefix.isEmpty()) metricPath = metricPrefix + unparsedMetric.substring(0, metricPathIndexRange);\n else metricPath = unparsedMetric.substring(0, metricPathIndexRange);\n }\n\n int metricValueIndexRange = unparsedMetric.indexOf(' ', metricPathIndexRange + 1);\n BigDecimal metricValueBigDecimal = null;\n if (metricValueIndexRange > 0) {\n String metricValueString = unparsedMetric.substring(metricPathIndexRange + 1, metricValueIndexRange);\n \n if (metricValueString.length() > 100) {\n logger.debug(\"Metric parse error. Metric value can't be more than 100 characters long. Metric value was \\\"\" + metricValueString.length() + \"\\\" characters long.\");\n }\n else {\n metricValueBigDecimal = new BigDecimal(metricValueString);\n }\n }\n\n String metricTimestampString = unparsedMetric.substring(metricValueIndexRange + 1, unparsedMetric.length());\n int metricTimestamp = Integer.parseInt(metricTimestampString);\n \n if ((metricPath == null) || metricPath.isEmpty() || (metricValueBigDecimal == null) ||\n (metricTimestampString == null) || metricTimestampString.isEmpty() || \n (metricTimestampString.length() != 10) || (metricTimestamp < 0)) {\n logger.warn(\"Metric parse error: \\\"\" + unparsedMetric + \"\\\"\");\n return null;\n }\n else {\n GraphiteMetric graphiteMetric = new GraphiteMetric(metricPath, metricValueBigDecimal, metricTimestamp, metricReceivedTimestampInMilliseconds); \n return graphiteMetric;\n }\n }\n catch (NumberFormatException e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator()); \n return null;\n }\n catch (Exception e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n public static List<GraphiteMetric> parseGraphiteMetrics(String unparsedMetrics, long metricReceivedTimestampInMilliseconds) {\n return parseGraphiteMetrics(unparsedMetrics, null, metricReceivedTimestampInMilliseconds);\n }\n \n public static List<GraphiteMetric> parseGraphiteMetrics(String unparsedMetrics, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if ((unparsedMetrics == null) || unparsedMetrics.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<GraphiteMetric> graphiteMetrics = new ArrayList();\n \n try {\n int currentIndex = 0;\n int newLineLocation = 0;\n\n while(newLineLocation != -1) {\n newLineLocation = unparsedMetrics.indexOf('\\n', currentIndex);\n\n String unparsedMetric;\n\n if (newLineLocation == -1) {\n unparsedMetric = unparsedMetrics.substring(currentIndex, unparsedMetrics.length());\n }\n else {\n unparsedMetric = unparsedMetrics.substring(currentIndex, newLineLocation);\n currentIndex = newLineLocation + 1;\n }\n\n if ((unparsedMetric != null) && !unparsedMetric.isEmpty()) {\n GraphiteMetric graphiteMetric = GraphiteMetric.parseGraphiteMetric(unparsedMetric.trim(), metricPrefix, metricReceivedTimestampInMilliseconds);\n\n if (graphiteMetric != null) {\n graphiteMetrics.add(graphiteMetric);\n }\n }\n }\n }\n catch (Exception e) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return graphiteMetrics;\n }\n\n public long getHashKey() {\n return this.hashKey_;\n }\n \n @Override\n public long getMetricHashKey() {\n return getHashKey();\n }\n \n public void setHashKey(long hashKey) {\n this.hashKey_ = hashKey;\n }\n \n @Override\n public void setMetricHashKey(long hashKey) {\n setHashKey(hashKey);\n }\n \n public String getMetricPath() {\n return metricPath_;\n }\n \n @Override\n public String getMetricKey() {\n return getMetricPath();\n }\n \n public BigDecimal getMetricValue() {\n return metricValue_;\n }\n \n @Override\n public BigDecimal getMetricValueBigDecimal() {\n return metricValue_;\n }\n \n @Override\n public String getMetricValueString() {\n if (metricValue_ == null) return null;\n return MathUtilities.getFastPlainStringWithNoTrailingZeros(metricValue_);\n }\n \n public long getMetricTimestamp() {\n return metricTimestamp_;\n }\n \n @Override\n public int getMetricTimestampInSeconds() {\n if (isMetricTimestampInSeconds_) return (int) metricTimestamp_;\n else return (int) (metricTimestamp_ / 1000);\n }\n \n @Override\n public long getMetricTimestampInMilliseconds() {\n if (!isMetricTimestampInSeconds_) return metricTimestamp_;\n else return (long) (metricTimestamp_ * 1000);\n }\n \n @Override\n public long getMetricReceivedTimestampInMilliseconds() {\n return metricReceivedTimestampInMilliseconds_;\n }\n\n public boolean isMetricTimestampInSeconds() {\n return isMetricTimestampInSeconds_;\n }\n \n}", "public class StackTrace {\n \n private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName());\n \n public static String getStringFromStackTrace(Exception exception) {\n try {\n StringWriter stringWriter = new StringWriter();\n PrintWriter printWriter = new PrintWriter(stringWriter);\n \n exception.printStackTrace(printWriter);\n \n return stringWriter.toString();\n }\n catch (Exception e) {\n logger.error(e.toString() + \" - Failed to convert stack-trace to string\");\n return null;\n }\n }\n \n public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) {\n try {\n \n StringBuilder stackTrace = new StringBuilder();\n \n for (StackTraceElement stackTraceElement : stackTraceElements) {\n stackTrace.append(stackTraceElement).append(System.lineSeparator());\n }\n \n return stackTrace.toString();\n }\n catch (Exception e) {\n logger.error(e.toString() + \" - Failed to convert stack-trace to string\");\n return null;\n }\n }\n \n}", "public class Threads {\n \n private static final Logger logger = LoggerFactory.getLogger(Threads.class.getName());\n \n public static void sleepMilliseconds(long milliseconds) {\n sleepMilliseconds(milliseconds, false);\n }\n \n public static void sleepMilliseconds(long milliseconds, boolean logSleepTime) {\n \n if (milliseconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + milliseconds + \" milliseconds\");\n }\n \n Thread.sleep(milliseconds);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepSeconds(int seconds) {\n sleepSeconds(seconds, false);\n }\n \n public static void sleepSeconds(int seconds, boolean logSleepTime) {\n \n if (seconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + seconds + \" seconds\");\n }\n \n Thread.sleep((long) (seconds * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepSeconds(double seconds) {\n sleepSeconds(seconds, false);\n }\n \n public static void sleepSeconds(double seconds, boolean logSleepTime) {\n \n if (seconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + seconds + \" seconds\");\n }\n \n Thread.sleep((long) (seconds * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepMinutes(int minutes) {\n sleepMinutes(minutes, false);\n }\n \n public static void sleepMinutes(int minutes, boolean logSleepTime) {\n \n if (minutes <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + minutes + \" minutes\");\n }\n \n Thread.sleep((long) (60 * minutes * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepMinutes(double minutes) {\n sleepMinutes(minutes, false);\n }\n \n public static void sleepMinutes(double minutes, boolean logSleepTime) {\n \n if (minutes <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + minutes + \" minutes\");\n }\n \n Thread.sleep((long) (60 * minutes * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void threadExecutorFixedPool(List threads, int nThreadPoolSize, long timeoutTime, TimeUnit timeoutTimeunit) {\n \n if ((threads == null) || threads.isEmpty() ||(nThreadPoolSize <= 0) || (timeoutTime <= 0) || (timeoutTimeunit == null)) {\n return;\n }\n \n try {\n ExecutorService threadExecutor = Executors.newFixedThreadPool(nThreadPoolSize);\n for (Object thread : threads) {\n threadExecutor.execute((Runnable) thread);\n }\n\n threadExecutor.shutdown();\n boolean didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n \n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n try {\n threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n }\n \n public static void threadExecutorCachedPool(List threads, long timeoutTime, TimeUnit timeoutTimeunit) {\n \n if ((threads == null) || threads.isEmpty() || (timeoutTime <= 0) || (timeoutTimeunit == null)) {\n return;\n }\n \n try {\n ExecutorService threadExecutor = Executors.newCachedThreadPool();\n \n for (Object thread : threads) {\n threadExecutor.execute((Runnable) thread);\n }\n\n threadExecutor.shutdown();\n boolean didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n \n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n try {\n threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n }\n \n public static void shutdownThreadExecutor(ExecutorService threadExecutor, Long timeoutTime, TimeUnit timeoutTimeunit, \n boolean forceShutdownIfTimeoutReached, boolean waitForeverForForceShutdownToFinish) {\n\n if (threadExecutor == null) {\n logger.error(\"ThreadExecutor cannot be null\");\n return;\n }\n \n if ((timeoutTime == null) || (timeoutTime <= 0)) {\n logger.error(\"TimeoutTime cannot be null or less than 0\");\n return;\n }\n \n if (timeoutTimeunit == null) {\n logger.error(\"Timeout-Timeunit cannot be null\");\n return;\n }\n\n boolean didFinishWithoutTimeout = false;\n \n try {\n threadExecutor.shutdown();\n didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n if (forceShutdownIfTimeoutReached) {\n try {\n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n } \n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n if (waitForeverForForceShutdownToFinish) {\n try {\n threadExecutor.awaitTermination(99999999, TimeUnit.DAYS);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n }\n \n}", "public class FileIo {\n\n private static final Logger logger = LoggerFactory.getLogger(FileIo.class.getName());\n \n /**\n * Creates a directory. \n * @return Returns false if unsuccessful or if an exception was encountered. Returns true if the directory was successfully created.\n */\n public static boolean createDirectory(String parentPath, String directoryName) {\n \n if ((parentPath == null) || parentPath.isEmpty() || (directoryName == null) || directoryName.isEmpty()) {\n return false;\n }\n\n try {\n File directory = new File(parentPath + File.separator + directoryName);\n boolean doesDirectoryExist = directory.exists();\n\n boolean createDirectorySuccess = true;\n if (!doesDirectoryExist) {\n createDirectorySuccess = directory.mkdir();\n }\n\n return createDirectorySuccess;\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n }\n\n /**\n * This is a quiet method.\n */ \n public static boolean deleteFile(String filePath, String filename) {\n \n if ((filePath == null) || filePath.isEmpty() || (filename == null) || filename.isEmpty()) {\n return false;\n }\n \n return deleteFile(filePath + File.separator + filename);\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean deleteFile(String filePathAndName) {\n \n if ((filePathAndName == null) || filePathAndName.isEmpty()) {\n return false;\n }\n \n boolean isSuccessfulDelete = false;\n\n try {\n File fileToDelete = new File(filePathAndName);\n isSuccessfulDelete = fileToDelete.delete();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulDelete = false;\n }\n \n return isSuccessfulDelete;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean deleteFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return false;\n }\n \n boolean isSuccessfulDelete = true;\n\n List<File> files = getListOfFilesInADirectory(directoryPath);\n \n if (files == null) {\n return false;\n }\n \n try {\n for (File file : files) {\n boolean fileDeleteSuccess = deleteFile(directoryPath, file.getName());\n\n if (!fileDeleteSuccess) {\n isSuccessfulDelete = false;\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulDelete = false;\n }\n \n return isSuccessfulDelete;\n }\n \n /**\n * This is a quiet method.\n * Only deletes files. Doesn't delete directories.\n */\n public static boolean deleteDirectoryFiles(Set<String> inputFilePathsAndNames) {\n \n if ((inputFilePathsAndNames == null)) {\n return false;\n }\n\n boolean didSuccessfullyDeleteAllFiles = true; \n \n try {\n for (String filePathAndName : inputFilePathsAndNames) {\n File file = new File(filePathAndName);\n\n if (!file.isDirectory()) {\n boolean deleteSuccess = deleteFile(filePathAndName);\n\n if (!deleteSuccess) {\n logger.debug(\"Warning - \" + filePathAndName + \" failed to delete\");\n didSuccessfullyDeleteAllFiles = false;\n }\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n return didSuccessfullyDeleteAllFiles;\n }\n \n /**\n * This is a quiet method.\n * Only deletes directories. Will fail if the directories have files in them.\n */\n public static boolean deleteDirectorySubdirectories(String rootDirectory) {\n \n if ((rootDirectory == null)) {\n return false;\n }\n\n boolean didSuccessfullyDeleteAllDirectories = true; \n \n try {\n List<File> files = getListOfFilesInADirectory(rootDirectory);\n\n for (File file : files) {\n if (file.isDirectory()) {\n boolean deleteSuccess = deleteDirectoryAndContents(file);\n\n if (!deleteSuccess) {\n logger.debug(\"Warning - failed to delete \" + file.getAbsolutePath());\n didSuccessfullyDeleteAllDirectories = false;\n }\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n return didSuccessfullyDeleteAllDirectories;\n }\n \n /**\n * This is a quiet method.\n * Method template code from http://www.exampledepot.com/egs/java.io/DeleteDir.html\n */\n public static boolean deleteDirectoryAndContents(File rootDirectory) {\n \n if ((rootDirectory == null) || !rootDirectory.isDirectory()) {\n return false;\n } \n \n try {\n String[] directoryContents = rootDirectory.list();\n for (int i = 0; i < directoryContents.length; i++) {\n boolean success = deleteDirectoryAndContents(new File(rootDirectory, directoryContents[i]));\n\n if (!success) {\n return false;\n }\n }\n \n return rootDirectory.delete();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(String filePathAndName) {\n \n if ((filePathAndName == null) || filePathAndName.isEmpty()) {\n return false;\n }\n\n File file = new File(filePathAndName);\n \n boolean doesFileExist;\n \n try {\n doesFileExist = file.exists();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n doesFileExist = false;\n }\n\n return doesFileExist;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(File file) {\n \n if (file == null) {\n return false;\n }\n \n boolean doesFileExist;\n \n try {\n doesFileExist = file.exists();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n doesFileExist = false;\n }\n\n return doesFileExist;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(String filePath, String filename) {\n if ((filePath == null) || filePath.isEmpty() || (filename == null) || filename.isEmpty()) {\n return false;\n }\n \n return doesFileExist(filePath + File.separator + filename);\n }\n \n public static long getFileLastModified(String filePathAndName) {\n File file = new File(filePathAndName);\n long lastModified = file.lastModified();\n\n return lastModified;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean renameFile(String filePath, String oldFilename, String newFilename) {\n \n if ((filePath == null) || filePath.isEmpty() ||\n (oldFilename == null) || oldFilename.isEmpty() || \n (newFilename == null) || newFilename.isEmpty()) {\n return false;\n }\n \n File oldFile = new File(filePath + File.separator + oldFilename);\n File newFile = new File(filePath + File.separator + newFilename);\n\n boolean isSuccessfulRename;\n \n try {\n isSuccessfulRename = oldFile.renameTo(newFile);\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulRename = false;\n }\n \n return isSuccessfulRename;\n }\n\n public static boolean copyFile(String sourceFilePath, String sourceFilename, String destinationFilePath, String destinationFilename) {\n \n if ((sourceFilePath == null) || sourceFilePath.isEmpty() ||\n (sourceFilename == null) || sourceFilename.isEmpty() || \n (destinationFilePath == null) || destinationFilePath.isEmpty() ||\n (destinationFilename == null) || destinationFilename.isEmpty()) {\n return false;\n }\n\n boolean isCopySuccess = false;\n \n FileChannel sourceFileChannel = null;\n FileChannel destinationFileChannel = null;\n\n try {\n File sourceFile = new File(sourceFilePath + File.separator + sourceFilename);\n File destinationFile = new File(destinationFilePath + File.separator + destinationFilename);\n\n if (sourceFile.exists()) {\n\n if (!destinationFile.exists()) {\n destinationFile.createNewFile();\n }\n\n sourceFileChannel = new FileInputStream(sourceFile).getChannel();\n destinationFileChannel = new FileOutputStream(destinationFile).getChannel();\n\n destinationFileChannel.transferFrom(sourceFileChannel, 0, sourceFileChannel.size());\n \n isCopySuccess = true;\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n finally {\n if (sourceFileChannel != null) {\n try {\n sourceFileChannel.close();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n if (destinationFileChannel != null) {\n try {\n destinationFileChannel.close();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return isCopySuccess;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static List<String> getListOfDirectoryNamesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<String> directoryNamesList = new ArrayList<>();\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n\n if (file.isDirectory()) {\n directoryNamesList.add(file.getName());\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return directoryNamesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfDirectoryFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<File> directoryFilesList = new ArrayList<>();\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n \n if (file.isDirectory()) {\n directoryFilesList.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return directoryFilesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<String> getListOfFilenamesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<String> filenamesList = new ArrayList<>();\n \n for (int i = 0; i < filenames.length; i++) {\n filenamesList.add(filenames[i]);\n }\n \n return filenamesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<File> files = new ArrayList<>();\n \n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n\n if (file.exists()) {\n files.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return files;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfFilesInADirectory(String directoryPath, List<String> filenames) {\n \n if ((directoryPath == null) || directoryPath.isEmpty() || (filenames == null) || filenames.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<File> files = new ArrayList<>();\n \n for (int i = 0; i < filenames.size(); i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames.get(i));\n\n if (file.exists()) {\n files.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return files;\n }\n \n public static String getFileExtensionFromFilename(String filename) {\n \n if ((filename == null) || filename.isEmpty()) {\n return null;\n }\n \n int indexOfBeginExtension = filename.lastIndexOf('.');\n\n if ((indexOfBeginExtension != -1) && ((indexOfBeginExtension + 1) != filename.length())) {\n String fileExtension = filename.substring(indexOfBeginExtension + 1, filename.length());\n return fileExtension;\n }\n else {\n return null;\n }\n }\n \n public static String getFilenameWithoutExtension(String filename) {\n \n if ((filename == null) || filename.isEmpty()) {\n return null;\n }\n \n int indexOfBeginExtension = filename.lastIndexOf('.');\n\n if ((indexOfBeginExtension != -1) && ((indexOfBeginExtension + 1) != filename.length())) {\n String filenameWithoutExtension = filename.substring(0, indexOfBeginExtension);\n return filenameWithoutExtension;\n }\n else {\n return null;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean saveStringToFile(String saveFilePath, String saveFilename, String saveString) {\n return saveStringToFile(saveFilePath + File.separator + saveFilename, saveString);\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean saveStringToFile(String saveFilePathAndName, String saveString) {\n \n if ((saveFilePathAndName == null) || saveFilePathAndName.isEmpty() ||\n (saveString == null) || saveString.isEmpty()) {\n return false;\n }\n \n BufferedWriter writer = null;\n \n try { \n File outputFile = new File(saveFilePathAndName); \n writer = new BufferedWriter(new FileWriter(outputFile));\n \n writer.write(saveString);\n \n return true;\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n finally {\n try {\n if (writer != null) {\n writer.close();\n }\n }\n catch (Exception e){\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n public static String readFileToString(String filePath, String filename) {\n String filePathAndName = filePath + File.separator + filename;\n return readFileToString(filePathAndName);\n }\n \n public static String readFileToString(String filePathAndName) {\n \n if ((filePathAndName == null) || (filePathAndName.length() == 0)) {\n return null;\n }\n \n File file;\n \n try {\n file = new File(filePathAndName);\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return null;\n }\n \n return readFileToString(file);\n }\n \n /**\n * This is a quiet method.\n */\n public static String readFileToString(File file) {\n \n if (file == null) {\n return null;\n }\n \n BufferedReader reader = null;\n \n try {\n reader = new BufferedReader(new FileReader(file));\n \n StringBuilder fileContents = new StringBuilder(\"\");\n boolean isFirstLine = true;\n \n String currentLine = reader.readLine();\n while (currentLine != null) {\n if (isFirstLine) isFirstLine = false;\n else fileContents.append(System.lineSeparator());\n \n fileContents.append(currentLine);\n currentLine = reader.readLine();\n } \n \n return fileContents.toString();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return null;\n }\n finally {\n try {\n if (reader != null) {\n reader.close();\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n\n public static String readFileToString(File file, int numRetries, int timeBetweenRetriesInMilliseconds) {\n \n if ((file == null) || (numRetries < 0) || (timeBetweenRetriesInMilliseconds < 0)) {\n return null;\n }\n \n String fileContents = null;\n \n for (int i = 0; (i <= numRetries) && (fileContents == null); i++) {\n fileContents = readFileToString(file);\n\n if (fileContents == null) {\n Threads.sleepMilliseconds(timeBetweenRetriesInMilliseconds);\n }\n }\n \n return fileContents;\n }\n \n}" ]
import com.pearson.statspoller.internal_metric_collectors.InternalCollectorFramework; import com.pearson.statspoller.metric_formats.graphite.GraphiteMetric; import com.pearson.statspoller.utilities.core_utils.StackTrace; import com.pearson.statspoller.utilities.core_utils.Threads; import com.pearson.statspoller.utilities.file_utils.FileIo; import java.io.BufferedReader; import java.io.StringReader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.internal_metric_collectors.linux.ProcessStatus; /** * @author Jeffrey Schmidt * * Collects aggregated process status metrics * * Based on raw data from /proc/(pid)/status * http://man7.org/linux/man-pages/man5/proc.5.html */ public class ProcessStatusCollector extends InternalCollectorFramework implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ProcessStatusCollector.class.getName()); private static final HashSet<String> CORE_STATES = getSetOfCoreProcessStates(); public ProcessStatusCollector(boolean isEnabled, long collectionInterval, String metricPrefix, String outputFilePathAndFilename, boolean writeOutputFiles) { super(isEnabled, collectionInterval, metricPrefix, outputFilePathAndFilename, writeOutputFiles); } @Override public void run() { while(super.isEnabled()) { long routineStartTime = System.currentTimeMillis(); // get the update stats in graphite format List<GraphiteMetric> graphiteMetrics = getProcessStatusMetrics(); // output graphite metrics super.outputGraphiteMetrics(graphiteMetrics); long routineTimeElapsed = System.currentTimeMillis() - routineStartTime; logger.info("Finished Linux-ProcessState metric collection routine. " + "MetricsCollected=" + graphiteMetrics.size() + ", MetricCollectionTime=" + routineTimeElapsed); long sleepTimeInMs = getCollectionInterval() - routineTimeElapsed; if (sleepTimeInMs >= 0) Threads.sleepMilliseconds(sleepTimeInMs); } } private List<GraphiteMetric> getProcessStatusMetrics() { List<GraphiteMetric> allGraphiteMetrics = new ArrayList<>(); try { int currentTimestampInSeconds = (int) (System.currentTimeMillis() / 1000); List<String> listOfDirectoriesInProc = FileIo.getListOfDirectoryNamesInADirectory(super.getLinuxProcFileSystemLocation()); List<String> listOfProcessDirectoriesInProc = new ArrayList<>(); for (String directoryInProc : listOfDirectoriesInProc) { if ((directoryInProc == null) || directoryInProc.isEmpty()) continue; boolean isDirectoryNumeric = StringUtils.isNumeric(directoryInProc); boolean doesStatusExist = FileIo.doesFileExist(super.getLinuxProcFileSystemLocation() + "/" + directoryInProc + "/status" ); if (isDirectoryNumeric && doesStatusExist) listOfProcessDirectoriesInProc.add(directoryInProc); } Map<String,String> stateOfEveryPid = new HashMap<>(); // k=pid#, v=status AtomicInteger countOfThreads = new AtomicInteger(0); getProcessStatusMetrics(listOfProcessDirectoriesInProc, stateOfEveryPid, countOfThreads); allGraphiteMetrics.addAll(createMetrics(listOfProcessDirectoriesInProc, stateOfEveryPid, countOfThreads, currentTimestampInSeconds)); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
2
westbury/dwg-lib
src/main/java/com/onespatial/dwglib/objects/Layout.java
[ "public class FileVersion\n{\n private final int version;\n\n public FileVersion(String fileVersionAsString)\n {\n switch (fileVersionAsString) {\n case \"AC1015\":\n // Release 15\n throw new UnsupportedFileVersionException(\"This file was produced by AutoCAD 2000, 2000i, or 2002. Only files produced by AutoCAD 2010 or later are supported.\");\n case \"AC1018\":\n // Release 18\n throw new UnsupportedFileVersionException(\"This file was produced by AutoCAD 2004, 2005, or 2006. Only files produced by AutoCAD 2010 or later are supported.\");\n case \"AC1021\":\n // Release 21\n throw new UnsupportedFileVersionException(\"This file was produced by AutoCAD 2007, 2008, or 2009. Only files produced by AutoCAD 2010 or later are supported.\");\n case \"AC1024\":\n version = 2010;\n break;\n case \"AC1027\":\n version = 2013;\n break;\n default:\n throw new UnsupportedFileVersionException(\"DWG format \" + fileVersionAsString + \" files are not supported. Only files produced by AutoCAD 2010 or later are supported.\");\n }\n\n }\n\n public boolean is2013OrLater()\n {\n return version >= 2013;\n }\n\n public String getVersionYear()\n {\n return Integer.toString(version);\n }\n\n}", "public class BitBuffer {\n private byte[] byteArray;\n\n private Issues issues;\n \n private int currentOffset;\n\n private int bitOffset;\n\n private int currentByte;\n\n private int endOffset;\n\n private BitBuffer(byte[] byteArray, Issues issues) {\n this.byteArray = byteArray;\n this.issues = issues;\n \n currentOffset = 0;\n currentByte = byteArray[0];\n bitOffset = 0;\n\n // TODO: must set actual last bit here\n this.endOffset = byteArray.length * 8;\n }\n\n public static BitBuffer wrap(byte[] byteArray, Issues issues) {\n return new BitBuffer(byteArray, issues);\n }\n\n public void position(int offset) {\n this.currentOffset = offset / 8;\n currentByte = byteArray[currentOffset];\n this.bitOffset = (offset % 8);\n }\n\n public int position() {\n return currentOffset * 8 + bitOffset;\n }\n\n // TODO remove this method and set in constructor\n public void setEndOffset(int endOffset) {\n this.endOffset = endOffset;\n }\n\n /**\n * bit (1 or 0)\n *\n * @return\n */\n public boolean getB() {\n if (!hasMoreData()) {\n throw new RuntimeException(\"end of stream reached unexpectedly\");\n }\n\n int mask = 0x80 >> bitOffset;\n boolean result = ((currentByte & mask) != 0);\n if (bitOffset == 7) {\n currentByte = byteArray[++currentOffset];\n bitOffset = 0;\n } else {\n bitOffset++;\n }\n return result;\n }\n\n public int getBB() {\n return getBitsUnsigned(2);\n }\n\n /**\n * raw char (not compressed)\n * @return\n */\n public int getRC() {\n boolean isNegative = getB();\n int value = getBitsUnsigned(7);\n\n return isNegative ? -value : value;\n }\n\n public int getUnsignedRC() {\n return getBitsUnsigned(8);\n }\n\n /**\n * raw short (not compressed)\n * @return\n */\n public int getRS() {\n int a = getBitsUnsigned(8);\n boolean isNegative = getB();\n int b = getBitsUnsigned(7);\n\n int value = a + (b << 8);\n return isNegative ? -value : value;\n }\n\n /**\n * raw long (not compressed)\n * @return\n */\n public int getRL() {\n int a = getBitsUnsigned(8);\n int b = getBitsUnsigned(8);\n int c = getBitsUnsigned(8);\n boolean isNegative = getB();\n int d = getBitsUnsigned(7);\n\n int value = a + (b << 8) + (c << 16) + (d << 24);\n return isNegative ? -value : value;\n }\n\n /**\n * bitshort 16\n * See 2.2 Bitshort\n *\n * @return\n */\n public int getBS() {\n int code = getBitsUnsigned(2);\n switch (code) {\n case 0:\n return getRS();\n case 1:\n return getBitsUnsigned(8);\n case 2:\n return 0;\n case 3:\n return 256;\n default:\n throw new RuntimeException(\"can't happen\");\n }\n }\n\n /**\n * bitlong 32\n * See 2.3 Bitlong\n *\n * @return\n */\n public int getBL() {\n int code = getBitsUnsigned(2);\n switch (code) {\n case 0:\n return getRL();\n case 1:\n return getBitsUnsigned(8);\n case 2:\n return 0;\n case 3:\n throw new RuntimeException(\"unknown bitlong code of 0b11\");\n default:\n throw new RuntimeException(\"can't happen\");\n }\n }\n\n /**\n * bitlonglong 64\n * See 2.4 BITLONGLONG\n *\n * @return\n */\n public long getBLL() {\n int length = get3B();\n\n long result = 0;\n int shift = 0;\n while (length-- != 0) {\n result |= (getBitsUnsigned(8) << shift);\n shift += 8;\n }\n\n return result;\n }\n\n /**\n * bitdouble\n * See 2.5 BITDOUBLE\n *\n * @return\n */\n public double getBD() {\n int code = getBitsUnsigned(2);\n switch (code) {\n case 0:\n return getRD();\n case 1:\n return 1.0;\n case 2:\n return 0.0;\n case 3:\n throw new RuntimeException(\"unknown bitdouble code of 0b11\");\n default:\n throw new RuntimeException(\"can't happen\");\n }\n }\n\n public Point2D get2RD() {\n double x = getRD();\n double y = getRD();\n return new Point2D(x, y);\n }\n\n public Point2D get2DD(Point2D base) {\n double x = getDD(base.x);\n double y = getDD(base.y);\n return new Point2D(x, y);\n }\n\n public Point2D get2BD() {\n double x = getBD();\n double y = getBD();\n return new Point2D(x, y);\n }\n\n public Point3D get3BD() {\n double x = getBD();\n double y = getBD();\n double z = getBD();\n return new Point3D(x, y, z);\n }\n\n /**\n * raw double (not compressed)\n * @return\n */\n public double getRD() {\n long byte0 = getBitsUnsigned(8);\n long byte1 = getBitsUnsigned(8);\n long byte2 = getBitsUnsigned(8);\n long byte3 = getBitsUnsigned(8);\n long byte4 = getBitsUnsigned(8);\n long byte5 = getBitsUnsigned(8);\n long byte6 = getBitsUnsigned(8);\n long byte7 = getBitsUnsigned(8);\n\n return Double.longBitsToDouble((byte7 << 56)\n | (byte6 << 48)\n | (byte5 << 40)\n | (byte4 << 32)\n | (byte3 << 24)\n | (byte2 << 16)\n | (byte1 << 8)\n | (byte0));\n }\n\n /**\n * 3B - Paragraph 2.1\n *\n * @return\n */\n public int get3B() {\n if (getB()) {\n if (getB()) {\n if (getB()) {\n return 7;\n } else {\n return 6;\n }\n } else {\n return 2;\n }\n } else {\n return 0;\n }\n }\n\n /**\n * handle\n * see 2.13 Handle References\n *\n * @return\n */\n public Handle getHandle() {\n int code = getBitsUnsigned(4);\n int counter = getBitsUnsigned(4);\n\n int [] handle = new int[counter];\n for (int i = 0; i < counter; i++) {\n handle[i] = getBitsUnsigned(8);\n }\n\n return new Handle(code, handle);\n }\n\n public Handle getHandle(Handle baseHandle) {\n int code = getBitsUnsigned(4);\n int counter = getBitsUnsigned(4);\n\n int [] handle = new int[counter];\n for (int i = 0; i < counter; i++) {\n handle[i] = getBitsUnsigned(8);\n }\n\n Handle tempHandle = new Handle(code, handle);\n\n int thisOffset;\n switch (tempHandle.code) {\n case 2:\n case 3:\n case 4:\n case 5:\n thisOffset = tempHandle.offset;\n break;\n case 6:\n thisOffset = baseHandle.offset + 1;\n break;\n case 8:\n thisOffset = baseHandle.offset - 1;\n break;\n case 0xA:\n thisOffset = baseHandle.offset + tempHandle.offset;\n break;\n case 0xC:\n thisOffset = baseHandle.offset - tempHandle.offset;\n break;\n default:\n throw new RuntimeException(\"bad case\");\n }\n\n return new Handle(5, thisOffset);\n }\n\n // Public for instrumentation only\n public int getBitsUnsigned(int numberOfBits) {\n assert numberOfBits <= 31;\n int result = 0;\n for (int i = 0; i < numberOfBits; i++) {\n result <<= 1;\n if (this.getB()) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * Unicode text\n *\n * @return\n */\n public String getTU() {\n int length = getBS();\n\n byte[] x = new byte[length*2];\n for (int i = 0; i < length; i++) {\n x[2*i+1] = (byte)this.getBitsUnsigned(8);\n x[2*i] = (byte)this.getBitsUnsigned(8);\n }\n try {\n return new String(x, \"UTF-16\");\n } catch (UnsupportedEncodingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n return \"\";\n } // TODO\n }\n\n public boolean hasMoreData() {\n return currentOffset*8 + bitOffset < endOffset;\n }\n\n public void B(Value<Boolean> value) {\n value.set(getB());\n }\n\n public void BS(Value<Integer> value) {\n value.set(getBS());\n }\n\n public void BL(Value<Integer> value) {\n value.set(getBL());\n }\n\n public void BD(Value<Double> value) {\n value.set(getBD());\n }\n\n public void RC(Value<Integer> value) {\n value.set(getRC());\n }\n\n public void expectB(boolean expected)\n {\n boolean actual = getB();\n if (actual != expected) {\n issues.addWarning(MessageFormat.format(\"Unknown bit value: {0} expected but {1} found. Investigation needed.\", expected, actual));\n }\n }\n\n public void expectRC(int expected)\n {\n int actual = getRC();\n if (actual != expected) {\n issues.addWarning(MessageFormat.format(\"Unknown RC value: {0} expected but {1} found. Investigation needed.\", expected, actual));\n }\n }\n\n public void expectBD(double expected) {\n double actual = getBD();\n if (actual != expected) {\n issues.addWarning(MessageFormat.format(\"Unknown bit-double value: {0} expected but {1} found. Investigation needed.\", expected, actual));\n }\n }\n\n public void CMC(Value<CmColor> color) {\n int expectZero = getBS();\n int rgbValue = getBL();\n int colorByte = getRC();\n if ((colorByte & 0x01) != 0) {\n // Read color name\n }\n if ((colorByte & 0x02) != 0) {\n // Read book name\n }\n\n color.set(new CmColor(rgbValue, colorByte));\n }\n\n public void H(Value<Handle> value) {\n Handle handle = getHandle();\n value.set(handle);\n }\n\n public void H(Value<Handle> value, HandleType type) {\n Handle handle = getHandle();\n value.set(handle);\n }\n\n public void threeBD(Value<Point3D> field) {\n double x = getBD();\n double y = getBD();\n double z = getBD();\n field.set(new Point3D(x, y, z));\n }\n\n // Two raw doubles\n public void twoRD(Value<Point2D> field) {\n double x = getRD();\n double y = getRD();\n field.set(new Point2D(x, y));\n }\n\n public void TU(Value<String> field) {\n String text = getTU();\n field.set(text);\n }\n\n /**\n * Paragraph 2.12 Object Type\n * \n * @return\n */\n public int getOT() {\n int code = getBitsUnsigned(2);\n switch (code) {\n case 0:\n return getBitsUnsigned(8);\n case 1:\n return getBitsUnsigned(8) + 0x01F0;\n case 3:\n // TODO issue warning and fall thru to case 2\n case 2:\n int loByte = getBitsUnsigned(8);\n int hiByte = getBitsUnsigned(8);\n return hiByte << 8 | loByte;\n default:\n throw new RuntimeException(\"cannot happen\");\n }\n }\n\n public void advanceToByteBoundary() {\n if (bitOffset != 0) {\n currentByte = byteArray[++currentOffset];\n bitOffset = 0;\n }\n }\n\n public void assertEndOfStream() {\n int currentBitOffset = currentOffset*8 + bitOffset;\n if (currentBitOffset != endOffset) {\n throw new RuntimeException(\"not at end of stream\");\n }\n }\n\n public CmColor getCMC()\n {\n int colorIndex = getBS();\n if (colorIndex == 0) {\n int rgbValue = getBL();\n int colorByte = getRC();\n return new CmColor(rgbValue, colorByte);\n } else {\n // no more fields\n // TODO complete this...\n return new CmColor(0, 0);\n }\n }\n\n public CmColor getENC()\n {\n // 2.1.1 page 13\n int colorIndex = getBS();\n if ((colorIndex & 0x2000) != 0) {\n int transparency = getBL();\n }\n // no more fields\n // TODO complete this...\n return new CmColor(0, 0);\n }\n\n public double getDD(double defaultValue)\n {\n int code = getBitsUnsigned(2);\n switch (code) {\n case 0:\n return defaultValue;\n case 1:\n {\n long b = Double.doubleToLongBits(defaultValue);\n\n long byte1 = getBitsUnsigned(8);\n long byte2 = getBitsUnsigned(8);\n long byte3 = getBitsUnsigned(8);\n long byte4 = getBitsUnsigned(8);\n\n return Double.longBitsToDouble((byte4 << 24)\n | (byte3 << 16)\n | (byte2 << 8)\n | (byte1 << 0)\n | (b & 0xFFFFFFFF00000000L));\n }\n case 2:\n {\n long b = Double.doubleToLongBits(defaultValue);\n\n long byte1 = getBitsUnsigned(8);\n long byte2 = getBitsUnsigned(8);\n long byte3 = getBitsUnsigned(8);\n long byte4 = getBitsUnsigned(8);\n long byte5 = getBitsUnsigned(8);\n long byte6 = getBitsUnsigned(8);\n\n return Double.longBitsToDouble((byte2 << 40)\n | (byte1 << 32)\n | (byte6 << 24)\n | (byte5 << 16)\n | (byte4 << 8)\n | (byte3 << 0)\n | (b & 0xFFFF000000000000L));\n }\n case 3:\n return getRD();\n default:\n throw new RuntimeException(\"cannot happen\");\n }\n }\n\n public int[] getBytes(int length) {\n int [] result = new int[length]; \n for (int i = 0; i < length; i++) {\n result[i] = this.getBitsUnsigned(8);\n }\n return result;\n }\n\n public Point3D getBE() {\n boolean extrusionBit = getB();\n if (extrusionBit) {\n return new Point3D(0.0, 0.0, 1.0);\n } else {\n return get3BD();\n }\n }\n\n public double getBT() {\n boolean thicknessBit = getB();\n if (thicknessBit) {\n return 0.0;\n } else {\n return getBD();\n }\n }\n\n}", "public class Handle\n{\n\n public final int code;\n\n public final int offset;\n\n public Handle(int code, int[] handle)\n {\n this.code = code;\n \n int value = 0;\n int shift = 0;\n for (int i = handle.length-1; i >= 0; i--) {\n \tvalue |= handle[i] << shift;\n \tshift += 8;\n }\n \n this.offset = value;\n }\n\n public Handle(int code, int value)\n {\n this.code = code;\n this.offset = value;\n }\n\n public String toString() {\n \treturn Integer.toString(code) + \": \" + offset + \"(\" + Integer.toHexString(offset) + \")\";\n }\n}", "public class Point2D {\n\n\tpublic final double x;\n\tpublic final double y;\n\t\n\tpublic Point2D(double x, double y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n @Override\n public String toString() {\n \treturn \"(\" + x + \", \" + y + \")\";\n }\n}", "public class Point3D {\n\n\tpublic final double x;\n\tpublic final double y;\n\tpublic final double z;\n\t\n\tpublic Point3D(double x, double y, double z) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n @Override\n public String toString() {\n \treturn \"(\" + x + \", \" + y + \", \" + z + \")\";\n }\n}" ]
import java.util.AbstractList; import java.util.List; import com.onespatial.dwglib.FileVersion; import com.onespatial.dwglib.bitstreams.BitBuffer; import com.onespatial.dwglib.bitstreams.Handle; import com.onespatial.dwglib.bitstreams.Point2D; import com.onespatial.dwglib.bitstreams.Point3D;
package com.onespatial.dwglib.objects; public class Layout extends NonEntityObject { public String pageSetupName; public String printerOrConfig; public int plotLayoutFlags; public double leftMargin; public double bottomMargin; public double rightMargin; public double topMargin; public double paperWidth; public double paperHeight; public String paperSize; public Point2D plotOrigin; public int paperUnits; public int plotRotation; public int plotType; public Point2D windowMinimum; public Point2D windowMaximum; public double realWorldUnits; public double drawingUnits; public String currentStyleSheet; public int scaleType; public double scaleFactor; public Point2D paperImageOrigin; public int shadePlotMode; public int shadePlotResLevel; public int shadePlotCustomDpi; public String layoutName; public int tabOrder; public int flag;
public Point3D ucsOrigin;
4
enguerrand/xdat
src/main/java/org/xdat/chart/Axis.java
[ "public class DataSheet implements Serializable, ListModel {\n\n\tstatic final long serialVersionUID = 8;\n\tprivate List<Design> data = new ArrayList<>();\n\tprivate Map<Integer, Design> designIdsMap = new HashMap<>();\n\tprivate List<Parameter> parameters = new LinkedList<>();\n\tprivate transient List<ListDataListener> listDataListener;\n\tprivate transient List<DatasheetListener> listeners;\n\tprivate String delimiter;\n\n\tpublic void initTransientData() {\n\t\tthis.listDataListener = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t}\n\n\tpublic DataSheet(String pathToInputFile, boolean dataHasHeaders, Main mainWindow, ProgressMonitor progressMonitor) throws IOException {\n\t\tinitTransientData();\n\t\tUserPreferences userPreferences = UserPreferences.getInstance();\n\t\tthis.delimiter = userPreferences.getDelimiter();\n\t\tif (userPreferences.isTreatConsecutiveAsOne())\n\t\t\tthis.delimiter = this.delimiter + \"+\";\n\t\timportData(pathToInputFile, dataHasHeaders, progressMonitor);\n\t\tboolean continueChecking = true;\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (parameter.isMixed(this) && continueChecking) {\n\t\t\t\tint userAction = JOptionPane.showConfirmDialog(mainWindow, \"Parameter \" + parameter.getName() + \" has numeric values in some designs\\n\" + \"and non-numerical values in others. \\nThis will result in the parameter being treated as a \\n\" + \"non-numeric parameter. \\n\" + \"If this is incorrect it is recommended to find the design(s)\\n\" + \"with non-numeric values and correct or remove them.\\n\\n\" + \"Press Ok to continue checking parameters or Cancel to\\n\" + \"suppress further warnings.\", \"Mixed Parameter Warning\", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);\n\t\t\t\tcontinueChecking = (userAction == JOptionPane.OK_OPTION);\n\t\t\t}\n\t\t\tparameter.setTicLabelDigitCount(userPreferences.getParallelCoordinatesAxisTicLabelDigitCount());\n\t\t}\n\t}\n\n\tprivate void importData(String pathToInputFile, boolean dataHasHeaders, ProgressMonitor progressMonitor) throws IOException {\n\t\tList<Design> buffer = new ArrayList<>();\n\t\tif (this.data != null) {\n\t\t\tbuffer = new ArrayList<>(this.data);\n\t\t}\n\t\tint lineCount = getLineCount(pathToInputFile);\n\t\tprogressMonitor.setMaximum(lineCount);\n\n\t\tBufferedReader f;\n\t\tString line;\n\t\tint idCounter = 1;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\t\tline = (f.readLine()).trim();\n\n\t\tString[] lineElements = line.split(this.delimiter);\n\t\tif (dataHasHeaders) {\n\t\t\t// if data has headers read the parameter names from the first line\n\t\t\tfor (String lineElement : lineElements) {\n\t\t\t\tthis.parameters.add(new Parameter(this.getUniqueParameterName(lineElement), this));\n\t\t\t}\n\t\t} else {\n\t\t\t// if data does not have headers read the first Design from the first line and create default Parameter names\n\t\t\tDesign newDesign = new Design(idCounter++);\n\t\t\tfor (int i = 0; i < lineElements.length; i++) {\n\t\t\t\tthis.parameters.add(new Parameter(\"Parameter \" + (i + 1), this));\n\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\n\t\t\t}\n\t\t\tthis.data.add(newDesign);\n\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t\tprogressMonitor.setProgress(idCounter - 1);\n\t\t}\n\t\ttry {\n\t\t\treadDesignsFromFile(progressMonitor, f, idCounter);\n\t\t} catch (IOException e) {\n\n\t\t\tthis.data = buffer;\n\t\t\tthrow e;\n\t\t}\n\t\tf.close();\n\t\tif (progressMonitor.isCanceled()) {\n\t\t\tthis.data = buffer;\n\t\t}\n\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\t}\n\n\tpublic void updateData(String pathToInputFile, boolean dataHasHeaders, ProgressMonitor progressMonitor, ClusterSet clusterSet) throws IOException, InconsistentDataException {\n\t\tint lineCount = getLineCount(pathToInputFile);\n\t\tprogressMonitor.setMaximum(lineCount);\n\n\t\tBufferedReader f;\n\t\tString line;\n\t\tint idCounter = 1;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\n\t\t// check datasheet to be read for consistency\n\t\tline = (f.readLine()).trim();\n\t\tString[] lineElements = line.split(this.delimiter);\n\t\tif (lineElements.length != this.getParameterCount()) {\n\t\t\tf.close();\n\t\t\tthrow new InconsistentDataException(pathToInputFile);\n\t\t}\n\n\t\tList<Design> buffer = new ArrayList<>(this.data);\n\t\tMap<Integer, Design> idbuffer = new HashMap<>(this.designIdsMap);\n\t\t// clusterId -> designHashes\n\t\tMap<Integer, Set<Integer>> clustersToDesignHashes = computeClusterDesignHashes(this.data);\n\t\tthis.data.clear();\n\t\tthis.designIdsMap.clear();\n\n\t\t// if data has headers read the parameter names from the first line\n\t\tif (dataHasHeaders){\n\t\t\tfor (Parameter parameter : this.parameters) {\n\t\t\t\tparameter.setName(null);\n\t\t\t}\n\t\t\tfor (int i = 0; i < lineElements.length; i++) {\n\t\t\t\tthis.parameters.get(i).setName(this.getUniqueParameterName(lineElements[i]));\n\t\t\t}\n\t\t\t// if data does not have headers read the first Design from the first line and create default Parameter names\n\t\t} else {\n\t\t\tDesign newDesign = new Design(idCounter++);\n\t\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\t\tif (lineElements.length <= i) {\n\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), \"-\", this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.parameters.get(i).setName(\"Parameter \" + (i + 1));\n\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tthis.data.add(newDesign);\n\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t}\n\n\t\ttry {\n\t\t\treadDesignsFromFile(progressMonitor, f, idCounter);\n\t\t} catch (IOException e) {\n\t\t\tthis.data = buffer;\n\t\t\tthis.designIdsMap = idbuffer;\n\t\t\tthrow e;\n\t\t}\n\t\tf.close();\n\t\tif (progressMonitor.isCanceled()) {\n\t\t\tthis.data = buffer;\n\t\t\tthis.designIdsMap = idbuffer;\n\t\t}\n\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tparameter.updateNumeric(this);\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\n\t\trestoreClustersFromHashes(clustersToDesignHashes, this.data, clusterSet);\n\n\t\tfireOnDataChanged(initialiseBooleanArray(true), initialiseBooleanArray(true), initialiseBooleanArray(true));\n\t\tfireDataPanelUpdateRequired();\n\n\t}\n\n\tprivate void restoreClustersFromHashes(Map<Integer, Set<Integer>> clustersToDesignHashes, List<Design> designs, ClusterSet clusterSet) {\n\t\tfor (Map.Entry<Integer, Set<Integer>> entry : clustersToDesignHashes.entrySet()) {\n\t\t\tInteger clusterId = entry.getKey();\n\t\t\tSet<Integer> designHashes = entry.getValue();\n\t\t\tclusterSet.findClusterById(clusterId).ifPresent(cluster -> {\n\t\t\t\tfor (Design design : designs) {\n\t\t\t\t\tif (designHashes.contains(design.computeValuesHash(parameters))) {\n\t\t\t\t\t\tdesign.setCluster(cluster);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate Map<Integer, Set<Integer>> computeClusterDesignHashes(List<Design> designs) {\n\t\tMap<Integer, Set<Integer>> clustersToDesignHashes = new HashMap<>();\n\t\tfor (Design design : designs) {\n\t\t\tCluster cluster = design.getCluster();\n\t\t\tif(cluster != null) {\n\t\t\t\tclustersToDesignHashes\n\t\t\t\t\t\t.computeIfAbsent(cluster.getUniqueId(), k -> new HashSet<>())\n\t\t\t\t\t\t.add(design.computeValuesHash(parameters));\n\t\t\t}\n\t\t}\n\t\treturn clustersToDesignHashes;\n\t}\n\n\tprivate void readDesignsFromFile(ProgressMonitor progressMonitor, BufferedReader f, int idCounter) throws IOException {\n\t\tString line;\n\t\tString[] lineElements;\n\t\twhile ((line = f.readLine()) != null && !progressMonitor.isCanceled()) // read all subsequent lines into Designs\n\t\t{\n\t\t\tprogressMonitor.setProgress(idCounter - 1);\n\t\t\tDesign newDesign;\n\t\t\tlineElements = line.split(this.delimiter);\n\t\t\tif (lineElements.length > 0) {\n\t\t\t\tnewDesign = new Design(idCounter++);\n\t\t\t\tboolean newDesignContainsValues = false;\n\t\t\t\tfor (String lineElement : lineElements) {\n\t\t\t\t\tif (lineElement.length() > 0 && (!lineElement.equals(\"\\\\s\"))) {\n\t\t\t\t\t\tnewDesignContainsValues = true; // found non-empty empty\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (newDesignContainsValues) {\n\t\t\t\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\t\t\t\tif (lineElements.length <= i || lineElements[i].length() <= 0 || lineElements[i].equals(\"\\\\s\")) {\n\t\t\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), \"-\", this);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.data.add(newDesign);\n\t\t\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setValueAt(Object newValue, int rowIndex, int columnIndex) {\n\t\tParameter parameter = this.parameters.get(columnIndex - 1);\n\t\tboolean previousNumeric = parameter.isNumeric();\n\t\tboolean[] axisAutofitRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisResetFilterRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisApplyFiltersRequired = initialiseBooleanArray(false);\n\t\tthis.data.get(rowIndex).setValue(parameters.get(columnIndex - 1), newValue.toString(), this);\n\n\t\tif (!previousNumeric) {\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\n\t\tOptional<Float> parsed = NumberParser.parseNumber(newValue.toString());\n\t\tboolean parsable = parsed.isPresent();\n\n\t\tif(previousNumeric && !parsable) {\n\t\t\tparameter.setNumeric(false, this);\n\t\t} else if (!previousNumeric && parsable) {\n\t\t\tparameter.updateNumeric(this);\n\t\t}\n\t\tif (previousNumeric != parameter.isNumeric()) {\n\t\t\taxisAutofitRequired[columnIndex - 1] = true;\n\t\t\taxisResetFilterRequired[columnIndex - 1] = true;\n\t\t}\n\n\t\taxisApplyFiltersRequired[columnIndex - 1] = true;\n\t\tfireOnDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired);\n\t}\n\n\tprivate int getLineCount(String pathToInputFile) throws IOException {\n\t\tBufferedReader f;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\t\tint lineCount = 0;\n\t\twhile ((f.readLine()) != null)\n\t\t\tlineCount++;\n\t\tf.close();\n\t\treturn lineCount;\n\t}\n\n\tpublic Design getDesign(int i) {\n\t\treturn this.data.get(i);\n\t}\n\n\tpublic Design getDesignByID(int id) {\n\t\treturn this.designIdsMap.get(id);\n\t}\n\n\tpublic void removeDesigns(int[] designsToRemove) {\n\t\tboolean[] axisAutofitRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisResetFilterRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisApplyFiltersRequired = initialiseBooleanArray(false);\n\n\t\tboolean[] discrete = new boolean[this.parameters.size()]; // check which parameters are discrete\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\tdiscrete[i] = !this.parameters.get(i).isNumeric();\n\t\t}\n\n\t\tfor (int i = designsToRemove.length - 1; i >= 0; i--) {\n\t\t\tDesign removedDesign = data.remove(designsToRemove[i]);\n\t\t\tthis.designIdsMap.remove(removedDesign.getId());\n\t\t\t// check if that makes any non-numeric parameter numeric\n\t\t\tfor (Parameter parameter : this.parameters) {\n\t\t\t\tif (!parameter.isNumeric()) {\n\t\t\t\t\tString string = removedDesign.getStringValue(parameter);\n\t\t\t\t\tif (!NumberParser.parseNumber(string).isPresent()) {\n\t\t\t\t\t\tparameter.updateNumeric(this);\n\t\t\t\t\t\tparameter.updateDiscreteLevels(this);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\taxisAutofitRequired[i] = discrete[i] && this.parameters.get(i).isNumeric();\n\t\t\taxisApplyFiltersRequired[i] = true;\n\t\t}\n\n\t\tfireOnDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired);\n\t\tfireDataPanelUpdateRequired();\n\t}\n\n\tpublic int getParameterCount() {\n\t\treturn this.parameters.size();\n\t}\n\n\tpublic String getParameterName(int index) {\n\t\tif (index >= this.parameters.size() || index < 0)\n\t\t\tthrow new IllegalArgumentException(\"Invalid Index \" + index);\n\t\treturn this.parameters.get(index).getName();\n\t}\n\n\tpublic Parameter getParameter(int index) {\n\t\tif (index >= this.parameters.size() || index < 0)\n\t\t\tthrow new IllegalArgumentException(\"Invalid Index \" + index);\n\t\treturn this.parameters.get(index);\n\t}\n\n\tpublic Parameter getParameter(String parameterName) {\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (parameterName.equals(parameter.getName())) {\n\t\t\t\treturn parameter;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Parameter \" + parameterName + \" not found\");\n\t}\n\n\tpublic int getParameterIndex(String parameterName) {\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\tif (parameterName.equals(this.parameters.get(i).getName())) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Parameter \" + parameterName + \" not found\");\n\t}\n\n public boolean parameterExists(Parameter param) {\n\t\treturn this.parameters.contains(param);\n\t}\n\n\tpublic double getMaxValueOf(Parameter param) {\n\t\tif (param.isNumeric()) {\n\t\t\tdouble max = Double.NEGATIVE_INFINITY;\n\t\t\tfor (Design datum : this.data) {\n\t\t\t\tif (max < datum.getDoubleValue(param)) {\n\t\t\t\t\tmax = datum.getDoubleValue(param);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn max;\n\t\t} else {\n\t\t\treturn param.getDiscreteLevelCount() - 1;\n\t\t}\n\t}\n\n\tpublic double getMinValueOf(Parameter param) {\n\t\tif (param.isNumeric()) {\n\t\t\tdouble min = Double.POSITIVE_INFINITY;\n\t\t\tfor (Design datum : this.data) {\n\t\t\t\tif (min > datum.getDoubleValue(param)) {\n\t\t\t\t\tmin = datum.getDoubleValue(param);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn min;\n\t\t} else {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\tpublic int getDesignCount() {\n\t\treturn this.data.size();\n\t}\n\n\tprivate String getUniqueParameterName(String nameSuggestion) {\n\t\tString name = nameSuggestion;\n\t\tint id = 2;\n\t\twhile (!isNameUnique(name)) {\n\t\t\tname = nameSuggestion + \" (\" + (id++) + \")\";\n\t\t}\n\t\treturn name;\n\t}\n\n\tprivate boolean isNameUnique(String name) {\n\t\tboolean unique = true;\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (name.equals(parameter.getName())) {\n\t\t\t\tunique = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn unique;\n\t}\n\n\tpublic void evaluateBoundsForAllDesigns(ParallelCoordinatesChart chart) {\n\t\tfor (int i = 0; i < this.getDesignCount(); i++) {\n\t\t\tthis.data.get(i).evaluateBounds(chart, this);\n\t\t}\n\t}\n\n\tpublic void moveParameter(int oldIndex, int newIndex) {\n\t\tParameter param = this.parameters.remove(oldIndex);\n\t\tthis.parameters.add(newIndex, param);\n\t}\n\n\tprivate boolean[] initialiseBooleanArray(boolean value) {\n\t\tboolean[] array = new boolean[this.getParameterCount()];\n\t\tfor (int i = 0; i < this.getParameterCount(); i++) {\n\t\t\tarray[i] = value;\n\t\t}\n\t\treturn array;\n\t}\n\n\t@Override\n\tpublic void addListDataListener(ListDataListener l) {\n\t\tlistDataListener.add(l);\n\t}\n\n\t@Override\n\tpublic Object getElementAt(int index) {\n\t\treturn this.parameters.get(index).getName();\n\t}\n\n\t@Override\n\tpublic int getSize() {\n\t\treturn this.parameters.size();\n\t}\n\n\t@Override\n\tpublic void removeListDataListener(ListDataListener l) {\n\t\tlistDataListener.remove(l);\n\t}\n\n\tpublic void addListener(DatasheetListener l) {\n\t\tthis.listeners.add(l);\n\t}\n\n\tpublic void removeListener(DatasheetListener l) {\n\t\tthis.listeners.remove(l);\n\t}\n\n\tprivate void fireListeners(Consumer<DatasheetListener> action) {\n\t\tfor (DatasheetListener listener : this.listeners) {\n\t\t\taction.accept(listener);\n\t\t}\n\t}\n\n\tvoid onClustersUpdated(List<Cluster> changed, List<Cluster> added, List<Cluster> removed) {\n\t\tfor (Cluster removedCluster : removed) {\n\t\t\tfor (int j = 0; j < getDesignCount(); j++) {\n\t\t\t\tif (removedCluster.equals(getDesign(j).getCluster())) {\n\t\t\t\t\tgetDesign(j).setCluster(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (changed.isEmpty() && added.isEmpty() && removed.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\tfireClustersChanged();\n\t}\n\n\tpublic Collection<Design> getDesigns() {\n\t\treturn Collections.unmodifiableList(this.data);\n\t}\n\n\tpublic List<Parameter> getParameters() {\n\t\treturn Collections.unmodifiableList(this.parameters);\n\t}\n\n\tpublic void fireClustersChanged() {\n\t\tfireListeners(DatasheetListener::onClustersChanged);\n\t}\n\n\tpublic void fireDataPanelUpdateRequired() {\n\t\tfireListeners(DatasheetListener::onDataPanelUpdateRequired);\n\t}\n\n\tpublic void fireOnDataChanged(boolean axisAutofitRequired, boolean axisResetFilterRequired, boolean axisApplyFiltersRequired) {\n\t\tboolean[] autofit = new boolean[parameters.size()];\n\t\tboolean[] resetFilter = new boolean[parameters.size()];\n\t\tboolean[] applyFilters = new boolean[parameters.size()];\n\t\tArrays.fill(autofit, axisAutofitRequired);\n\t\tArrays.fill(resetFilter, axisResetFilterRequired);\n\t\tArrays.fill(applyFilters, axisApplyFiltersRequired);\n\t\tfireOnDataChanged(autofit, resetFilter, applyFilters);\n\t}\n\n\tpublic void fireOnDataChanged(boolean[] axisAutofitRequired, boolean[] axisResetFilterRequired, boolean[] axisApplyFiltersRequired) {\n\t\tfireListeners(l -> l.onDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired));\n\t}\n}", "public class Parameter implements Serializable {\n\tstatic final long serialVersionUID = 4L;\n\tprivate String name;\n\tprivate boolean numeric = true;\n\tprivate TreeSet<String> discreteLevels = new TreeSet<>(new ReverseStringComparator());\n private int ticLabelDigitCount = 3;\n\tpublic Parameter(String name, DataSheet dataSheet) {\n\t\tthis.name = name;\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\n\t/**\n\t * Checks whether the parameter is mixed. A parameter is mixed if at least\n\t * one design has a numeric value and at least one design has a non-numeric\n\t * value.\n\t * \n\t * @return true, if the parameter is mixed\n\t * @param dataSheet\n\t */\n\tboolean isMixed(DataSheet dataSheet) {\n\t\treturn getType(dataSheet) == ParameterType.MIXED;\n\t}\n\n\tprivate ParameterType getType(DataSheet dataSheet){\n\t\tboolean foundNumericValue = false;\n\t\tboolean foundStringValue = false;\n for (Design design : dataSheet.getDesigns()) {\n String string = design.getStringValue(this);\n if(NumberParser.parseNumber(string).isPresent()){\n foundNumericValue = true;\n } else {\n foundStringValue = true;\n }\n if(foundNumericValue && foundStringValue) {\n return ParameterType.MIXED;\n }\n }\n if (foundStringValue) {\n return ParameterType.NON_NUMERIC;\n } else if (foundNumericValue) {\n return ParameterType.NUMERIC;\n }\n // This can only happen if we have no designs. Consider the parameter numeric in this case\n return ParameterType.NUMERIC;\n\t}\n\n\tpublic boolean isNumeric() {\n\t\treturn numeric;\n\t}\n\n\tvoid setNumeric(boolean numeric, DataSheet dataSheet) {\n\t\tif (numeric == this.numeric) {\n\t\t\treturn;\n\t\t}\n\t\tthis.numeric = numeric;\n\t\tupdateDiscreteLevels(dataSheet);\n\t}\n\n\t/**\n\t * Gets a numeric representation of a string value for this parameter.\n\t * <p>\n\t * If the parameter is numeric, an attempt is made to parse the string as a\n\t * Double. If this attempt fails, the parameter is not considered numeric anymore,\n\t * but is transformed into a discrete parameter.\n\t * <p>\n\t * If the parameter is not numeric, the string is looked up in the TreeSet\n\t * discreteLevels that should contain all discrete values (that is Strings)\n\t * that were found in the data sheet for this parameter. If the value is not\n\t * found it is added as a new discrete level for this parameter. The treeSet\n\t * is then searched again in order to get the correct index of the new\n\t * discrete level.\n\t * <p>\n\t * If this second search does not yield the result, something unexpected has\n\t * gone wrong and a CorruptDataException is thrown.\n\t * \n\t * @param string\n\t * the string\n\t * @return the numeric representation of the given string\n\t */\n\tdouble getDoubleValueOf(String string) {\n\t\tif (this.numeric) {\n\t\t\tOptional<Float> parsed = NumberParser.parseNumber(string);\n\t\t\tif(parsed.isPresent()) {\n\t\t\t\treturn parsed.get();\n\t\t\t}\n\t\t}\n\n\t\tint index = 0;\n\t\tIterator<String> it = discreteLevels.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tif (string.equalsIgnoreCase(it.next())) {\n\t\t\t\treturn index;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\n\t\t// String not found, add it to discrete levels\n\t\tthis.discreteLevels.add(string);\n\t\tindex = 0;\n\t\tit = discreteLevels.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tString next = it.next();\n\t\t\tif (string.equalsIgnoreCase(next)) {\n\t\t\t\treturn index;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\tthrow new CorruptDataException(this);\n\t}\n\n\t/**\n\t * Gets the string representation of a given double value for this\n\t * parameter.\n\t * <p>\n\t * If the parameter is numeric, the provided value is simply converted to a\n\t * String and returned.\n\t * <p>\n\t * If it is discrete, the double value is casted to an Integer value and\n\t * this value is used as an index to look up the corresponding discrete\n\t * value string in the TreeSet discreteLevels.\n\t * <p>\n\t * If no value is found for the given index the data is assumed to be\n\t * corrupt and a CorruptDataException is thrown.\n\t * \n\t * @param value\n\t * the numeric value\n\t * @return the string representation of the given double value for this\n\t * parameter.\n\t */\n\tpublic String getStringValueOf(double value) {\n\t\tif (this.numeric) {\n\t\t\treturn Double.toString(value);\n\t\t} else {\n\t\t\tint index = (int) value;\n\t\t\tint currentIndex = 0;\n\t\t\tIterator<String> it = discreteLevels.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tString next = it.next();\n\t\t\t\tif (currentIndex == index) {\n\t\t\t\t\treturn next;\n\t\t\t\t}\n\t\t\t\tcurrentIndex++;\n\t\t\t}\n\t\t\tthrow new CorruptDataException(this);\n\t\t}\n\t}\n\n\tpublic int getDiscreteLevelCount() {\n\t\tif (this.isNumeric()) {\n\t\t\tthrow new RuntimeException(\"Parameter \" + this.name + \" is numeric!\");\n\t\t} else {\n\t\t\t// log(\"getDiscreteLevelCount returning size \"+this.discreteLevels.size());\n\t\t\treturn this.discreteLevels.size();\n\t\t}\n\t}\n\n\tvoid updateNumeric(DataSheet dataSheet) {\n\t\tthis.setNumeric(getType(dataSheet) == ParameterType.NUMERIC, dataSheet);\n\n\t}\n\n\tvoid updateDiscreteLevels(DataSheet dataSheet){\n\t this.discreteLevels.clear();\n\t if (isNumeric()) {\n\t return;\n }\n\t this.discreteLevels.addAll(dataSheet.getDesigns()\n .stream()\n .map(d -> d.getStringValue(this))\n .collect(Collectors.toSet()));\n }\n\n\n public void setTicLabelDigitCount(int value) {\n this.ticLabelDigitCount = value;\n }\n\n public int getTicLabelDigitCount(){\n return this.ticLabelDigitCount;\n }\n\n public String getTicLabelFormat() {\n int digitCount = getTicLabelDigitCount();\n return \"%\"+(digitCount+1)+\".\"+digitCount+\"f\";\n }\n\n\tpublic int getLongestTicLabelStringLength(FontMetrics fm, String numberFormat, DataSheet dataSheet) {\n\t\tif (this.isNumeric()) {\n\t\t\tdouble minValue = Double.POSITIVE_INFINITY;\n\t\t\tdouble maxValue = Double.NEGATIVE_INFINITY;\n\n\t\t\tfor (int i = 0; i < dataSheet.getDesignCount(); i++) {\n\t\t\t\tif (dataSheet.getDesign(i).getDoubleValue(this) > maxValue)\n\t\t\t\t\tmaxValue = dataSheet.getDesign(i).getDoubleValue(this);\n\t\t\t\tif (dataSheet.getDesign(i).getDoubleValue(this) < minValue)\n\t\t\t\t\tminValue = dataSheet.getDesign(i).getDoubleValue(this);\n\t\t\t}\n\t\t\tint minLength = fm.stringWidth(String.format(numberFormat, minValue));\n\t\t\tint maxLength = fm.stringWidth(String.format(numberFormat, maxValue));\n\t\t\treturn Math.max(minLength, maxLength);\n\t\t} else {\n\t\t\tint length = 0;\n\t\t\tfor (int i = 0; i < this.getDiscreteLevelCount(); i++) {\n\t\t\t\tint tempLength = fm.stringWidth(this.getStringValueOf(i));\n\t\t\t\tif (tempLength > length)\n\t\t\t\t\tlength = tempLength;\n\t\t\t}\n\t\t\treturn length;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n\tprivate static class ReverseStringComparator implements Comparator<String>, Serializable {\n\t\tstatic final long serialVersionUID = 0L;\n\t\tpublic int compare(String s1, String s2) {\n\t\t\treturn (s2.compareToIgnoreCase(s1));\n\t\t}\n\t}\n}", "public class IntegerSetting extends Setting<Integer> {\n private final int min;\n private final int max;\n public IntegerSetting(String title, int hardCodedDefault, Key defaultValuePreferenceKey, int min, int max) {\n super(title, hardCodedDefault, SettingsType.INTEGER, defaultValuePreferenceKey);\n this.min = min;\n this.max = max;\n }\n\n @Override\n void setDefaultImpl(Key key, Integer defaultValue) {\n UserPreferences.putInt(key, defaultValue);\n }\n\n @Override\n Integer getDefaultImpl(Key key, Integer fallback) {\n return UserPreferences.getInt(key, fallback);\n }\n\n public int getMin() {\n return min;\n }\n\n public int getMax() {\n return max;\n }\n}", "public enum Key {\n SCATTER_CHART_2D_TIC_LABEL_FONTSIZE_Y(\"scatterChart2DTicLabelFontsizeY\"),\n PARALLEL_COORDINATES_AUTO_FIT_AXIS(\"ParallelCoordinatesAutoFitAxis\"),\n LOCALE(\"locale\"),\n SCATTER_CHART_2D_DISPLAY_MODE(\"ScatterChart2DDisplayMode\"),\n SCATTER_CHART_2D_AUTOFIT_X(\"scatterChart2DAutofitX\"),\n SCATTER_CHART_2D_AUTOFIT_Y(\"scatterChart2DAutofitY\"),\n SCATTER_CHART_2D_AXIS_TITLE_FONTSIZE_X(\"scatterChart2DAxisTitleFontsizeX\"),\n SCATTER_CHART_2D_AXIS_TITLE_FONTSIZE_Y(\"scatterChart2DAxisTitleFontsizeY\"),\n SCATTER_CHART_2D_TIC_COUNT_X(\"scatterChart2DTicCountX\"),\n SCATTER_CHART_2D_TIC_COUNT_Y(\"scatterChart2DTicCountY\"),\n SCATTER_CHART_2D_TIC_LABEL_FONTSIZE_X(\"scatterChart2DTicLabelFontsizeX\"),\n SCATTER_CHART_2D_DATA_POINT_SIZE(\"scatterChart2DDataPointSize\"),\n SCATTER_CHART_2D_FOREGROUND_COLOR(\"scatterChart2DForegroundColor\"),\n SCATTER_CHART_2D_BACKGROUND_COLOR(\"scatterChart2DBackgroundColor\"),\n SCATTER_CHART_2D_ACTIVE_DESIGN_COLOR(\"scatterChart2DActiveDesignColor\"),\n SCATTER_CHART_2D_SELECTED_DESIGN_COLOR(\"scatterChart2DSelectedDesignColor\"),\n PARALLEL_COORDINATES_AXIS_ACTIVE(\"ParallelCoordinatesAxisActive\"),\n PARALLEL_COORDINATES_AXIS_COLOR(\"ParallelCoordinatesAxisColor\"),\n PARALLEL_COORDINATES_VERTICALLY_OFFSET_AXIS_LABELS(\"ParallelCoordinatesVerticallyOffsetAxisLabels\"),\n PARALLEL_COORDINATES_LABELS_VERTICAL_DISTANCE(\"ParallelCoordinatesAxisLabelsVerticalDistance\"),\n PARALLEL_COORDINATES_AXIS_LABEL_FONT_COLOR(\"ParallelCoordinatesAxisLabelFontColor\"),\n PARALLEL_COORDINATES_AXIS_LABEL_FONT_SIZE(\"ParallelCoordinatesAxisLabelFontSize\"),\n PARALLEL_COORDINATES_AXIS_TIC_COUNT(\"ParallelCoordinatesAxisTicCount\"),\n PARALLEL_COORDINATES_AXIS_TIC_LABEL_FONT_COLOR(\"ParallelCoordinatesAxisTicLabelFontColor\"),\n PARALLEL_COORDINATES_AXIS_TIC_LABEL_FORMAT(\"ParallelCoordinatesAxisTicLabelFormat\"),\n PARALLEL_COORDINATES_AXIS_TIC_LABEL_DIGIT_COUNT(\"ParallelCoordinatesAxisTicLabelDigitCount\"),\n PARALLEL_COORDINATES_AXIS_TIC_LENGTH(\"ParallelCoordinatesAxisTicLength\"),\n PARALLEL_COORDINATES_AXIS_WIDTH(\"ParallelCoordinatesAxisWidth\"),\n PARALLEL_COORDINATES_FILTER_COLOR(\"ParallelCoordinatesFilterColor\"),\n PARALLEL_COORDINATES_FILTER_HEIGHT(\"ParallelCoordinatesFilterHeight\"),\n PARALLEL_COORDINATES_FILTER_WIDTH(\"ParallelCoordinatesFilterWidth\"),\n TIC_LABEL_FONT_SIZE(\"ticLabelFontSize\"),\n DESIGN_LABEL_FONT_SIZE(\"designLabelFontSize\"),\n LINE_THICKNESS(\"lineThickness\"),\n SELECTED_DESIGN_LINE_THICKNESS(\"selectedDesignLineThickness\"),\n SHOW_FILTERED_DESIGNS(\"showFilteredDesigns\"),\n PARALLEL_COORDINATES_SHOW_ONLY_SELECTED_DESIGNS(\"parallelCoordinatesShowOnlySelectedDesigns\"),\n ACTIVE_DESIGN_DEFAULT_COLOR(\"activeDesignDefaultColor\"),\n SELECTED_DESIGN_DEFAULT_COLOR(\"selectedDesignDefaultColor\"),\n IN_ACTIVE_DESIGN_DEFAULT_COLOR(\"inActiveDesignDefaultColor\"),\n SHOW_DESIGN_IDS(\"showDesignIDs\"),\n ANTI_ALIASING(\"antiAliasing\"),\n USE_ALPHA(\"useAlpha\"),\n DESIGN_ID_FONT_SIZE(\"designIDFontSize\"),\n PARALLEL_CHART_BACKGROUND_COLOR(\"backgroundColor\"),\n PARALLEL_COORDINATES_FILTER_INVERTED(\"ParallelCoordinatesFilterInverted\"),\n PARALLEL_COORDINATES_AXIS_INVERTED(\"ParallelCoordinatesAxisInverted\"),\n PARALLEL_COORDINATES_AXIS_DEFAULT_MIN(\"ParallelCoordinatesAxisDefaultMin\"),\n PARALLEL_COORDINATES_AXIS_DEFAULT_MAX(\"ParallelCoordinatesAxisDefaultMax\"),\n DIRECTORY_TO_IMPORT_FROM(\"dirToImportFrom\"),\n LAST_FILE_BROWSING_DIRECTORY(\"lastFileBrowsingDirectory\"),\n USER_DIR(\"userDir\"),\n DELIMITER(\"delimiter\"),\n TREAT_CONSECUTIVE_AS_ONE(\"treatConsecutiveAsOne\"),\n OTHER_DELIMITER(\"otherDelimiter\"),\n ;\n\n private final String id;\n\n Key(String id) {\n this.id = id;\n }\n\n public String getId() {\n return id;\n }\n}", "public abstract class Setting<T> implements Serializable {\n static final long serialVersionUID = 1L;\n private final Key key;\n private final T hardCodedDefault;\n private T currentValue;\n private final String title;\n private final SettingsType type;\n private transient List<SettingsListener<T>> listeners;\n\n Setting(String title, T hardCodedDefault, SettingsType type, Key key) {\n this.title = title;\n this.type = type;\n this.key = key;\n this.hardCodedDefault = hardCodedDefault;\n this.currentValue = getDefault();\n initTransientData();\n }\n\n public void addListener(SettingsListener<T> l) {\n this.listeners.add(l);\n }\n\n public void setCurrentToDefault(){\n setDefault(currentValue);\n }\n\n abstract T getDefaultImpl(Key key, T fallback);\n\n abstract void setDefaultImpl(Key key, T defaultValue);\n\n public void setDefault(T defaultValue){\n if (this.key == null) {\n return;\n }\n setDefaultImpl(this.key, defaultValue);\n }\n\n public T getDefault() {\n if (this.key == null) {\n return hardCodedDefault;\n }\n return getDefaultImpl(this.key, hardCodedDefault);\n }\n\n public T get(){\n return currentValue;\n }\n\n public boolean set(T value) {\n return set(value, null);\n }\n\n public boolean set(T value, @Nullable SettingsTransaction transaction) {\n if (Objects.equals(value, this.currentValue)) {\n return false;\n }\n this.currentValue = value;\n if (transaction != null) {\n transaction.addChanged(this);\n }\n this.listeners.forEach(l -> l.onValueChanged(this, transaction));\n return true;\n }\n\n public String getTitle() {\n return title;\n }\n\n public SettingsType getType() {\n return type;\n }\n\n public Key getKey(){\n return key;\n }\n\n public void initTransientData() {\n this.listeners = new ArrayList<>();\n }\n\n public boolean resetToDefault(@Nullable SettingsTransaction t) {\n return set(getDefault(), t);\n }\n}", "public class SettingsGroup implements Serializable {\n\n static final long serialVersionUID = 1L;\n\n private final Map<Key, Setting<?>> settingsMap;\n\n private SettingsGroup(Collection<Setting<?>> settings) {\n LinkedHashMap<Key, Setting<?>> m = new LinkedHashMap<>();\n for (Setting setting : settings) {\n m.put(setting.getKey(), setting);\n }\n this.settingsMap = Collections.unmodifiableMap(m);\n }\n\n public Map<Key, Setting<?>> getSettings() {\n return settingsMap;\n }\n\n public Setting<?> getSetting(Key key) {\n Setting<?> setting = settingsMap.get(key);\n if (setting == null) {\n throw new IllegalArgumentException(\"No setting stored under key \"+key);\n }\n return setting;\n }\n\n public BooleanSetting getBooleanSetting(Key key) {\n return (BooleanSetting) getSetting(key);\n }\n\n public ColorSetting getColorSetting(Key key) {\n return (ColorSetting) getSetting(key);\n }\n\n public DoubleSetting getDoubleSetting(Key key) {\n return (DoubleSetting) getSetting(key);\n }\n\n public IntegerSetting getIntegerSetting(Key key) {\n return (IntegerSetting) getSetting(key);\n }\n\n public StringSetting getStringSetting(Key key) {\n return (StringSetting) getSetting(key);\n }\n\n public boolean getBoolean(Key key) {\n return getBooleanSetting(key).get();\n }\n\n public Color getColor(Key key) {\n return getColorSetting(key).get();\n }\n\n public Integer getInteger(Key key) {\n return getIntegerSetting(key).get();\n }\n\n public Double getDouble(Key key) {\n return getDoubleSetting(key).get();\n }\n\n public String getString(Key key) {\n return getStringSetting(key).get();\n }\n\n public static Builder newBuilder(){\n return new Builder();\n }\n\n public void resetToDefault() {\n SettingsTransaction transaction = new SettingsTransaction();\n\n transaction.execute(this.settingsMap.values().stream()\n .map(s ->\n (Function<SettingsTransaction, Boolean>) s::resetToDefault\n )\n .collect(Collectors.toList())\n );\n }\n\n public static class Builder {\n private boolean built = false;\n private List<Setting<?>> settings = new ArrayList<>();\n private Builder() {\n }\n\n public <T> Builder addSetting(Setting<T> setting) {\n throwIfBuilt();\n settings.add(setting);\n return this;\n }\n\n public SettingsGroup build(){\n throwIfBuilt();\n built = true;\n return new SettingsGroup(this.settings);\n }\n\n private void throwIfBuilt() {\n if (built) {\n throw new IllegalStateException(\"already built!\");\n }\n }\n }\n\n public void initTransientData(){\n settingsMap.values().forEach(Setting::initTransientData);\n }\n}", "public class SettingsGroupFactory {\n public static SettingsGroup buildGeneralParallelCoordinatesChartSettingsGroup() {\n return SettingsGroup.newBuilder()\n .addSetting(new BooleanSetting(\"Offset Axis Labels\", true, Key.PARALLEL_COORDINATES_VERTICALLY_OFFSET_AXIS_LABELS))\n .addSetting(new IntegerSetting(\"Axis Label vertical Distance\", 10, Key.PARALLEL_COORDINATES_LABELS_VERTICAL_DISTANCE, 0, 100))\n .addSetting(new BooleanSetting(\"Use Anti Aliasing\", true, Key.ANTI_ALIASING))\n .addSetting(new BooleanSetting(\"Use Transparency\", true, Key.USE_ALPHA))\n .addSetting(new ColorSetting(\"Background Color\", Color.WHITE, Key.PARALLEL_CHART_BACKGROUND_COLOR))\n .addSetting(new ColorSetting(\"Active Design Color\", new Color(0, 150, 0, 128), Key.ACTIVE_DESIGN_DEFAULT_COLOR))\n .addSetting(new ColorSetting(\"Selected Design Color\", Color.BLUE, Key.SELECTED_DESIGN_DEFAULT_COLOR))\n .addSetting(new ColorSetting(\"Filtered Design Color\", new Color(200, 200, 200, 100), Key.IN_ACTIVE_DESIGN_DEFAULT_COLOR))\n .addSetting(new ColorSetting(\"Filter Color\", Color.RED, Key.PARALLEL_COORDINATES_FILTER_COLOR))\n .addSetting(new BooleanSetting(\"Use Anti Aliasing\", true, Key.ANTI_ALIASING))\n .addSetting(new BooleanSetting(\"Show filtered Designs\", false, Key.SHOW_FILTERED_DESIGNS))\n .addSetting(new BooleanSetting(\"Show only selected Designs\", false, Key.PARALLEL_COORDINATES_SHOW_ONLY_SELECTED_DESIGNS))\n .addSetting(new BooleanSetting(\"Show Design IDs\", true, Key.SHOW_DESIGN_IDS))\n .addSetting(new IntegerSetting(\"Design Label Font Size\", 10, Key.DESIGN_LABEL_FONT_SIZE, 0, 100))\n .addSetting(new IntegerSetting(\"Selected Design Line Thickness\", 2, Key.SELECTED_DESIGN_LINE_THICKNESS, 0, 10))\n .addSetting(new IntegerSetting(\"Design Line Thickness\", 1, Key.LINE_THICKNESS, 0, 10))\n .addSetting(new IntegerSetting(\"Filter Symbol Width\", 7, Key.PARALLEL_COORDINATES_FILTER_WIDTH, 1, 30))\n .addSetting(new IntegerSetting(\"Filter Symbol Height\", 10, Key.PARALLEL_COORDINATES_FILTER_HEIGHT, 1, 60))\n .build();\n }\n\n public static SettingsGroup buildParallelCoordinatesChartAxisSettingsGroup() {\n IntegerSetting digitCountSetting = new IntegerSetting(\"Tic Label Digit Count\", 3, Key.PARALLEL_COORDINATES_AXIS_TIC_LABEL_DIGIT_COUNT, 0, 20);\n return SettingsGroup.newBuilder()\n .addSetting(new BooleanSetting(\"Active\", true, Key.PARALLEL_COORDINATES_AXIS_ACTIVE))\n .addSetting(new ColorSetting(\"Axis Color\", Color.BLACK, Key.PARALLEL_COORDINATES_AXIS_COLOR))\n .addSetting(new ColorSetting(\"Axis Label Color\", Color.BLACK, Key.PARALLEL_COORDINATES_AXIS_LABEL_FONT_COLOR))\n .addSetting(new IntegerSetting(\"Axis Label Fontsize\", 20, Key.PARALLEL_COORDINATES_AXIS_LABEL_FONT_SIZE, 0, 100))\n .addSetting(new IntegerSetting(\"Axis Spacing\", 200, Key.PARALLEL_COORDINATES_AXIS_WIDTH, 0, 1000))\n .addSetting(new IntegerSetting(\"Tic Size\", 4, Key.PARALLEL_COORDINATES_AXIS_TIC_LENGTH, 0, 100))\n .addSetting(new IntegerSetting(\"Number of Tics\", 11, Key.PARALLEL_COORDINATES_AXIS_TIC_COUNT, 0, 1000))\n .addSetting(new ColorSetting(\"Tic Label Color\", Color.BLACK, Key.PARALLEL_COORDINATES_AXIS_TIC_LABEL_FONT_COLOR))\n .addSetting(new IntegerSetting(\"Tic Label Fontsize\", 10, Key.TIC_LABEL_FONT_SIZE, 0, 100))\n .addSetting(digitCountSetting)\n .addSetting(new BooleanSetting(\"Invert Filter\", false, Key.PARALLEL_COORDINATES_FILTER_INVERTED))\n .addSetting(new BooleanSetting(\"Invert Axis\", false, Key.PARALLEL_COORDINATES_AXIS_INVERTED))\n .addSetting(new BooleanSetting(\"Autofit Axis\", true, Key.PARALLEL_COORDINATES_AUTO_FIT_AXIS))\n .addSetting(new DoubleSetting(\"Min\", 0, Key.PARALLEL_COORDINATES_AXIS_DEFAULT_MIN, digitCountSetting))\n .addSetting(new DoubleSetting(\"Max\", 1, Key.PARALLEL_COORDINATES_AXIS_DEFAULT_MAX, digitCountSetting))\n .build();\n }\n}" ]
import org.xdat.data.DataSheet; import org.xdat.data.Parameter; import org.xdat.settings.IntegerSetting; import org.xdat.settings.Key; import org.xdat.settings.Setting; import org.xdat.settings.SettingsGroup; import org.xdat.settings.SettingsGroupFactory; import java.awt.Color; import java.io.Serializable;
/* * Copyright 2014, Enguerrand de Rochefort * * This file is part of xdat. * * xdat 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. * * xdat 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 xdat. If not, see <http://www.gnu.org/licenses/>. * */ package org.xdat.chart; /** * A serializable representation of all relevant settings for an Axis on a * Parallel coordinates chart. * <p> * An Axis is used to represent a Parameter. Each Axis has an upper Filter and a * lower Filter, which are represented by triangles and can be dragged by the * user. The positions of the Filters determine which Designs are displayed, and * which are not. * * @see ParallelCoordinatesChart * @see Filter * @see org.xdat.data.Parameter * @see org.xdat.data.Design */ public class Axis implements Serializable { static final long serialVersionUID = 7L; private ParallelCoordinatesChart chart; private Parameter parameter; private Filter upperFilter; private Filter lowerFilter;
private SettingsGroup settings;
5
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/run/loader/DCELoader.java
[ "public class Configuration {\n\tpublic enum Sections {\n\t\tMACROSCOPY, MICROSCOPY, CYTOPATHOLOGY, LIQUID_CYTOPATHOLOGY, CONCLUSION, OTHERS;\n\t}\n\n\tpublic enum Criteria {\n\t\tONE_REPORT_ONE_REGISTRY, MANY_REPORT_ONE_REGISTRY, MANY_REPORT_MANY_REGISTRY;\n\t}\n\n\tpublic enum Classifiers {\n\t\tNAIVE, BAYES, BAYES_NET, BERNOULLI, SVM;\n\t}\n\n\tpublic enum WeightingSchemes {\n\t\tTF, IDF, TFIDF;\n\t}\n\n\tpublic enum SmoothingTechniques {\n\t\tADD_ONE, ADD_ALPHA, GOOD_TURING;\n\t}\n\n\tpublic enum Sources {\n\t\tDCE_REPORT, SIGH_REPORT, TOTLAUD_REPORT, ALL;\n\t}\n\n\tpublic enum Stemmers {\n\t\t// TODO test with PTStemmer V1 available at Maven repositories\n\t\tNONE, ORENGO, PORTER, SAVOY, COGROO;\n\t}\n\n\tpublic enum SentenceDetectors {\n\t\tNONE, OPENNLP, COGROO;\n\t}\n\n\tpublic enum Tokenizers {\n\t\tWORD, ALPHABETIC, OPENNLP, COGROO;\n\t}\n\n\tpublic enum Chunkers {\n\t\tNONE, COGROO;\n\t}\n\n\tpublic enum Targets {\n\t\tMORPHOLOGY, MORPHOLOGY_GROUP, TOPOGRAPHY, TOPOGRAPHY_CATEGORY, TOPOGRAPHY_GROUP;\n\t}\n\n\tpublic enum MetastasisStatus {\n\t\tALL, NONM1;\n\t}\n\n\tprivate Set<Sections> sections;\n\tprivate Criteria criteria;\n\tprivate int minReports = 1;\n\tprivate Classifiers classifier;\n\tprivate WeightingSchemes weightScheme;\n\tprivate SmoothingTechniques smoothing;\n\tprivate double svmCostParameter = 1;\n\tprivate Sources source;\n\tprivate boolean stoplist;\n\tprivate int ngrams = 1;\n\tprivate SentenceDetectors sentenceDetector;\n\tprivate Tokenizers tokenizer;\n\tprivate Stemmers stemmer;\n\tprivate Chunkers chunker;\n\tprivate Targets target;\n\tprivate MetastasisStatus meta;\n\tprivate int patientYear = -1;\n\n\tpublic Configuration(Set<Sections> sections, Criteria criteria, Classifiers classifier,\n\t\t\tWeightingSchemes weightScheme, SmoothingTechniques smoothing, double svmCParameter, Sources source,\n\t\t\tboolean stoplist, int ngrams, SentenceDetectors sentenceDetector, Tokenizers tokenizer, Stemmers stemmer,\n\t\t\tChunkers chunker, Targets target, int minReports, int year, MetastasisStatus meta) {\n\t\tsuper();\n\t\tthis.sections = sections;\n\t\tthis.criteria = criteria;\n\t\tif (criteria == Criteria.MANY_REPORT_ONE_REGISTRY)\n\t\t\tthis.minReports = minReports;\n\t\tthis.classifier = classifier;\n\t\tthis.weightScheme = weightScheme;\n\t\tthis.smoothing = smoothing;\n\t\tthis.svmCostParameter = svmCParameter;\n\t\tthis.source = source;\n\t\tthis.stoplist = stoplist;\n\t\tthis.ngrams = ngrams;\n\t\tthis.sentenceDetector = sentenceDetector;\n\t\tthis.tokenizer = tokenizer;\n\t\tthis.stemmer = stemmer;\n\t\tthis.chunker = chunker;\n\t\tthis.target = target;\n\t\tthis.patientYear = year;\n\t\tthis.meta = meta;\n\t}\n\n\tpublic Set<Sections> getSections() {\n\t\treturn sections;\n\t}\n\n\tpublic Criteria getCriteria() {\n\t\treturn criteria;\n\t}\n\n\tpublic int getMinReports() {\n\t\treturn minReports;\n\t}\n\n\tpublic Classifiers getClassifier() {\n\t\treturn classifier;\n\t}\n\n\tpublic WeightingSchemes getWeightScheme() {\n\t\treturn weightScheme;\n\t}\n\n\tpublic SmoothingTechniques getSmoothing() {\n\t\treturn smoothing;\n\t}\n\n\tpublic double getSvmCostParameter() {\n\t\treturn svmCostParameter;\n\t}\n\n\tpublic Sources getSource() {\n\t\treturn source;\n\t}\n\n\tpublic boolean getStoplist() {\n\t\treturn stoplist;\n\t}\n\t\n\tpublic int getNGrams() {\n\t\treturn ngrams;\n\t}\n\n\tpublic SentenceDetectors getSentenceDetector() {\n\t\treturn sentenceDetector;\n\t}\n\n\tpublic Tokenizers getTokenizer() {\n\t\treturn tokenizer;\n\t}\n\n\tpublic Stemmers getStemmer() {\n\t\treturn stemmer;\n\t}\n\n\tpublic Chunkers getChunker() {\n\t\treturn chunker;\n\t}\n\n\tpublic Targets getTarget() {\n\t\treturn target;\n\t}\n\n\tpublic MetastasisStatus getMetastasisStatus() {\n\t\treturn meta;\n\t}\n\n\tpublic int getPatientYear() {\n\t\treturn patientYear;\n\t}\n\n\tpublic String getInstanceDependentStringRepresentation() {\n\t\treturn (Arrays.toString(sections.toArray()) + \"-\" + criteria + \"-\" + minReports + \"-\" + source + \"-\"\n\t\t\t\t+ sentenceDetector + \"-\" + tokenizer + \"Tokenizer-\" + stemmer + \"Stemmer-\" + chunker + \"Chunker-\"\n\t\t\t\t+ target + \"-\" + meta + \"-\" + patientYear).toLowerCase();\n\t}\n\n\tpublic String getStringRepresentation() {\n\t\treturn (Arrays.toString(sections.toArray()) + \"-\" + criteria + \"-\" + minReports + \"-\" + classifier + \"-\"\n\t\t\t\t+ weightScheme + \"-\" + smoothing + \"-\" + svmCostParameter + \"-\" + Constants.ALPHA + \"-\" + source + \"-\"\n\t\t\t\t+ stoplist + \"-\" + ngrams + \"-\" + sentenceDetector + \"-\" + tokenizer + \"-\" + stemmer + \"-\" + chunker + \"-\" + target\n\t\t\t\t+ \"-\" + meta + \"-\" + patientYear).toLowerCase();\n\t}\n\n}", "public class Constants {\n\n\tpublic static final int THREADS = 1;\n\tpublic static final int CONNECTIONS = THREADS * 2;\n\n\t// TODO change to something better, maybe setting automatically on the main method.\n\tpublic static final boolean RECREATE_DB = true;\n\tpublic static final int BATCH_SIZE = 100;\n\n\t// TODO move to a config file\n\t/** Root directory where reference tables are located. */\n\tpublic static final String REF_DIR = \"src/ref/\";\n\n\t/** Directory containing large data files. */\n\tpublic static final String DATA_DIR = \"src/data/\";\n\n\t// TODO defined in models.xml for CoGrOO implementation. May not be necessary.\n\t/** Directory containing models (e.g. OpenNLP models). */\n\tpublic static final String MODEL_DIR = \"src/models/\";\n\n\t/** Defines if a cache of instances is used or not. */\n\tpublic static final boolean CACHE = false;\n\n\t/** Indicates wheter to generate stats or not. */\n\tpublic static final boolean STATS = false;\n\n\tpublic static final float TEST_RATIO = 0.1f;\n\t// public static final int THRESHOLD = 10;\n\n\t// TODO move to a class smoothing or something\n\tpublic static final double ALPHA = 0.5d;\n\n\tpublic static Configuration CONFIG;\n\n}", "public class DAOFactory {\r\n\t// TODO migrate to JPA Persistence:\r\n\t// http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/\r\n\tprivate static final int CONNECTIONS = Constants.CONNECTIONS;\r\n\r\n\tprivate static final DAOFactory instance = new DAOFactory();\r\n\r\n\tpublic static DAOFactory getDAOFactory() {\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tprivate SessionFactory sessionFactory;\r\n\tprivate Session[] session = new Session[CONNECTIONS];\r\n\r\n\tprivate TopographyDAO[] topographyDAO = new TopographyDAO[CONNECTIONS];\r\n\tprivate TopographyCategoryDAO[] topographyCategoryDAO = new TopographyCategoryDAO[CONNECTIONS];\r\n\tprivate TopographyGroupDAO[] topographyGroupDAO = new TopographyGroupDAO[CONNECTIONS];\r\n\r\n\tprivate MorphologyDAO[] morphologyDAO = new MorphologyDAO[CONNECTIONS];\r\n\tprivate MorphologyGroupDAO[] morphologyGroupDAO = new MorphologyGroupDAO[CONNECTIONS];\r\n\r\n\tprivate DceDAO[] dceDAO = new DceDAO[CONNECTIONS];\r\n\tprivate SighDAO[] sighDAO = new SighDAO[CONNECTIONS];\r\n\tprivate RhcDAO[] rhcDAO = new RhcDAO[CONNECTIONS];\r\n\tprivate PatientDAO[] patientDAO = new PatientDAO[CONNECTIONS];\r\n\r\n\tprivate DAOFactory() {\r\n\t\tAnnotationConfiguration cfg = new AnnotationConfiguration();\r\n\r\n\t\tcfg.addAnnotatedClass(Topography.class);\r\n\t\tcfg.addAnnotatedClass(TopographyCategory.class);\r\n\t\tcfg.addAnnotatedClass(TopographyGroup.class);\r\n\r\n\t\tcfg.addAnnotatedClass(Morphology.class);\r\n\t\tcfg.addAnnotatedClass(MorphologyGroup.class);\r\n\r\n\t\tcfg.addAnnotatedClass(RHC.class);\r\n\t\tcfg.addAnnotatedClass(DCE.class);\r\n\t\tcfg.addAnnotatedClass(SighReport.class);\r\n\t\tcfg.addAnnotatedClass(Patient.class);\r\n\t\tcfg.configure();\r\n\r\n\t\t// TODO set fetch size according to Constants.BATCH_SIZE\r\n\r\n\t\tif (Constants.RECREATE_DB) {\r\n\t\t\tSchemaExport se = new SchemaExport(cfg);\r\n\t\t\tse.create(true, true);\r\n\t\t}\r\n\r\n\t\tthis.sessionFactory = cfg.buildSessionFactory();\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tsession[i] = sessionFactory.openSession();\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyDAO[i] = new TopographyDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyCategoryDAO[i] = new TopographyCategoryDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyGroupDAO[i] = new TopographyGroupDAO(session[i]);\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tmorphologyDAO[i] = new MorphologyDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tmorphologyGroupDAO[i] = new MorphologyGroupDAO(session[i]);\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tdceDAO[i] = new DceDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tsighDAO[i] = new SighDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\trhcDAO[i] = new RhcDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tpatientDAO[i] = new PatientDAO(session[i]);\r\n\t}\r\n\r\n\tint sess = 0;\r\n\r\n\tprivate int getNextSession() {\r\n\t\tsess++;\r\n\t\tif (sess >= CONNECTIONS)\r\n\t\t\tsess = 0;\r\n\t\treturn sess;\r\n\t}\r\n\r\n\tpublic ClassifiableDAO getIcdClassDAO() {\r\n\t\tswitch (Constants.CONFIG.getTarget()) {\r\n\t\tcase MORPHOLOGY:\r\n\t\t\treturn (ClassifiableDAO) getMorphologyDAO();\r\n\t\tcase MORPHOLOGY_GROUP:\r\n\t\t\treturn (ClassifiableDAO) getMorphologyGroupDAO();\r\n\t\tcase TOPOGRAPHY:\r\n\t\t\treturn (ClassifiableDAO) getTopographyDAO();\r\n\t\tcase TOPOGRAPHY_CATEGORY:\r\n\t\t\treturn (ClassifiableDAO) getTopographyCategoryDAO();\r\n\t\tcase TOPOGRAPHY_GROUP:\r\n\t\t\treturn (ClassifiableDAO) getTopographyGroupDAO();\r\n\t\tdefault:\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic TopographyDAO getTopographyDAO() {\r\n\t\treturn topographyDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic TopographyCategoryDAO getTopographyCategoryDAO() {\r\n\t\treturn topographyCategoryDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic TopographyGroupDAO getTopographyGroupDAO() {\r\n\t\treturn topographyGroupDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic MorphologyDAO getMorphologyDAO() {\r\n\t\treturn morphologyDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic MorphologyGroupDAO getMorphologyGroupDAO() {\r\n\t\treturn morphologyGroupDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic DceDAO getDceDAO() {\r\n\t\treturn dceDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic SighDAO getSighDAO() {\r\n\t\treturn sighDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic RhcDAO getRhcDAO() {\r\n\t\treturn rhcDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic PatientDAO getPatientDAO() {\r\n\t\treturn patientDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic void close() {\r\n\t\tfor (Session s : session)\r\n\t\t\ts.close();\r\n\t\tsessionFactory.close();\r\n\t}\r\n\r\n}\r", "public class DceDAO {\n\n\tprivate Session session;\n\t\n\tpublic DceDAO(Session session) {\n\t\tthis.session = session;\n\t}\n\n\tpublic void save(DCE p) {\n\t\tthis.session.save(p);\n\t}\n\n\tpublic void delete(DCE p) {\n\t\tthis.session.delete(p);\n\t}\n\t\n\tpublic boolean exists(Long id) {\n\t\treturn this.session.get(DCE.class, id) == null ? false : true;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<DCE> list() {\n\t\treturn this.session.createCriteria(DCE.class).list();\n\t}\n\t\n\tpublic DCE locate(Integer hospitalId) {\n\t\treturn (DCE) this.session.createCriteria(DCE.class)\n\t\t\t\t.add(Restrictions.eq(\"hospitalId\", hospitalId)).uniqueResult();\n\t}\n\n\tpublic DCE load(Long id) {\n\t\treturn (DCE) this.session.load(DCE.class, id);\n\t}\n\n\tpublic void update(DCE p) {\n\t\tthis.session.update(p);\n\t}\n\t\n\tpublic void saveOrUpdate(DCE p) {\n\t\tthis.session.saveOrUpdate(p);\n\t}\n\t\n\tpublic void beginTransaction() {\n\t\tthis.session.beginTransaction();\n\t}\n\t\n\tpublic void commit() {\n\t\tthis.session.getTransaction().commit();\n\t}\n\t\n\tpublic void flushAndClear() {\n\t\tthis.session.flush();\n\t\tthis.session.clear();\n\t}\n\t\n}", "public class PatientDAO {\r\n\tprivate Session session;\r\n\r\n\t// public static final String USER_ENTITY = Patient.class.getName();\r\n\r\n\tpublic PatientDAO(Session session) {\r\n\t\tthis.session = session;\r\n\t}\r\n\r\n\tpublic void save(Patient p) {\r\n\t\tthis.session.save(p);\r\n\t}\r\n\r\n\tpublic void delete(Patient p) {\r\n\t\tthis.session.delete(p);\r\n\t}\r\n\r\n\tpublic Patient load(Long id) {\r\n\t\treturn (Patient) this.session.load(Patient.class, id);\r\n\t}\r\n\r\n\tpublic Patient locate(Integer rgh) {\r\n\t\treturn (Patient) this.session.createCriteria(Patient.class)\r\n\t\t\t\t.add(Restrictions.eq(\"rgh\", rgh)).uniqueResult();\r\n\t}\r\n\t\r\n\tpublic Integer count() {\r\n\t\treturn (Integer) this.session.createCriteria(Patient.class).setProjection(Projections.rowCount()).uniqueResult();\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Patient> list() {\r\n\t\treturn this.session.createCriteria(Patient.class).addOrder(Order.asc(\"rgh\")).list();\r\n\t}\r\n\r\n\tpublic void update(Patient p) {\r\n\t\tthis.session.update(p);\r\n\t}\r\n\t\r\n\tpublic void saveOrUpdate(Patient p) {\r\n\t\tthis.session.saveOrUpdate(p);\r\n\t}\r\n\t\r\n\tpublic void beginTransaction() {\r\n\t\tthis.session.beginTransaction();\r\n\t}\r\n\t\r\n\tpublic void commit() {\r\n\t\tthis.session.getTransaction().commit();\r\n\t}\r\n\t\r\n\tpublic void flushAndClear() {\r\n\t\tthis.session.flush();\r\n\t\tthis.session.clear();\r\n\t}\r\n\t\r\n\tpublic void merge(Patient p) {\r\n\t\tthis.session.merge(p);\r\n\t}\r\n}\r", "@Entity\r\npublic class DCE implements Report {\r\n\t@Id\r\n\t@GeneratedValue\r\n\tprivate Long id;\r\n\r\n\t@Column\r\n\t@Index(name = \"internalid_ndx\")\r\n\tprivate Integer hospitalId;\r\n\r\n\t// Longest known (939586) contains 21448 characters.\r\n\t@Column(length = 30000)\r\n\t@Deprecated\r\n\tprivate String text;\r\n\t\r\n\t// TODO change fields to aggregation, with classes that implements a well-defined interface.\r\n\r\n\t@Column(length = 100000)\r\n\tprivate String macroscopy;\r\n\r\n\t@Column(length = 100000)\r\n\tprivate String microscopy;\r\n\r\n\t@Column(length = 100000)\r\n\tprivate String cytopathology;\r\n\t\r\n\t@Column(length = 100000)\r\n\tprivate String liquidCytopathology;\r\n\r\n\t@Column(length = 100000)\r\n\tprivate String others;\r\n\r\n\t// bidirectional relationship\r\n\t@ManyToOne\r\n\t@JoinColumn(name = \"patient_fk\")\r\n\tprivate Patient rgh;\r\n\r\n\tpublic DCE() {\r\n\r\n\t}\r\n\r\n\tpublic void setRgh(Patient rgh) {\r\n\t\tthis.rgh = rgh;\r\n\t}\r\n\r\n\t@Deprecated\r\n\tpublic DCE(Integer hospitalId, String text) {\r\n\t\tthis.hospitalId = hospitalId;\r\n\t\tthis.text = text;\r\n\t}\r\n\r\n\tpublic DCE(Integer hospitalId, String macroscopy, String microscopy, String cytopathology, String liquidCytopathology, String others) {\r\n\t\tthis.hospitalId = hospitalId;\r\n\t\tthis.macroscopy = macroscopy;\r\n\t\tthis.microscopy = microscopy;\r\n\t\tthis.cytopathology = cytopathology;\r\n\t\tthis.liquidCytopathology = liquidCytopathology;\r\n\t\tthis.others = others;\r\n\t}\r\n\r\n\tpublic DCE(Integer hospitalId, Map<Configuration.Sections, String> sections) {\r\n\t\tthis.hospitalId = hospitalId;\r\n\t\tthis.macroscopy = sections.remove(Configuration.Sections.MACROSCOPY);\r\n\t\tthis.microscopy = sections.remove(Configuration.Sections.MICROSCOPY);\r\n\t\tthis.cytopathology = sections.remove(Configuration.Sections.CYTOPATHOLOGY);\r\n\t\tthis.liquidCytopathology = sections.remove(Configuration.Sections.LIQUID_CYTOPATHOLOGY);\r\n\t\t\r\n\t\tfor (Map.Entry<Configuration.Sections, String> entry : sections.entrySet()) {\r\n\t\t\tthis.others += entry;\r\n\t\t}\t\r\n\t}\r\n\r\n\tpublic Long getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic Integer getHospitalId() {\r\n\t\treturn hospitalId;\r\n\t}\r\n\r\n\tpublic String getText() {\r\n\t\tString lineSeparator = System.getProperty(\"line.separator\");\r\n\t\treturn macroscopy + lineSeparator + microscopy + lineSeparator + cytopathology + lineSeparator + liquidCytopathology + lineSeparator + others;\r\n\t}\r\n\r\n\tpublic String[] getTexts() {\r\n\t\treturn new String[] { macroscopy, microscopy, cytopathology, liquidCytopathology, others };\r\n\t}\r\n\r\n\tpublic Map<Configuration.Sections, String> getZonedTexts() {\r\n\t\tMap<Configuration.Sections, String> ret = new HashMap<Configuration.Sections, String>();\r\n\t\tif (macroscopy != null && !macroscopy.isEmpty())\r\n\t\t\tret.put(Configuration.Sections.MACROSCOPY, macroscopy);\r\n\t\tif (microscopy != null && !microscopy.isEmpty())\r\n\t\t\tret.put(Configuration.Sections.MICROSCOPY, microscopy);\r\n\t\tif (cytopathology != null && !cytopathology.isEmpty())\r\n\t\t\tret.put(Configuration.Sections.CYTOPATHOLOGY, cytopathology);\r\n\t\tif (liquidCytopathology != null && !liquidCytopathology.isEmpty())\r\n\t\t\tret.put(Configuration.Sections.LIQUID_CYTOPATHOLOGY, liquidCytopathology);\r\n\t\tif (others != null && !others.isEmpty())\r\n\t\t\tret.put(Configuration.Sections.OTHERS, others);\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic Patient getRgh() {\r\n\t\treturn rgh;\r\n\t}\r\n\r\n\tprivate static final Logger LOG = Logger.getLogger(DCE.class);\r\n\r\n\tpublic static final int THREADS = Constants.THREADS;\r\n\tprivate static final Pattern COMMA = Pattern.compile(\",\");\r\n\r\n\t/**\r\n\t * \r\n\t * @param index\r\n\t * @param directory\r\n\t */\r\n\tpublic static void loadFromDirectory(File index, File directory) {\r\n\t\tif (directory == null || index == null || !directory.isDirectory() || !index.isFile() || !index.canRead()) {\r\n\t\t\tSystem.err.println(\"Error loading DCE.\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tMap<Integer, Integer>[] map = new HashMap[THREADS];\r\n\t\tfor (int i = 0; i < THREADS; i++)\r\n\t\t\tmap[i] = new HashMap<Integer, Integer>();\r\n\r\n\t\t/*\r\n\t\t * *********************************************************************\r\n\t\t * *****\r\n\t\t */\r\n\r\n\t\tPatientDAO patientDao = DAOFactory.getDAOFactory().getPatientDAO();\r\n\t\tpatientDao.beginTransaction();\r\n\r\n\t\ttry {\r\n\t\t\tBufferedReader indexReader = new BufferedReader(new FileReader(index));\r\n\t\t\tint i = 0, k = 1;\r\n\t\t\tindexReader.readLine(); // Header\r\n\t\t\tfor (String entry = indexReader.readLine(); entry != null\r\n\t\t\t\t\t&& !entry.isEmpty(); entry = indexReader.readLine()) {\r\n\t\t\t\tk++;\r\n\t\t\t\tif (k % Constants.BATCH_SIZE == 0) {\r\n\t\t\t\t\tLOG.debug(k);\r\n\t\t\t\t\tpatientDao.flushAndClear();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tString[] cells = COMMA.split(entry);\r\n\t\t\t\tif (cells.length != 2)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tInteger laudoId = Integer.parseInt(cells[0]);\r\n\t\t\t\tInteger rgh = Integer.parseInt(cells[1]);\r\n\r\n\t\t\t\tPatient p = patientDao.locate(rgh);\r\n\t\t\t\tif (p == null) {\r\n\t\t\t\t\tp = new Patient(rgh);\r\n\t\t\t\t\tpatientDao.save(p);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmap[i].put(laudoId, rgh);\r\n\t\t\t\ti = (i + 1) % THREADS;\r\n\t\t\t}\r\n\t\t\tindexReader.close();\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tpatientDao.commit();\r\n\r\n\t\tDCELoader[] dceLoader = new DCELoader[THREADS];\r\n\t\tfor (int i = 0; i < THREADS; i++) {\r\n\t\t\tdceLoader[i] = new DCELoader(map[i], directory);\r\n\t\t\tdceLoader[i].start();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < THREADS; i++) {\r\n\t\t\ttry {\r\n\t\t\t\tdceLoader[i].join();\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// TODO Auto-generated catch block\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n}\r", "@Entity\npublic class Patient {\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\n\t@Column(unique=true)\n\t@Index(name = \"rgh_ndx\")\n\tprivate Integer rgh;\n\n\t// bidirectional relationship\n\t@OneToMany(mappedBy=\"rgh\")\n\tprivate List<RHC> rhc;\n\n\t// bidirectional relationship\n\t@OneToMany(mappedBy=\"rgh\")\n\tprivate List<DCE> dce;\n\t\n\t// bidirectional relationship\n\t@OneToMany(mappedBy=\"rgh\")\n\tprivate List<SighReport> sighReport;\n\t\n\tpublic Patient() {\n\t}\n\n\tpublic Patient(Integer rgh) {\n\t\t\n\t\tthis.rgh = rgh;\n\t}\n\n\tpublic void addRHC(RHC rhc) {\n\t\trhc.setRgh(this);\n\t\tif (this.rhc == null)\n\t\t\tthis.rhc = new ArrayList<RHC>();\n\t\tthis.rhc.add(rhc);\n\t}\n\t\n\tpublic void addDCE(DCE dce) {\n\t\tdce.setRgh(this);\n\t\tif (this.dce == null)\n\t\t\tthis.dce = new ArrayList<DCE>();\n\t\tthis.dce.add(dce);\n\t}\n\t\n\tpublic void addSighReport(SighReport report) {\n\t\treport.setRgh(this);\n\t\tif (this.sighReport == null)\n\t\t\tthis.sighReport = new ArrayList<SighReport>();\n\t\tthis.sighReport.add(report);\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic Integer getRgh() {\n\t\treturn rgh;\n\t}\n\n\tpublic List<RHC> getRhc() {\n\t\treturn rhc;\n\t}\n\t\n\tpublic List<RHC> getDistinctRhc() {\n\t\tList<RHC> ret = new ArrayList<RHC>();\n\t\tSet<String> control = new HashSet<String>();\n\t\tString code;\n\t\tfor (RHC r : rhc) {\n\t\t\tcode = r.getIcdClass().getCode();\n\t\t\tif (!control.contains(code)) {\n\t\t\t\tcontrol.add(code);\n\t\t\t\tret.add(r);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\t/**\n\t * \n\t * @return\n\t * @deprecated use getTexts instead.\n\t */\n\tpublic List<DCE> getDce() {\n\t\treturn dce;\n\t}\n\t\n\t/**\n\t * \n\t * @return\n\t * @deprecated use getTexts instead.\n\t */\n\tpublic List<SighReport> getSighReport() {\n\t\treturn sighReport;\n\t}\n\t\n\tpublic List getTexts() {\n\t\tswitch (Constants.CONFIG.getSource()) {\n\t\tcase SIGH_REPORT:\n\t\t\treturn sighReport;\n\t\tcase DCE_REPORT:\n\t\t\treturn dce;\n\t\tcase ALL:\n\t\t\tList<Report> all = new ArrayList<Report>(sighReport);\n\t\t\tall.addAll(dce);\n\t\t\treturn all;\n\t\tcase TOTLAUD_REPORT:\n\t\t\t// TODO\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.apache.log4j.Logger; import br.usp.ime.icdc.Configuration; import br.usp.ime.icdc.Constants; import br.usp.ime.icdc.dao.DAOFactory; import br.usp.ime.icdc.dao.DceDAO; import br.usp.ime.icdc.dao.PatientDAO; import br.usp.ime.icdc.model.DCE; import br.usp.ime.icdc.model.Patient;
package br.usp.ime.icdc.run.loader; public class DCELoader extends Thread { // Longest known valid sequence of numbers has 15 characters. private static final Pattern HEXA = Pattern.compile("[a-f0-9]{20,}"); private static final String SECTION_DIVIDER = "---------"; // Ordered by corpus frequency private static final Map<String, Configuration.Sections> sectionsTranslator = new HashMap<String, Configuration.Sections>(); static { sectionsTranslator.put("MACROSCOPIA", Configuration.Sections.MACROSCOPY); sectionsTranslator.put("MICROSCOPIA", Configuration.Sections.MICROSCOPY); sectionsTranslator.put("EXAME CITOPATOLÓGICO CÉRVICO-VAGINAL", Configuration.Sections.CYTOPATHOLOGY); // sections.add("LAUDO COMPLEMENTAR DE IMUNOISTOQUÍMICA"); // sections.add("IMUNOISTOQUÍMICA"); // sections.add("REVISÃO DE LMINAS"); // sic // sections.add("EXAME CITOLÓGICO"); // sections.add("PUNÇÃO ASPIRATIVA"); sectionsTranslator.put("EXAME CITOPATOLÓGICO CÉRVICO-VAGINAL EM MEIO LÍQUIDO", Configuration.Sections.LIQUID_CYTOPATHOLOGY); } /** * reportId => patientId */ private Map<Integer, Integer> map; private File dir; private DceDAO dceDao = DAOFactory.getDAOFactory().getDceDAO(); private PatientDAO patientDao = DAOFactory.getDAOFactory().getPatientDAO(); private static final Logger LOG = Logger.getLogger(DCELoader.class); public DCELoader(Map<Integer, Integer> map, File dir) { this.map = map; this.dir = dir; } @Override public void run() { int total = map.keySet().size(); dceDao.beginTransaction(); StringBuilder sb = null; Iterator<Map.Entry<Integer, Integer>> iter = map.entrySet().iterator(); String line = null, oldText = null, newText = null; BufferedReader br = null; // zoneDescription => text Map<Configuration.Sections, String> sections = null; Configuration.Sections currentSection = null; int i = -1; long start = System.currentTimeMillis(); // Runs for each file while (iter.hasNext()) { i++; if (i % Constants.BATCH_SIZE == 0) { long now = System.currentTimeMillis(); double milisecondsPerEntry = (now - start) / (double) i; int remain = (int) ((milisecondsPerEntry * (total - i)) / 1000); LOG.debug(i + "/" + total + " (" + 100 * i / total + "%) " + remain + " seconds remaining"); dceDao.flushAndClear(); } Map.Entry<Integer, Integer> entry = iter.next(); Integer laudoId = entry.getKey(); Integer rgh = entry.getValue(); File f = new File(dir, laudoId + ".txt"); if (!f.exists() || !f.canRead()) { System.err.println("Cannot read file " + f.getName()); continue; } try { br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); sb = new StringBuilder(); sections = new HashMap<Configuration.Sections, String>(); currentSection = null; // The first section might not be prepended by the section // divider. line = br.readLine(); if (!line.equals("")) { currentSection = getNewSection(line); sb.append(line); sb.append("\n"); } // Runs for each line for (line = br.readLine(); line != null; line = br.readLine()) { line = HEXA.matcher(line).replaceAll(""); // After the section divider, we have the section header. if (line.equals(SECTION_DIVIDER)) { // currentSection == null iff the file starts with a section divider if (currentSection != null) { newText = sb.toString(); oldText = ""; // Updates the current section with the new value. // Should not happen that often, if ever. if (sections.containsKey(currentSection)) { LOG.debug("Found a document with at least two " + currentSection + " sections in file " + f.getName()); oldText = sections.get(currentSection); } sections.put(currentSection, oldText + newText); sb = new StringBuilder(); } line = br.readLine(); currentSection = getNewSection(line); } sb.append(line); // TODO change to OS dependent line separator (is Weka // compatible?) sb.append("\n"); } br.close(); } catch (IOException e) { e.printStackTrace(); continue; } Patient p = patientDao.locate(rgh);
DCE dce = new DCE(laudoId, sections);
5
SQiShER/java-object-diff
src/main/java/de/danielbechler/diff/DefaultNodeQueryService.java
[ "public interface CategoryResolver\n{\n\tSet<String> resolveCategories(DiffNode node);\n}", "public interface ComparisonStrategy\n{\n\tvoid compare(final DiffNode node, @Deprecated Class<?> type, final Object working, final Object base);\n}", "public interface ComparisonStrategyResolver\n{\n\tComparisonStrategy resolveComparisonStrategy(DiffNode node);\n}", "public enum PrimitiveDefaultValueMode\n{\n\t/**\n\t * Default values of primitive types will be treated like any other value. Since there is no distinction, any\n\t * change to a primitive value will be marked as {@linkplain de.danielbechler.diff.node.DiffNode.State#CHANGED}.\n\t */\n\tASSIGNED,\n\n\t/**\n\t * Default values of primitive types will be treated as if the property has not been set. The consequence of\n\t * this is that a change from default value to something else will be marked as {@linkplain\n\t * de.danielbechler.diff.node.DiffNode.State#ADDED} and from something else to the default value as {@linkplain\n\t * de.danielbechler.diff.node.DiffNode.State#REMOVED}.\n\t */\n\tUNASSIGNED\n}", "public interface PrimitiveDefaultValueModeResolver\n{\n\tPrimitiveDefaultValueMode resolvePrimitiveDefaultValueMode(DiffNode node);\n}", "public interface IsReturnableResolver\n{\n\tboolean isReturnable(DiffNode node);\n}", "public interface IsIntrospectableResolver\n{\n\t/**\n\t * @return Returns <code>true</code> if the object represented by the given node should be compared via\n\t * introspection.\n\t */\n\tboolean isIntrospectable(DiffNode node);\n}", "@SuppressWarnings(\"UnusedDeclaration\")\npublic class DiffNode\n{\n\tpublic static final DiffNode ROOT = null;\n\n\tprivate final Accessor accessor;\n\tprivate final Map<ElementSelector, DiffNode> children = new LinkedHashMap<ElementSelector, DiffNode>(10);\n\n\tprivate State state = State.UNTOUCHED;\n\tprivate DiffNode parentNode;\n\tprivate NodePath circleStartPath;\n\tprivate DiffNode circleStartNode;\n\tprivate Class<?> valueType;\n\tprivate TypeInfo valueTypeInfo;\n\tprivate IdentityStrategy childIdentityStrategy;\n\tprivate final Collection<String> additionalCategories = new TreeSet<String>();\n\n\tpublic void setChildIdentityStrategy(final IdentityStrategy identityStrategy)\n\t{\n\t\tthis.childIdentityStrategy = identityStrategy;\n\t}\n\n\tpublic static DiffNode newRootNode()\n\t{\n\t\treturn new DiffNode();\n\t}\n\n\tpublic static DiffNode newRootNodeWithType(final Class<?> valueType)\n\t{\n\t\tfinal DiffNode rootNode = newRootNode();\n\t\trootNode.setType(valueType);\n\t\treturn rootNode;\n\t}\n\n\tpublic DiffNode(final DiffNode parentNode, final Accessor accessor, final Class<?> valueType)\n\t{\n\t\tAssert.notNull(accessor, \"accessor\");\n\t\tthis.accessor = accessor;\n\t\tthis.valueType = valueType;\n\t\tsetParentNode(parentNode);\n\t}\n\n\tpublic DiffNode(final DiffNode parentNode, final Accessor accessor)\n\t{\n\t\tthis(parentNode, accessor, null);\n\t}\n\n\tprivate DiffNode()\n\t{\n\t\tthis.parentNode = ROOT;\n\t\tthis.accessor = RootAccessor.getInstance();\n\t}\n\n\t/**\n\t * @return The state of this node.\n\t */\n\tpublic State getState()\n\t{\n\t\treturn this.state;\n\t}\n\n\t/**\n\t * @param state The state of this node.\n\t */\n\tpublic void setState(final State state)\n\t{\n\t\tAssert.notNull(state, \"state\");\n\t\tthis.state = state;\n\t}\n\n\tpublic boolean matches(final NodePath path)\n\t{\n\t\treturn path.matches(getPath());\n\t}\n\n\tpublic boolean hasChanges()\n\t{\n\t\tif (isAdded() || isChanged() || isRemoved())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tfinal AtomicBoolean result = new AtomicBoolean(false);\n\t\tvisitChildren(new Visitor()\n\t\t{\n\t\t\tpublic void node(final DiffNode node, final Visit visit)\n\t\t\t{\n\t\t\t\tif (node.hasChanges())\n\t\t\t\t{\n\t\t\t\t\tresult.set(true);\n\t\t\t\t\tvisit.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn result.get();\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#ADDED}</code>\n\t */\n\tpublic final boolean isAdded()\n\t{\n\t\treturn state == State.ADDED;\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#CHANGED}</code>\n\t */\n\tpublic final boolean isChanged()\n\t{\n\t\treturn state == State.CHANGED;\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#REMOVED}</code>\n\t */\n\tpublic final boolean isRemoved()\n\t{\n\t\treturn state == State.REMOVED;\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#UNTOUCHED}</code>\n\t */\n\tpublic final boolean isUntouched()\n\t{\n\t\treturn state == State.UNTOUCHED;\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#CIRCULAR}</code>\n\t */\n\tpublic boolean isCircular()\n\t{\n\t\treturn state == State.CIRCULAR;\n\t}\n\n\t/**\n\t * @return The absolute property path from the object root up to this node.\n\t */\n\tpublic NodePath getPath()\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn NodePath.startBuildingFrom(parentNode.getPath())\n\t\t\t\t\t.element(accessor.getElementSelector())\n\t\t\t\t\t.build();\n\t\t}\n\t\telse if (accessor instanceof RootAccessor)\n\t\t{\n\t\t\treturn NodePath.withRoot();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn NodePath.startBuilding().element(accessor.getElementSelector()).build();\n\t\t}\n\t}\n\n\tpublic ElementSelector getElementSelector()\n\t{\n\t\treturn accessor.getElementSelector();\n\t}\n\n\t/**\n\t * @return Returns the type of the property represented by this node, or null if unavailable.\n\t */\n\tpublic Class<?> getValueType()\n\t{\n\t\tif (valueType != null)\n\t\t{\n\t\t\treturn valueType;\n\t\t}\n\t\tif (valueTypeInfo != null)\n\t\t{\n\t\t\treturn valueTypeInfo.getType();\n\t\t}\n\t\tif (accessor instanceof TypeAwareAccessor)\n\t\t{\n\t\t\treturn ((TypeAwareAccessor) accessor).getType();\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Allows to explicity set the type of this node. This will overshadow the type returned by {@linkplain\n\t * #getValueTypeInfo()} as well as the one returned by the accessor.\n\t *\n\t * @param aClass The type of the value represented by this node.\n\t */\n\tpublic final void setType(final Class<?> aClass)\n\t{\n\t\tthis.valueType = aClass;\n\t}\n\n\tpublic TypeInfo getValueTypeInfo()\n\t{\n\t\treturn valueTypeInfo;\n\t}\n\n\tpublic void setValueTypeInfo(final TypeInfo typeInfo)\n\t{\n\t\tthis.valueTypeInfo = typeInfo;\n\t}\n\n\t/**\n\t * @return <code>true</code> if this node has children.\n\t */\n\tpublic boolean hasChildren()\n\t{\n\t\treturn !children.isEmpty();\n\t}\n\n\tpublic int childCount()\n\t{\n\t\treturn children.size();\n\t}\n\n\t/**\n\t * Retrieve a child with the given property name relative to this node.\n\t *\n\t * @param propertyName The name of the property represented by the child node.\n\t * @return The requested child node or <code>null</code>.\n\t */\n\tpublic DiffNode getChild(final String propertyName)\n\t{\n\t\treturn getChild(new BeanPropertyElementSelector(propertyName));\n\t}\n\n\t/**\n\t * Retrieve a child that matches the given path element relative to this node.\n\t *\n\t * @param elementSelector The path element of the child node to get.\n\t * @return The requested child node or <code>null</code>.\n\t */\n\tpublic DiffNode getChild(final ElementSelector elementSelector)\n\t{\n\t\tif (elementSelector instanceof CollectionItemElementSelector && childIdentityStrategy != null)\n\t\t{\n\t\t\treturn children.get(((CollectionItemElementSelector) elementSelector).copyWithIdentityStrategy(childIdentityStrategy));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn children.get(elementSelector);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a child that matches the given absolute path, starting from the current node.\n\t *\n\t * @param nodePath The path from the object root to the requested child node.\n\t * @return The requested child node or <code>null</code>.\n\t */\n\tpublic DiffNode getChild(final NodePath nodePath)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getChild(nodePath.getElementSelectors());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn getChild(nodePath.getElementSelectors());\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a child that matches the given path element relative to this node.\n\t *\n\t * @param selectors The path element of the child node to get.\n\t * @return The requested child node or <code>null</code>.\n\t */\n\tpublic DiffNode getChild(final List<ElementSelector> selectors)\n\t{\n\t\tAssert.notEmpty(selectors, \"selectors\");\n\t\tfinal ElementSelector selector = selectors.get(0);\n\t\tif (selectors.size() == 1)\n\t\t{\n\t\t\tif (selector == RootElementSelector.getInstance())\n\t\t\t{\n\t\t\t\treturn isRootNode() ? this : null;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn getChild(selector);\n\t\t\t}\n\t\t}\n\t\telse if (selectors.size() > 1)\n\t\t{\n\t\t\tfinal DiffNode child;\n\t\t\tif (selector == RootElementSelector.getInstance())\n\t\t\t{\n\t\t\t\tchild = isRootNode() ? this : null;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchild = getChild(selector);\n\t\t\t}\n\t\t\tif (child != null)\n\t\t\t{\n\t\t\t\treturn child.getChild(selectors.subList(1, selectors.size()));\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Adds a child to this node and sets this node as its parent node.\n\t *\n\t * @param node The node to add.\n\t */\n\tpublic void addChild(final DiffNode node)\n\t{\n\t\tif (node == this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add a node to itself. \" +\n\t\t\t\t\t\"This would cause inifite loops and must never happen.\");\n\t\t}\n\t\telse if (node.isRootNode())\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add root node as child. \" +\n\t\t\t\t\t\"This is not allowed and must be a mistake.\");\n\t\t}\n\t\telse if (node.getParentNode() != null && node.getParentNode() != this)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"Detected attempt to add child node that is already the \" +\n\t\t\t\t\t\"child of another node. Adding nodes multiple times is not allowed, since it could \" +\n\t\t\t\t\t\"cause infinite loops.\");\n\t\t}\n\t\tif (node.getParentNode() == null)\n\t\t{\n\t\t\tnode.setParentNode(this);\n\t\t}\n\t\tchildren.put(node.getElementSelector(), node);\n\t\tif (state == State.UNTOUCHED && node.hasChanges())\n\t\t{\n\t\t\tstate = State.CHANGED;\n\t\t}\n\t}\n\n\t/**\n\t * Visit this and all child nodes.\n\t *\n\t * @param visitor The visitor to use.\n\t */\n\tpublic final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}\n\n\tprotected final void visit(final Visitor visitor, final Visit visit)\n\t{\n\t\ttry\n\t\t{\n\t\t\tvisitor.node(this, visit);\n\t\t}\n\t\tcatch (final StopVisitationException e)\n\t\t{\n\t\t\tvisit.stop();\n\t\t}\n\t\tif (visit.isAllowedToGoDeeper() && hasChildren())\n\t\t{\n\t\t\tvisitChildren(visitor);\n\t\t}\n\t\tif (visit.isStopped())\n\t\t{\n\t\t\tthrow new StopVisitationException();\n\t\t}\n\t}\n\n\t/**\n\t * Visit all child nodes but not this one.\n\t *\n\t * @param visitor The visitor to use.\n\t */\n\tpublic final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic final void visitParents(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\tif (parentNode != null)\n\t\t{\n\t\t\tvisitor.node(parentNode, visit);\n\t\t\tif (!visit.isStopped())\n\t\t\t{\n\t\t\t\tparentNode.visitParents(visitor);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * If this node represents a bean property this method returns all annotations of its field.\n\t * <p/>\n\t * Only works for fields having a name that matches the name derived from the getter.\n\t *\n\t * @return The annotations of the field, or an empty set if there is no field with the name derived from the getter.\n\t */\n\tpublic Set<Annotation> getFieldAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getFieldAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}\n\n\t/**\n\t * @param annotationClass the annotation we are looking for\n\t * @param <T>\n\t * @return The given annotation of the field, or null if not annotated or if there is no field with the name derived\n\t * from the getter.\n\t */\n\tpublic <T extends Annotation> T getFieldAnnotation(final Class<T> annotationClass)\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn ((PropertyAwareAccessor) accessor).getFieldAnnotation(annotationClass);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * If this node represents a bean property this method returns all annotations of its getter.\n\t *\n\t * @return A set of annotations of this nodes property getter or an empty set.\n\t */\n\tpublic Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}\n\n\tpublic <T extends Annotation> T getPropertyAnnotation(final Class<T> annotationClass)\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn ((PropertyAwareAccessor) accessor).getReadMethodAnnotation(annotationClass);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * If this node represents a bean property, this method will simply return its name. Otherwise it will return the\n\t * property name of its closest bean property representing ancestor. This way intermediate nodes like those\n\t * representing collection, map or array items will be semantically tied to their container objects.\n\t * <p/>\n\t * That is especially useful for inclusion and exclusion rules. For example, when a List is explicitly included by\n\t * property name, it would be weird if the inclusion didn't also apply to its items.\n\t */\n\tpublic String getPropertyName()\n\t{\n\t\tif (isPropertyAware())\n\t\t{\n\t\t\treturn ((PropertyAwareAccessor) accessor).getPropertyName();\n\t\t}\n\t\telse if (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getPropertyName();\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns <code>true</code> when this node represents a bean property and can therefore be queried for property\n\t * specific information like annotations or property types. But there will also be nodes that represent collection\n\t * items, map entries, etc. In those cases this method will return <code>false</code>.\n\t */\n\tpublic final boolean isPropertyAware()\n\t{\n\t\treturn accessor instanceof PropertyAwareAccessor;\n\t}\n\n\tpublic final boolean isRootNode()\n\t{\n\t\treturn accessor instanceof RootAccessor;\n\t}\n\n\t/**\n\t * Convenience method for <code>{@link #getState()} == {@link DiffNode.State#IGNORED}</code>\n\t */\n\tpublic final boolean isIgnored()\n\t{\n\t\treturn state == State.IGNORED;\n\t}\n\n\t/**\n\t * @see de.danielbechler.diff.inclusion.TypePropertyAnnotationInclusionResolver\n\t * @deprecated This method was a shortcut to extract the \"exclude\" flag from the ObjectDiffProperty\n\t * annotation. Since we found a better way to do that, it is not needed anymore and will be removed in future\n\t * versions. The name is also misleading. It implies that here lies the truth about the exclusion, but only the\n\t * InclusionService can tell for sure. This flag is just only little piece of the puzzle.\n\t */\n\t@Deprecated\n\tpublic boolean isExcluded()\n\t{\n\t\tif (accessor instanceof ExclusionAware)\n\t\t{\n\t\t\treturn ((ExclusionAware) accessor).isExcludedByAnnotation();\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns an unmodifiable {@link java.util.Set} of {@link java.lang.String} with the categories of this node.\n\t *\n\t * @return an unmodifiable {@link java.util.Set} of {@link java.lang.String} with the categories of this node\n\t */\n\tpublic final Set<String> getCategories()\n\t{\n\t\tfinal Set<String> categories = new TreeSet<String>();\n\t\tif (parentNode != null)\n\t\t{\n\t\t\tcategories.addAll(parentNode.getCategories());\n\t\t}\n\t\tif (accessor instanceof CategoryAware)\n\t\t{\n\t\t\tfinal Set<String> categoriesFromAccessor = ((CategoryAware) accessor).getCategoriesFromAnnotation();\n\t\t\tif (categoriesFromAccessor != null)\n\t\t\t{\n\t\t\t\tcategories.addAll(categoriesFromAccessor);\n\t\t\t}\n\t\t}\n\t\tcategories.addAll(additionalCategories);\n\n\t\treturn unmodifiableSet(categories);\n\t}\n\n\t/**\n\t * @return The parent node, if any.\n\t */\n\tpublic DiffNode getParentNode()\n\t{\n\t\treturn parentNode;\n\t}\n\n\t/**\n\t * Sets the parent node.\n\t *\n\t * @param parentNode The parent of this node. May be null, if this is a root node.\n\t */\n\tprotected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}\n\n\tpublic Object get(final Object target)\n\t{\n\t\treturn accessor.get(target);\n\t}\n\n\tpublic void set(final Object target, final Object value)\n\t{\n\t\taccessor.set(target, value);\n\t}\n\n\tpublic void unset(final Object target)\n\t{\n\t\taccessor.unset(target);\n\t}\n\n\tpublic Object canonicalGet(Object target)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\ttarget = parentNode.canonicalGet(target);\n\t\t}\n\t\treturn get(target);\n\t}\n\n\tpublic void canonicalSet(Object target, final Object value)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\tObject parent = parentNode.canonicalGet(target);\n\t\t\tif (parent == null)\n\t\t\t{\n\t\t\t\tparent = parentNode.newInstance();\n\t\t\t\tparentNode.canonicalSet(target, parent);\n\t\t\t}\n\t\t\ttarget = parent;\n\t\t}\n\t\tset(target, value);\n\t}\n\n\tprivate Object newInstance()\n\t{\n\t\tif (valueTypeInfo != null)\n\t\t{\n\t\t\treturn valueTypeInfo.newInstance();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void canonicalUnset(Object target)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\ttarget = parentNode.canonicalGet(target);\n\t\t}\n\t\tunset(target);\n\t}\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn accessor.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object o)\n\t{\n\t\tif (this == o)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal DiffNode that = (DiffNode) o;\n\n\t\tif (!accessor.equals(that.accessor))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString()\n\t{\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(getClass().getSimpleName());\n\t\tsb.append(\"(\");\n\t\tsb.append(\"state=\");\n\t\tsb.append(getState().toString());\n\t\tif (getValueType() != null)\n\t\t{\n\t\t\tsb.append(\", type=\").append(getValueType().getCanonicalName());\n\t\t}\n\t\tif (childCount() == 1)\n\t\t{\n\t\t\tsb.append(\", \").append(childCount()).append(\" child\");\n\t\t}\n\t\telse if (childCount() > 1)\n\t\t{\n\t\t\tsb.append(\", \").append(childCount()).append(\" children\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsb.append(\", no children\");\n\t\t}\n\t\tif (!getCategories().isEmpty())\n\t\t{\n\t\t\tsb.append(\", categorized as \").append(getCategories());\n\t\t}\n\t\tsb.append(\", accessed via \").append(accessor);\n\t\tsb.append(')');\n\t\treturn sb.toString();\n\t}\n\n\tpublic void addCategories(final Collection<String> additionalCategories)\n\t{\n\t\tAssert.notNull(additionalCategories, \"additionalCategories\");\n\t\tthis.additionalCategories.addAll(additionalCategories);\n\t}\n\n\t/**\n\t * @return Returns the path to the first node in the hierarchy that represents the same object instance as\n\t * this one. (Only if {@link #isCircular()} returns <code>true</code>.\n\t */\n\tpublic NodePath getCircleStartPath()\n\t{\n\t\treturn circleStartPath;\n\t}\n\n\tpublic void setCircleStartPath(final NodePath circularStartPath)\n\t{\n\t\tthis.circleStartPath = circularStartPath;\n\t}\n\n\tpublic DiffNode getCircleStartNode()\n\t{\n\t\treturn circleStartNode;\n\t}\n\n\tpublic void setCircleStartNode(final DiffNode circleStartNode)\n\t{\n\t\tthis.circleStartNode = circleStartNode;\n\t}\n\n\t/**\n\t * The state of a {@link DiffNode} representing the difference between two objects.\n\t */\n\tpublic enum State\n\t{\n\t\tADDED(\"The value has been added to the working object\"),\n\t\tCHANGED(\"The value exists but differs between the base and working object\"),\n\t\tREMOVED(\"The value has been removed from the working object\"),\n\t\tUNTOUCHED(\"The value is identical in the working and base object\"),\n\t\tCIRCULAR(\"Special state to mark circular references\"),\n\t\tIGNORED(\"The value has not been looked at and has been ignored\"),\n\t\tINACCESSIBLE(\"When a comparison was not possible because the underlying value was not accessible\");\n\n\t\tprivate final String reason;\n\n\t\tState(final String reason)\n\t\t{\n\t\t\tthis.reason = reason;\n\t\t}\n\n\t\tpublic String getReason()\n\t\t{\n\t\t\treturn reason;\n\t\t}\n\t}\n\n\t/**\n\t * Visitor to traverse a node graph.\n\t */\n\tpublic interface Visitor\n\t{\n\t\tvoid node(DiffNode node, Visit visit);\n\t}\n}" ]
import de.danielbechler.diff.category.CategoryResolver; import de.danielbechler.diff.comparison.ComparisonStrategy; import de.danielbechler.diff.comparison.ComparisonStrategyResolver; import de.danielbechler.diff.comparison.PrimitiveDefaultValueMode; import de.danielbechler.diff.comparison.PrimitiveDefaultValueModeResolver; import de.danielbechler.diff.filtering.IsReturnableResolver; import de.danielbechler.diff.inclusion.IsIgnoredResolver; import de.danielbechler.diff.introspection.IsIntrospectableResolver; import de.danielbechler.diff.node.DiffNode; import java.util.Set;
/* * Copyright 2016 Daniel Bechler * * 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 de.danielbechler.diff; class DefaultNodeQueryService implements NodeQueryService { private final CategoryResolver categoryResolver; private final IsIntrospectableResolver introspectableResolver; private final IsIgnoredResolver ignoredResolver; private final IsReturnableResolver returnableResolver;
private final ComparisonStrategyResolver comparisonStrategyResolver;
2
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/spring/boot/config/J2CacheAutoConfig.java
[ "@Data\npublic class CacheConfig {\n\n /**\n * 缓存提供者 可选\n * <p>\n * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider\n * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider\n * <p>\n * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展\n */\n private List<String> providerClassList = new ArrayList<>();\n\n private String cacheSerializerClass = \"com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer\";\n\n /**\n * 自动加载的线程数\n */\n private int autoLoadThreadCount = 5;\n\n // 具体的缓存中间件相关配置\n\n private String redisMode = CacheConst.REDIS_MODE_SINGLE;\n\n private LettuceConfig lettuceConfig = new LettuceConfig();\n\n private NotifyConfig notifyConfig = new NotifyConfig();\n\n private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>();\n\n @Data\n public static class CaffeineConfig {\n\n private int size = 10_000;\n private int expire = 0;\n\n }\n\n @Data\n public static class NotifyConfig {\n\n private String notifyClass = \"com.jayqqaa12.jbase.cache.notify.NullNotify\";\n private String notifyTopic = CacheConst.DEFAULT_TOPIC;\n\n private String host;\n private String groupId = CacheConst.DEFAULT_TOPIC;\n\n\n }\n\n\n @Data\n public class LettuceConfig {\n\n /**\n * 命名空间 可以用来区分不同 项目\n */\n private String namespace = CacheConst.NAMESPACE;\n /**\n * single 单点 cluster 集群\n */\n private String schema = CacheConst.REDIS_MODE_SINGLE;\n private String hosts = \"127.0.0.1:6379\";\n private String password = \"\";\n private int database = 0;\n private int maxTotal = 100;\n private int maxIdle = 10;\n private int minIdle = 10;\n private int timeout = 10000;\n private int clusterTopologyRefresh = 3000;\n\n\n }\n\n\n}", "@Slf4j\n@Data\npublic class JbaseCache {\n\n private CacheProviderGroup provider;\n\n private Notify notify;\n\n private AutoLoadSchedule autoLoadSchdule;\n\n private JbaseCache() {\n\n }\n\n\n public static JbaseCache build(CacheConfig cacheConfig) {\n JbaseCache cache = new JbaseCache();\n cache.provider = new CacheProviderGroup(cacheConfig);\n cache.autoLoadSchdule = new AutoLoadSchedule(cacheConfig.getAutoLoadThreadCount(), cache);\n\n try {\n cache.notify = (Notify) Class.forName(cacheConfig.getNotifyConfig().getNotifyClass()).newInstance();\n cache.notify.init(cacheConfig, cache);\n } catch (Exception e) {\n throw new CacheException(\"nonexistent notify class \");\n }\n\n return cache;\n }\n\n\n public void stop() {\n provider.stop();\n notify.stop();\n autoLoadSchdule.shutdown();\n }\n\n\n public <T> T get(String region, String key, Supplier<Object> function)\n throws CacheException {\n\n return get(region, key, function, 0);\n }\n\n public <T> T get(String region, String key, Supplier<Object> function, int expire)\n throws CacheException {\n\n T obj = get(region, key);\n// 有数据就直接返回\n if (obj != null) {\n return obj;\n }\n\n try {\n LockKit.getLock(region, key).lock();\n obj = get(region, key);\n // double check\n if (obj != null) {\n return obj;\n }\n\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n Object value = function.get();\n set(region, key, value, expire);\n\n stopWatch.stop();\n log.info(\"get from load data by data source key= {}@{} cost time={}ms \", key, region, stopWatch.getTime());\n //添加auto load\n autoLoadSchdule.add(AutoLoadObject.builder()\n .key(key).region(region).expire(expire).function(function)\n .build());\n\n return (T) value;\n } finally {\n LockKit.returnLock(region, key);\n }\n }\n\n\n public <T> T get(String region, String key) throws CacheException {\n\n CacheObject<T> cacheObject = provider.getLevel1Provider(region).get(key);\n\n try {\n // 1级有数据就直接返回\n if (cacheObject != null) {\n\n log.debug(\"get data from level 1 key={}@{}\", region, key);\n return cacheObject.getValue();\n }\n\n LockKit.getLock(region, key).lock();\n // double check\n cacheObject = provider.getLevel1Provider(region).get(key);\n // 1级有数据就直接返回\n if (cacheObject != null) {\n log.debug(\"get data from level 1 key={}@{}\", region, key);\n return cacheObject.getValue();\n }\n\n //从2级获取数据\n cacheObject = provider.getLevel2Provider(region).get(key);\n //不为空写入1级缓存\n if (cacheObject != null) {\n provider.getLevel1Provider(region,cacheObject.getExpire()).set(key, cacheObject);\n log.debug(\"get data from level 2 key={}@{}\", region, key);\n return cacheObject.getValue();\n }\n } finally {\n autoLoadSchdule.refresh(region, key);\n LockKit.returnLock(region, key);\n }\n //如果为空就加载数据\n\n return null;\n }\n\n public void set(String region, String key, Object value) throws CacheException {\n set(region, key, value, 0);\n }\n\n public void set(String region, String key, Object value, int expire) throws CacheException {\n\n CacheObject cacheObject = CacheObject.builder()\n .key(key).region(region)\n .loadTime(System.currentTimeMillis())\n .value(value).build();\n\n provider.getLevel1Provider(region, expire).set(key, cacheObject, expire);\n provider.getLevel2Provider(region, expire).set(key, cacheObject, expire);\n\n //notify other\n notify.send(new Command(Command.OPT_EVICT_KEY, region, key));\n }\n\n public void delete(String region, String key) throws CacheException {\n\n provider.getLevel1Provider(region).delete(key);\n provider.getLevel2Provider(region).delete(key);\n\n //notify other\n notify.send(new Command(Command.OPT_CLEAR_KEY, region, key));\n }\n\n\n public void handlerCommand(Command command) {\n if (command.isLocal()) {\n return;\n }\n \n provider.getLevel1Provider(command.getRegion())\n .delete(command.getKeys());\n\n switch (command.getOperator()) {\n case Command.OPT_CLEAR_KEY:\n \n autoLoadSchdule.remove(command.getRegion(), command.getKeys());\n\n case Command.OPT_EVICT_KEY:\n\n CacheObject cacheObject = provider.getLevel2Provider(command.getRegion())\n .get(command.getKeys());\n\n //如果不是快过期的数据就放入一级缓存\n if (cacheObject != null&& !cacheObject.canAutoLoad()) {\n provider.getLevel1Provider(command.getRegion(),cacheObject.getExpire())\n .set(command.getKeys(), cacheObject, cacheObject.getExpire());\n\n log.debug(\"receive OPT_EVICT_KEY reload level1 cache from level 2 key={}@{} \",\n command.getKeys(), command.getRegion());\n }\n\n break;\n\n }\n }\n\n}", "public class CaffeineCacheProvider implements CacheProvider {\n\n private CacheConfig cacheConfig;\n\n private Map<String, Cache> cacheMap = new HashMap<>();\n private CaffeineConfig defualtConfig = new CaffeineConfig();\n\n @Override\n public void init(CacheConfig cacheConfig) {\n\n this.cacheConfig = cacheConfig;\n\n this.defualtConfig.setSize(10000);\n this.defualtConfig.setExpire(60 * 30);\n\n }\n\n @Override\n public Cache\n buildCache(String region, int expire) {\n CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig);\n\n return newCache(region, config.getSize(), expire);\n }\n\n private Cache newCache(String region, int size, int expire) {\n return cacheMap.computeIfAbsent(region, v -> {\n Caffeine<Object, Object> caffeine = Caffeine.newBuilder();\n\n caffeine = caffeine.maximumSize(size);\n if (expire > 0) {\n caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS);\n }\n\n com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build();\n return new CaffeineCache(loadingCache);\n });\n }\n\n @Override\n public Cache buildCache(String region) {\n CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig);\n return newCache(region, config.getSize(), config.getExpire());\n }\n\n\n @Override\n public void stop() {\n cacheMap.clear();\n }\n}", "@Slf4j\npublic class LettuceCacheProvider implements CacheProvider {\n\n private static AbstractRedisClient redisClient;\n private GenericObjectPool<StatefulConnection<String, byte[]>> pool;\n\n private LettuceByteCodec codec = new LettuceByteCodec();\n\n private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>();\n private CacheConfig cacheConfig;\n\n @Override\n public void init(CacheConfig cacheConfig) {\n this.cacheConfig = cacheConfig;\n\n String hosts = cacheConfig.getLettuceConfig().getHosts();\n\n int database = cacheConfig.getLettuceConfig().getDatabase();\n String password = cacheConfig.getLettuceConfig().getPassword();\n\n int clusterTopologyRefresh = cacheConfig.getLettuceConfig().getClusterTopologyRefresh();\n\n if (REDIS_MODE_CLUSTER.equalsIgnoreCase(cacheConfig.getLettuceConfig().getSchema())) {\n List<RedisURI> redisURIs = new ArrayList<>();\n String[] hostArray = hosts.split(\",\");\n for (String host : hostArray) {\n String[] redisArray = host.split(\":\");\n RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1]));\n uri.setDatabase(database);\n uri.setPassword(password);\n// uri.setSentinelMasterId(sentinelMasterId);\n redisURIs.add(uri);\n }\n redisClient = RedisClusterClient.create(redisURIs);\n ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()\n //开启自适应刷新\n .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT,\n ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS)\n .enableAllAdaptiveRefreshTriggers()\n .adaptiveRefreshTriggersTimeout(Duration.ofMillis(clusterTopologyRefresh))\n //开启定时刷新,时间间隔根据实际情况修改\n .enablePeriodicRefresh(Duration.ofMillis(clusterTopologyRefresh))\n .build();\n ((RedisClusterClient) redisClient).setOptions(\n ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build());\n } else {\n String[] redisArray = hosts.split(\":\");\n RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1]));\n uri.setDatabase(database);\n uri.setPassword(password);\n redisClient = RedisClient.create(uri);\n }\n\n try {\n redisClient.setDefaultTimeout(Duration.ofMillis(cacheConfig.getLettuceConfig().getTimeout()));\n } catch (Exception e) {\n log.warn(\"Failed to set default timeout, using default 10000 milliseconds.\", e);\n }\n\n //connection pool configurations\n GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();\n poolConfig.setMaxTotal(cacheConfig.getLettuceConfig().getMaxTotal());\n poolConfig.setMaxIdle(cacheConfig.getLettuceConfig().getMaxIdle());\n poolConfig.setMinIdle(cacheConfig.getLettuceConfig().getMinIdle());\n\n pool = ConnectionPoolSupport.createGenericObjectPool(() -> {\n if (redisClient instanceof RedisClient) {\n return ((RedisClient) redisClient).connect(codec);\n } else if (redisClient instanceof RedisClusterClient) {\n return ((RedisClusterClient) redisClient).connect(codec);\n }\n return null;\n }, poolConfig);\n\n }\n\n @Override\n public Cache buildCache(String region, int expire) throws CacheException {\n return buildCache(region);\n }\n\n @Override\n public Cache buildCache(String region) throws CacheException {\n\n try {\n\n CacheSerializer cacheSerializer = (CacheSerializer) Class\n .forName(cacheConfig.getCacheSerializerClass()).newInstance();\n String namespace = this.cacheConfig.getLettuceConfig().getNamespace();\n\n return regions\n .computeIfAbsent(namespace + \":\" + region,\n k -> new LettuceCache(cacheSerializer, namespace, region, pool));\n }catch (Exception e){\n throw new CacheException(e);\n }\n\n }\n\n @Override\n public void stop() {\n\n pool.close();\n regions.clear();\n redisClient.shutdown();\n\n }\n}", "public class SpelKeyGenerator {\n\n private static final ExpressionParser parser = new SpelExpressionParser();\n private static final ConcurrentHashMap<String, Expression> expCache = new ConcurrentHashMap<>();\n\n /**\n *\n */\n public static String buildKey(String key, JoinPoint invocation) throws NoSuchMethodException {\n\n if (key.indexOf(\"#\") == -1) {// 如果不是表达式,直接返回字符串\n return key;\n }\n\n String keySpEL = \"\";\n String pre = \"\";\n String str[] = key.split(\"\\\\#\");\n if (str.length > 1) {\n pre = str[0];\n for (int i = 1; i < str.length; i++) {\n keySpEL = keySpEL + \"#\" + str[i];\n }\n } else {\n keySpEL = key;\n }\n\n MethodSignature signature = (MethodSignature) invocation.getSignature();\n Method method = signature.getMethod();\n Class<?>[] parameterTypes = method.getParameterTypes();\n ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();\n String[] parameterNames = parameterNameDiscoverer.getParameterNames(\n invocation.getTarget().getClass().getDeclaredMethod(method.getName(), parameterTypes));\n StandardEvaluationContext context = new StandardEvaluationContext();\n\n for (int i = 0; i < parameterNames.length; i++) {\n context.setVariable(parameterNames[i], invocation.getArgs()[i]);\n }\n\n Expression expression = expCache.get(keySpEL);\n if (null == expression) {\n expression = parser.parseExpression(keySpEL);\n expCache.put(keySpEL, expression);\n }\n\n String value = expression.getValue(context, String.class);\n\n if (!StringUtils.isEmpty(pre)) {\n return pre + value;\n } else {\n return value;\n }\n\n }\n}", "@Aspect\n@Service\npublic class CacheAspect {\n\n @Autowired\n private JbaseCache j2Cache;\n\n\n @Around(\"@annotation(cache)\")\n public Object interceptor(ProceedingJoinPoint invocation, Cache cache) throws Throwable {\n String region = StringUtils.isEmpty(cache.region()) ? null : cache.region();\n String key = SpelKeyGenerator.buildKey(cache.key(), invocation);\n Object result = j2Cache.get(region, key);\n if (result == null) {\n result = invocation.proceed();\n j2Cache.set(region, key, result, cache.expire());\n }\n\n if (cache.autoLoad()) {\n //添加auto load\n j2Cache.getAutoLoadSchdule().add(AutoLoadObject.builder()\n .key(key).region(region).expire(cache.expire())\n .function(rethrowSupplier(() -> invocation.proceed()))\n .build());\n }\n\n return result;\n }\n\n\n}", "@Aspect\n@Service\n@Slf4j\npublic class CacheClearArrayAspect {\n\n\n @Autowired\n private JbaseCache j2Cache;\n\n\n /**\n * 清除缓存在DB操作前\n * <p>\n * 防止DB操作成功缓存更新失败\n * <p>\n * 如果为了一致性完成操作后再清除一次\n */\n @Around(\"@annotation(cacheClears)\")\n public Object interceptor(ProceedingJoinPoint invocation, CacheClearArray cacheClears)\n throws Throwable {\n\n for (CacheClear cacheClear : cacheClears.value()) {\n String region = StringUtils.isEmpty(cacheClear.region()) ? null : cacheClear.region();\n String key = SpelKeyGenerator.buildKey(cacheClear.key(), invocation);\n j2Cache.delete(region, key);\n\n if (key.contains(\"null\")) {\n log.error(\"cache remove but key is null key={},method={}\", key, invocation.toString());\n }\n }\n\n Object rest = invocation.proceed();\n for (CacheClear cacheClear : cacheClears.value()) {\n String region = StringUtils.isEmpty(cacheClear.region()) ? null : cacheClear.region();\n String key = SpelKeyGenerator.buildKey(cacheClear.key(), invocation);\n j2Cache.delete(region, key);\n\n if (key.contains(\"null\")) {\n log.error(\"cache remove but key is null key={},method={}\", key, invocation.toString());\n }\n }\n\n return rest;\n\n }\n\n\n}", "@Aspect\n@Service\n@Slf4j\npublic class CacheClearAspect {\n\n @Autowired\n private JbaseCache j2Cache;\n\n\n /**\n * 清除缓存在DB操作前\n * <p>\n * 防止DB操作成功缓存更新失败\n * <p>\n * 如果为了一致性完成操作后再清除一次\n *\n * @param invocation\n * @param cacheClear\n * @throws Throwable\n */\n @Around(\"@annotation(cacheClear)\")\n public Object interceptor(ProceedingJoinPoint invocation, CacheClear cacheClear) throws Throwable {\n String region = StringUtils.isEmpty(cacheClear.region()) ? null : cacheClear.region();\n String key = SpelKeyGenerator.buildKey(cacheClear.key(), invocation);\n\n j2Cache.delete(region, key);\n Object result = invocation.proceed();\n j2Cache.delete(region, key);\n\n\n if (key.toString().contains(\"null\")) {\n log.info(\"cache remove but key is null key={},method={}\",key,invocation.toString());\n }\n\n return result;\n\n }\n\n\n}" ]
import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.JbaseCache; import com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider; import com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider; import com.jayqqaa12.jbase.cache.spring.aspect.SpelKeyGenerator; import com.jayqqaa12.jbase.cache.spring.aspect.CacheAspect; import com.jayqqaa12.jbase.cache.spring.aspect.CacheClearArrayAspect; import com.jayqqaa12.jbase.cache.spring.aspect.CacheClearAspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.*;
package com.jayqqaa12.jbase.cache.spring.boot.config; /** * 使用方式 定义CacheConfig并配置来进行使用 * * Created by 12 on 2017/9/20. */ @Configuration @EnableConfigurationProperties({SpringBootRedisConfig.class}) @EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true) @Import({
CacheAspect.class,
5
mmlevin/secu3droid
secu3droid/src/org/secu3/android/DiagnosticsActivity.java
[ "public class ProtoFieldInteger extends BaseProtoField implements Parcelable {\n\tprivate int value;\n\tprivate int multiplier;\n\tprivate boolean signed;\n\n\t@Override\n\tpublic void writeToParcel(Parcel dest, int flags) {\n\t\tsuper.writeToParcel(dest, flags);\n\t\tdest.writeInt(value);\n\t\tdest.writeInt(multiplier);\n\t\tdest.writeInt(signed ? 1 : 0);\n\t}\n\n\tpublic static final Parcelable.Creator<ProtoFieldInteger> CREATOR = new Parcelable.Creator<ProtoFieldInteger>() {\n\t\tpublic ProtoFieldInteger createFromParcel(Parcel in) {\n\t\t\treturn new ProtoFieldInteger(in);\n\t\t}\n\n\t\tpublic ProtoFieldInteger[] newArray(int size) {\n\t\t\treturn new ProtoFieldInteger[size];\n\t\t}\n\t};\n\n\tpublic ProtoFieldInteger(Parcel in) {\n\t\tsuper(in);\n\t\tvalue = in.readInt();\n\t\tmultiplier = in.readInt();\n\t\tsigned = in.readInt() != 0;\n\t}\n\n\tpublic ProtoFieldInteger(ProtoFieldInteger field) {\n\t\tsuper(field);\n\t\tif (field != null) {\n\t\t\tthis.value = field.value;\n\t\t\tthis.multiplier = field.multiplier;\n\t\t\tthis.signed = field.signed;\n\t\t}\n\t}\n\n\tpublic ProtoFieldInteger(Context context, int nameId, int type,\n\t\t\tboolean signed, boolean binary) {\n\t\tvalue = 0;\n\t\tsetData(null);\n\n\t\tsetNameId(nameId);\n\t\tsetType(type);\n\t\tsetSigned(signed);\n\t\tsetMultiplier(1);\n\t\tsetBinary(binary);\n\t\tif (nameId != 0)\n\t\t\tthis.setName(context.getString(nameId));\n\n\t\tswitch (type) {\n\t\tcase R.id.field_type_int4:\n\t\t\tsetLength(1);\n\t\t\tbreak;\n\t\tcase R.id.field_type_int8:\n\t\t\tsetLength(isBinary() ? 1 : 2);\n\t\t\tbreak;\n\t\tcase R.id.field_type_int16:\n\t\t\tsetLength(isBinary() ? 2 : 4);\n\t\t\tbreak;\n\t\tcase R.id.field_type_int24:\n\t\t\tsetLength(isBinary() ? 3 : 6);\n\t\t\tbreak;\n\t\tcase R.id.field_type_int32:\n\t\t\tsetLength(isBinary() ? 4 : 8);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsetLength(0);\n\t\t}\n\t}\n\n\tpublic int getValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(int value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic boolean isSigned() {\n\t\treturn signed;\n\t}\n\n\tpublic void setSigned(boolean signed) {\n\t\tthis.signed = signed;\n\t}\n\n\t@Override\n\tpublic void setData(String data) {\n\t\tsuper.setData(data);\n\t\tif (data != null) {\n\t\t\tint v = 0;\n\t\t\tif (isBinary())\n\t\t\t\tv = BinToInt(data);\n\t\t\tif (signed) {\n\t\t\t\tswitch (getType()) {\n\t\t\t\tcase R.id.field_type_int4:\n\t\t\t\tcase R.id.field_type_int24:\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"No rules for converting 4/24-bit value into a signed number\");\n\t\t\t\tcase R.id.field_type_int8:\n\t\t\t\t\tif (isBinary())\n\t\t\t\t\t\tv = Integer.valueOf(v).byteValue();\n\t\t\t\t\telse\n\t\t\t\t\t\tv = Integer.valueOf(data, 16).byteValue();\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.id.field_type_int16:\n\t\t\t\t\tif (isBinary())\n\t\t\t\t\t\tv = Integer.valueOf(v).shortValue();\n\t\t\t\t\telse\n\t\t\t\t\t\tv = Integer.valueOf(data, 16).shortValue();\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.id.field_type_int32:\n\t\t\t\t\tif (isBinary())\n\t\t\t\t\t\tv = Long.valueOf(v).intValue();\n\t\t\t\t\telse\n\t\t\t\t\t\tv = Long.valueOf(data, 16).intValue();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!isBinary())\n\t\t\t\t\tv = Integer.parseInt(data, 16);\n\t\t\t}\n\t\t\tsetValue(v * multiplier);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void pack() {\n\t\tint v = value / multiplier;\n\t\tswitch (getType()) {\n\t\tcase R.id.field_type_int4:\n\t\t\tif (signed)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"No rules for converting 4/24-bit value into a signed number\");\n\t\t\tif (!isBinary())\n\t\t\t\tsetData(String.format(\"%01X\", v));\n\t\t\tbreak;\n\t\tcase R.id.field_type_int8:\n\t\t\tif (signed)\n\t\t\t\tv = Integer.valueOf(v).byteValue();\n\t\t\tif (!isBinary())\n\t\t\t\tsetData(String.format(\"%02X\", (byte)v));\n\t\t\tbreak;\n\t\tcase R.id.field_type_int16:\n\t\t\tif (signed)\n\t\t\t\tv = Integer.valueOf(v).shortValue();\n\t\t\tif (!isBinary())\n\t\t\t\tsetData(String.format(\"%04X\", (short)v));\n\t\t\tbreak;\n\t\tcase R.id.field_type_int24:\n\t\t\tif (signed)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"No rules for converting 4/24-bit value into a signed number\");\n\t\t\tif (!isBinary())\n\t\t\t\tsetData(String.format(\"%06X\", v));\n\t\t\tbreak;\n\t\tcase R.id.field_type_int32:\n\t\t\tif (signed)\n\t\t\t\tv = Long.valueOf(v).intValue();\n\t\t\tif (!isBinary())\n\t\t\t\tsetData(String.format(\"%08X\", v));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tif (isBinary())\n\t\t\tsetData(IntToBin(v));\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\tthis.value = 0;\n\t}\n\n\tpublic int getMultiplier() {\n\t\treturn multiplier;\n\t}\n\n\tpublic void setMultiplier(int multiplier) {\n\t\tthis.multiplier = multiplier;\n\t}\n}", "public class Secu3Packet implements Parcelable {\n\tpublic final static int INPUT_TYPE = R.string.packet_dir_input;\n\tpublic final static int OUTPUT_TYPE = R.string.packet_dir_output;\n\n\tpublic final static int INPUT_OUTPUT_POS = 0;\n\tpublic final static int PACKET_ID_POS = 1;\n\n\tpublic final static int SECUR_USE_BT_FLAG = 1;\n\tpublic final static int SECUR_SET_BTBR_FLAG = 2;\n\tpublic final static int SECUR_USE_IMMO_FLAG = 4;\n\n\tpublic final static int BITNUMBER_EPHH_VALVE = 0;\n\tpublic final static int BITNUMBER_CARB = 1;\n\tpublic final static int BITNUMBER_GAS = 2;\n\tpublic final static int BITNUMBER_EPM_VALVE = 3;\n\tpublic final static int BITNUMBER_CE_STATE = 4;\n\tpublic final static int BITNUMBER_COOL_FAN = 5;\n\tpublic final static int BITNUMBER_ST_BLOCK = 6;\n\n\tpublic static final int COPT_ATMEGA16 = 0;\n\tpublic static final int COPT_ATMEGA32 = 1;\n\tpublic static final int COPT_ATMEGA64 = 2;\n\tpublic static final int COPT_ATMEGA128 = 3;\n\tpublic static final int COPT_VPSEM = 4;\n\tpublic static final int COPT_WHEEL_36_1 = 5; /*\n\t\t\t\t\t\t\t\t\t\t\t\t * Obsolete! Left for\n\t\t\t\t\t\t\t\t\t\t\t\t * compatibility reasons\n\t\t\t\t\t\t\t\t\t\t\t\t */\n\tpublic static final int COPT_INVERSE_IGN_OUTPUTS = 6; /*\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Obsolete! Left for\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t * compatibility reasons\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n\tpublic static final int COPT_DWELL_CONTROL = 7;\n\tpublic static final int COPT_COOLINGFAN_PWM = 8;\n\tpublic static final int COPT_REALTIME_TABLES = 9;\n\tpublic static final int COPT_ICCAVR_COMPILER = 10;\n\tpublic static final int COPT_AVRGCC_COMPILER = 11;\n\tpublic static final int COPT_DEBUG_VARIABLES = 12;\n\tpublic static final int COPT_PHASE_SENSOR = 13;\n\tpublic static final int COPT_PHASED_IGNITION = 14;\n\tpublic static final int COPT_FUEL_PUMP = 15;\n\tpublic static final int COPT_THERMISTOR_CS = 16;\n\tpublic static final int COPT_SECU3T = 17;\n\tpublic static final int COPT_DIAGNOSTICS = 18;\n\tpublic static final int COPT_HALL_OUTPUT = 19;\n\tpublic static final int COPT_REV9_BOARD = 20;\n\tpublic static final int COPT_STROBOSCOPE = 21;\n\n\tpublic final static int SECU3_ECU_ERRORS_COUNT = 11;\n\n\tpublic final static int ETTS_GASOLINE_SET = 0; // tables's set: petrol\n\tpublic final static int ETTS_GAS_SET = 1; // tables's set: gas\n\n\tpublic final static int ETMT_STRT_MAP = 0; // start map\n\tpublic final static int ETMT_IDLE_MAP = 1; // idle map\n\tpublic final static int ETMT_WORK_MAP = 2; // work map\n\tpublic final static int ETMT_TEMP_MAP = 3; // temp.corr. map\n\tpublic final static int ETMT_NAME_STR = 4; // name of tables's set\n\n\tpublic static final String COPT[] = { \"COPT_ATMEGA16\", \"COPT_ATMEGA32\",\n\t\t\t\"COPT_ATMEGA64\", \"COPT_ATMEGA128\", \"COPT_VPSEM\", \"COPT_WHEEL_36_1\", /*\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Obsolete\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * !\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Left\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * for\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * compatibility\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * reasons\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n\t\t\t\"COPT_INVERSE_IGN_OUTPUTS\", /*\n\t\t\t\t\t\t\t\t\t\t * Obsolete! Left for compatibility\n\t\t\t\t\t\t\t\t\t\t * reasons\n\t\t\t\t\t\t\t\t\t\t */\n\t\t\t\"COPT_DWELL_CONTROL\", \"COPT_COOLINGFAN_PWM\",\n\t\t\t\"COPT_REALTIME_TABLES\", \"COPT_ICCAVR_COMPILER\",\n\t\t\t\"COPT_AVRGCC_COMPILER\", \"COPT_DEBUG_VARIABLES\",\n\t\t\t\"COPT_PHASE_SENSOR\", \"COPT_PHASED_IGNITION\", \"COPT_FUEL_PUMP\",\n\t\t\t\"COPT_THERMISTOR_CS\", \"COPT_SECU3T\", \"COPT_DIAGNOSTICS\",\n\t\t\t\"COPT_HALL_OUTPUT\", \"COPT_REV9_BOARD\", \"COPT_STROBOSCOPE\" };\n\n\tpublic final static int OPCODE_EEPROM_PARAM_SAVE = 1;\n\tpublic final static int OPCODE_CE_SAVE_ERRORS = 2;\n\tpublic final static int OPCODE_READ_FW_SIG_INFO = 3;\n\tpublic final static int OPCODE_LOAD_TABLSET = 4; // realtime tables\n\tpublic final static int OPCODE_SAVE_TABLSET = 5; // realtime tables\n\tpublic final static int OPCODE_DIAGNOST_ENTER = 6; // enter diagnostic mode\n\tpublic final static int OPCODE_DIAGNOST_LEAVE = 7; // leave diagnostic mode\n\n\tpublic final static int BAUD_RATE[] = { 2400, 4800, 9600, 14400, 19200,\n\t\t\t28800, 38400, 57600 };\n\tpublic final static int BAUD_RATE_INDEX[] = { 0x340, 0x1A0, 0xCF, 0x8A,\n\t\t\t0x67, 0x44, 0x33, 0x22 };\n\tpublic final static int INJECTOR_SQIRTS_PER_CYCLE[] = {1,2,4};\n\n\tpublic final static int INJCFG_TROTTLEBODY = 0;\n\tpublic final static int INJCFG_SIMULTANEOUS = 1;\n\tpublic final static int INJCFG_SEMISEQUENTIAL = 2;\n\tpublic final static int INJCFG_FULLSEQUENTIAL = 3;\n\n\t/** Вычисляет индекс элемента в масиве **/\n\tpublic static int indexOf(int array[], int search) {\n\t\tfor (int i = 0; i != array.length; i++)\n\t\t\tif (array[i] == search)\n\t\t\t\treturn i;\n\t\treturn -1;\n\t}\n\n\tpublic static int bitTest(int value, int bitNumber) {\n\t\tvalue >>= bitNumber;\n\t\treturn (value & 0x01);\n\t}\n\n\t// There are several special reserved symbols in binary mode: 0x21, 0x40,\n\t// 0x0D, 0x0A\n\tprivate final static int FIBEGIN = 0x21; // '!' indicates beginning of the\n\t\t\t\t\t\t\t\t\t\t\t\t// ingoing packet\n\tprivate final static int FOBEGIN = 0x40; // '@' indicates beginning of the\n\t\t\t\t\t\t\t\t\t\t\t\t// outgoing packet\n\tprivate final static int FIOEND = 0x0D; // '\\r' indicates ending of the\n\t\t\t\t\t\t\t\t\t\t\t// ingoing/outgoing packet\n\tprivate final static int FESC = 0x0A; // '\\n' Packet escape (FESC)\n\t// Following bytes are used only in escape sequeces and may appear in the\n\t// data without any problems\n\tprivate final static int TFIBEGIN = 0x81; // Transposed FIBEGIN\n\tprivate final static int TFOBEGIN = 0x82; // Transposed FOBEGIN\n\tprivate final static int TFIOEND = 0x83; // Transposed FIOEND\n\tprivate final static int TFESC = 0x84; // Transposed FESC\n\n\tprivate String EscTxPacket(String packetBuffer) {\n\t\tArrayList<Integer> buf = new ArrayList<>(\n\t\t\t\tpacketBuffer.length() - 3);\n\t\tfor (int i = 0; i != packetBuffer.length(); i++) {\n\t\t\tif ((i >= 2) && (i < packetBuffer.length()-1)) {\n\t\t\t\tif (packetBuffer.charAt(i) == FIBEGIN) {\n\t\t\t\t\tbuf.add(FESC);\n\t\t\t\t\tbuf.add(TFIBEGIN);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (packetBuffer.charAt(i) == FIOEND) {\n\t\t\t\t\tbuf.add(FESC);\n\t\t\t\t\tbuf.add(FIOEND);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (packetBuffer.charAt(i) == FESC) {\n\t\t\t\t\tbuf.add(FESC);\n\t\t\t\t\tbuf.add(TFESC);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuf.add((int) packetBuffer.charAt(i));\n\t\t}\n\t\tint[] outBuf = new int[buf.size()];\n\t\tfor (int i = 0; i != buf.size(); i++)\n\t\t\toutBuf[i] = buf.get(i);\n\t\treturn new String(outBuf, 0, outBuf.length);\n\t}\n\n\tpublic static int[] EscRxPacket(int[] packetBuffer) {\n\t\tint[] buf = new int[packetBuffer.length];\n\t\tboolean esc = false;\n\t\tint idx = 0;\n\t\tfor (int i = 0; i != packetBuffer.length; i++) {\n\t\t\tif ((packetBuffer[i] == FESC) && (i >= 2)) {\n\t\t\t\tesc = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (esc) {\n\t\t\t\tesc = false;\n\t\t\t\tif (packetBuffer[i] == TFOBEGIN)\n\t\t\t\t\tbuf[idx++] = FOBEGIN;\n\t\t\t\telse if (packetBuffer[i] == TFIOEND)\n\t\t\t\t\tbuf[idx++] = FIOEND;\n\t\t\t\telse if (packetBuffer[i] == TFESC)\n\t\t\t\t\tbuf[idx++] = FESC;\n\t\t\t} else\n\t\t\t\tbuf[idx++] = packetBuffer[i];\n\t\t}\n\t\treturn buf;\n\t}\n\n\tpublic int[] EscTxPacket(int[] packetBuffer) {\n\t\tArrayList<Integer> buf = new ArrayList<>(packetBuffer.length);\n\t\tfor (int i = 0; i != packetBuffer.length; i++) {\n\t\t\tif (packetBuffer[i] == FIBEGIN) {\n\t\t\t\tbuf.add(FESC);\n\t\t\t\tbuf.add(TFIBEGIN);\n\t\t\t} else if (packetBuffer[i] == FIOEND) {\n\t\t\t\tbuf.add(FESC);\n\t\t\t\tbuf.add(FIOEND);\n\t\t\t} else if (packetBuffer[i] == FESC) {\n\t\t\t\tbuf.add(FESC);\n\t\t\t\tbuf.add(TFESC);\n\t\t\t} else\n\t\t\t\tbuf.add(packetBuffer[i]);\n\t\t}\n\t\tint[] outBuf = new int[buf.size()];\n\t\tfor (int i = 0; i != buf.size(); i++)\n\t\t\toutBuf[i] = buf.get(i);\n\t\treturn outBuf;\n\t}\n\n\tprivate ArrayList<BaseProtoField> fields;\n\n\tprivate String name;\n\tprivate String packetId;\n\tprivate int packetIdResId;\n\tprivate int packetDirResId;\n\tprivate int nameId;\n\n\tprivate String input_type;\n\tprivate String output_type;\n\tprivate boolean binary;\n\tprivate String data;\n\n\tpublic static final Parcelable.Creator<Secu3Packet> CREATOR = new Parcelable.Creator<Secu3Packet>() {\n\t\tpublic Secu3Packet createFromParcel(Parcel in) {\n\t\t\treturn new Secu3Packet(in);\n\t\t}\n\n\t\tpublic Secu3Packet[] newArray(int size) {\n\t\t\treturn new Secu3Packet[size];\n\t\t}\n\t};\n\tpublic static final int MAX_PACKET_SIZE = 128;\n\n\tprivate Secu3Packet(Parcel in) {\n\t\tthis.name = in.readString();\n\t\tthis.packetId = in.readString();\n\t\tthis.packetIdResId = in.readInt();\n\t\tthis.packetDirResId = in.readInt();\n\t\tthis.nameId = in.readInt();\n\t\tthis.input_type = in.readString();\n\t\tthis.output_type = in.readString();\n\t\tthis.binary = in.readInt() != 0;\n\t\tthis.data = in.readString();\n\t\tint counter = in.readInt();\n\t\tthis.fields = (counter == 0) ? null : new ArrayList<BaseProtoField>();\n\t\tfor (int i = 0; i != counter; i++) {\n\t\t\tint type = in.readInt();\n\t\t\tswitch (type) {\n\t\t\tcase R.id.field_type_int4:\n\t\t\tcase R.id.field_type_int8:\n\t\t\tcase R.id.field_type_int16:\n\t\t\tcase R.id.field_type_int24:\n\t\t\tcase R.id.field_type_int32:\n\t\t\t\tthis.fields.add((BaseProtoField) in\n\t\t\t\t\t\t.readParcelable(ProtoFieldInteger.class\n\t\t\t\t\t\t\t\t.getClassLoader()));\n\t\t\t\tbreak;\n\t\t\tcase R.id.field_type_float4:\n\t\t\tcase R.id.field_type_float8:\n\t\t\tcase R.id.field_type_float16:\n\t\t\tcase R.id.field_type_float24:\n\t\t\tcase R.id.field_type_float32:\n\t\t\t\tthis.fields\n\t\t\t\t\t\t.add((BaseProtoField) in\n\t\t\t\t\t\t\t\t.readParcelable(ProtoFieldFloat.class\n\t\t\t\t\t\t\t\t\t\t.getClassLoader()));\n\t\t\t\tbreak;\n\t\t\tcase R.id.field_type_string:\n\t\t\t\tthis.fields\n\t\t\t\t\t\t.add((BaseProtoField) in\n\t\t\t\t\t\t\t\t.readParcelable(ProtoFieldString.class\n\t\t\t\t\t\t\t\t\t\t.getClassLoader()));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void writeToParcel(Parcel dest, int flags) {\n\t\tdest.writeString(name);\n\t\tdest.writeString(packetId);\n\t\tdest.writeInt(packetIdResId);\n\t\tdest.writeInt(packetDirResId);\n\t\tdest.writeInt(nameId);\n\t\tdest.writeString(input_type);\n\t\tdest.writeString(output_type);\n\t\tint bin = 0;\n\t\tif (binary)\n\t\t\tbin = 1;\n\t\tdest.writeInt(bin); // Do not know why, but in my case\n\t\t\t\t\t\t\t// dest.writeInt(binary?1:0) interrupts routine\n\t\tdest.writeString(data);\n\t\tint counter = (fields == null) ? 0 : fields.size();\n\t\tdest.writeInt(counter);\n\t\tfor (int i = 0; i != counter; i++) {\n\t\t\tBaseProtoField field = fields.get(i);\n\t\t\tdest.writeInt(field.getType());\n\t\t\tdest.writeParcelable(field, 0);\n\t\t}\n\t}\n\n\tpublic Secu3Packet(Context context, int nameId, int packetIdResId,\n\t\t\tboolean binary) {\n\t\tsetFields(null);\n\t\tsetNameId(nameId);\n\t\tsetPacketIdResId(packetIdResId);\n\t\tsetPacketDirResId(packetDirResId);\n\t\tinput_type = context.getString(R.string.packet_dir_input);\n\t\toutput_type = context.getString(R.string.packet_dir_output);\n\t\tsetBinary(binary);\n\n\t\tif (nameId != 0)\n\t\t\tthis.setName(context.getString(nameId));\n\t\tif (packetIdResId != 0) {\n\t\t\tthis.setPacketId(context.getString(packetIdResId));\n\t\t\tif (packetId.length() > 1)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Packet ID lenght cannot be greater than 1\");\n\t\t}\n\t}\n\n\tpublic Secu3Packet(Secu3Packet packet) {\n\t\tif (packet != null) {\n\t\t\tthis.name = packet.name;\n\t\t\tthis.nameId = packet.nameId;\n\t\t\tthis.input_type = packet.input_type;\n\t\t\tthis.output_type = packet.output_type;\n\t\t\tthis.binary = packet.binary;\n\t\t\tthis.data = packet.data;\n\t\t\tthis.packetId = packet.packetId;\n\t\t\tthis.packetIdResId = packet.packetIdResId;\n\t\t\tthis.packetDirResId = packet.packetDirResId;\n\t\t\tthis.fields = null;\n\t\t\tif (packet.fields != null) {\n\t\t\t\tthis.fields = new ArrayList<>();\n\t\t\t\tBaseProtoField field;\n\t\t\t\tfor (int i = 0; i != packet.fields.size(); ++i) {\n\t\t\t\t\tfield = packet.fields.get(i);\n\t\t\t\t\tif (field instanceof ProtoFieldString)\n\t\t\t\t\t\taddField(new ProtoFieldString((ProtoFieldString) field));\n\t\t\t\t\telse if (field instanceof ProtoFieldInteger)\n\t\t\t\t\t\taddField(new ProtoFieldInteger(\n\t\t\t\t\t\t\t\t(ProtoFieldInteger) field));\n\t\t\t\t\telse if (field instanceof ProtoFieldFloat)\n\t\t\t\t\t\taddField(new ProtoFieldFloat((ProtoFieldFloat) field));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ArrayList<BaseProtoField> getFields() {\n\t\treturn fields;\n\t}\n\n\tpublic void setFields(ArrayList<BaseProtoField> fields) {\n\t\tthis.fields = fields;\n\t}\n\n\tpublic void addField(BaseProtoField field) {\n\t\tif (field != null) {\n\t\t\tif (fields == null)\n\t\t\t\tfields = new ArrayList<>();\n\t\t\tfields.add(field);\n\t\t}\n\t}\n\n\tpublic BaseProtoField getField(int fieldNameId) {\n\t\tBaseProtoField field;\n\t\tfor (int i = 0; i != fields.size(); ++i) {\n\t\t\tfield = fields.get(i);\n\t\t\tif (field.getNameId() == fieldNameId)\n\t\t\t\treturn field;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic BaseProtoField findField(int fieldId) {\n\t\tif (fields != null) {\n\t\t\tfor (int i = 0; i != fields.size(); i++) {\n\t\t\t\tif (fields.get(i).getNameId() == fieldId)\n\t\t\t\t\treturn fields.get(i);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(String data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic boolean parse(String data) {\n\t\tif ((data != null) && (fields != null)) {\n\t\t\tBaseProtoField field;\n\n\t\t\tif (data.charAt(INPUT_OUTPUT_POS) != input_type\n\t\t\t\t\t.charAt(INPUT_OUTPUT_POS))\n\t\t\t\tthrow new IllegalArgumentException(\"Not an input packet\");\n\t\t\tchar ch = data.charAt(PACKET_ID_POS);\n\t\t\tif (ch != packetId.charAt(0))\n\t\t\t\treturn false; // Wrong packet type to analyze\n\t\t\tsetData(data);\n\t\t\tint position = 2; // Skip first 2 chars\n\t\t\tint delta;\n\t\t\tint length = data.length();\n\t\t\tfor (int i = 0; i != fields.size(); i++) {\n\t\t\t\tfield = fields.get(i);\n\t\t\t\tdelta = field.getLength();\n\t\t\t\tif (position + delta > length) throw new IllegalArgumentException(\"Packet too short\");\n\t\t\t\tString subdata = data.substring(position, position += delta);\n\t\t\t\tfield.setData(subdata);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isBinary() {\n\t\treturn binary;\n\t}\n\n\tpublic void setBinary(boolean binary) {\n\t\tthis.binary = binary;\n\t}\n\n\tpublic String getPacketId() {\n\t\treturn packetId;\n\t}\n\n\tpublic void setPacketId(String packetId) {\n\t\tthis.packetId = packetId;\n\t}\n\n\tpublic int getNameId() {\n\t\treturn nameId;\n\t}\n\n\tpublic void setNameId(int nameId) {\n\t\tthis.nameId = nameId;\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\n\tpublic int getPacketIdResId() {\n\t\treturn packetIdResId;\n\t}\n\n\tpublic void setPacketIdResId(int packetIdResId) {\n\t\tthis.packetIdResId = packetIdResId;\n\t}\n\n\t@Override\n\tpublic int describeContents() {\n\t\treturn 0;\n\t}\n\n\tpublic Intent getIntent() {\n\t\tIntent intent = new Intent(\n\t\t\t\tSecu3Service.EVENT_SECU3_SERVICE_RECEIVE_PACKET);\n\t\tintent.putExtra(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PARAM_PACKET,\n\t\t\t\tthis);\n\t\treturn intent;\n\t}\n\n\tpublic Intent getSkeletonIntent() {\n\t\tIntent intent = new Intent(\n\t\t\t\tSecu3Service.EVENT_SECU3_SERVICE_RECEIVE_SKELETON_PACKET);\n\t\tintent.putExtra(\n\t\t\t\tSecu3Service.EVENT_SECU3_SERVICE_RECEIVE_PARAM_SKELETON_PACKET,\n\t\t\t\tthis);\n\t\treturn intent;\n\t}\n\n\tpublic String pack() {\n\t\tif (fields != null) {\n\t\t\tString pack = String.format(\"%s%s\", output_type, getPacketId());\n\t\t\tfor (int i = 0; i != fields.size(); i++) {\n\t\t\t\tBaseProtoField field = fields.get(i);\n\t\t\t\tfield.pack();\n\t\t\t\tpack += field.getData();\n\t\t\t}\n\t\t\tpack += \"\\r\";\n\t\t\tif (isBinary())\n\t\t\t\tpack = EscTxPacket(pack);\n\t\t\treturn pack;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void reset() {\n\t\tif (fields != null) {\n\t\t\tfor (int i = 0; i != fields.size(); i++) {\n\t\t\t\tfields.get(i).reset();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic int getPacketDirResId() {\n\t\treturn packetDirResId;\n\t}\n\n\tpublic void setPacketDirResId(int packetDirResId) {\n\t\tthis.packetDirResId = packetDirResId;\n\t}\n}", "public class Secu3Service extends Service implements OnSharedPreferenceChangeListener {\t\n\tprivate static final String LOG_TAG = \"Secu3Service\";\t\n\t\n\tpublic static final String ACTION_SECU3_SERVICE_START = \"org.secu3.android.intent.action.SECU3_SERVICE_START\";\t\n\tpublic static final String ACTION_SECU3_SERVICE_STOP = \"org.secu3.android.intent.action.SECU3_SERVICE_STOP\";\n\tpublic static final String ACTION_SECU3_SERVICE_SET_TASK = \"org.secu3.android.intent.action.SECU3_SERVICE_SET_TASK\";\n\tpublic static final String ACTION_SECU3_SERVICE_SET_TASK_PARAM = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_SET_TASK_PARAM\";\n\tpublic static final String ACTION_SECU3_SERVICE_SET_TASK_PARAM_EXTRA = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_SET_TASK_PARAM_EXTRA\";\n\tpublic static final String ACTION_SECU3_SERVICE_SEND_PACKET= \"org.secu3.android.intent.action.SECU3_SERVICE_SEND_PACKET\";\n\tpublic static final String ACTION_SECU3_SERVICE_SEND_PACKET_PARAM_PACKET= \"org.secu3.android.intent.action.extra.SECU3_SERVICE_SEND_PACKET_PARAM_PACKET\";\t\n\tpublic static final String ACTION_SECU3_SERVICE_SEND_PACKET_PARAM_PROGRESS = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_SEND_PACKET_PARAM_PROGRESS\";\n\t\n\tpublic static final String EVENT_SECU3_SERVICE_STATUS_ONLINE = \"org.secu3.android.intent.action.STATUS_ONLINE\";\n\tpublic static final String EVENT_SECU3_SERVICE_STATUS = \"org.secu3.android.intent.action.extra.STATUS\";\n\tpublic static final String EVENT_SECU3_SERVICE_PROGRESS = \"org.secu3.android.intent.action.SECU3_SERVICE_PROGRESS\";\n\tpublic static final String EVENT_SECU3_SERVICE_PROGRESS_CURRENT = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_PROGRESS_CURRENT\";\n\tpublic static final String EVENT_SECU3_SERVICE_PROGRESS_TOTAL = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_PROGRESS_TOTAL\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_PACKET= \"org.secu3.android.intent.action.SECU3_SERVICE_RECEIVE_PACKET\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_PARAM_PACKET= \"org.secu3.android.intent.action.extra.SECU3_SERVICE_RECEIVE_PARAM_PACKET\";\n\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON = \"org.secu3.android.intent.action.SECU3_SERVICE_OBTAIN_PACKET_SKELETON\";\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON_PARAM = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_OBTAIN_PACKET_SKELETON_PARAM\";\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON_DIR = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_OBTAIN_PACKET_SKELETON_DIR\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_SKELETON_PACKET = \"org.secu3.android.intent.action.SECU3_SERVICE_RECEIVE_SKELETON_PACKET\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_PARAM_SKELETON_PACKET = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_RECEIVE_PARAM_SKELETON_PACKET\";\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PARAMETER = \"org.secu3.android.intent.action.SECU3_SERVICE_OBTAIN_PARAMETER\";\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PARAMETER_ID = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_OBTAIN_PARAMETER_ID\";\n\tpublic static final String ACTION_SECU3_SERVICE_OBTAIN_PARAMETER_FUNSET_NAMES = \"org.secu3.android.intent.action.extra.SECU3_SERVICE_OBTAIN_PARAMETER_FUNSET_NAMES\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_PARAMETER = \"org.secu3.android.intent.action.SECU3_SERVICE_RECEIVE_PARAMETER\";\n\tpublic static final String EVENT_SECU3_SERVICE_RECEIVE_PARAMETER_FUNSET_NAMES = \"org.secu3.android.intent.action.extra.EVENT_SECU3_SERVICE_RECEIVE_PARAMETER_FUNSET_NAMES\";\n\t\n\t\n\tNotificationManager notificationManager;\n\tprivate Secu3Manager secu3Manager = null;\n\tpublic static Secu3Notification secu3Notification = null;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tPreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);\n\t\tsecu3Notification = new Secu3Notification(this);\n\t\tsuper.onCreate();\t\t\n\t}\n\t\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tSharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);\n\t\tString deviceAddress = sharedPref.getString(getString(R.string.pref_bluetooth_device_key), null);\n\t\tonSharedPreferenceChanged (sharedPref,getString(R.string.pref_write_log_key));\n\t\tonSharedPreferenceChanged (sharedPref,getString(R.string.pref_write_raw_log_key));\n\t\tint maxConRetries = Integer.parseInt(sharedPref.getString(getString(R.string.pref_connection_retries_key), this.getString(R.string.defaultConnectionRetries)));\n\t\tLog.d(LOG_TAG, \"prefs device addr: \"+deviceAddress);\n\t\tif (ACTION_SECU3_SERVICE_START.equals(intent.getAction())){\n\t\t\tif (BluetoothAdapter.getDefaultAdapter() != null) {\n\t\t\t\tif (secu3Manager == null){\n\t\t\t\t\tif (BluetoothAdapter.checkBluetoothAddress(deviceAddress)){\n\t\t\t\t\t\tsecu3Manager = new Secu3Manager(this, deviceAddress, maxConRetries);\n\t\t\t\t\t\tboolean enabled = secu3Manager.enable();\n\t\t\t\t\t\tif (enabled) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tstartForeground(R.string.foreground_service_started_notification, secu3Notification.secu3Notification);\n\t\t\t\t\t\t\tsecu3Notification.toast(R.string.msg_service_started);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstopSelf();\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstopSelf();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tsecu3Notification.toast(R.string.msg_service_already_started);\n\t\t\t\t\tsendBroadcast(intent);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsecu3Notification.toast(R.string.msg_bluetooth_unsupported);\n\t\t\t\tstopSelf();\n\t\t\t}\n\t\t} else if (ACTION_SECU3_SERVICE_STOP.equals(intent.getAction())){\n\t\t\tLog.d(LOG_TAG, \"Stopping service\");\n\t\t\tsecu3Notification.notificationManager.cancelAll();\n\t\t\tSecu3Manager manager = secu3Manager;\n\t\t\tsecu3Manager = null;\n\t\t\tif (manager != null){\n\t\t\t\tif (manager.getDisableReason() != 0){\n\t\t\t\t\tsecu3Notification.notifyServiceStopped(manager.getDisableReason());\n\t\t\t\t\tsecu3Notification.toast(getString(R.string.msg_service_stopped_by_problem, getString(manager.getDisableReason())));\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tsecu3Notification.toast(R.string.msg_service_stopped);\n\t\t\t\t}\n\t\t\t\tmanager.disable();\n\t\t\t}\t\t\t\n\t\t\tstopSelf();\n\t\t\tSystem.exit(0);\t\t\t\n\t\t} else if (ACTION_SECU3_SERVICE_SET_TASK.equals(intent.getAction())) {\n\t\t\tSECU3_TASK task = SECU3_TASK.values()[intent.getIntExtra(ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_NONE.ordinal())];\n\t\t\tif (secu3Manager != null) {\n\t\t\t\tsecu3Manager.setTask(task);\n\t\t\t\tsendBroadcast(intent);\n\t\t\t}\n\t\t} else if (ACTION_SECU3_SERVICE_SEND_PACKET.equals(intent.getAction())) {\n\t\t\tif (secu3Manager != null) {\n\t\t\t\tSecu3Packet packet = intent.getParcelableExtra(ACTION_SECU3_SERVICE_SEND_PACKET_PARAM_PACKET);\n\t\t\t\tint packets_counter = intent.getIntExtra(ACTION_SECU3_SERVICE_SEND_PACKET_PARAM_PROGRESS, 0); \n\t\t\t\tsecu3Manager.appendPacket (packet, packets_counter);\n\t\t\t\tsendBroadcast(intent);\n\t\t\t}\n\t\t} else if (ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON.equals(intent.getAction())) {\n\t\t\tif (secu3Manager != null) {\n\t\t\t\tSecu3ProtoWrapper wrapper = secu3Manager.getProtoWrapper();\n\t\t\t\tif (wrapper != null) {\n\t\t\t\t\tSecu3Packet packet = wrapper.obtainPacketSkeleton(intent.getIntExtra(ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON_PARAM, 0),intent.getIntExtra(ACTION_SECU3_SERVICE_OBTAIN_PACKET_SKELETON_DIR, 0));\n\t\t\t\t\tif (packet != null) {\n\t\t\t\t\t\tsendBroadcast(packet.getSkeletonIntent());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (ACTION_SECU3_SERVICE_OBTAIN_PARAMETER.equals(intent.getAction())) {\n\t\t\tif (ACTION_SECU3_SERVICE_OBTAIN_PARAMETER_FUNSET_NAMES.equals(intent.getStringExtra(ACTION_SECU3_SERVICE_OBTAIN_PARAMETER_ID))) {\n\t\t\t\tif (secu3Manager != null) {\n\t\t\t\t\tSecu3ProtoWrapper wrapper = secu3Manager.getProtoWrapper();\n\t\t\t\t\tif (wrapper != null) {\n\t\t\t\t\t\tsendBroadcast(new Intent(EVENT_SECU3_SERVICE_RECEIVE_PARAMETER).putExtra(EVENT_SECU3_SERVICE_RECEIVE_PARAMETER_FUNSET_NAMES, wrapper.getFunsetNames()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t\t\t\n\t\treturn super.onStartCommand(intent, flags, startId);\t\n\t}\n\t\n\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n\t\tif (getString(R.string.pref_write_log_key).equals(key)) {\n\t\t\tboolean writeLog = sharedPreferences.getBoolean(key, false);\n\t\t\tif (secu3Manager != null) {\n\t\t\t\tsecu3Manager.setTask(writeLog ? SECU3_TASK.SECU3_START_SENSOR_LOGGING:SECU3_TASK.SECU3_STOP_SENSOR_LOGGING);\n\t\t\t}\n\t\t} else if (getString(R.string.pref_write_raw_log_key).equals(key)) {\n\t\t\tboolean writeLog = sharedPreferences.getBoolean(key, false);\n\t\t\tif (secu3Manager != null) {\n\t\t\t\tsecu3Manager.setTask(writeLog?SECU3_TASK.SECU3_START_RAW_LOGGING:SECU3_TASK.SECU3_STOP_RAW_LOGGING);\n\t\t\t}\n\t\t}\t\t\n\t}\t\n}", "public class PacketUtils {\n\t\n\tprivate float m_period_distance = 0f;\n\tprivate float engine_displacement = 1.0f;\n\n\tpublic static final float FUEL_DENSITY = 0.71f;\n\tpublic static final int MAX_FUEL_CONSTANT = 131072;\n\n\tprivate Context context;\n\n\tpublic UnioutUtils uniout;\n\t\n\tpublic PacketUtils(Context context) {\n\t\tthis.context = context;\n\t\tSharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tString pulses = sharedPreferences.getString(context.getString(R.string.pref_speed_pulse_key), context.getString(R.string.defaultSpeedPulse));\n\t\tfloat f_pulses = (float)Integer.parseInt(pulses);\n\t\tm_period_distance = 1000.0f / f_pulses;\n\t\tuniout = new UnioutUtils(context, 20000000,f_pulses);\n\t}\n\t\n\tpublic Secu3Packet buildPacket (Secu3Packet packetSkeleton, ParamPagerAdapter paramAdapter) {\n\t\tif ((packetSkeleton != null) && (packetSkeleton.getFields() != null) && (packetSkeleton.getFields().size() > 0)) {\n\t\t\tBaseProtoField field;\n\t\t\tBaseParamItem item;\n\t\t\tint fieldId;\n\t\t\tint flags = 0;\n\t\t\tfor (int i = 0; i != packetSkeleton.getFields().size(); i++) {\n\t\t\t\tfield = packetSkeleton.getFields().get(i);\n\t\t\t\tfieldId = field.getNameId();\n\t\t\t\tswitch (fieldId) {\n\t\t\t\t\tcase R.string.secur_par_flags_title:\n\t\t\t\t\t\tParamItemBoolean item_secur = (ParamItemBoolean) paramAdapter.findItemByNameId(R.string.secur_par_use_immobilizer_title);\n\t\t\t\t\t\tif (item_secur.getValue()) flags |= Secu3Packet.SECUR_USE_IMMO_FLAG;\n\t\t\t\t\t\titem_secur = (ParamItemBoolean) paramAdapter.findItemByNameId(R.string.secur_par_use_bluetooth_title);\n\t\t\t\t\t\tif (item_secur.getValue()) flags |= Secu3Packet.SECUR_USE_BT_FLAG;\n\t\t\t\t\t\t((ProtoFieldInteger) field).setValue (flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.miscel_baudrate_title:\n\t\t\t\t\t\tint baud_rate = Secu3Packet.BAUD_RATE_INDEX[((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.miscel_baudrate_title)).getIndex()];\n\t\t\t\t\t\t((ProtoFieldInteger) field).setValue (baud_rate);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_injector_config_title:\n\t\t\t\t\t\tint config = ((ParamItemSpinner)paramAdapter.findItemByNameId(R.string.injctr_par_injector_config_title)).getIndex() << 4;\n\t\t\t\t\t\tconfig |= Secu3Packet.INJECTOR_SQIRTS_PER_CYCLE[((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.injctr_par_number_of_squirts_per_cycle_title)).getIndex()];\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(config);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_injector_cyl_disp_title:\n\t\t\t\t\t\tint engine_cylinders = ((ProtoFieldInteger)packetSkeleton.findField(R.string.injctr_par_cyl_num_title)).getValue();\n\t\t\t\t\t\tif (engine_cylinders != 0) {\n\t\t\t\t\t\t\tengine_displacement = ((ParamItemFloat) paramAdapter.findItemByNameId(R.string.injctr_par_enjine_displacement_title)).getValue();\n\t\t\t\t\t\t\tengine_displacement /= engine_cylinders;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t((ProtoFieldFloat) field).setValue(engine_displacement);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.adccor_map_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_voltage_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_temper_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_tps_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_addi1_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_addi2_sensor_correction_title:\n\t\t\t\t\t\tbuildCorrection(paramAdapter, paramAdapter.findItemByNameId(field.getNameId()));\n\t\t\t\t\t\t((ProtoFieldFloat) field).setValue (buildCorrection(paramAdapter, paramAdapter.findItemByNameId(field.getNameId())));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.temper_fan_pwm_freq_title:\n\t\t\t\t\t\t((ProtoFieldInteger) field).setValue((int) Math.round(524288.0/((ParamItemInteger)paramAdapter.findItemByNameId(R.string.temper_fan_pwm_freq_title)).getValue()));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_1_flags_title:\n\t\t\t\t\t\tflags = ((ParamItemSpinner)paramAdapter.findItemByNameId(R.string.unioutput1_logical_functions_title)).getIndex();\n\t\t\t\t\t\tif (flags >= UnioutUtils.UNIOUT_LF_COUNT -1) flags = UnioutUtils.UNIOUT_LF_NONE;\n\t\t\t\t\t\tflags <<= 4;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput1_condition_1_inverse_title)).getValue()?0x01:0x00;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput1_condition_2_inverse_title)).getValue()?0x02:0x00;\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_2_flags_title:\n\t\t\t\t\t\tflags = ((ParamItemSpinner)paramAdapter.findItemByNameId(R.string.unioutput2_logical_functions_title)).getIndex();\n\t\t\t\t\t\tif (flags >= UnioutUtils.UNIOUT_LF_COUNT -1) flags = UnioutUtils.UNIOUT_LF_NONE;\n\t\t\t\t\t\tflags <<= 4;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput2_condition_1_inverse_title)).getValue()?0x01:0x00;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput2_condition_2_inverse_title)).getValue()?0x02:0x00;\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_3_flags_title:\n\t\t\t\t\t\tflags = ((ParamItemSpinner)paramAdapter.findItemByNameId(R.string.unioutput3_logical_functions_title)).getIndex();\n\t\t\t\t\t\tif (flags >= UnioutUtils.UNIOUT_LF_COUNT -1) flags = UnioutUtils.UNIOUT_LF_NONE;\n\t\t\t\t\t\tflags <<= 4;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput3_condition_1_inverse_title)).getValue()?0x01:0x00;\n\t\t\t\t\t\tflags |= ((ParamItemBoolean)paramAdapter.findItemByNameId(R.string.unioutput3_condition_2_inverse_title)).getValue()?0x02:0x00;\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_logic_function_1_2_title:\n\t\t\t\t\t\tflags = ((ParamItemSpinner)paramAdapter.findItemByNameId(R.string.uniout_par_logic_function_1_2_title)).getIndex();\n\t\t\t\t\t\tif (flags >= UnioutUtils.UNIOUT_LF_COUNT -1) flags = UnioutUtils.UNIOUT_LF_NONE;\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.unioutput1_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition2_off_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition2_off_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition2_off_value_title:\n\t\t\t\t\t\tint uniout_condition = ((ProtoFieldInteger)packetSkeleton.findField(uniout.getConditionFieldIdForValue(fieldId))).getValue();\n\t\t\t\t\t\t item = paramAdapter.findItemByNameId(fieldId);\n\t\t\t\t\t\t((ProtoFieldInteger)field).setValue(uniout.unioutEncodeCondVal(((ParamItemFloat) item).getValue(), uniout_condition));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((item = paramAdapter.findItemByNameId(field.getNameId())) != null){\n\t\t\t\t\t\t\tif (item instanceof ParamItemInteger)\n\t\t\t\t\t\t\t\t((ProtoFieldInteger) field).setValue(((ParamItemInteger) item).getValue());\n\t\t\t\t\t\t\telse if (item instanceof ParamItemFloat)\n\t\t\t\t\t\t\t\t((ProtoFieldFloat) field).setValue(((ParamItemFloat) item).getValue());\n\t\t\t\t\t\t\telse if (item instanceof ParamItemString) {\n\t\t\t\t\t\t\t\tString value = ((ParamItemString) item).getValue();\n\t\t\t\t\t\t\t\tif (value == null) value = \"\";\n\t\t\t\t\t\t\t\t((ProtoFieldString) field).setValue(value);\n\t\t\t\t\t\t\t} else if (item instanceof ParamItemBoolean)\n\t\t\t\t\t\t\t\t((ProtoFieldInteger) field).setValue(((ParamItemBoolean) item).getValue() ? 1 : 0);\n\t\t\t\t\t\t\telse if (item instanceof ParamItemSpinner)\n\t\t\t\t\t\t\t\t((ProtoFieldInteger) field).setValue(((ParamItemSpinner) item).getIndex());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn packetSkeleton;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate float buildCorrection(ParamPagerAdapter paramAdapter, BaseParamItem item) {\n\t\tint factorId = 0;\n\t\tswitch (item.getNameId()) {\n\t\tcase R.string.adccor_map_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_map_sensor_factor_title;\n\t\t\tbreak;\n\t\tcase R.string.adccor_voltage_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_voltage_sensor_factor_title;\n\t\t\tbreak;\n\t\tcase R.string.adccor_temper_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_temper_sensor_factor_title;\n\t\t\tbreak;\n\t\tcase R.string.adccor_tps_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_tps_sensor_factor_title;\n\t\t\tbreak;\n\t\tcase R.string.adccor_addi1_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_addi1_sensor_factor_title;\n\t\t\tbreak;\n\t\tcase R.string.adccor_addi2_sensor_correction_title:\n\t\t\tfactorId = R.string.adccor_addi2_sensor_factor_title;\n\t\t\tbreak;\n\t\t}\n\t\tParamItemFloat factorItem = (ParamItemFloat) paramAdapter.findItemByNameId(factorId);\n\t\tif (factorItem != null) {\n\t\t\tfloat factorValue = factorItem.getValue();\n\t\t\tfloat correctionValue = ((ParamItemFloat) item).getValue();\n\t\t\tcorrectionValue = correctionValue * 400 * factorValue;\n\t\t\treturn correctionValue;\n\t\t}\n\t\treturn 0;\n\t}\n\t\t\t\n\tpublic void setParamFromPacket (ParamPagerAdapter paramAdapter, Secu3Packet packet)\n\t{\n\t\tint uniout_flags,uniout_condition, fieldId;\n\t\tBaseParamItem item;\n\n\t\tif ((packet != null) && (packet.getFields() != null) && (packet.getFields().size() > 0)) {\n\t\t\tBaseProtoField field;\n\t\t\tfor (int i = 0; i != packet.getFields().size(); i++) {\n\t\t\t\tfield = packet.getFields().get(i);\n\t\t\t\tfieldId = field.getNameId();\n\t\t\t\tswitch (fieldId) {\n\t\t\t\t\tcase R.string.secur_par_flags_title: {\n\t\t\t\t\t\tint flags = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.secur_par_use_bluetooth_title)).setValue((flags & Secu3Packet.SECUR_USE_BT_FLAG) != 0);\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.secur_par_use_immobilizer_title)).setValue((flags & Secu3Packet.SECUR_USE_IMMO_FLAG) != 0);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_injector_config_title:\n\t\t\t\t\t\tint config = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.injctr_par_injector_config_title)).setIndex(config >> 4);\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.injctr_par_number_of_squirts_per_cycle_title)).setIndex(\n\t\t\t\t\t\t\t\tSecu3Packet.indexOf(Secu3Packet.INJECTOR_SQIRTS_PER_CYCLE, config & 0x0F));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_injector_cyl_disp_title:\n\t\t\t\t\t\tengine_displacement = ((ProtoFieldFloat) field).getValue();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_cyl_num_title:\n\t\t\t\t\t\tint engine_cylinders = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\tengine_displacement *= engine_cylinders;\n\t\t\t\t\t\t((ParamItemFloat) paramAdapter.findItemByNameId(R.string.injctr_par_enjine_displacement_title)).setValue(engine_displacement);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.injctr_par_injector_sd_igl_const_title:\n\t\t\t\t\t\tint fuel_const = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\tLog.d(\"secu3\", String.format(\"Get fuel constant %d\", fuel_const));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.miscel_baudrate_title:\n\t\t\t\t\t\tint baud_rate_index = Secu3Packet.indexOf(Secu3Packet.BAUD_RATE_INDEX, ((ProtoFieldInteger) field).getValue());\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.miscel_baudrate_title)).setIndex(baud_rate_index);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.temper_fan_pwm_freq_title:\n\t\t\t\t\t\t((ParamItemInteger) paramAdapter.findItemByNameId(R.string.temper_fan_pwm_freq_title)).setValue((int) Math.round(524288.0 / ((ProtoFieldInteger) field).getValue()));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.adccor_map_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_voltage_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_temper_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_tps_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_addi1_sensor_correction_title:\n\t\t\t\t\tcase R.string.adccor_addi2_sensor_correction_title:\n\t\t\t\t\t\t((ParamItemFloat) paramAdapter.findItemByNameId(fieldId)).setValue(calculateFactor(packet, field));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.unioutput1_condition_1_title:\n\t\t\t\t\tcase R.string.unioutput2_condition_1_title:\n\t\t\t\t\tcase R.string.unioutput3_condition_1_title:\n\t\t\t\t\t\tuniout_condition = ((ProtoFieldInteger)packet.findField(fieldId)).getValue();\n\t\t\t\t\t\tif (uniout_condition > UnioutUtils.UNIOUT_COND_TMR) uniout_condition--;\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(fieldId)).setIndex(uniout_condition);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_logic_function_1_2_title:\n\t\t\t\t\t\tuniout_flags = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\tif (uniout_flags == UnioutUtils.UNIOUT_LF_NONE) uniout_flags = UnioutUtils.UNIOUT_LF_COUNT - 1;\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.uniout_par_logic_function_1_2_title)).setIndex(uniout_flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_1_flags_title:\n\t\t\t\t\t\tuniout_flags = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput1_condition_1_inverse_title)).setValue((uniout_flags & 0x01) != 0);\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput1_condition_2_inverse_title)).setValue((uniout_flags & 0x02) != 0);\n\t\t\t\t\t\tif ((uniout_flags >>= 4) == UnioutUtils.UNIOUT_LF_NONE) uniout_flags = UnioutUtils.UNIOUT_LF_COUNT - 1;\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput1_condition_2_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput1_condition_2_inverse_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput1_condition2_on_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput1_condition2_off_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n \t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.unioutput1_logical_functions_title)).setIndex(uniout_flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_2_flags_title:\n\t\t\t\t\t\tuniout_flags = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput2_condition_1_inverse_title)).setValue((uniout_flags & 0x01) != 0);\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput2_condition_2_inverse_title)).setValue((uniout_flags & 0x02) != 0);\n\t\t\t\t\t\tif ((uniout_flags >>= 4) == UnioutUtils.UNIOUT_LF_NONE) uniout_flags = UnioutUtils.UNIOUT_LF_COUNT - 1;\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput2_condition_2_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput2_condition_2_inverse_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput2_condition2_on_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT - 1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput2_condition2_off_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT - 1);\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.unioutput2_logical_functions_title)).setIndex(uniout_flags);\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.uniout_par_unioutput_3_flags_title:\n\t\t\t\t\t\tuniout_flags = ((ProtoFieldInteger) field).getValue();\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput3_condition_1_inverse_title)).setValue((uniout_flags & 0x01) != 0);\n\t\t\t\t\t\t((ParamItemBoolean) paramAdapter.findItemByNameId(R.string.unioutput3_condition_2_inverse_title)).setValue((uniout_flags & 0x02) != 0);\n\t\t\t\t\t\tif ((uniout_flags >>= 4) == UnioutUtils.UNIOUT_LF_NONE) uniout_flags = UnioutUtils.UNIOUT_LF_COUNT - 1;\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput3_condition_2_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput3_condition_2_inverse_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT -1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput3_condition2_on_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT - 1);\n\t\t\t\t\t\tparamAdapter.findItemByNameId(R.string.unioutput3_condition2_off_value_title).setEnabled(uniout_flags < UnioutUtils.UNIOUT_LF_COUNT - 1);\n\t\t\t\t\t\t((ParamItemSpinner) paramAdapter.findItemByNameId(R.string.unioutput3_logical_functions_title)).setIndex(uniout_flags);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase R.string.unioutput1_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput1_condition2_off_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput2_condition2_off_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition1_on_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition1_off_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition2_on_value_title:\n\t\t\t\t\tcase R.string.unioutput3_condition2_off_value_title:\n\t\t\t\t\t\tuniout_condition = ((ProtoFieldInteger)packet.findField(uniout.getConditionFieldIdForValue(fieldId))).getValue();\n\t\t\t\t\t\titem = paramAdapter.findItemByNameId(fieldId);\n\t\t\t\t\t\tuniout.setParametersItem(((ProtoFieldInteger) field).getValue(), uniout_condition, (ParamItemFloat) item);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((item = paramAdapter.findItemByNameId(fieldId)) != null) {\n\t\t\t\t\t\t\t\t\tif (item instanceof ParamItemInteger) ((ParamItemInteger) item).setValue(((ProtoFieldInteger) field).getValue());\n\t\t\t\t\t\t\t\t\telse if (item instanceof ParamItemFloat) ((ParamItemFloat) item).setValue(((ProtoFieldFloat) field).getValue());\n\t\t\t\t\t\t\t\t\telse if (item instanceof ParamItemBoolean) ((ParamItemBoolean) item).setValue(((ProtoFieldInteger) field).getValue()==1);\n\t\t\t\t\t\t\t\t\telse if (item instanceof ParamItemSpinner) ((ParamItemSpinner) item).setIndex(((ProtoFieldInteger)field).getValue());\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate float calculateFactor(Secu3Packet packet, BaseProtoField field) {\n\t\tif ((packet != null) && (field != null)) {\n\t\t\tProtoFieldFloat factorField;\n\t\t\tfloat correctionValue,factorValue;\n\t\t\tint correctionId = field.getNameId();\n\t\t\tint factorId = 0;\n\t\t\tswitch (correctionId) {\n\t\t\t\tcase R.string.adccor_map_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_map_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.string.adccor_voltage_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_voltage_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.string.adccor_temper_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_temper_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.string.adccor_tps_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_tps_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.string.adccor_addi1_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_addi1_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.string.adccor_addi2_sensor_correction_title:\n\t\t\t\t\tfactorId = R.string.adccor_addi2_sensor_factor_title;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcorrectionValue = ((ProtoFieldFloat) field).getValue();\n\t\t\tfactorField = ((ProtoFieldFloat) packet.findField(factorId));\n\t\t\tif (factorField != null) {\n\t\t\t\tfactorValue = factorField.getValue();\n\t\t\t\tif (factorValue != 0) {\n\t\t\t\t\tcorrectionValue = correctionValue / factorValue / 400;\n\t\t\t\t} else return 0;\n\t\t\t\treturn correctionValue;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic static void setFunsetNames(ParamPagerAdapter paramAdapter, String[] funsetNames) {\n\t\tif (funsetNames != null) {\t\t\t\n\t\t\tString data = \"\";\n\t\t\tfor (int i=0; i != funsetNames.length-1; i++) {\n\t\t\t\tdata += funsetNames[i] + \"|\";\n\t\t\t}\n\t\t\tdata += funsetNames[funsetNames.length - 1];\n\t\t\tparamAdapter.setSpinnerItemValue(R.string.funset_maps_set_gasoline_title, data);\n\t\t\tparamAdapter.setSpinnerItemValue(R.string.funset_maps_set_gas_title, data);\n\t\t}\n\t}\n\n\tpublic static void setDiagInpFromPacket (ParamItemsAdapter adapter, Secu3Packet packet) {\n\t\tif (packet != null) {\n\t\t\tif (packet.getNameId() ==R.string.diaginp_dat_title) {\n\t\t\t\tif (adapter != null) {\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_voltage_title, (((ProtoFieldFloat) packet.findField(R.string.diag_input_voltage_title)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_map_s, (((ProtoFieldFloat) packet.findField(R.string.diag_input_map_s)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_temp, (((ProtoFieldFloat) packet.findField(R.string.diag_input_temp)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_add_io1, (((ProtoFieldFloat) packet.findField(R.string.diag_input_add_io1)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_add_io2, (((ProtoFieldFloat) packet.findField(R.string.diag_input_add_io2)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_ks1_title, (((ProtoFieldFloat) packet.findField(R.string.diag_input_ks1_title)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_ks2_title, (((ProtoFieldFloat) packet.findField(R.string.diag_input_ks2_title)).getValue()));\n\t\t\t\t\tadapter.setFloatItem(R.string.diag_input_carb_title, (((ProtoFieldFloat) packet.findField(R.string.diag_input_carb_title)).getValue()));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_gas_v, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & 1) != 0));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_ckps, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & (1 << 1)) != 0));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_ref_s, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & (1 << 2)) != 0));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_ps, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & (1 << 3)) != 0));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_bl, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & (1 << 4)) != 0));\n\t\t\t\t\tadapter.setBooleanItem(R.string.diag_input_de, ((((ProtoFieldInteger) packet.findField(R.string.diag_input_bitfield_title)).getValue() & (1 << 5)) != 0));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tpublic float calcSpeed (int rawSpeed) {\n\t\tfloat speed = 0;\n\t\tif ((rawSpeed != 0) && (rawSpeed != 65535)) {\n\t\t\tfloat period_s = (float)rawSpeed/250000.0f;\n\t\t\tspeed = (m_period_distance / period_s) * 3600.0f / 1000.0f;\n\t\t\tif (speed >= 999.9f) speed = 999.9f;\n\t\t}\n\t\treturn speed;\n\t}\n\t\n\tpublic float calcDistance (int rawDistance) {\n\t\tfloat distance = m_period_distance * rawDistance / 1000.0f;\n\t\tif (distance > 9999.99f) distance = 9999.99f;\n\t\treturn distance;\n\t}\n\n\tpublic static int calcInjectorConstant (float cylynder_displacement, int engine_cylinders, int injector_config, int injector_squirt_num, float injector_flow_rate)\n\t{\n\t\t//Log.d(\"secu3\", String.format(\"Cylinder displacement %f\", cylynder_displacement));\n\t\t//Log.d(\"secu3\", String.format(\"Engine cylynders %d\", engine_cylinders));\n\t\t//Log.d(\"secu3\", String.format(\"Injector config %d\", injector_config));\n\t\t//Log.d(\"secu3\", String.format(\"Squirt number %d\", injector_squirt_num));\n\t\t//Log.d(\"secu3\", String.format(\"Flow rate %f\", injector_flow_rate));\n\t\tint inj_num, bnk_num;\n\t\tswitch (injector_config) {\n\t\t\tcase Secu3Packet.INJCFG_TROTTLEBODY:\n\t\t\t\tinj_num = 1;\n\t\t\t\tbnk_num = 1;\n\t\t\t\tbreak;\n\t\t\tcase Secu3Packet.INJCFG_SIMULTANEOUS:\n\t\t\t\tinj_num = engine_cylinders;\n\t\t\t\tbnk_num = 1;\n\t\t\t\tbreak;\n\t\t\tcase Secu3Packet.INJCFG_SEMISEQUENTIAL:\n\t\t\t\tinj_num = engine_cylinders;\n\t\t\t\tbnk_num = engine_cylinders / 2;\n\t\t\t\tbreak;\n\t\t\tcase Secu3Packet.INJCFG_FULLSEQUENTIAL:\n\t\t\tdefault:\n\t\t\t\tinj_num = engine_cylinders;\n\t\t\t\tbnk_num = engine_cylinders;\n\t\t\t\tbreak;\n\t\t}\n\t\tfloat mifr = injector_flow_rate * FUEL_DENSITY;\n\t\treturn Math.round(((cylynder_displacement * 3.482f * 18750000.0f) / mifr) * ((float)bnk_num * (float) engine_cylinders) / ((float)inj_num * (float)injector_squirt_num));\n\t}\n\n\tpublic String getSensorString(int protocol_version, Secu3Packet packet) {\n\t\tString result = \"\";\n\t\tresult += (String.format(Locale.US, context.getString(R.string.status_rpm_title), ((ProtoFieldInteger) packet.getField(R.string.sensor_dat_rpm_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_map_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_map_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_voltage_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_voltage_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_temperature_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_temperature_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_angle_correction_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_angle_correction_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_knock_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_knock_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_knock_retard_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_knock_retard_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_air_flow_title),((ProtoFieldInteger) packet.getField(R.string.sensor_dat_air_flow_title)).getValue()));\n\t\tint bitfield = ((ProtoFieldInteger) packet.getField(R.string.sensor_dat_bitfield_title)).getValue();\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_fi_valve_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_EPHH_VALVE)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_carb_status_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_CARB)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_gas_valve_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_GAS)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_power_valve_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_EPM_VALVE)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_ecf_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_COOL_FAN)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_starter_block_title),Secu3Packet.bitTest(bitfield, Secu3Packet.BITNUMBER_ST_BLOCK)));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_addi1_voltage_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_addi1_voltage_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_addi2_voltage_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_addi2_voltage_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_tps_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_tps_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.status_choke_position_title),((ProtoFieldFloat) packet.getField(R.string.sensor_dat_choke_position_title)).getValue()));\n\n\t\tif (protocol_version >= SettingsActivity.PROTOCOL_28082013_SUMMER_RELEASE) {\n\t\t\tresult += (String.format(Locale.US,context.getString(R.string.status_speed_title),calcSpeed(((ProtoFieldInteger) packet.getField(R.string.sensor_dat_speed_title)).getValue())));\n\t\t\tresult += (String.format(Locale.US,context.getString(R.string.status_distance_title),calcDistance(((ProtoFieldInteger) packet.getField(R.string.sensor_dat_distance_title)).getValue())));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic String getRawSensorString (int protocol_version, Secu3Packet packet) {\n\t\tString result = \"\";\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_map_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_map_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_voltage_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_voltage_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_temperature_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_temperature_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_knock_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_knock_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_tps_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_tps_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_addi1_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_addi1_title)).getValue()));\n\t\tresult += (String.format(Locale.US,context.getString(R.string.raw_status_addi2_title),((ProtoFieldFloat) packet.getField(R.string.adcraw_addi2_title)).getValue()));\n\t\treturn result;\n\t}\n}", "public class ParamItemsAdapter extends BaseAdapter {\t\n\tprivate ArrayList <BaseParamItem> items = null;\n\n\tpublic ParamItemsAdapter(ArrayList<BaseParamItem> items) {\n\t\tthis.items = items; \n\t}\n\t\n\tpublic BaseParamItem findItemByNameId (int Id) {\n\t\tif (items != null) {\n\t\t\tint size = items.size();\n\t\t\tfor (int i = 0; i != size; i++) {\n\t\t\t\tif (items.get(i).getNameId() == Id) return items.get(i); \n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\t\n\t\n\t@Override\n\tpublic int getCount() {\n\t\tif (items != null)\n\t\t\treturn items.size();\n\t\telse return 0;\n\t}\n\n\t@Override\n\tpublic Object getItem(int position) {\n\t\treturn items.get(position);\n\t}\n\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n BaseParamItem i = items.get(position);\t \t \n return i.getView();\n\t}\n \t\t\n\tpublic void setValue(String value, int position) {\n\t\tBaseParamItem i = items.get(position);\n\t\tif (i instanceof ParamItemInteger) {\n\t\t\t\tNumberFormat format = NumberFormat.getInstance(Locale.US);\n\t\t\t\tNumber number;\n\t\t\t\ttry {\n\t\t\t\t\tnumber = format.parse(value);\t\t\t\t\t\t\n\t\t\t\t\t((ParamItemInteger) i).setValue(number.intValue());\n\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} \t\t\t\t\t\n\t\t} else if (i instanceof ParamItemFloat) {\n\t\t\tNumberFormat format = NumberFormat.getInstance(Locale.US);\n\t\t\tNumber number;\n\t\t\ttry {\n\t\t\t\tnumber = format.parse(value);\n\t\t\t\t((ParamItemFloat) i).setValue(number.floatValue());\t\t\t\t\t\t\n\t\t\t} catch (ParseException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} \t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t} else if (i instanceof ParamItemBoolean) {\n\t\t\t((ParamItemBoolean) i).setValue(Boolean.parseBoolean(value));\n\t\t} else if (i instanceof ParamItemString) {\n\t\t\t((ParamItemString) i).setValue(value);\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\t\n\tpublic void setIntegerItem (int id, int value) {\n\t\tBaseParamItem item;\n\t\tif ((item = findItemByNameId(id)) != null ) ((ParamItemInteger)item).setValue (value);\n\t}\n\t\n\tpublic void setFloatItem (int id, float value) {\n\t\tBaseParamItem item;\n\t\tif ((item = findItemByNameId(id)) != null ) ((ParamItemFloat)item).setValue (value);\n\t}\n\t\n\tpublic void setBooleanItem (int id, boolean value) {\n\t\tBaseParamItem item;\n\t\tif ((item = findItemByNameId(id)) != null ) ((ParamItemBoolean)item).setValue (value);\n\t}\n\t\n\tpublic void setSpinnerItemIndex (int id, int index) {\n\t\tBaseParamItem item;\n\t\tif ((item = findItemByNameId(id)) != null ) ((ParamItemSpinner)item).setIndex(index);\n\t}\n\n\tpublic void setSpinnerItemValue (int id, String value) {\n\t\tBaseParamItem item;\n\t\tif ((item = findItemByNameId(id)) != null ) ((ParamItemSpinner)item).setValue(value);\n\t}\t\t\n}", "public interface OnParamItemChangeListener {\n\tvoid onParamItemChange (BaseParamItem item);\n}" ]
import java.util.ArrayList; import java.util.List; import org.secu3.android.api.io.ProtoFieldInteger; import org.secu3.android.api.io.Secu3Packet; import org.secu3.android.api.io.Secu3Service; import org.secu3.android.api.utils.PacketUtils; import org.secu3.android.parameters.ParamItemsAdapter; import org.secu3.android.parameters.items.*; import org.secu3.android.parameters.items.BaseParamItem.OnParamItemChangeListener; import android.support.v4.app.ListFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.TextView;
/* Secu3Droid - An open source, free manager for SECU-3 engine * control unit * Copyright (C) 2013 Maksim M. Levin. Russia, Voronezh * * SECU-3 - An open source, free engine control unit * Copyright (C) 2007 Alexey A. Shabelnikov. Ukraine, Gorlovka * * 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/>. * * contacts: * http://secu-3.org * email: mmlevin@mail.ru */ package org.secu3.android; public class DiagnosticsActivity extends FragmentActivity implements OnItemClickListener, OnParamItemChangeListener{ private static final String BLDEENABLED = "BLDEENABLED"; private static final String PAGE = "page"; private static final String OUTPUTS = "outputs"; private boolean isOnline = false; private ListFragment inputFragment = null; private int protocolversion = SettingsActivity.PROTOCOL_UNKNOWN; private ArrayList<BaseParamItem> outputItems = null; private ViewPager pager = null; private ReceiveMessages receiver = null; private TextView textViewStatus = null; private Secu3Packet OpCompNc = null; private Secu3Packet DiagOutDat = null; private boolean BlDeDiagEnabled = false; public static class OutputDiagListFragment extends ListFragment { OnItemClickListener listener; public void setOnItemClickListener (OnItemClickListener listener) { this.listener = listener; } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (listener != null) listener.onItemClick(l, v, position, id); super.onListItemClick(l, v, position, id); } } private class DiagnosticsPagerAdapter extends FragmentPagerAdapter{ private List<Fragment> fragments = null; private final String titles[]; public DiagnosticsPagerAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; titles = getBaseContext().getResources().getStringArray(R.array.diagnostics_fragments_title); } @Override public Fragment getItem (int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Override public CharSequence getPageTitle(int position) { return titles[position]; } } public class ReceiveMessages extends BroadcastReceiver { public IntentFilter intentFilter = null; public ReceiveMessages() { intentFilter = new IntentFilter();
intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PACKET);
2
sorinMD/MCTS
src/main/java/mcts/MCTSConfig.java
[ "public class NullSeedTrigger extends SeedTrigger{\n\n\t@Override\n\tpublic void addNode(TreeNode node, GameFactory gameFactory) {\n\t\t// do nothing\n\t}\n\n\t@Override\n\tpublic void cleanUp() {\n\t\t// do nothing\n\t}\n\n}", "@JsonTypeInfo(use = Id.CLASS,\ninclude = JsonTypeInfo.As.PROPERTY,\nproperty = \"type\")\n@JsonSubTypes({\n\t@Type(value = NullSeedTrigger.class),\n\t@Type(value = CatanTypePDFSeedTrigger.class)\n})\npublic abstract class SeedTrigger {\n\t@JsonIgnore\n\tprotected MCTS mcts;\n\t@JsonIgnore\n\tprotected HashSet<Seeder> aliveSeeders = new HashSet<>();\n\t@JsonIgnore\n\tprotected boolean initialised = false;\n\t/**\n\t * Max number of seeders alive at one point.\n\t */\n\tpublic int maxSeederCount = 2;\n\t\n\t/**\n\t * Add a new node to the queue, and possibly start the evaluation thread\n\t * @param node\n\t */\n\tpublic abstract void addNode(TreeNode node, GameFactory factory);\n\t\n\t/**\n\t * e.g. clears queue(s), resets counters etc\n\t */\n\tpublic abstract void cleanUp();\n\t\n\t/**\n\t * Give access to the thread pool executor in MCTS and initialise fields\n\t * @param mcts\n\t */\n\tpublic void init(MCTS mcts){\n\t\tthis.mcts = mcts;\n\t\tinitialised = true;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[name-\" + this.getClass().getName() + \"; maxSeederCount-\" + maxSeederCount + \"]\";\n\t}\n}", "@JsonTypeInfo(use = Id.CLASS,\ninclude = JsonTypeInfo.As.PROPERTY,\nproperty = \"type\")\n@JsonSubTypes({\n\t@Type(value = UCT.class),\n\t@Type(value = UCTAction.class),\n\t@Type(value = PUCT.class),\n\t@Type(value = RAVE.class),\n})\npublic abstract class SelectionPolicy {\n\t/**\n\t * Flag for deciding if we should use the action probabilities to weight the selection.\n\t * Should be used with MCTS with belief. It has no effect on POMCP or observable MCTS.\n\t */\n\tpublic boolean weightedSelection = true;\n\tprotected final double eps = 1e-6;\n\t/**\n\t * The number of visits before the statistics in the nodes are used for\n\t * computing the node value. Equal to saying how many visits before adding\n\t * this node to the tree.\n\t */\n public int MINVISITS = 1;\n\t/**\n\t * The exploration constant\n\t */\n public double C0 = 1.0;\n /**\n * Flag to decide if the parent visits should take into account if the node was legal\n */\n public boolean ismcts = false; \n \n\t/**\n\t * Used in the tree level of the algorithm to select the next action either only according to the game's\n\t * transition model if it is a chance node or according to the selection policy if it is a {@link StandardNode}\n\t * \n\t * @param tn\n\t * @param tree\n\t * @param gameFactory factory that can be used to generate a game and provide access to the belief\n\t * @param obsGame the game that provides observations if the algorithm is POMCP, null otherwise\n\t * @return a pair, where the node is the selected child node and the boolean\n\t * represents if all the siblings have been visited at least\n\t * {@link #TreePolicy#MINVISITS} number of times\n\t */\n\tpublic Selection selectChild(TreeNode tn, Tree tree, GameFactory gameFactory, Game obsGame) {\n\t\tif(tn instanceof StandardNode){\n\t\t\treturn selectChild((StandardNode)tn, tree, gameFactory, obsGame);\n\t\t}else {//chance nodes\n\t\t\tif(obsGame != null) {//the POMCP case\n\t\t\t\t//two cases when the chance exists in the fully-observable game, or when this is a belief specific chance node \n\t\t\t\tTreeNode temp = obsGame.generateNode();\n\t\t\t\tif(temp instanceof ChanceNode) {\n\t\t\t\t\t//perform the same action in both observable state and belief, but sample from the observable state\n\t\t\t\t\tint[] action = obsGame.sampleNextAction();\n\t\t\t\t\tobsGame.performAction(action, true);\t\t\t\t\t\n\t\t\t\t\tGame game = gameFactory.getGame(tn.getState());\n\t\t\t\t\tgame.performAction(action,true);\n\t\t\t\t\tTreeNode child = game.generateNode();\n\t\t\t\t\ttree.putNodeIfAbsent(child);\n\t\t\t\t\tSelection pair = new Selection(true, tree.getNode(child.getKey()),1.0);\n\t\t\t\t\treturn pair;\n\t\t\t\t}else {\n\t\t\t\t\t/* \n\t\t\t\t\t * The special case where the chance node decides whether the game is won or not in the belief space.\n\t\t\t\t\t * This decision is already made in the observable game, so choose the action that leads us to the same situation as in the observable game.\n\t\t\t\t\t*/\n\t\t\t\t\tGame game = gameFactory.getGame(tn.getState());\n\t\t\t\t\tArrayList<int[]> actions = game.listPossiblities(false).getOptions();\n\t\t\t\t\tint[] chosen = null;\n\t\t\t\t\tfor(int[] act : actions) {\n\t\t\t\t\t\tGame t = game.copy();\n\t\t\t\t\t\tt.performAction(act, false);\n\t\t\t\t\t\tif(t.isTerminal() == obsGame.isTerminal()) {\n\t\t\t\t\t\t\tchosen = act;\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\tgame.performAction(chosen, false);\n\t\t\t\t\tTreeNode child = game.generateNode();\n\t\t\t\t\ttree.putNodeIfAbsent(child);\n\t\t\t\t\tSelection pair = new Selection(true, tree.getNode(child.getKey()),1.0);\n\t\t\t\t\treturn pair; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t}else {\n\t\t\t\t//sample from the possible outcomes and get a possible child node\n\t\t\t\tGame game = gameFactory.getGame(tn.getState());\n\t\t\t\tgame.gameTick();\n\t\t\t\tTreeNode child = game.generateNode();\n\t\t\t\t//also add the new node to the tree as we want to build the tree past this step\n\t\t\t\ttree.putNodeIfAbsent(child);\n\t\t\t\t//it is a chance node, so MINVISITS doesn't apply here\n\t\t\t\tSelection pair = new Selection(true, tree.getNode(child.getKey()),1.0);\n\t\t\t\treturn pair; \n\t\t\t}\n\t\t}\n\t}\n \n\t/**\n\t * Implements the specific policy\n\t * @param tn\n\t * @param tree\n\t * @param gameFactory factory that can be used to generate a game and provide access to the belief\n\t * @param obsGame the game that provides observations if the algorithm is POMCP, null otherwise\n\t * @return a pair, where the node is the selected child node and the boolean\n\t * represents if all the siblings have been visited at least\n\t * {@link #TreePolicy#MINVISITS} number of times\n\t */\n\tprotected abstract Selection selectChild(StandardNode tn, Tree tree, GameFactory gameFactory, Game obsGame);\n\t\n\t/**\n\t * To be called after the search has finished to get the best action based\n\t * on value. Ties are broken randomly.\n\t * \n\t * @param tree\n\t * @return the action with the highest value\n\t */\n public int selectBestAction(Tree tree){\n \tThreadLocalRandom rnd = ThreadLocalRandom.current();\n \tStandardNode root = (StandardNode)tree.getRoot();\n double v, maxv;\n int maxind=0;\n maxv = -Double.MAX_VALUE;\n \tfor (int k=0; k<root.getChildren().size(); k++){\n \t\tif(this instanceof UCTAction)\n \t\t\tv = ((double)root.wins[root.getCurrentPlayer()][k])/root.childVisits[k] + rnd.nextDouble() * eps;\n \t\telse{\n\t \tTreeNode n = tree.getNode(root.getChildren().get(k));\n\t v = ((double)n.getWins(root.getCurrentPlayer()))/(n.getnVisits()) + rnd.nextDouble() * eps;\n \t\t}\n \n if (maxv<=v){\n maxv = v;\n maxind = k;\n }\n }\n return maxind;\n }\n\t\n\t/**\n\t * To be called after the search has finished to get the best action based\n\t * on number of visits. Ties are broken randomly.\n\t * \n\t * @param tree\n\t * @return the action that has the highest number of visits\n\t */\n public int selectMostExploredAction(Tree tree){\n \tThreadLocalRandom rnd = ThreadLocalRandom.current();\n \tStandardNode root = (StandardNode)tree.getRoot();\n \tdouble maxVisits = 0;\n \tdouble current = 0;\n int maxind=0;\n \tfor (int k=0; k<root.getChildren().size(); k++){\n if(this instanceof UCTAction)\n \tcurrent = ((double)root.childVisits[k]) + rnd.nextDouble() * eps;\n else{\n\t \tTreeNode n = tree.getNode(root.getChildren().get(k));\n\t current = ((double)n.getnVisits()) + rnd.nextDouble() * eps;\n }\n \tif (maxVisits <= current){\n maxVisits = current;\n maxind = k;\n }\n }\n return maxind;\n }\n \n\t/**\n\t * To be called after the search has finished. Adds a small random value to\n\t * each such that ties will be broken randomly when the list is ordered.\n\t * \n\t * @param tree\n\t * @return the values of the children which is of the same size and has the\n\t * same order as the set of legal actions actions\n\t */\n public double[] getChildrenValues(Tree tree){\n \tThreadLocalRandom rnd = ThreadLocalRandom.current();\n \tStandardNode root = (StandardNode)tree.getRoot();\n \tdouble[] values = new double[root.getChildren().size()];\n \tfor (int k=0; k<root.getChildren().size(); k++){\n \t\tif(this instanceof UCTAction)\n \t\tvalues[k] = ((double)root.wins[root.getCurrentPlayer()][k])/root.childVisits[k] + rnd.nextDouble() * eps;\n \t\telse{\n \t\t\tTreeNode n = tree.getNode(root.getChildren().get(k));\n \t\t\tvalues[k] = ((double)n.getWins(root.getCurrentPlayer()))/(n.getnVisits()) + rnd.nextDouble() * eps;\n \t\t}\n }\n \treturn values;\n }\n \n\t@Override\n\tpublic String toString() {\n\t\treturn \"[name-\" + this.getClass().getName() + \"; C-\" + C0 + \"; MINVISITS-\" + MINVISITS + \"]\";\n\t}\n\n \n}", "public class UCT extends SelectionPolicy{\n public UCT() {}\n \n\t/**\n\t * Select node based on the best UCT value.\n\t * Ties are broken randomly.\n\t * \n\t * @param node\n\t * @param tree\n\t * @return\n\t */\n protected Selection selectChild(StandardNode node, Tree tree, GameFactory factory, Game obsGame){\n \tThreadLocalRandom rnd = ThreadLocalRandom.current();\n double v;\n double maxv = -Double.MAX_VALUE;\n TreeNode chosen = null;\n int chosenIdx = 0;\n boolean allSiblingsVisited = true;\n ArrayList<Key> children = node.getChildren();\n ArrayList<int[]> actions = node.getActions();\n ArrayList<Double> actLegalProb;\n if(weightedSelection) \n \tactLegalProb = node.getActionProbs();\n else\n \tactLegalProb = new ArrayList<Double>(Collections.nCopies(actions.size(), 1.0));\n double actProb = 1.0;\n if(obsGame != null) {//POMCP case\n \tArrayList<int[]> stateActions = obsGame.listPossiblities(false).getOptions();\n \tactLegalProb = Utils.createActMask(stateActions, actions);\n }\n int nChildren = children.size();\n //precompute sum and 'freeze' values\n int sumVisits = 0; \n int[] visits = new int[nChildren];\n double[] wins = new double[nChildren];\n int[] vLoss = new int[nChildren];\n int[] parentVisits = new int[nChildren]; \n for (int k=0; k<nChildren; k++){\n \tTreeNode n = tree.getNode(children.get(k));\n \tsynchronized (n) {\n \tvisits[k] = n.getnVisits();\n \twins[k] = n.getWins(node.getCurrentPlayer());\n \tvLoss[k] = n.getvLoss();\n \tsumVisits += visits[k];\n \tparentVisits[k] = n.getParentVisits();\n\t\t\t}\n }\n \n for (int k=0; k<nChildren; k++){\n if (visits[k] < MINVISITS){\n \tv = Double.MAX_VALUE - rnd.nextDouble();\n allSiblingsVisited = false;\n if(actLegalProb != null) {\n \tif(actLegalProb.get(k).doubleValue() == 0.0)\n \t\tv = -Double.MAX_VALUE;\n \telse\n \t\tv *= actLegalProb.get(k).doubleValue();\n }\n }\n else{\n v = (wins[k] - vLoss[k])/(visits[k]);\n //include exploration factor\n int pVisits = sumVisits;\n if(ismcts)\n \tpVisits = parentVisits[k];\n v += C0*Math.sqrt(Math.log(pVisits)/(visits[k])) + rnd.nextDouble() * eps;\n //weigh with the probability that represents the likelihood of the action being legal\n if(actLegalProb != null) {\n \tif(actLegalProb.get(k).doubleValue() == 0.0)\n \t\tv= -Double.MAX_VALUE; // we need to do this due to virtual loss, in which case we might get the value for other legal actions under 0\n \telse\n \t\tv *= actLegalProb.get(k).doubleValue();\n }\n }\n\t\t\tif(actLegalProb != null && actLegalProb.get(k) == 1.0)\n\t\t\t\ttree.getNode(children.get(k)).incrementParentVisits();\n if (maxv <= v){\n maxv = v;\n chosen = tree.getNode(children.get(k));\n chosenIdx = k;\n if(actLegalProb != null) \n \tactProb = actLegalProb.get(k);\n }\n }\n \n //when game is not observable and we need to update belief; i.e. POMCP and other belief MCTS algorithms\n if(factory.getBelief() != null) { \n \tint[] action = actions.get(chosenIdx);\n \tGame game = factory.getGame(node.getState());\n \tgame.performAction(action, false);\n \tif(obsGame != null)\n \t\tobsGame.performAction(action, false);\n }\n \n\t\t/*\n\t\t * increment virtual loss to discourage other threads from selecting the\n\t\t * same action. This also breaks cyclic behaviour with time\n\t\t */\n chosen.incrementVLoss();\n Selection pair = new Selection(allSiblingsVisited, chosen, actProb);\n \n return pair;\n \n }\n}", "public class UCTAction extends SelectionPolicy{\n public UCTAction() {}\n \n\t/**\n\t * Select node based on the best UCT value.\n\t * Ties are broken randomly.\n\t * \n\t * @param node\n\t * @param tree\n\t * @return\n\t */\n protected Selection selectChild(StandardNode node, Tree tree, GameFactory factory, Game obsGame){\n \tThreadLocalRandom rnd = ThreadLocalRandom.current();\n double v;\n double maxv = -Double.MAX_VALUE;\n Key chosen = null;\n boolean allSiblingsVisited = true;\n ArrayList<Key> children = ((StandardNode) node).getChildren();\n ArrayList<Double> actLegalProb = ((StandardNode) node).getActionProbs();\n ArrayList<int[]> actions = node.getActions();\n if(weightedSelection)\n \tactLegalProb = node.getActionProbs();\n else\n \tactLegalProb = new ArrayList<Double>(Collections.nCopies(actions.size(), 1.0));\n double actProb = 1.0;\n if(obsGame != null) {\n \tArrayList<int[]> stateActions = obsGame.listPossiblities(false).getOptions();\n \tactLegalProb = Utils.createActMask(stateActions, actions);\n }\n int nChildren = children.size();\n StandardNode parent = ((StandardNode) node);\n int idx = -1;\n \n //precompute sum and 'freeze' values\n int sumVisits = 0;\n int[] visits = new int[nChildren];\n double[] wins = new double[nChildren];\n int[] vLoss = new int[nChildren];\n for (int k=0; k< nChildren; k++){\n \tsumVisits+=parent.childVisits[k];\n }\n synchronized (parent) {\n \twins = parent.wins[parent.getCurrentPlayer()].clone();\n \tvisits = parent.childVisits.clone();\n \tvLoss = parent.vloss.clone();\n }\n \n for (int k=0; k< nChildren; k++){\n \n \tif (visits[k] < MINVISITS){\n \tv = Double.MAX_VALUE - rnd.nextDouble();\n allSiblingsVisited = false;\n if(actLegalProb != null) {\n \tif(actLegalProb.get(k).doubleValue() == 0.0)\n \t\tv = -Double.MAX_VALUE;\n \telse\n \t\tv *= actLegalProb.get(k).doubleValue();\n }\n }\n else{\n v = (wins[k] - vLoss[k])/visits[k];\n //include exploration factor\n v += C0*Math.sqrt(Math.log(sumVisits)/(visits[k])) + rnd.nextDouble() * eps;\n //weight with the probability that represents the likelihood of the action being legal\n if(actLegalProb != null) {\n \tif(actLegalProb.get(k).doubleValue() == 0.0)\n \t\tv= -Double.MAX_VALUE; // we need to do this due to virtual loss, in which case we might get the value for other legal actions under 0\n \telse\n \t\tv *= actLegalProb.get(k).doubleValue();\n }\n }\n if (maxv <= v){\n maxv = v;\n chosen = children.get(k);\n idx = k;\n if(actLegalProb != null) \n \tactProb = actLegalProb.get(k);\n }\n }\n \n if(factory.getBelief() != null) {\n \tint[] action = actions.get(idx);\n \tGame game = factory.getGame(node.getState());\n \tgame.performAction(action, false);\n \tif(obsGame != null)\n \t\tobsGame.performAction(action, false);\n }\n \n\t\t/*\n\t\t * increment virtual loss to discourage other threads from selecting the\n\t\t * same action. This also breaks cyclic behaviour with time\n\t\t */\n parent.vloss[idx]++;\n TreeNode child = tree.getNode(chosen);\n \n Selection pair = new Selection(allSiblingsVisited, child, actProb);\n \n return pair;\n \n }\n}", "public class ActionUpdater extends UpdatePolicy{\n public ActionUpdater(boolean ex, boolean ev) {\n \texpectedReturn = ex;\n \teveryVisit = ev;\n }\n \n public ActionUpdater() {\n\t\t// dummy constructor required for json....\n\t}\n\t@Override\n\tpublic void update(ArrayList<Selection> visited, double[] reward, int nRollouts) {\n\t\tif(expectedReturn) {\n\t\t\t//Use log probabilities for precision...this works for now as reward is between 0-1 TODO: separate probs and rewards\n\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\treward[k] = Math.log(reward[k] );\n\t\t\t}\n\t\t\tif(everyVisit) {\n\t\t\t\tdouble[] r = new double[reward.length];\n\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\tr[k] = Math.exp(reward[k]);\n\t\t\t\t}\n\t\t\t\t//update the terminal/leaf node first\n\t\t\t\tif(visited.get(visited.size()-1).getNode() instanceof StandardNode)\n\t\t\t\t\t((StandardNode)visited.get(visited.size()-1).getNode()).update(r, null, nRollouts);\n\t\t\t\telse\n\t\t\t\t\tvisited.get(visited.size()-1).getNode().update(r, nRollouts);\n\t\t\t\t\n\t\t\t\tdouble logActProb = Math.log(visited.get(visited.size()-1).getActProb());\n\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t}\n\t\t\t\t//update the others now\t\t\t\n\t\t\t\tfor(int i = visited.size()-2; i >= 0; i--) {\n\t\t\t\t\tr = new double[reward.length];\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\tr[k] = Math.exp(reward[k]);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(visited.get(i).getNode() instanceof StandardNode)\n\t\t\t\t\t\t((StandardNode)visited.get(i).getNode()).update(r, visited.get(i+1).getNode().getKey(), nRollouts);\n\t\t\t\t\telse\n\t\t\t\t\t\tvisited.get(i).getNode().update(r, nRollouts);\n\t\t\t\t\tlogActProb = Math.log(visited.get(i).getActProb());\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else {\n\t\t\t\tHashMapList<TreeNode, double[]> updateValues = new HashMapList<TreeNode, double[]>();\n\t\t\t\tHashMapList<TreeNode, TreeNode> updateAction = new HashMapList<TreeNode, TreeNode>();\n\t\t\t\t//update the terminal/leaf node first\n\t\t\t\tdouble[] r = new double[reward.length];\n\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\tr[k] = Math.exp(reward[k]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(visited.get(visited.size()-1).getNode() instanceof StandardNode)\n\t\t\t\t\t((StandardNode)visited.get(visited.size()-1).getNode()).update(r, null, nRollouts);\n\t\t\t\telse\n\t\t\t\t\tvisited.get(visited.size()-1).getNode().update(r, nRollouts);\n\t\t\t\t\n\t\t\t\tdouble logActProb = Math.log(visited.get(visited.size()-1).getActProb());\n\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t}\n\n\t\t\t\tfor(int i = visited.size()-2; i >= 0; i--) {\n\t\t\t\t\tr = new double[reward.length];\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\tr[k] = Math.exp(reward[k]);\n\t\t\t\t\t}\n\t\t\t\t\tupdateValues.put(visited.get(i).getNode(), r);\n\t\t\t\t\tupdateAction.put(visited.get(i).getNode(),visited.get(i+1).getNode());\n\t\t\t\t\tlogActProb = Math.log(visited.get(i).getActProb());\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\tfor(TreeNode state : updateValues.keySet()) {\n\t\t\t\t\tHashSet<TreeNode> updated = new HashSet<TreeNode>();\n\t\t\t\t\tArrayList<TreeNode> actList = updateAction.get(state);\n\t\t\t\t\tArrayList<double[]> retList = updateValues.get(state);\n\t\t\t\t\tfor(int i=0; i < actList.size(); i++) {\n\t\t\t\t\t\tif(updated.contains(actList.get(i)))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif(state instanceof StandardNode)\n\t\t\t\t\t\t\t((StandardNode)state).update(retList.get(i), actList.get(i).getKey(), nRollouts);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstate.update(retList.get(i), nRollouts);\n\t\t\t\t\t\tupdated.add(actList.get(i));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\t//NOTE: since we don't apply any expectation or discount the nodes are updated from start to finish here\n\t\t\tHashMapList<TreeNode, TreeNode> pairs = new HashMapList<>();\n\t\t\t//update all visited nodes but avoid duplicates\n\t\t\tfor(int i = 0; i < visited.size()-1; i++){\n\t\t\t\tif(pairs.containsKeyValue(visited.get(i).getNode(),visited.get(i+1).getNode())){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(visited.get(i).getNode() instanceof StandardNode)\n\t\t\t\t\t((StandardNode)visited.get(i).getNode()).update(reward, visited.get(i+1).getNode().getKey(), nRollouts);\n\t\t\t\telse\n\t\t\t\t\tvisited.get(i).getNode().update(reward, nRollouts);\n\t\t\t\tif(!everyVisit)\n\t\t\t\t\tpairs.put(visited.get(i).getNode(), visited.get(i+1).getNode());\n\t\t\t}\n\t\t\t//update the terminal/leaf node\n\t\t\tif(visited.get(visited.size()-1).getNode() instanceof StandardNode)\n\t\t\t\t((StandardNode)visited.get(visited.size()-1).getNode()).update(reward, null, nRollouts);\n\t\t\telse\n\t\t\t\tvisited.get(visited.size()-1).getNode().update(reward, nRollouts);\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[name-\" + this.getClass().getName() + \"; expectedReturn-\" + expectedReturn + \"; everyVisit-\" + everyVisit + \"]\";\n\t}\n\n\n}", "public class StateUpdater extends UpdatePolicy{\n public StateUpdater(boolean ex, boolean ev) {\n \texpectedReturn = ex;\n \teveryVisit = ev;\n }\n \n public StateUpdater() {\n\t\t// dummy constructor required for json....\n\t}\n \n\t@Override\n\tpublic void update(ArrayList<Selection> visited, double[] reward, int nRollouts) {\n\t\tif(expectedReturn) {\n\t\t\t//Use log probabilities for precision...this works for now as reward is between 0-1 TODO: separate probs and rewards\n\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\treward[k] = Math.log(reward[k]);\n\t\t\t}\n\t\t\t\n\t\t\tif(everyVisit) {\n\t\t\t\tfor(int i = visited.size()-1; i >= 0; i--) {\n\t\t\t\t\tdouble[] r = new double[reward.length];\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\tr[k] = Math.exp(reward[k]);\n\t\t\t\t\t}\n\t\t\t\t\tvisited.get(i).getNode().update(r, nRollouts);\n\t\t\t\t\tdouble logActProb = Math.log(visited.get(i).getActProb());\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else {\n\t\t\t\tHashMap<TreeNode, double[]> updateValues = new HashMap<>();\n\t\t\t\tfor(int i = visited.size()-1; i >= 0; i--) {\n\t\t\t\t\tdouble[] r = new double[reward.length];\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\tr[k] = Math.exp(reward[k]) ;\n\t\t\t\t\t}\n\t\t\t\t\tupdateValues.put(visited.get(i).getNode(), r);\n\t\t\t\t\tdouble logActProb = Math.log(visited.get(i).getActProb());\n\t\t\t\t\tfor (int k =0; k < reward.length; k++) {\n\t\t\t\t\t\treward[k] += logActProb;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor(Entry<TreeNode, double[]> entry : updateValues.entrySet()) {\n\t\t\t\t\tentry.getKey().update(entry.getValue(), nRollouts);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}else {\n\t\t\t//NOTE: since we don't apply any expectation or discount the nodes are updated from start to finish here\n\t\t\tif(everyVisit) {\n\t\t\t\tvisited.forEach(s -> s.getNode().update(reward, nRollouts));\n\t\t\t}else {\n\t\t\t\t//hashset to avoid updating nodes multiple times\n\t\t\t\tHashSet<TreeNode> v = new HashSet<TreeNode>(visited.size());\n\t\t\t\tfor(Selection s : visited)\n\t\t\t\t\tv.add(s.getNode());\n\t\t\t\t//update all visited nodes\n\t\t\t\tv.forEach(n -> n.update(reward, nRollouts));\n\t\t\t}\n\t\t}\n\t}\n \n\t@Override\n\tpublic String toString() {\n\t\treturn \"[name-\" + this.getClass().getName() + \"; expectedReturn-\" + expectedReturn + \"; everyVisit-\" + everyVisit + \"]\";\n\t}\n\n}", "@JsonTypeInfo(use = Id.CLASS,\ninclude = JsonTypeInfo.As.PROPERTY,\nproperty = \"type\")\n@JsonSubTypes({\n\t@Type(value = StateUpdater.class),\n\t@Type(value = ActionUpdater.class),\n})\npublic abstract class UpdatePolicy {\n\tpublic boolean expectedReturn = false;\n\tpublic boolean everyVisit = false;\n\t\n\tpublic abstract void update(ArrayList<Selection> visited, double[] reward, int nRollouts);\n}" ]
import mcts.seeder.NullSeedTrigger; import mcts.seeder.SeedTrigger; import mcts.tree.selection.SelectionPolicy; import mcts.tree.selection.UCT; import mcts.tree.selection.UCTAction; import mcts.tree.update.ActionUpdater; import mcts.tree.update.StateUpdater; import mcts.tree.update.UpdatePolicy;
package mcts; /** * * @author sorinMD * */ public class MCTSConfig { //default values and policies public int nIterations = 10000; public int nThreads = 4; public long timeLimit = 0; public int treeSize = 500000; public int maxTreeDepth = 50; public boolean afterstates = true; public boolean observableRollouts = false; /**Number of rollouts to be performed per iteration from the current leaf node*/ public int nRolloutsPerIteration = 1; public boolean pomcp = false;
public SeedTrigger trigger = new NullSeedTrigger();
0
maizi0122/Ripened
ripened/src/main/java/org/studio/maizi/ripened/impl/Ripened.java
[ "public interface IPlugin {\n\n /**\n * get the name of this plugin.\n *\n * @return the name of this plugin.\n */\n String getName();\n\n /**\n * the plugin's action\n *\n * @param params the params of action\n */\n void action(ActionParams params);\n\n}", "public interface IRipened {\n\n /**\n * set the context of viewInjection\n *\n * @param viContext the context of viewInjection\n * @return the current obj\n */\n IRipened setVIContext(VIContext viContext);\n\n /**\n * obtain the context of RapeField.\n * @return the context of RapeField.\n */\n VIContext getVIContext();\n\n /**\n * inject automatic in an activity.\n *\n * @param context current context which relate to an instance of window\n * @param listener additional params, when your class of listener have no empty-parameter constructor, you should pass the listener object manually...\n * @return the current obj\n */\n IRipened inject(Activity context, Object... listener);\n\n /**\n * inject automatic in a fragment.\n *\n * @param fragment the fragment object.\n * @param root the root view in your fragment.\n * @param listener additional params, when your class of listener have no empty-parameter constructor, you should pass the listener object manually...\n * @return the current obj\n */\n IRipened inject(Fragment fragment, View root, Object... listener);\n\n /**\n * inject automatic in a adapter.\n *\n * @param adapter this impl class of adapter.\n * @param root the root view of current item.\n * @param holder the holder of adapter\n * @param listeners additional params, when your class of listener have no empty-parameter constructor, you should pass the listener object manually...\n * @return the current obj\n */\n IRipened inject(Adapter adapter, View root, Object holder, Object... listeners);\n}", "@SuppressWarnings(\"all\")\npublic class VIContext {\n\n private static final String CLS_NOT_FOUND = \"can not find class: %s, please check your code...\";\n private static final String NO_EMPTY_CONS = \"class: %s have no empty-param constructor, please check your code...\";\n private static final String NONE_PUBLIC = \"class: %s's empty-param constructor with non-public modifier, please check your code...\";\n\n private static final Map<String, String> PLUGIN_CENTER = new HashMap<String, String>() {\n {\n this.put(\"Adapter\", \"org.studio.maizi.ripened.impl.AdapterSetter\");\n this.put(\"Content\", \"org.studio.maizi.ripened.impl.ContentSetter\");\n this.put(\"Event\", \"org.studio.maizi.ripened.impl.EventBinder\");\n this.put(\"Animation\", \"org.studio.maizi.ripened.impl.AnimationSetter\");\n }\n };\n\n private static final Map<String, String> ANNO_PLUGIN_MAPPING = new HashMap<String, String>() {\n {\n this.put(\"Adapter\", \"Adapter\");\n this.put(\"ContentView\", \"Content\");\n this.put(\"EventTarget\", \"Event\");\n this.put(\"RegistListener\", \"Event\");\n this.put(\"Anim\", \"Animation\");\n }\n };\n\n /**\n * the container of IPlugin\n */\n private Set<IPlugin> plugins = new HashSet<>();\n\n /**\n * add plugin\n *\n * @param plugins the object of plugin.\n * @return current obj.\n */\n public VIContext addPlugin(IPlugin... plugins) {\n for (IPlugin plugin : plugins)\n this.plugins.add(plugin);\n return this;\n }\n\n /**\n * add plugin aware from annotation.\n *\n * @param classes the classes of annotation.\n * @return current obj.\n */\n public VIContext addPlugin(Annotation... annos) {\n for (Annotation anno : annos) {\n String name = anno.annotationType().getSimpleName();\n String pluginName;\n if ((pluginName = ANNO_PLUGIN_MAPPING.get(name)) != null) {\n String fullClsName = PLUGIN_CENTER.get(pluginName);\n try {\n Class<?> clazz = Class.forName(fullClsName);\n IPlugin plugin = IPlugin.class.cast(clazz.newInstance());\n addPlugin(plugin);\n } catch (ClassNotFoundException e) {\n throw new VIRuntimeException(StringFormatter.format(CLS_NOT_FOUND, fullClsName), e);\n } catch (InstantiationException e) {\n throw new VIRuntimeException(StringFormatter.format(NO_EMPTY_CONS, fullClsName), e);\n } catch (IllegalAccessException e) {\n throw new VIRuntimeException(StringFormatter.format(NONE_PUBLIC, fullClsName), e);\n }\n }\n }\n return this;\n }\n\n /**\n * remove a plugin from the current VIContext.\n *\n * @param plugin the object of plugin\n * @return\n */\n public boolean removePlugin(IPlugin plugin) {\n return plugins.remove(plugin);\n }\n\n /**\n * remove all the plugins from the current VIContext.\n *\n * @param plugin\n */\n public void removeAllPlugin(IPlugin plugin) {\n plugins.clear();\n }\n\n /**\n * get all the plugins from the current VIContext.\n *\n * @return\n */\n public Set<IPlugin> getPlugins() {\n return plugins;\n }\n\n /**\n * get the plugin of IContent if there we have.\n *\n * @return\n */\n public IPlugin getContentPlugin() {\n for (IPlugin plugin : plugins) {\n if (plugin.getName().equals(\"Content\"))\n return plugin;\n }\n return null;\n }\n}", "public class ActionParams {\n /**\n * an instance of activity or fragment or holder of an adapter.\n */\n private Object obj;\n /**\n * when the init param start with an adapter,this object is adapter for transfer.\n */\n private Object transfer;\n /**\n * the field current scanning.\n */\n private Field field;\n /**\n * the ResId's value of which field current scanning with the annotation of ResId\n */\n private int resId;\n /**\n * the holder of an adapter.\n */\n private Object holder;\n /**\n * all the listeners.\n */\n private Object[] listeners;\n\n public ActionParams(Object obj, Object transfer, Field field, int resId, Object holder, Object[] listeners) {\n this.obj = obj;\n this.transfer = transfer;\n this.field = field;\n this.resId = resId;\n this.holder = holder;\n this.listeners = listeners;\n }\n\n public Object getObj() {\n return obj;\n }\n\n public void setObj(Object obj) {\n this.obj = obj;\n }\n\n public Object getTransfer() {\n return transfer;\n }\n\n public void setTransfer(Object transfer) {\n this.transfer = transfer;\n }\n\n public Field getField() {\n return field;\n }\n\n public void setField(Field field) {\n this.field = field;\n }\n\n public int getResId() {\n return resId;\n }\n\n public void setResId(int resId) {\n this.resId = resId;\n }\n\n public Object getHolder() {\n return holder;\n }\n\n public void setHolder(Object holder) {\n this.holder = holder;\n }\n\n public Object[] getListeners() {\n return listeners;\n }\n\n public void setListeners(Object[] listeners) {\n this.listeners = listeners;\n }\n}", "public class VIRuntimeException extends RuntimeException {\n\n public VIRuntimeException(String detailMessage) { super(detailMessage); }\n\n public VIRuntimeException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); }\n}", "public class StringFormatter {\n\n /**\n * format the string.\n * @param str the string which will be format\n * @param obj the object which match each place with it's turn.\n * @return the string formatted\n */\n public static String format(String str, Object... obj) {\n return new Formatter().format(str, obj).toString();\n }\n}", "public enum Type {\n Activity,\n Fragment,\n Adapter,\n}" ]
import android.view.View; import android.widget.Adapter; import org.studio.maizi.ripened.IPlugin; import org.studio.maizi.ripened.IRipened; import org.studio.maizi.ripened.VIContext; import org.studio.maizi.ripened.anno.ResId; import org.studio.maizi.ripened.dto.ActionParams; import org.studio.maizi.ripened.exception.VIRuntimeException; import org.studio.maizi.ripened.util.StringFormatter; import org.studio.maizi.ripened.util.Type; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import android.app.Activity; import android.app.Fragment;
/* * $HomePage: https://github.com/maizi0122/ $ * $Revision: 000001 $ * $Date: 2015-10-18 09:05:31 -0000 (Sun, 18 Oct 2015) $ * * ==================================================================== * Copyright (C) 2015 The Maizi-Studio Open Source 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. * ==================================================================== * * This project powered by Maizi-Studio, but works with the * license of apache,so you should abide by this license. * Any question contacting with email below: * maizi0122@gmail.com */ package org.studio.maizi.ripened.impl; /** * an implementation of IRipened.<br /> * Created by maizi on 13-10-8.<br /> * <p>auto view injection */ @SuppressWarnings("all") public class Ripened implements IRipened { private static final String NULL_CTX = "param context can not be null, please check your code..."; private static final String NULL_FRAG_OR_ROOT = "params fragment or root can not be null, please check your code..."; private static final String NULL_ADAPTER_OR_ROOT_OR_HOLDER = "params adapter or root or holder can not be null, please check your code..."; private static final String ILLEGAL_ID = "can not find the view by id: %s annotation(ResId):#0x %s .please check your code..."; private static final String ILLEGAL_FIELD = "Field: %s was not a subclass of view,please check your code..."; private static final String CAST_EXCEPTION = "Field: %s : %s"; private VIContext viContext; public Ripened() { } public Ripened(VIContext viContext) { this.viContext = viContext; } @Override public IRipened setVIContext(VIContext viContext) { this.viContext = viContext; return this; } @Override public VIContext getVIContext() { return viContext; } @Override public IRipened inject(Activity context, Object... listeners) { if (context == null) throw new RuntimeException(NULL_CTX); Class<? extends Activity> clazz = context.getClass(); analysis(context, null, clazz, null, listeners); return this; } @Override public IRipened inject(Fragment fragment, View root, Object... listeners) { if (fragment == null || root == null) throw new RuntimeException(NULL_FRAG_OR_ROOT); Class<? extends Fragment> clazz = fragment.getClass(); analysis(fragment, root, clazz, null, listeners); return this; } @Override public IRipened inject(Adapter adapter, View root, Object holder, Object... listeners) { if (adapter == null || root == null || holder == null) throw new RuntimeException(NULL_ADAPTER_OR_ROOT_OR_HOLDER); Class<?> clazz = holder.getClass(); analysis(adapter, root, clazz, holder/*, adapter*/); return this; } /** * analysis the object of activity of fragment<br /> * if you setup the IEventBinder, we can also help you bind the listener smartly.<br /> * In fact, we are not force you to use auto-event binding, you can bind the listener all by yourself.<br /> * * @param obj may be an instance of activity|fragment|hodler * @param root the root view of current item. * @param clazz the class of current obj,in case current runtime. * @param listeners additional params, when your class of listener have no empty-parameter constructor, you should pass the listener object manually...additional params, when your class of listener have no empty-parameter constructor, you should pass the listener object manually... */ private void analysis(Object obj, View root, Class<?> clazz, Object holder, Object... listeners) { Type type = null; Activity context = null; if (obj instanceof Activity) { context = Activity.class.cast(obj); type = Type.Activity; analysisPlugin(clazz); } else if (obj instanceof Fragment) { type = Type.Fragment; } else if (obj instanceof Adapter) { type = Type.Adapter; } IPlugin contentView = null; if (viContext != null && (contentView = viContext.getContentPlugin()) != null) contentView.action(new ActionParams(obj, null, null, 0, null, null)); Field[] declaredFields = clazz.getDeclaredFields(); if (type.equals(Type.Adapter)) declaredFields = holder.getClass().getDeclaredFields(); Object transfer = null; for (Field field : declaredFields) { field.setAccessible(true); analysisPlugin(field); ResId anno = field.getAnnotation(ResId.class); int resId = 0; if (type.equals(Type.Adapter)) { if (transfer == null) transfer = obj; } if (anno != null) { resId = anno.value(); View viewById = null; if (type.equals(Type.Activity)) viewById = context.findViewById(resId); else if (type.equals(Type.Fragment) || type.equals(Type.Adapter)) viewById = root.findViewById(resId); if (viewById == null) {
throw new VIRuntimeException(StringFormatter.format(ILLEGAL_ID, field.toString(), Integer.toHexString(resId)));
5
Guichaguri/BetterFps
src/main/java/guichaguri/betterfps/transformers/MathTransformer.java
[ "public class BetterFpsConfig {\r\n\r\n public AlgorithmType algorithm = AlgorithmType.RIVENS_HALF;\r\n\r\n public boolean updateChecker = true;\r\n\r\n public boolean preallocateMemory = false;\r\n\r\n public boolean fog = true;\r\n\r\n public boolean beaconBeam = true;\r\n\r\n public boolean fastHopper = true;\r\n\r\n public boolean fastBeacon = true;\r\n\r\n public boolean fastSearch = true;\r\n\r\n public boolean asyncSearch = true;\r\n\r\n public enum AlgorithmType {\r\n @SerializedName(\"vanilla\") VANILLA,\r\n @SerializedName(\"java\") JAVA,\r\n @SerializedName(\"libgdx\") LIBGDX,\r\n @SerializedName(\"random\") RANDOM,\r\n @SerializedName(\"rivens-full\") RIVENS_FULL,\r\n @SerializedName(\"rivens-half\") RIVENS_HALF,\r\n @SerializedName(\"rivens\") RIVENS,\r\n @SerializedName(\"taylors\") TAYLORS;\r\n }\r\n\r\n}\r", "public enum AlgorithmType {\r\n @SerializedName(\"vanilla\") VANILLA,\r\n @SerializedName(\"java\") JAVA,\r\n @SerializedName(\"libgdx\") LIBGDX,\r\n @SerializedName(\"random\") RANDOM,\r\n @SerializedName(\"rivens-full\") RIVENS_FULL,\r\n @SerializedName(\"rivens-half\") RIVENS_HALF,\r\n @SerializedName(\"rivens\") RIVENS,\r\n @SerializedName(\"taylors\") TAYLORS;\r\n}\r", "public class BetterFpsHelper {\r\n\r\n public static final Logger LOG = LogManager.getLogger(\"BetterFps\");\r\n\r\n private static BetterFpsConfig INSTANCE = null;\r\n private static File CONFIG_FILE = null;\r\n\r\n public static BetterFpsConfig getConfig() {\r\n if(INSTANCE == null) loadConfig();\r\n return INSTANCE;\r\n }\r\n\r\n public static void loadConfig() {\r\n File configPath;\r\n if(BetterFps.GAME_DIR == null) {\r\n configPath = new File(\"config\");\r\n } else {\r\n configPath = new File(BetterFps.GAME_DIR, \"config\");\r\n }\r\n\r\n CONFIG_FILE = new File(configPath, \"betterfps.json\");\r\n\r\n // Temporary code - Import old config file to the new one\r\n File oldConfig;\r\n if(BetterFps.GAME_DIR == null) {\r\n oldConfig = new File(\"config\" + File.pathSeparator + \"betterfps.json\");\r\n } else {\r\n oldConfig = new File(BetterFps.GAME_DIR, \"config\" + File.pathSeparator + \"betterfps.json\");\r\n }\r\n if(oldConfig.exists()) {\r\n FileReader reader = null;\r\n try {\r\n reader = new FileReader(oldConfig);\r\n INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);\r\n saveConfig();\r\n return;\r\n } catch(Exception ex) {\r\n LOG.error(\"Could not load the old config file. It will be deleted.\");\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n oldConfig.deleteOnExit();\r\n }\r\n }\r\n // -------\r\n\r\n FileReader reader = null;\r\n try {\r\n if(CONFIG_FILE.exists()) {\r\n reader = new FileReader(CONFIG_FILE);\r\n INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);\r\n }\r\n } catch(Exception ex) {\r\n LOG.error(\"Could not load the config file\", ex);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n\r\n if(INSTANCE == null) INSTANCE = new BetterFpsConfig();\r\n\r\n saveConfig();\r\n }\r\n\r\n public static void saveConfig() {\r\n FileWriter writer = null;\r\n try {\r\n if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs();\r\n writer = new FileWriter(CONFIG_FILE);\r\n new Gson().toJson(INSTANCE, writer);\r\n } catch(Exception ex) {\r\n LOG.error(\"Could not save the config file\", ex);\r\n } finally {\r\n IOUtils.closeQuietly(writer);\r\n }\r\n }\r\n\r\n}\r", "public class BetterFpsTweaker implements ITweaker {\r\n\r\n public static InputStream getResourceStream(String path) {\r\n return BetterFpsTweaker.class.getClassLoader().getResourceAsStream(path);\r\n }\r\n\r\n public static URL getResource(String path) {\r\n return BetterFpsTweaker.class.getClassLoader().getResource(path);\r\n }\r\n\r\n private static final String[] TRANSFORMERS = new String[] {\r\n \"guichaguri.betterfps.transformers.PatcherTransformer\",\r\n \"guichaguri.betterfps.transformers.MathTransformer\"\r\n };\r\n\r\n private final String[] EXCLUDED = new String[] {\r\n \"guichaguri.betterfps.transformers\",\r\n \"guichaguri.betterfps.tweaker\",\r\n \"guichaguri.betterfps.patchers\"\r\n };\r\n\r\n private final String[] LOAD_DISABLED = new String[] {\r\n \"guichaguri.betterfps.installer\",\r\n \"guichaguri.betterfps.math\",\r\n \"guichaguri.betterfps.patches\"\r\n };\r\n\r\n private List<String> args;\r\n\r\n @Override\r\n public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {\r\n this.args = new ArrayList<String>(args);\r\n\r\n this.args.add(\"--version\");\r\n this.args.add(profile);\r\n\r\n if(assetsDir != null) {\r\n this.args.add(\"--assetsDir\");\r\n this.args.add(assetsDir.getAbsolutePath());\r\n }\r\n if(gameDir != null) {\r\n this.args.add(\"--gameDir\");\r\n this.args.add(gameDir.getAbsolutePath());\r\n }\r\n\r\n BetterFps.GAME_DIR = gameDir;\r\n }\r\n\r\n @Override\r\n public void injectIntoClassLoader(LaunchClassLoader cl) {\r\n loadMappings();\r\n\r\n for(String transformer : TRANSFORMERS) {\r\n cl.registerTransformer(transformer);\r\n }\r\n\r\n for(String excluded : EXCLUDED) {\r\n cl.addTransformerExclusion(excluded);\r\n }\r\n\r\n for(String loadDisabled : LOAD_DISABLED) {\r\n cl.addClassLoaderExclusion(loadDisabled);\r\n }\r\n }\r\n\r\n @Override\r\n public String getLaunchTarget() {\r\n return \"net.minecraft.client.main.Main\";\r\n }\r\n\r\n @Override\r\n public String[] getLaunchArguments() {\r\n\r\n ArrayList args = (ArrayList)Launch.blackboard.get(\"ArgumentList\");\r\n if(args.isEmpty()) args.addAll(this.args);\r\n\r\n this.args = null;\r\n\r\n // Just in case someone needs to know whether BetterFps is running\r\n Launch.blackboard.put(\"BetterFpsVersion\", BetterFps.VERSION);\r\n\r\n return new String[0];\r\n }\r\n\r\n private void loadMappings() {\r\n BetterFpsHelper.LOG.debug(\"Loading Mappings...\");\r\n try {\r\n Mappings.loadMappings(getResourceStream(\"betterfps.srg\"));\r\n } catch(IOException ex) {\r\n BetterFpsHelper.LOG.error(\"Could not load mappings. Things will not work!\");\r\n }\r\n }\r\n}\r", "public enum Mappings {\n\n // TODO: new mapping system. Maybe reading this class by a gradle task and saving the map in a file?\n\n // Prefixes\n // C_ is for classes\n // M_ is for methods\n // F_ is for fields\n\n M_StaticBlock(Type.METHOD, \"StaticBlock\", \"<clinit>\"),\n M_Constructor(Type.METHOD, \"Constructor\", \"<init>\"),\n\n C_Minecraft(Type.CLASS, \"Minecraft\"),\n C_World(Type.CLASS, \"World\"),\n C_Chunk(Type.CLASS, \"Chunk\"),\n C_Block(Type.CLASS, \"Block\"),\n C_EntityPlayer(Type.CLASS, \"EntityPlayer\"),\n C_EntityPlayerSP(Type.CLASS, \"EntityPlayerSP\"),\n C_MathHelper(Type.CLASS, \"MathHelper\"),\n C_PrimedTNT(Type.CLASS, \"EntityTNTPrimed\"),\n C_ClientBrandRetriever(Type.CLASS, \"ClientBrandRetriever\"),\n C_GuiOptions(Type.CLASS, \"GuiOptions\"),\n C_WorldClient(Type.CLASS, \"WorldClient\"),\n C_WorldServer(Type.CLASS, \"WorldServer\"),\n C_IntegratedServer(Type.CLASS, \"IntegratedServer\"),\n C_DedicatedServer(Type.CLASS, \"DedicatedServer\"),\n C_TileEntityBeacon(Type.CLASS, \"TileEntityBeacon\"),\n C_TileEntityBeaconRenderer(Type.CLASS, \"TileEntityBeaconRenderer\"),\n C_BeamSegment(Type.CLASS, \"TileEntityBeacon$BeamSegment\"),\n C_TileEntityHopper(Type.CLASS, \"TileEntityHopper\"),\n C_BlockHopper(Type.CLASS, \"BlockHopper\"),\n C_ModelBox(Type.CLASS, \"ModelBox\"),\n C_EntityRenderer(Type.CLASS, \"EntityRenderer\"),\n C_IInventory(Type.CLASS, \"IInventory\"),\n C_GuiContainerCreative(Type.CLASS, \"GuiContainerCreative\"),\n C_RenderPlayer(Type.CLASS, \"RenderPlayer\"),\n\n M_startGame(Type.METHOD, \"startGame\"), // Minecraft\n M_sin(Type.METHOD, \"sin\"), // MathHelper\n M_cos(Type.METHOD, \"cos\"), // MathHelper\n M_tick(Type.METHOD, \"tick\"), // World\n M_onUpdate(Type.METHOD, \"onUpdate\"), // Entity\n M_updateBlocks(Type.METHOD, \"updateBlocks\"), // World\n M_getClientModName(Type.METHOD, \"getClientModName\"), // ClientBrandRetriever\n M_freeMemory(Type.METHOD, \"freeMemory\"), // Minecraft\n M_initGui(Type.METHOD, \"initGui\"), // GuiScreen\n M_startServer(Type.METHOD, \"startServer\"), // MinecraftServer\n M_captureDroppedItems(Type.METHOD, \"captureDroppedItems\"), // TileEntityHopper\n M_getHopperInventory(Type.METHOD, \"getHopperInventory\"), // TileEntityHopper\n\n F_memoryReserve(Type.FIELD, \"memoryReserve\"), // Minecraft\n F_SIN_TABLE(Type.FIELD, \"SIN_TABLE\"); // MathHelper\n\n public static void loadMappings(InputStream srg) throws IOException {\n List<String> lines = IOUtils.readLines(srg, \"UTF-8\");\n for(String line : lines) {\n String[] m = line.split(\" \");\n String identifier = m[m.length - 1];\n\n for(Mappings mp : values()) {\n if(m[0].equals(\"CL:\")) {\n if(m.length >= 4 && mp.type == Type.CLASS && mp.identifier.equals(identifier)) {\n mp.deobfName = m[2];\n mp.obfName = m[1];\n }\n } else if(m[0].equals(\"FD:\")) {\n if(m.length >= 4 && mp.type == Type.FIELD && mp.identifier.equals(identifier)) {\n loadNames(m, mp, 2, 1);\n }\n } else if(m[0].equals(\"MD:\")) {\n if(m.length >= 6 && mp.type == Type.METHOD && mp.identifier.equals(identifier)) {\n loadNames(m, mp, 3, 1);\n mp.deobfDesc = m[4];\n mp.obfDesc = m[2];\n }\n }\n }\n }\n }\n\n private static void loadNames(String[] m, Mappings mp, int deobf, int obf) {\n String[] name = m[deobf].split(\"/\");\n mp.deobfName = name[name.length - 1];\n mp.ownerDeobfName = StringUtils.join(name, \"/\", 0, name.length - 1);\n\n name = m[obf].split(\"/\");\n mp.obfName = name[name.length - 1];\n mp.ownerObfName = StringUtils.join(name, \"/\", 0, name.length - 1);\n }\n\n public final Type type;\n public final String identifier;\n protected String deobfName, obfName;\n protected String ownerDeobfName, ownerObfName;\n protected String deobfDesc, obfDesc;\n\n Mappings(Type type, String identifier) {\n this.type = type;\n this.identifier = identifier;\n }\n\n Mappings(Type type, String identifier, String name) {\n this(type, identifier);\n this.deobfName = name;\n this.obfName = name;\n }\n\n public boolean is(String n) {\n n = n.replaceAll(\"\\\\.\", \"/\");\n return deobfName.equals(n) || obfName.equals(n);\n }\n\n public boolean isObf(String n) {\n return !deobfName.equals(obfName) && obfName.equals(n.replaceAll(\"\\\\.\", \"/\"));\n }\n\n public boolean isDesc(String n) {\n return (deobfDesc != null && n.equals(deobfDesc)) || (obfDesc != null && n.equals(obfDesc));\n }\n\n public boolean isOwner(String n) {\n n = n.replaceAll(\"\\\\.\", \"/\");\n return ownerDeobfName == null || ownerObfName == null || n.equals(ownerDeobfName) || n.equals(ownerObfName);\n }\n\n public boolean is(String n, String d) {\n return is(n) && isDesc(d);\n }\n\n public boolean is(MethodNode method) {\n return (method.name.equals(deobfName) || method.name.equals(obfName)) && isDesc(method.desc);\n }\n\n public boolean is(FieldNode field) {\n return (field.name.equals(deobfName) || field.name.equals(obfName)) && isDesc(field.desc);\n }\n\n public boolean is(MethodInsnNode method) {\n return is(method.name) && isDesc(method.desc) && isOwner(method.owner);\n }\n\n public boolean is(FieldInsnNode field) {\n return is(field.name) && isDesc(field.desc) && isOwner(field.owner);\n }\n\n @Override\n public String toString() {\n return identifier;\n }\n\n enum Type {\n CLASS, METHOD, FIELD\n }\n\n}" ]
import guichaguri.betterfps.BetterFpsConfig; import guichaguri.betterfps.BetterFpsConfig.AlgorithmType; import guichaguri.betterfps.BetterFpsHelper; import guichaguri.betterfps.tweaker.BetterFpsTweaker; import guichaguri.betterfps.tweaker.Mappings; import java.io.InputStream; import java.util.LinkedHashMap; import net.minecraft.launchwrapper.IClassTransformer; import org.apache.commons.io.IOUtils; import org.objectweb.asm.tree.*;
package guichaguri.betterfps.transformers; /** * @author Guilherme Chaguri */ public class MathTransformer implements IClassTransformer { // Config Name, Class Name private static final LinkedHashMap<AlgorithmType, String> algorithmClasses = new LinkedHashMap<AlgorithmType, String>(); static { algorithmClasses.put(AlgorithmType.RIVENS, "guichaguri/betterfps/math/RivensMath"); algorithmClasses.put(AlgorithmType.TAYLORS, "guichaguri/betterfps/math/TaylorMath"); algorithmClasses.put(AlgorithmType.LIBGDX, "guichaguri/betterfps/math/LibGDXMath"); algorithmClasses.put(AlgorithmType.RIVENS_FULL, "guichaguri/betterfps/math/RivensFullMath"); algorithmClasses.put(AlgorithmType.RIVENS_HALF, "guichaguri/betterfps/math/RivensHalfMath"); algorithmClasses.put(AlgorithmType.JAVA, "guichaguri/betterfps/math/JavaMath"); algorithmClasses.put(AlgorithmType.RANDOM, "guichaguri/betterfps/math/RandomMath"); } private final String METHOD_SIN = "sin"; private final String METHOD_COS = "cos"; @Override public byte[] transform(String name, String transformedName, byte[] bytes) { if(bytes == null) return null;
if(Mappings.C_MathHelper.is(name)) {
4
adridadou/eth-contract-api
src/test/java/org/adridadou/EventsTest.java
[ "public class EthereumFacade {\n public static final Charset CHARSET = Charsets.UTF_8;\n private final EthereumContractInvocationHandler handler;\n private final OutputTypeHandler outputTypeHandler;\n private final InputTypeHandler inputTypeHandler;\n private final EthereumProxy ethereumProxy;\n private final SwarmService swarmService;\n private final SolidityCompiler solidityCompiler;\n\n public EthereumFacade(EthereumProxy ethereumProxy, InputTypeHandler inputTypeHandler, OutputTypeHandler outputTypeHandler, SwarmService swarmService, SolidityCompiler solidityCompiler) {\n this.inputTypeHandler = inputTypeHandler;\n this.outputTypeHandler = outputTypeHandler;\n this.swarmService = swarmService;\n this.solidityCompiler = solidityCompiler;\n this.handler = new EthereumContractInvocationHandler(ethereumProxy, inputTypeHandler, outputTypeHandler);\n this.ethereumProxy = ethereumProxy;\n }\n\n public EthereumFacade addInputHandlers(final List<InputTypeConverter> handlers) {\n inputTypeHandler.addConverters(handlers);\n return this;\n }\n\n public EthereumFacade addOutputHandlers(final List<OutputTypeConverter> handlers) {\n outputTypeHandler.addConverters(handlers);\n return this;\n }\n\n public EthereumFacade addFutureConverter(final FutureConverter futureConverter) {\n handler.addFutureConverter(futureConverter);\n return this;\n }\n\n public <T> T createContractProxy(CompiledContract contract, EthAddress address, EthAccount account, Class<T> contractInterface) {\n return createContractProxy(contract.getAbi(), address, account, contractInterface);\n }\n\n public <T> T createContractProxy(EthAddress address, EthAccount account, Class<T> contractInterface) {\n return createContractProxy(getAbi(address), address, account, contractInterface);\n }\n\n public <T> T createContractProxy(ContractAbi abi, EthAddress address, EthAccount account, Class<T> contractInterface) {\n T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler);\n handler.register(proxy, contractInterface, abi, address, account);\n return proxy;\n }\n\n public <T> Builder<T> createContractProxy(EthAddress address, Class<T> contractInterface) {\n return new Builder<>(contractInterface, address, getAbi(address));\n }\n\n public <T> Builder<T> createContractProxy(EthAddress address, ContractAbi abi, Class<T> contractInterface) {\n return new Builder<>(contractInterface, address, abi);\n }\n\n public <T> Builder<T> createContractProxy(CompiledContract contract, EthAddress address, Class<T> contractInterface) {\n return new Builder<>(contractInterface, address, contract.getAbi());\n }\n\n public ContractAbi getAbi(final EthAddress address) {\n SmartContractByteCode code = ethereumProxy.getCode(address);\n SmartContractMetadata metadata = getMetadata(code.getMetadaLink().orElseThrow(() -> new EthereumApiException(\"no metadata link found for smart contract on address \" + address.toString())));\n return metadata.getAbi();\n }\n\n public CompletableFuture<EthAddress> publishContract(CompiledContract contract, EthAccount account, Object... constructorArgs) {\n return ethereumProxy.publish(contract, account, constructorArgs);\n }\n\n public SwarmHash publishMetadataToSwarm(CompiledContract contract) {\n return swarmService.publish(contract.getMetadata().getValue());\n }\n\n public boolean addressExists(final EthAddress address) {\n return ethereumProxy.addressExists(address);\n }\n\n public EthValue getBalance(final EthAddress addr) {\n return ethereumProxy.getBalance(addr);\n }\n\n public EthValue getBalance(final EthAccount account) {\n return ethereumProxy.getBalance(account.getAddress());\n }\n\n public EthereumEventHandler events() {\n return ethereumProxy.events();\n }\n\n public CompletableFuture<EthExecutionResult> sendEther(EthAccount fromAccount, EthAddress to, EthValue value) {\n return ethereumProxy.sendTx(value, EthData.empty(), fromAccount, to);\n }\n\n public BigInteger getNonce(EthAddress address) {\n return ethereumProxy.getNonce(address);\n }\n\n public SmartContractByteCode getCode(EthAddress address) {\n return ethereumProxy.getCode(address);\n }\n\n public SmartContractMetadata getMetadata(SwarmMetadaLink swarmMetadaLink) {\n try {\n return swarmService.getMetadata(swarmMetadaLink.getHash());\n } catch (IOException e) {\n throw new EthereumApiException(\"error while getting metadata\", e);\n }\n }\n\n public CompletableFuture<Map<String, CompiledContract>> compile(SoliditySource src) {\n if(src instanceof SoliditySourceString){\n return CompletableFuture.supplyAsync(() -> compileInternal((SoliditySourceString)src));\n }\n\n if(src instanceof SoliditySourceFile) {\n return CompletableFuture.supplyAsync(() -> compileInternal((SoliditySourceFile)src));\n }\n\n throw new EthereumApiException(\"error while trying to compile \" + src);\n }\n\n private Map<String, CompiledContract> compileInternal(SoliditySourceFile src) {\n try {\n SolidityCompiler.Result result = solidityCompiler.compileSrc(src.getSource(), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.METADATA);\n if (result.isFailed()) {\n throw new EthereumApiException(\"Contract compilation failed:\\n\" + result.errors);\n }\n CompilationResult res = CompilationResult.parse(result.output);\n if (res.contracts == null || res.contracts.isEmpty()) {\n throw new EthereumApiException(\"Compilation failed, no contracts returned:\\n\" + result.errors);\n }\n return res.contracts.entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getKey, e -> CompiledContract.from(src, e.getKey(), e.getValue())));\n } catch (IOException e) {\n throw new EthereumApiException(\"error while compiling solidity smart contract\", e);\n }\n }\n\n private Map<String, CompiledContract> compileInternal(SoliditySourceString src) {\n try {\n SolidityCompiler.Result result = solidityCompiler.compileSrc(src.getSource().getBytes(EthereumFacade.CHARSET), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.METADATA);\n if (result.isFailed()) {\n throw new EthereumApiException(\"Contract compilation failed:\\n\" + result.errors);\n }\n CompilationResult res = CompilationResult.parse(result.output);\n if (res.contracts.isEmpty()) {\n throw new EthereumApiException(\"Compilation failed, no contracts returned:\\n\" + result.errors);\n }\n return res.contracts.entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getKey, e -> CompiledContract.from(src, e.getKey(), e.getValue())));\n } catch (IOException e) {\n throw new EthereumApiException(\"error while compiling solidity smart contract\", e);\n }\n }\n\n public <T> Observable<T> observeEvents(ContractAbi abi, EthAddress address, String eventName, Class<T> cls) {\n return ethereumProxy.observeEvents(abi, address, eventName, cls);\n }\n\n public class Builder<T> {\n private final Class<T> contractInterface;\n private final EthAddress address;\n private final ContractAbi abi;\n\n public Builder(Class<T> contractInterface, EthAddress address, ContractAbi abi) {\n this.contractInterface = contractInterface;\n this.address = address;\n this.abi = abi;\n }\n\n public T forAccount(final EthAccount account) {\n T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler);\n EthereumFacade.this.handler.register(proxy, contractInterface, abi, address, account);\n return proxy;\n }\n }\n}", "public class TestConfig {\n public static final int DEFAULT_GAS_LIMIT = 4_700_000;\n public static final long DEFAULT_GAS_PRICE = 50_000_000_000L;\n private final Date initialTime;\n private final long gasLimit;\n private final long gasPrice;\n private final Map<EthAccount, EthValue> balances;\n\n public TestConfig(Date initialTime, long gasLimit, long gasPrice, Map<EthAccount, EthValue> balances) {\n this.initialTime = initialTime;\n this.gasLimit = gasLimit;\n this.gasPrice = gasPrice;\n this.balances = balances;\n }\n\n public long getGasLimit() {\n return gasLimit;\n }\n\n public long getGasPrice() {\n return gasPrice;\n }\n\n public Map<EthAccount, EthValue> getBalances() {\n return balances;\n }\n\n public Date getInitialTime() {\n return initialTime;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n private long gasLimit = DEFAULT_GAS_LIMIT;\n private long gasPrice = DEFAULT_GAS_PRICE;\n private final Map<EthAccount, EthValue> balances = new HashMap<>();\n private Date initialTime = new Date();\n\n public Builder gasLimit(long gasLimit) {\n this.gasLimit = gasLimit;\n return this;\n }\n\n public Builder gasPrice(long gasPrice) {\n this.gasPrice = gasPrice;\n return this;\n }\n\n public Builder balance(EthAccount account, EthValue value) {\n this.balances.put(account,value);\n return this;\n }\n\n public Builder initialTime(Date date) {\n this.initialTime = date;\n return this;\n }\n\n public TestConfig build() {\n return new TestConfig(initialTime, gasLimit, gasPrice, balances);\n }\n }\n}", "public class AccountProvider {\n\n public static final int BIT_LENGTH = 256;\n\n private AccountProvider() {}\n\n public static EthAccount fromPrivateKey(final byte[] privateKey) {\n return new EthAccount(new BigInteger(1, privateKey));\n }\n\n public static EthAccount fromPrivateKey(final String privateKey) {\n return AccountProvider.fromPrivateKey(Hex.decode(privateKey));\n }\n\n public static EthAccount fromECKey(final ECKey ecKey) {\n return new EthAccount(ecKey.getPrivKey());\n }\n\n public static EthAccount fromSeed(final String id) {\n return AccountProvider.fromPrivateKey(doSha3(id.getBytes(EthereumFacade.CHARSET)));\n }\n\n public static SecureKey fromKeystore(final File file) {\n return new FileSecureKey(file);\n }\n\n public static List<SecureKey> listMainKeystores() {\n return listKeystores(new File(WalletUtils.getMainnetKeyDirectory()));\n }\n\n public static List<SecureKey> listRopstenKeystores() {\n return listKeystores(new File(WalletUtils.getTestnetKeyDirectory()));\n }\n\n public static List<SecureKey> listKeystores(final File directory) {\n File[] files = Optional.ofNullable(directory.listFiles()).orElseThrow(() -> new EthereumApiException(\"cannot find the folder \" + WalletUtils.getMainnetKeyDirectory()));\n return Arrays.stream(files)\n .filter(File::isFile)\n .map(AccountProvider::fromKeystore)\n .collect(Collectors.toList());\n }\n\n private static byte[] doSha3(byte[] message) {\n SHA3Digest digest = new SHA3Digest(BIT_LENGTH);\n byte[] hash = new byte[digest.getDigestSize()];\n\n if (message.length != 0) {\n digest.update(message, 0, message.length);\n }\n digest.doFinal(hash, 0);\n return hash;\n }\n}", "public class EthereumFacadeProvider {\n public static final ChainId MAIN_CHAIN_ID = ChainId.id(0);\n public static final ChainId ROPSTEN_CHAIN_ID = ChainId.id(3);\n public static final ChainId ETHER_CAMP_CHAIN_ID = ChainId.id(161);\n\n private EthereumFacadeProvider() {}\n\n public static Builder forNetwork(final BlockchainConfig config) {\n return new Builder(config);\n }\n\n public static EthereumFacade forTest(TestConfig config){\n EthereumTest ethereumj = new EthereumTest(config);\n EthereumEventHandler ethereumListener = new EthereumEventHandler();\n ethereumListener.onReady();\n return new Builder(BlockchainConfig.builder()).create(ethereumj, ethereumListener);\n }\n\n public static EthereumFacade forRemoteNode(final String url, final ChainId chainId) {\n Web3JFacade web3j = new Web3JFacade(Web3j.build(new HttpService(url)), new OutputTypeHandler(), chainId);\n EthereumRPC ethRpc = new EthereumRPC(web3j, new EthereumRpcEventGenerator(web3j));\n InputTypeHandler inputTypeHandler = new InputTypeHandler();\n OutputTypeHandler outputTypeHandler = new OutputTypeHandler();\n EthereumEventHandler ethereumListener = new EthereumEventHandler(); \n web3j.observeBlocks().take(1).subscribe(b-> ethereumListener.onReady());\n return new EthereumFacade(new EthereumProxy(ethRpc, ethereumListener, inputTypeHandler, outputTypeHandler), inputTypeHandler, outputTypeHandler, new SwarmService(SwarmService.PUBLIC_HOST),SolidityCompiler.getInstance());\n }\n\n public static InfuraBuilder forInfura(final InfuraKey key) {\n return new InfuraBuilder(key);\n }\n\n public static class InfuraBuilder {\n private final InfuraKey key;\n\n public InfuraBuilder(InfuraKey key) {\n this.key = key;\n }\n\n public EthereumFacade createMain() {\n return forRemoteNode(\"https://main.infura.io/\" + key.key, EthereumFacadeProvider.MAIN_CHAIN_ID);\n }\n\n public EthereumFacade createRopsten() {\n return forRemoteNode(\"https://ropsten.infura.io/\" + key.key, EthereumFacadeProvider.ROPSTEN_CHAIN_ID);\n }\n }\n\n public static class Builder {\n\n private final BlockchainConfig configBuilder;\n\n public Builder(BlockchainConfig configBuilder) {\n this.configBuilder = configBuilder;\n }\n\n public BlockchainConfig extendConfig() {\n return configBuilder;\n }\n\n public EthereumFacade create(){\n GenericConfig.config = configBuilder.toString();\n EthereumReal ethereum = new EthereumReal(EthereumFactory.createEthereum(GenericConfig.class));\n return create(ethereum, new EthereumEventHandler());\n }\n\n public EthereumFacade create(EthereumBackend ethereum, EthereumEventHandler ethereumListener) {\n InputTypeHandler inputTypeHandler = new InputTypeHandler();\n OutputTypeHandler outputTypeHandler = new OutputTypeHandler();\n return new EthereumFacade(new EthereumProxy(ethereum, ethereumListener,inputTypeHandler, outputTypeHandler),inputTypeHandler, outputTypeHandler, SwarmService.from(SwarmService.PUBLIC_HOST), SolidityCompiler.getInstance());\n }\n }\n\n private static class GenericConfig {\n private static String config;\n\n @Bean\n public SystemProperties systemProperties() {\n SystemProperties props = new SystemProperties();\n props.overrideParams(ConfigFactory.parseString(config));\n return props;\n }\n }\n}", "public static EthValue ether(final BigInteger value) {\n return wei(value.multiply(ETHER_CONVERSION.toBigInteger()));\n}" ]
import org.adridadou.ethereum.EthereumFacade; import org.adridadou.ethereum.ethj.TestConfig; import org.adridadou.ethereum.keystore.AccountProvider; import org.adridadou.ethereum.EthereumFacadeProvider; import org.adridadou.ethereum.values.*; import org.junit.Test; import rx.Observable; import java.util.concurrent.CompletableFuture; import static org.adridadou.ethereum.values.EthValue.ether; import static org.junit.Assert.assertEquals;
package org.adridadou; /** * Created by davidroon on 20.04.16. * This code is released under Apache 2 license */ public class EventsTest { private final EthAccount mainAccount = AccountProvider.fromSeed("hello"); private final EthereumFacade ethereum = EthereumFacadeProvider.forTest(TestConfig.builder()
.balance(mainAccount, ether(1000))
4
HugoGresse/Anecdote
app/src/main/java/io/gresse/hugo/anecdote/api/WebsiteApiService.java
[ "public class Configuration {\n\n public static final boolean DEBUG = BuildConfig.DEBUG;\n public static final String API_VERSION = \"2\";\n public static final String API_URL = \"https://anecdote-api.firebaseio.com/v\" + API_VERSION + \"/websites.json\";\n public static final String DOWNLOAD_FOLDER = \"Anecdote\";\n public static final int IMAGE_SAVE_TOAST_DURATION = 5000;\n public static final String DONATION_LINK = \"https://paypal.me/HugoGresse/5\";\n\n}", "public class LoadRemoteWebsiteEvent implements Event {\n}", "public class OnRemoteWebsiteResponseEvent implements Event {\n\n public boolean isSuccessful;\n public List<Website> websiteList;\n\n public OnRemoteWebsiteResponseEvent(boolean isSuccessful, List<Website> websiteList) {\n this.isSuccessful = isSuccessful;\n this.websiteList = websiteList;\n }\n}", "public class Website {\n\n public static final String SOURCE_LOCAL = \"local\";\n public static final String SOURCE_REMOTE = \"remote\";\n public static final String SOURCE_CALCULATED = \"calc\";\n\n public int version;\n public String slug;\n public String name;\n public int color;\n public int like;\n public String source;\n public String userAgent;\n\n public List<WebsitePage> pages;\n\n public Website() {\n this(null, SOURCE_LOCAL);\n }\n\n public Website(String name, String source) {\n this.pages = new ArrayList<>();\n this.source = source;\n this.name = name;\n }\n\n /**\n * Validate this object by preventing any crash when using it\n */\n public void validateData() {\n if (TextUtils.isEmpty(name)) {\n name = Long.toHexString(Double.doubleToLongBits(Math.random()));\n }\n\n for(WebsitePage websitePage : pages){\n websitePage.validate();\n }\n\n if (TextUtils.isEmpty(slug)) {\n if (source.equals(SOURCE_REMOTE)) {\n slug = \"api-\" + name;\n } else if (source.equals(SOURCE_CALCULATED)) {\n slug = \"calc-\" + name;\n } else {\n slug = \"local-\" + name;\n }\n }\n }\n\n /**\n * Check if the version missmatch between the two object\n *\n * @param website the new website\n * @return true if up to date, false otherweise\n */\n public boolean isUpToDate(Website website) {\n return website.version <= version;\n }\n\n /**\n * Check if the user can edit this website manually or not\n *\n * @return true if editable\n */\n public boolean isEditable() {\n return source.equals(SOURCE_LOCAL);\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 Website website = (Website) o;\n\n if (!slug.equals(website.slug)) return false;\n return source.equals(website.source);\n\n }\n\n @Override\n public int hashCode() {\n int result = slug.hashCode();\n result = 31 * result + source.hashCode();\n return result;\n }\n\n @Override\n public String toString() {\n return \"Website{\" +\n \"version=\" + version +\n \", slug='\" + slug + '\\'' +\n \", name='\" + name + '\\'' +\n \", color=\" + color +\n \", like=\" + like +\n \", source='\" + source + '\\'' +\n \", userAgent='\" + userAgent + '\\'' +\n \", pages=\" + pages +\n '}';\n }\n}", "public interface Event {\n}", "public class RequestFailedEvent implements Event {\n\n public static final int ERROR_GENERAL = 0;\n public static final int ERROR_LOADFAIL = 1;\n public static final int ERROR_PROCESSING = 2;\n public static final int ERROR_RESPONSEFAIL = 3;\n public static final int ERROR_PARSING = 4;\n public static final int ERROR_NOINTERNET = 5;\n public static final int ERROR_SERVER = 6;\n public static final int ERROR_WRONGCONFIG = 7;\n\n public Event originalEvent;\n public int error;\n private String websiteName;\n @Nullable\n public Exception exception;\n public String additionalError;\n\n public RequestFailedEvent(Event originalEvent,\n int error,\n String websiteName,\n @Nullable Exception exception) {\n this(originalEvent, error, websiteName, exception, null);\n\n }\n\n public RequestFailedEvent(Event originalEvent,\n int error,\n String websiteName,\n @Nullable Exception exception,\n @Nullable String additionalError) {\n this.originalEvent = originalEvent;\n this.error = error;\n this.websiteName = websiteName;\n this.additionalError = additionalError;\n this.exception = exception;\n }\n\n /**\n * Format the current fail event to return an human readable message\n * @param context app context to get resources from\n * @return the human readable error message\n */\n public String formatErrorMessage(Context context){\n switch (error){\n default:\n case ERROR_GENERAL:\n return context.getResources().getString(R.string.error_general);\n case ERROR_NOINTERNET:\n return context.getResources().getString(R.string.error_nointernet);\n case ERROR_SERVER:\n return context.getResources().getString(R.string.error_server);\n case ERROR_WRONGCONFIG:\n return context.getResources().getString(R.string.error_wrongconfig);\n case ERROR_LOADFAIL:\n return context.getResources().getString(R.string.error_loadfail, websiteName);\n case ERROR_PROCESSING:\n return context.getResources().getString(R.string.error_processing);\n case ERROR_RESPONSEFAIL:\n return context.getResources().getString(R.string.error_responsefail, additionalError);\n case ERROR_PARSING:\n return context.getResources().getString(R.string.error_parsing, websiteName);\n }\n }\n\n @Override\n public String toString() {\n return \"RequestFailedEvent{\" +\n \"error='\" + error + '\\'' +\n \", websiteName=\" + websiteName + \" \" +\n \", exception=\" + exception +\n '}';\n }\n}", "public class NetworkConnectivityChangeEvent implements Event {\n\n public NetworkConnectivityListener.State state;\n\n public NetworkConnectivityChangeEvent(NetworkConnectivityListener.State state) {\n this.state = state;\n }\n}", "public class NetworkConnectivityListener {\n\n public static final String TAG = NetworkConnectivityListener.class.getSimpleName();\n\n private State mState;\n private ConnectivityBroadcastReceiver mReceiver;\n private Context mContext;\n @Nullable\n private ConnectivityListener mListener;\n private Handler mMainHandler;\n private Runnable mConnectivityRunnable;\n\n private class ConnectivityBroadcastReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n\n if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || mListener == null) {\n return;\n }\n\n ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();\n boolean networkAvailable = networkInfo != null && networkInfo.isConnected();\n\n if (networkAvailable) {\n mState = State.CONNECTED;\n } else {\n mState = State.NOT_CONNECTED;\n }\n\n mMainHandler.post(mConnectivityRunnable);\n }\n }\n\n public enum State {\n UNKNOWN,\n\n /**\n * This state is returned if there is connectivity to any network\n **/\n CONNECTED,\n /**\n * This state is returned if there is no connectivity to any network. This is set\n * to true under two circumstances:\n * <ul>\n * <li>When connectivity is lost to one network, and there is no other available\n * network to attempt to switch to.</li>\n * <li>When connectivity is lost to one network, and the attempt to switch to\n * another network fails.</li>\n */\n NOT_CONNECTED;\n }\n\n /**\n * Create a new NetworkConnectivityListener.\n */\n public NetworkConnectivityListener() {\n mState = State.UNKNOWN;\n mReceiver = new ConnectivityBroadcastReceiver();\n mConnectivityRunnable = new Runnable() {\n @Override\n public void run() {\n if (mListener != null) {\n mListener.onConnectivityChange(mState);\n }\n }\n };\n }\n\n /**\n * This method starts listening for network connectivity state changes.\n *\n * @param context app context\n */\n public synchronized void startListening(Context context, ConnectivityListener connectivityListener) {\n if (mListener == null) {\n mContext = context;\n mMainHandler = new Handler(context.getMainLooper());\n mListener = connectivityListener;\n\n IntentFilter filter = new IntentFilter();\n filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\n context.registerReceiver(mReceiver, filter);\n }\n }\n\n /**\n * This method stops this class from listening for network changes.\n */\n public synchronized void stopListening() {\n if (mListener != null) {\n mContext.unregisterReceiver(mReceiver);\n mMainHandler = null;\n mContext = null;\n mListener = null;\n }\n }\n\n /**\n * Listener for connectivity change with simple state\n */\n public interface ConnectivityListener {\n void onConnectivityChange(State state);\n }\n\n\n}" ]
import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.gresse.hugo.anecdote.Configuration; import io.gresse.hugo.anecdote.api.event.LoadRemoteWebsiteEvent; import io.gresse.hugo.anecdote.api.event.OnRemoteWebsiteResponseEvent; import io.gresse.hugo.anecdote.api.model.Website; import io.gresse.hugo.anecdote.event.Event; import io.gresse.hugo.anecdote.event.RequestFailedEvent; import io.gresse.hugo.anecdote.event.NetworkConnectivityChangeEvent; import io.gresse.hugo.anecdote.util.NetworkConnectivityListener; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
package io.gresse.hugo.anecdote.api; /** * Get the Anecdote website setting from remote api * <p/> * Created by Hugo Gresse on 26/04/16. */ public class WebsiteApiService { private static final String TAG = WebsiteApiService.class.getSimpleName(); @Nullable protected LoadRemoteWebsiteEvent mFailedEvent; private OkHttpClient mOkHttpClient; private List<Website> mWebsites; private Request mCurrentRequest; public WebsiteApiService() { mOkHttpClient = new OkHttpClient(); } /** * Download remote website configuration * * @param event the original event */ private void getRemoteSetting(final LoadRemoteWebsiteEvent event) { mCurrentRequest = new Request.Builder() .url(Configuration.API_URL) .build(); Log.d(TAG, "newCall"); mOkHttpClient.newCall(mCurrentRequest).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { Log.e(TAG, "onFailure", e); mCurrentRequest = null; mFailedEvent = event;
postEventToMainThread(new RequestFailedEvent(
5
numenta/htm.java
src/test/java/org/numenta/nupic/model/ComputeCycleTest.java
[ "public class Parameters implements Persistable {\n /** keep it simple */\n private static final long serialVersionUID = 1L;\n \n private static final Map<KEY, Object> DEFAULTS_ALL;\n private static final Map<KEY, Object> DEFAULTS_TEMPORAL;\n private static final Map<KEY, Object> DEFAULTS_SPATIAL;\n private static final Map<KEY, Object> DEFAULTS_ENCODER;\n\n\n static {\n Map<KEY, Object> defaultParams = new ParametersMap();\n\n /////////// Universal Parameters ///////////\n\n defaultParams.put(KEY.SEED, 42);\n defaultParams.put(KEY.RANDOM, new MersenneTwister((int)defaultParams.get(KEY.SEED)));\n\n /////////// Temporal Memory Parameters ///////////\n Map<KEY, Object> defaultTemporalParams = new ParametersMap();\n defaultTemporalParams.put(KEY.COLUMN_DIMENSIONS, new int[]{2048});\n defaultTemporalParams.put(KEY.CELLS_PER_COLUMN, 32);\n defaultTemporalParams.put(KEY.ACTIVATION_THRESHOLD, 13);\n defaultTemporalParams.put(KEY.LEARNING_RADIUS, 2048);\n defaultTemporalParams.put(KEY.MIN_THRESHOLD, 10);\n defaultTemporalParams.put(KEY.MAX_NEW_SYNAPSE_COUNT, 20);\n defaultTemporalParams.put(KEY.MAX_SYNAPSES_PER_SEGMENT, 255);\n defaultTemporalParams.put(KEY.MAX_SEGMENTS_PER_CELL, 255);\n defaultTemporalParams.put(KEY.INITIAL_PERMANENCE, 0.21);\n defaultTemporalParams.put(KEY.CONNECTED_PERMANENCE, 0.5);\n defaultTemporalParams.put(KEY.PERMANENCE_INCREMENT, 0.10);\n defaultTemporalParams.put(KEY.PERMANENCE_DECREMENT, 0.10);\n defaultTemporalParams.put(KEY.PREDICTED_SEGMENT_DECREMENT, 0.0);\n defaultTemporalParams.put(KEY.LEARN, true);\n DEFAULTS_TEMPORAL = Collections.unmodifiableMap(defaultTemporalParams);\n defaultParams.putAll(DEFAULTS_TEMPORAL);\n\n //////////// Spatial Pooler Parameters ///////////\n Map<KEY, Object> defaultSpatialParams = new ParametersMap();\n defaultSpatialParams.put(KEY.INPUT_DIMENSIONS, new int[]{64});\n defaultSpatialParams.put(KEY.POTENTIAL_RADIUS, -1);\n defaultSpatialParams.put(KEY.POTENTIAL_PCT, 0.5);\n defaultSpatialParams.put(KEY.GLOBAL_INHIBITION, false);\n defaultSpatialParams.put(KEY.INHIBITION_RADIUS, 0);\n defaultSpatialParams.put(KEY.LOCAL_AREA_DENSITY, -1.0);\n defaultSpatialParams.put(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 10.0);\n defaultSpatialParams.put(KEY.STIMULUS_THRESHOLD, 0.0);\n defaultSpatialParams.put(KEY.SYN_PERM_INACTIVE_DEC, 0.008);\n defaultSpatialParams.put(KEY.SYN_PERM_ACTIVE_INC, 0.05);\n defaultSpatialParams.put(KEY.SYN_PERM_CONNECTED, 0.10);\n defaultSpatialParams.put(KEY.SYN_PERM_BELOW_STIMULUS_INC, 0.01);\n defaultSpatialParams.put(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);\n defaultSpatialParams.put(KEY.MIN_PCT_OVERLAP_DUTY_CYCLES, 0.001);\n defaultSpatialParams.put(KEY.MIN_PCT_ACTIVE_DUTY_CYCLES, 0.001);\n defaultSpatialParams.put(KEY.DUTY_CYCLE_PERIOD, 1000);\n defaultSpatialParams.put(KEY.MAX_BOOST, 10.0);\n defaultSpatialParams.put(KEY.WRAP_AROUND, true);\n defaultSpatialParams.put(KEY.LEARN, true);\n DEFAULTS_SPATIAL = Collections.unmodifiableMap(defaultSpatialParams);\n defaultParams.putAll(DEFAULTS_SPATIAL);\n \n /////////// Encoder Parameters ///////////\n Map<KEY, Object> defaultEncoderParams = new ParametersMap();\n defaultEncoderParams.put(KEY.N, 500);\n defaultEncoderParams.put(KEY.W, 21);\n defaultEncoderParams.put(KEY.MIN_VAL, 0.);\n defaultEncoderParams.put(KEY.MAX_VAL, 1000.);\n defaultEncoderParams.put(KEY.RADIUS, 21.);\n defaultEncoderParams.put(KEY.RESOLUTION, 1.);\n defaultEncoderParams.put(KEY.PERIODIC, false);\n defaultEncoderParams.put(KEY.CLIP_INPUT, false);\n defaultEncoderParams.put(KEY.FORCED, false);\n defaultEncoderParams.put(KEY.FIELD_NAME, \"UNSET\");\n defaultEncoderParams.put(KEY.FIELD_TYPE, \"int\");\n defaultEncoderParams.put(KEY.ENCODER, \"ScalarEncoder\");\n defaultEncoderParams.put(KEY.FIELD_ENCODING_MAP, Collections.emptyMap());\n defaultEncoderParams.put(KEY.AUTO_CLASSIFY, Boolean.FALSE);\n DEFAULTS_ENCODER = Collections.unmodifiableMap(defaultEncoderParams);\n defaultParams.putAll(DEFAULTS_ENCODER);\n\n DEFAULTS_ALL = Collections.unmodifiableMap(defaultParams);\n }\n\n /**\n * Constant values representing configuration parameters for the {@link TemporalMemory}\n */\n public static enum KEY {\n /////////// Universal Parameters ///////////\n /**\n * Total number of columns\n */\n COLUMN_DIMENSIONS(\"columnDimensions\", int[].class),\n /**\n * Total number of cells per column\n */\n CELLS_PER_COLUMN(\"cellsPerColumn\", Integer.class, 1, null),\n /**\n * Learning variable\n */\n LEARN(\"learn\", Boolean.class),\n /**\n * Random Number Generator\n */\n RANDOM(\"random\", Random.class),\n /**\n * Seed for random number generator\n */\n SEED(\"seed\", Integer.class),\n\n /////////// Temporal Memory Parameters ///////////\n /**\n * If the number of active connected synapses on a segment\n * is at least this threshold, the segment is said to be active.\n */\n ACTIVATION_THRESHOLD(\"activationThreshold\", Integer.class, 0, null),\n /**\n * Radius around cell from which it can\n * sample to form distal {@link DistalDendrite} connections.\n */\n LEARNING_RADIUS(\"learningRadius\", Integer.class, 0, null),\n /**\n * If the number of synapses active on a segment is at least this\n * threshold, it is selected as the best matching\n * cell in a bursting column.\n */\n MIN_THRESHOLD(\"minThreshold\", Integer.class, 0, null),\n /**\n * The maximum number of synapses added to a segment during learning.\n */\n MAX_NEW_SYNAPSE_COUNT(\"maxNewSynapseCount\", Integer.class),\n /**\n * The maximum number of synapses that can be added to a segment.\n */\n MAX_SYNAPSES_PER_SEGMENT(\"maxSynapsesPerSegment\", Integer.class),\n /**\n * The maximum number of {@link Segment}s a {@link Cell} can have.\n */\n MAX_SEGMENTS_PER_CELL(\"maxSegmentsPerCell\", Integer.class),\n /**\n * Initial permanence of a new synapse\n */\n INITIAL_PERMANENCE(\"initialPermanence\", Double.class, 0.0, 1.0),\n /**\n * If the permanence value for a synapse\n * is greater than this value, it is said\n * to be connected.\n */\n CONNECTED_PERMANENCE(\"connectedPermanence\", Double.class, 0.0, 1.0),\n /**\n * Amount by which permanence of synapses\n * are incremented during learning.\n */\n PERMANENCE_INCREMENT(\"permanenceIncrement\", Double.class, 0.0, 1.0),\n /**\n * Amount by which permanences of synapses\n * are decremented during learning.\n */\n PERMANENCE_DECREMENT(\"permanenceDecrement\", Double.class, 0.0, 1.0),\n /**\n * Amount by which active permanences of synapses of previously \n * predicted but inactive segments are decremented.\n */\n PREDICTED_SEGMENT_DECREMENT(\"predictedSegmentDecrement\", Double.class, 0.0, 9.0),\n /** TODO: Remove this and add Logging (slf4j) */\n //TM_VERBOSITY(\"tmVerbosity\", Integer.class, 0, 10),\n \n\n /////////// Spatial Pooler Parameters ///////////\n INPUT_DIMENSIONS(\"inputDimensions\", int[].class),\n /** <b>WARNING:</b> potentialRadius **must** be set to \n * the inputWidth if using \"globalInhibition\" and if not \n * using the Network API (which sets this automatically) \n */\n POTENTIAL_RADIUS(\"potentialRadius\", Integer.class),\n /**\n * The percent of the inputs, within a column's potential radius, that a\n * column can be connected to. If set to 1, the column will be connected\n * to every input within its potential radius. This parameter is used to\n * give each column a unique potential pool when a large potentialRadius\n * causes overlap between the columns. At initialization time we choose\n * ((2*potentialRadius + 1)^(# inputDimensions) * potentialPct) input bits\n * to comprise the column's potential pool.\n */\n POTENTIAL_PCT(\"potentialPct\", Double.class), //TODO add range here?\n /**\n * If true, then during inhibition phase the winning columns are selected\n * as the most active columns from the region as a whole. Otherwise, the\n * winning columns are selected with respect to their local neighborhoods.\n * Using global inhibition boosts performance x60.\n */\n GLOBAL_INHIBITION(\"globalInhibition\", Boolean.class),\n /**\n * The inhibition radius determines the size of a column's local\n * neighborhood. A cortical column must overcome the overlap score of\n * columns in its neighborhood in order to become active. This radius is\n * updated every learning round. It grows and shrinks with the average\n * number of connected synapses per column.\n */\n INHIBITION_RADIUS(\"inhibitionRadius\", Integer.class, 0, null),\n /**\n * The desired density of active columns within a local inhibition area\n * (the size of which is set by the internally calculated inhibitionRadius,\n * which is in turn determined from the average size of the connected\n * potential pools of all columns). The inhibition logic will insure that\n * at most N columns remain ON within a local inhibition area, where\n * N = localAreaDensity * (total number of columns in inhibition area).\n */\n LOCAL_AREA_DENSITY(\"localAreaDensity\", Double.class), //TODO add range here?\n /**\n * An alternate way to control the density of the active columns. If\n * numActiveColumnsPerInhArea is specified then localAreaDensity must be\n * less than 0, and vice versa. When using numActiveColumnsPerInhArea, the\n * inhibition logic will insure that at most 'numActiveColumnsPerInhArea'\n * columns remain ON within a local inhibition area (the size of which is\n * set by the internally calculated inhibitionRadius, which is in turn\n * determined from the average size of the connected receptive fields of all\n * columns). When using this method, as columns learn and grow their\n * effective receptive fields, the inhibitionRadius will grow, and hence the\n * net density of the active columns will *decrease*. This is in contrast to\n * the localAreaDensity method, which keeps the density of active columns\n * the same regardless of the size of their receptive fields.\n */\n NUM_ACTIVE_COLUMNS_PER_INH_AREA(\"numActiveColumnsPerInhArea\", Double.class),//TODO add range here?\n /**\n * This is a number specifying the minimum number of synapses that must be\n * on in order for a columns to turn ON. The purpose of this is to prevent\n * noise input from activating columns. Specified as a percent of a fully\n * grown synapse.\n */\n STIMULUS_THRESHOLD(\"stimulusThreshold\", Double.class), //TODO add range here?\n /**\n * The amount by which an inactive synapse is decremented in each round.\n * Specified as a percent of a fully grown synapse.\n */\n SYN_PERM_INACTIVE_DEC(\"synPermInactiveDec\", Double.class, 0.0, 1.0),\n /**\n * The amount by which an active synapse is incremented in each round.\n * Specified as a percent of a fully grown synapse.\n */\n SYN_PERM_ACTIVE_INC(\"synPermActiveInc\", Double.class, 0.0, 1.0),\n /**\n * The default connected threshold. Any synapse whose permanence value is\n * above the connected threshold is a \"connected synapse\", meaning it can\n * contribute to the cell's firing.\n */\n SYN_PERM_CONNECTED(\"synPermConnected\", Double.class, 0.0, 1.0),\n /**\n * <b>WARNING:</b> This is a <i><b>derived</b><i> value, and is overwritten\n * by the SpatialPooler algorithm's initialization.\n * \n * The permanence increment amount for columns that have not been\n * recently active\n */\n SYN_PERM_BELOW_STIMULUS_INC(\"synPermBelowStimulusInc\", Double.class, 0.0, 1.0),\n /**\n * <b>WARNING:</b> This is a <i><b>derived</b><i> value, and is overwritten\n * by the SpatialPooler algorithm's initialization.\n * \n * Values below this are \"clipped\" and zero'd out.\n */\n SYN_PERM_TRIM_THRESHOLD(\"synPermTrimThreshold\", Double.class, 0.0, 1.0),\n /**\n * A number between 0 and 1.0, used to set a floor on how often a column\n * should have at least stimulusThreshold active inputs. Periodically, each\n * column looks at the overlap duty cycle of all other columns within its\n * inhibition radius and sets its own internal minimal acceptable duty cycle\n * to: minPctDutyCycleBeforeInh * max(other columns' duty cycles). On each\n * iteration, any column whose overlap duty cycle falls below this computed\n * value will get all of its permanence values boosted up by\n * synPermActiveInc. Raising all permanences in response to a sub-par duty\n * cycle before inhibition allows a cell to search for new inputs when\n * either its previously learned inputs are no longer ever active, or when\n * the vast majority of them have been \"hijacked\" by other columns.\n */\n MIN_PCT_OVERLAP_DUTY_CYCLES(\"minPctOverlapDutyCycles\", Double.class),//TODO add range here?\n /**\n * A number between 0 and 1.0, used to set a floor on how often a column\n * should be activate. Periodically, each column looks at the activity duty\n * cycle of all other columns within its inhibition radius and sets its own\n * internal minimal acceptable duty cycle to: minPctDutyCycleAfterInh *\n * max(other columns' duty cycles). On each iteration, any column whose duty\n * cycle after inhibition falls below this computed value will get its\n * internal boost factor increased.\n */\n MIN_PCT_ACTIVE_DUTY_CYCLES(\"minPctActiveDutyCycles\", Double.class),//TODO add range here?\n /**\n * The period used to calculate duty cycles. Higher values make it take\n * longer to respond to changes in boost or synPerConnectedCell. Shorter\n * values make it more unstable and likely to oscillate.\n */\n DUTY_CYCLE_PERIOD(\"dutyCyclePeriod\", Integer.class),//TODO add range here?\n /**\n * The maximum overlap boost factor. Each column's overlap gets multiplied\n * by a boost factor before it gets considered for inhibition. The actual\n * boost factor for a column is number between 1.0 and maxBoost. A boost\n * factor of 1.0 is used if the duty cycle is >= minOverlapDutyCycle,\n * maxBoost is used if the duty cycle is 0, and any duty cycle in between is\n * linearly extrapolated from these 2 endpoints.\n */\n MAX_BOOST(\"maxBoost\", Double.class), //TODO add range here?\n /**\n * Determines if inputs at the beginning and end of an input dimension should\n * be considered neighbors when mapping columns to inputs.\n */\n WRAP_AROUND(\"wrapAround\", Boolean.class),\n \n ///////////// SpatialPooler / Network Parameter(s) /////////////\n /** Number of cycles to send through the SP before forwarding data to the rest of the network. */\n SP_PRIMER_DELAY(\"sp_primer_delay\", Integer.class),\n \n ///////////// Encoder Parameters //////////////\n /** number of bits in the representation (must be &gt;= w) */\n N(\"n\", Integer.class),\n /** \n * The number of bits that are set to encode a single value - the\n * \"width\" of the output signal\n */\n W(\"w\", Integer.class),\n /** The minimum value of the input signal. */\n MIN_VAL(\"minVal\", Double.class),\n /** The maximum value of the input signal. */\n MAX_VAL(\"maxVal\", Double.class),\n /**\n * inputs separated by more than, or equal to this distance will have non-overlapping\n * representations\n */\n RADIUS(\"radius\", Double.class),\n /** inputs separated by more than, or equal to this distance will have different representations */\n RESOLUTION(\"resolution\", Double.class),\n /**\n * If true, then the input value \"wraps around\" such that minval = maxval\n * For a periodic value, the input must be strictly less than maxval,\n * otherwise maxval is a true upper bound.\n */\n PERIODIC(\"periodic\", Boolean.class),\n /** \n * if true, non-periodic inputs smaller than minval or greater\n * than maxval will be clipped to minval/maxval \n */\n CLIP_INPUT(\"clipInput\", Boolean.class),\n /** \n * If true, skip some safety checks (for compatibility reasons), default false \n * Mostly having to do with being able to set the window size &lt; 21 \n */\n FORCED(\"forced\", Boolean.class),\n /** Name of the field being encoded */\n FIELD_NAME(\"fieldName\", String.class),\n /** Primitive type of the field, used to auto-configure the type of encoder */\n FIELD_TYPE(\"fieldType\", String.class),\n /** Encoder name */\n ENCODER(\"encoderType\", String.class),\n /** Designates holder for the Multi Encoding Map */\n FIELD_ENCODING_MAP(\"fieldEncodings\", Map.class),\n CATEGORY_LIST(\"categoryList\", List.class),\n \n // Network Layer indicator for auto classifier generation\n AUTO_CLASSIFY(\"hasClassifiers\", Boolean.class),\n\n /** Maps encoder input field name to type of classifier to be used for them */\n INFERRED_FIELDS(\"inferredFields\", Map.class), // Map<String, Classifier.class>\n\n // How many bits to use if encoding the respective date fields.\n // e.g. Tuple(bits to use:int, radius:double)\n DATEFIELD_SEASON(\"season\", Tuple.class), \n DATEFIELD_DOFW(\"dayOfWeek\", Tuple.class),\n DATEFIELD_WKEND(\"weekend\", Tuple.class),\n DATEFIELD_HOLIDAY(\"holiday\", Tuple.class),\n DATEFIELD_TOFD(\"timeOfDay\", Tuple.class),\n DATEFIELD_CUSTOM(\"customDays\", Tuple.class), // e.g. Tuple(bits:int, List<String>:\"mon,tue,fri\")\n DATEFIELD_PATTERN(\"formatPattern\", String.class);\n \n\n private static final Map<String, KEY> fieldMap = new HashMap<>();\n\n static {\n for (KEY key : KEY.values()) {\n fieldMap.put(key.getFieldName(), key);\n }\n }\n\n public static KEY getKeyByFieldName(String fieldName) {\n return fieldMap.get(fieldName);\n }\n\n final private String fieldName;\n final private Class<?> fieldType;\n final private Number min;\n final private Number max;\n\n /**\n * Constructs a new KEY\n *\n * @param fieldName\n * @param fieldType\n */\n private KEY(String fieldName, Class<?> fieldType) {\n this(fieldName, fieldType, null, null);\n }\n\n /**\n * Constructs a new KEY with range check\n *\n * @param fieldName\n * @param fieldType\n * @param min\n * @param max\n */\n private KEY(String fieldName, Class<?> fieldType, Number min, Number max) {\n this.fieldName = fieldName;\n this.fieldType = fieldType;\n this.min = min;\n this.max = max;\n }\n\n public Class<?> getFieldType() {\n return fieldType;\n }\n\n public String getFieldName() {\n return fieldName;\n }\n\n public Number getMin() {\n return min;\n }\n\n public Number getMax() {\n return max;\n }\n\n public boolean checkRange(Number value) {\n if (value == null) {\n throw new IllegalArgumentException(\"checkRange argument can not be null\");\n }\n return (min == null && max == null) ||\n (min != null && max == null && value.doubleValue() >= min.doubleValue()) ||\n (max != null && min == null && value.doubleValue() <= max.doubleValue()) ||\n (min != null && value.doubleValue() >= min.doubleValue() && max != null && value.doubleValue() <= max.doubleValue());\n }\n\n }\n\n /**\n * Save guard decorator around params map\n */\n private static class ParametersMap extends EnumMap<KEY, Object> {\n /**\n * Default serialvers\n */\n private static final long serialVersionUID = 1L;\n\n ParametersMap() {\n super(Parameters.KEY.class);\n }\n\n @Override public Object put(KEY key, Object value) {\n if (value != null) {\n if (!key.getFieldType().isInstance(value)) {\n throw new IllegalArgumentException(\n \"Can not set Parameters Property '\" + key.getFieldName() + \"' because of type mismatch. The required type is \" + key.getFieldType());\n }\n if (value instanceof Number && !key.checkRange((Number)value)) {\n throw new IllegalArgumentException(\n \"Can not set Parameters Property '\" + key.getFieldName() + \"' because of value '\" + value + \"' not in range. Range[\" + key.getMin() + \"-\" + key.getMax() + \"]\");\n }\n }\n return super.put(key, value);\n }\n }\n\n /**\n * Map of parameters to their values\n */\n private final Map<Parameters.KEY, Object> paramMap = Collections.synchronizedMap(new ParametersMap());\n\n //TODO apply from container to parameters\n \n /**\n * Returns the size of the internal parameter storage.\n * @return\n */\n public int size() {\n return paramMap.size();\n }\n\n /**\n * Factory method. Return global {@link Parameters} object with default values\n *\n * @return {@link Parameters} object\n */\n public static Parameters getAllDefaultParameters() {\n return getParameters(DEFAULTS_ALL);\n }\n\n /**\n * Factory method. Return temporal {@link Parameters} object with default values\n *\n * @return {@link Parameters} object\n */\n public static Parameters getTemporalDefaultParameters() {\n return getParameters(DEFAULTS_TEMPORAL);\n }\n\n\n /**\n * Factory method. Return spatial {@link Parameters} object with default values\n *\n * @return {@link Parameters} object\n */\n public static Parameters getSpatialDefaultParameters() {\n return getParameters(DEFAULTS_SPATIAL);\n }\n\n /**\n * Factory method. Return Encoder {@link Parameters} object with default values\n * @return\n */\n public static Parameters getEncoderDefaultParameters() {\n return getParameters(DEFAULTS_ENCODER);\n }\n /**\n * Called internally to populate a {@link Parameters} object with the keys\n * and values specified in the passed in map.\n *\n * @return {@link Parameters} object\n */\n private static Parameters getParameters(Map<KEY, Object> map) {\n Parameters result = new Parameters();\n for (KEY key : map.keySet()) {\n result.set(key, map.get(key));\n }\n return result;\n }\n\n\n /**\n * Constructs a new {@code Parameters} object.\n * It is private. Only allow instantiation with Factory methods.\n * This way we will never have erroneous Parameters with missing attributes\n */\n private Parameters() {\n }\n\n /**\n * Sets the fields specified by this {@code Parameters} on the specified\n * {@link Connections} object.\n *\n * @param cn\n */\n public void apply(Object cn) {\n BeanUtil beanUtil = BeanUtil.getInstance();\n Set<KEY> presentKeys = paramMap.keySet();\n synchronized (paramMap) {\n for (KEY key : presentKeys) {\n if((cn instanceof Connections) && \n (key == KEY.SYN_PERM_BELOW_STIMULUS_INC || key == KEY.SYN_PERM_TRIM_THRESHOLD)) {\n continue;\n }\n if(key == KEY.RANDOM) {\n ((Random)get(key)).setSeed(Long.valueOf(((int)get(KEY.SEED))));\n }\n beanUtil.setSimpleProperty(cn, key.fieldName, get(key));\n }\n }\n }\n \n /**\n * Copies the specified parameters into this {@code Parameters}\n * object over writing the intersecting keys and values.\n * @param p the Parameters to perform a union with.\n * @return this Parameters object combined with the specified\n * Parameters object.\n */\n public Parameters union(Parameters p) {\n for(KEY k : p.paramMap.keySet()) {\n set(k, p.get(k));\n }\n return this;\n }\n \n /**\n * Returns a Set view of the keys in this {@code Parameter}s \n * object\n * @return\n */\n public Set<KEY> keys() {\n Set<KEY> retVal = paramMap.keySet();\n return retVal;\n }\n \n /**\n * Returns a separate instance of the specified {@code Parameters} object.\n * @return a unique instance.\n */\n public Parameters copy() {\n return new Parameters().union(this);\n }\n \n /**\n * Returns an empty instance of {@code Parameters};\n * @return\n */\n public static Parameters empty() {\n return new Parameters();\n }\n\n /**\n * Set parameter by Key{@link KEY}\n *\n * @param key\n * @param value\n */\n public void set(KEY key, Object value) {\n paramMap.put(key, value);\n }\n\n /**\n * Get parameter by Key{@link KEY}\n *\n * @param key\n * @return\n */\n public Object get(KEY key) {\n return paramMap.get(key);\n }\n\n /**\n * @param key IMPORTANT! This is a nuclear option, should be used with care. \n * Will knockout key's parameter from map and compromise integrity\n */\n public void clearParameter(KEY key) {\n paramMap.remove(key);\n }\n\n /**\n * Convenience method to log difference this {@code Parameters} and specified\n * {@link Connections} object.\n *\n * @param cn\n * @return true if find it different\n */\n public boolean logDiff(Object cn) {\n if (cn == null) {\n throw new IllegalArgumentException(\"cn Object is required and can not be null\");\n }\n boolean result = false;\n BeanUtil beanUtil = BeanUtil.getInstance();\n BeanUtil.PropertyInfo[] properties = beanUtil.getPropertiesInfoForBean(cn.getClass());\n for (int i = 0; i < properties.length; i++) {\n BeanUtil.PropertyInfo property = properties[i];\n String fieldName = property.getName();\n KEY propKey = KEY.getKeyByFieldName(property.getName());\n if (propKey != null) {\n Object paramValue = this.get(propKey);\n Object cnValue = beanUtil.getSimpleProperty(cn, fieldName);\n \n // KEY.POTENTIAL_RADIUS is defined as Math.min(cn.numInputs, potentialRadius) so just log...\n if(propKey == KEY.POTENTIAL_RADIUS) {\n System.out.println(\n \"Difference is OK: Property:\" + fieldName + \" is different - CN:\" + cnValue + \" | PARAM:\" + paramValue);\n }else if ((paramValue != null && !paramValue.equals(cnValue)) || (paramValue == null && cnValue != null)) {\n result = true;\n System.out.println(\n \"Property:\" + fieldName + \" is different - CONNECTIONS:\" + cnValue + \" | PARAMETERS:\" + paramValue);\n }\n }\n }\n return result;\n }\n\n //TODO I'm not sure we need maintain implicit setters below. Kinda contradict unified access with KEYs\n\n /**\n * Returns the seeded random number generator.\n *\n * @param r the generator to use.\n */\n public void setRandom(Random r) {\n paramMap.put(KEY.RANDOM, r);\n }\n\n /**\n * Sets the number of {@link Column}.\n *\n * @param columnDimensions\n */\n public void setColumnDimensions(int[] columnDimensions) {\n paramMap.put(KEY.COLUMN_DIMENSIONS, columnDimensions);\n }\n\n /**\n * Sets the number of {@link Cell}s per {@link Column}\n *\n * @param cellsPerColumn\n */\n public void setCellsPerColumn(int cellsPerColumn) {\n paramMap.put(KEY.CELLS_PER_COLUMN, cellsPerColumn);\n }\n\n /**\n * <p>\n * Sets the activation threshold.\n * </p>\n * If the number of active connected synapses on a segment\n * is at least this threshold, the segment is said to be active.\n *\n * @param activationThreshold\n */\n public void setActivationThreshold(int activationThreshold) {\n paramMap.put(KEY.ACTIVATION_THRESHOLD, activationThreshold);\n }\n\n /**\n * Radius around cell from which it can\n * sample to form distal dendrite connections.\n *\n * @param learningRadius\n */\n public void setLearningRadius(int learningRadius) {\n paramMap.put(KEY.LEARNING_RADIUS, learningRadius);\n }\n\n /**\n * If the number of synapses active on a segment is at least this\n * threshold, it is selected as the best matching\n * cell in a bursting column.\n *\n * @param minThreshold\n */\n public void setMinThreshold(int minThreshold) {\n paramMap.put(KEY.MIN_THRESHOLD, minThreshold);\n }\n\n /**\n * The maximum number of synapses added to a segment during learning.\n *\n * @param maxSynapsesPerSegment\n */\n public void setMaxSynapsesPerSegment(int maxSynapsesPerSegment) {\n paramMap.put(KEY.MAX_SYNAPSES_PER_SEGMENT, maxSynapsesPerSegment);\n }\n \n /**\n * The maximum number of {@link Segment}s a {@link Cell} can have.\n *\n * @param maxSegmentsPerCell\n */\n public void setMaxSegmentsPerCell(int maxSegmentsPerCell) {\n paramMap.put(KEY.MAX_SEGMENTS_PER_CELL, maxSegmentsPerCell);\n }\n \n /**\n * The maximum number of new synapses\n * @param count\n */\n public void setMaxNewSynapseCount(int count) {\n paramMap.put(KEY.MAX_NEW_SYNAPSE_COUNT, count);\n }\n\n /**\n * Seed for random number generator\n *\n * @param seed\n */\n public void setSeed(int seed) {\n paramMap.put(KEY.SEED, seed);\n }\n\n /**\n * Initial permanence of a new synapse\n *\n * @param initialPermanence\n */\n public void setInitialPermanence(double initialPermanence) {\n paramMap.put(KEY.INITIAL_PERMANENCE, initialPermanence);\n }\n\n /**\n * If the permanence value for a synapse\n * is greater than this value, it is said\n * to be connected.\n *\n * @param connectedPermanence\n */\n public void setConnectedPermanence(double connectedPermanence) {\n paramMap.put(KEY.CONNECTED_PERMANENCE, connectedPermanence);\n }\n\n /**\n * Amount by which permanences of synapses\n * are incremented during learning.\n *\n * @param permanenceIncrement\n */\n public void setPermanenceIncrement(double permanenceIncrement) {\n paramMap.put(KEY.PERMANENCE_INCREMENT, permanenceIncrement);\n }\n\n /**\n * Amount by which permanences of synapses\n * are decremented during learning.\n *\n * @param permanenceDecrement\n */\n public void setPermanenceDecrement(double permanenceDecrement) {\n paramMap.put(KEY.PERMANENCE_DECREMENT, permanenceDecrement);\n }\n\n ////////////////////////////// SPACIAL POOLER PARAMS //////////////////////////////////\n\n /**\n * A list representing the dimensions of the input\n * vector. Format is [height, width, depth, ...], where\n * each value represents the size of the dimension. For a\n * topology of one dimension with 100 inputs use 100, or\n * [100]. For a two dimensional topology of 10x5 use\n * [10,5].\n *\n * @param inputDimensions\n */\n public void setInputDimensions(int[] inputDimensions) {\n paramMap.put(KEY.INPUT_DIMENSIONS, inputDimensions);\n }\n\n /**\n * This parameter determines the extent of the input\n * that each column can potentially be connected to.\n * This can be thought of as the input bits that\n * are visible to each column, or a 'receptiveField' of\n * the field of vision. A large enough value will result\n * in 'global coverage', meaning that each column\n * can potentially be connected to every input bit. This\n * parameter defines a square (or hyper square) area: a\n * column will have a max square potential pool with\n * sides of length 2 * potentialRadius + 1.\n * \n * <b>WARNING:</b> potentialRadius **must** be set to \n * the inputWidth if using \"globalInhibition\" and if not \n * using the Network API (which sets this automatically) \n *\n *\n * @param potentialRadius\n */\n public void setPotentialRadius(int potentialRadius) {\n paramMap.put(KEY.POTENTIAL_RADIUS, potentialRadius);\n }\n\n /**\n * The inhibition radius determines the size of a column's local\n * neighborhood. of a column. A cortical column must overcome the overlap\n * score of columns in his neighborhood in order to become actives. This\n * radius is updated every learning round. It grows and shrinks with the\n * average number of connected synapses per column.\n *\n * @param inhibitionRadius the local group size\n */\n public void setInhibitionRadius(int inhibitionRadius) {\n paramMap.put(KEY.INHIBITION_RADIUS, inhibitionRadius);\n }\n\n /**\n * The percent of the inputs, within a column's\n * potential radius, that a column can be connected to.\n * If set to 1, the column will be connected to every\n * input within its potential radius. This parameter is\n * used to give each column a unique potential pool when\n * a large potentialRadius causes overlap between the\n * columns. At initialization time we choose\n * ((2*potentialRadius + 1)^(# inputDimensions) *\n * potentialPct) input bits to comprise the column's\n * potential pool.\n *\n * @param potentialPct\n */\n public void setPotentialPct(double potentialPct) {\n paramMap.put(KEY.POTENTIAL_PCT, potentialPct);\n }\n\n /**\n * If true, then during inhibition phase the winning\n * columns are selected as the most active columns from\n * the region as a whole. Otherwise, the winning columns\n * are selected with respect to their local\n * neighborhoods. Using global inhibition boosts\n * performance x60.\n *\n * @param globalInhibition\n */\n public void setGlobalInhibition(boolean globalInhibition) {\n paramMap.put(KEY.GLOBAL_INHIBITION, globalInhibition);\n }\n\n /**\n * The desired density of active columns within a local\n * inhibition area (the size of which is set by the\n * internally calculated inhibitionRadius, which is in\n * turn determined from the average size of the\n * connected potential pools of all columns). The\n * inhibition logic will insure that at most N columns\n * remain ON within a local inhibition area, where N =\n * localAreaDensity * (total number of columns in\n * inhibition area).\n *\n * @param localAreaDensity\n */\n public void setLocalAreaDensity(double localAreaDensity) {\n paramMap.put(KEY.LOCAL_AREA_DENSITY, localAreaDensity);\n }\n\n /**\n * An alternate way to control the density of the active\n * columns. If numActivePerInhArea is specified then\n * localAreaDensity must be less than 0, and vice versa.\n * When using numActivePerInhArea, the inhibition logic\n * will insure that at most 'numActivePerInhArea'\n * columns remain ON within a local inhibition area (the\n * size of which is set by the internally calculated\n * inhibitionRadius, which is in turn determined from\n * the average size of the connected receptive fields of\n * all columns). When using this method, as columns\n * learn and grow their effective receptive fields, the\n * inhibitionRadius will grow, and hence the net density\n * of the active columns will *decrease*. This is in\n * contrast to the localAreaDensity method, which keeps\n * the density of active columns the same regardless of\n * the size of their receptive fields.\n *\n * @param numActiveColumnsPerInhArea\n */\n public void setNumActiveColumnsPerInhArea(double numActiveColumnsPerInhArea) {\n paramMap.put(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, numActiveColumnsPerInhArea);\n }\n\n /**\n * This is a number specifying the minimum number of\n * synapses that must be on in order for a columns to\n * turn ON. The purpose of this is to prevent noise\n * input from activating columns. Specified as a percent\n * of a fully grown synapse.\n *\n * @param stimulusThreshold\n */\n public void setStimulusThreshold(double stimulusThreshold) {\n paramMap.put(KEY.STIMULUS_THRESHOLD, stimulusThreshold);\n }\n\n /**\n * The amount by which an inactive synapse is\n * decremented in each round. Specified as a percent of\n * a fully grown synapse.\n *\n * @param synPermInactiveDec\n */\n public void setSynPermInactiveDec(double synPermInactiveDec) {\n paramMap.put(KEY.SYN_PERM_INACTIVE_DEC, synPermInactiveDec);\n }\n\n /**\n * The amount by which an active synapse is incremented\n * in each round. Specified as a percent of a\n * fully grown synapse.\n *\n * @param synPermActiveInc\n */\n public void setSynPermActiveInc(double synPermActiveInc) {\n paramMap.put(KEY.SYN_PERM_ACTIVE_INC, synPermActiveInc);\n }\n\n /**\n * The default connected threshold. Any synapse whose\n * permanence value is above the connected threshold is\n * a \"connected synapse\", meaning it can contribute to\n * the cell's firing.\n *\n * @param synPermConnected\n */\n public void setSynPermConnected(double synPermConnected) {\n paramMap.put(KEY.SYN_PERM_CONNECTED, synPermConnected);\n }\n\n /**\n * Sets the increment of synapse permanences below the stimulus\n * threshold\n *\n * @param synPermBelowStimulusInc\n */\n public void setSynPermBelowStimulusInc(double synPermBelowStimulusInc) {\n paramMap.put(KEY.SYN_PERM_BELOW_STIMULUS_INC, synPermBelowStimulusInc);\n }\n\n /**\n * @param synPermTrimThreshold\n */\n public void setSynPermTrimThreshold(double synPermTrimThreshold) {\n paramMap.put(KEY.SYN_PERM_TRIM_THRESHOLD, synPermTrimThreshold);\n }\n\n /**\n * A number between 0 and 1.0, used to set a floor on\n * how often a column should have at least\n * stimulusThreshold active inputs. Periodically, each\n * column looks at the overlap duty cycle of\n * all other columns within its inhibition radius and\n * sets its own internal minimal acceptable duty cycle\n * to: minPctDutyCycleBeforeInh * max(other columns'\n * duty cycles).\n * On each iteration, any column whose overlap duty\n * cycle falls below this computed value will get\n * all of its permanence values boosted up by\n * synPermActiveInc. Raising all permanences in response\n * to a sub-par duty cycle before inhibition allows a\n * cell to search for new inputs when either its\n * previously learned inputs are no longer ever active,\n * or when the vast majority of them have been\n * \"hijacked\" by other columns.\n *\n * @param minPctOverlapDutyCycles\n */\n public void setMinPctOverlapDutyCycles(double minPctOverlapDutyCycles) {\n paramMap.put(KEY.MIN_PCT_OVERLAP_DUTY_CYCLES, minPctOverlapDutyCycles);\n }\n\n /**\n * A number between 0 and 1.0, used to set a floor on\n * how often a column should be activate.\n * Periodically, each column looks at the activity duty\n * cycle of all other columns within its inhibition\n * radius and sets its own internal minimal acceptable\n * duty cycle to:\n * minPctDutyCycleAfterInh *\n * max(other columns' duty cycles).\n * On each iteration, any column whose duty cycle after\n * inhibition falls below this computed value will get\n * its internal boost factor increased.\n *\n * @param minPctActiveDutyCycles\n */\n public void setMinPctActiveDutyCycles(double minPctActiveDutyCycles) {\n paramMap.put(KEY.MIN_PCT_ACTIVE_DUTY_CYCLES, minPctActiveDutyCycles);\n }\n\n /**\n * The period used to calculate duty cycles. Higher\n * values make it take longer to respond to changes in\n * boost or synPerConnectedCell. Shorter values make it\n * more unstable and likely to oscillate.\n *\n * @param dutyCyclePeriod\n */\n public void setDutyCyclePeriod(int dutyCyclePeriod) {\n paramMap.put(KEY.DUTY_CYCLE_PERIOD, dutyCyclePeriod);\n }\n\n /**\n * The maximum overlap boost factor. Each column's\n * overlap gets multiplied by a boost factor\n * before it gets considered for inhibition.\n * The actual boost factor for a column is number\n * between 1.0 and maxBoost. A boost factor of 1.0 is\n * used if the duty cycle is &gt;= minOverlapDutyCycle,\n * maxBoost is used if the duty cycle is 0, and any duty\n * cycle in between is linearly extrapolated from these\n * 2 end points.\n *\n * @param maxBoost\n */\n public void setMaxBoost(double maxBoost) {\n paramMap.put(KEY.MAX_BOOST, maxBoost);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder(\"{\\n\");\n StringBuilder spatialInfo = new StringBuilder();\n StringBuilder temporalInfo = new StringBuilder();\n StringBuilder otherInfo = new StringBuilder();\n this.paramMap.keySet();\n for (KEY key : paramMap.keySet()) {\n if (DEFAULTS_SPATIAL.containsKey(key)) {\n buildParamStr(spatialInfo, key);\n } else if (DEFAULTS_TEMPORAL.containsKey(key)) {\n buildParamStr(temporalInfo, key);\n } else {\n buildParamStr(otherInfo, key);\n }\n }\n if (spatialInfo.length() > 0) {\n result.append(\"\\tSpatial: {\\n\").append(spatialInfo).append(\"\\t}\\n\");\n }\n if (temporalInfo.length() > 0) {\n result.append(\"\\tTemporal: {\\n\").append(temporalInfo).append(\"\\t}\\n\");\n }\n if (otherInfo.length() > 0) {\n result.append(\"\\tOther: {\\n\").append(otherInfo).append(\"\\t}\\n\");\n }\n return result.append(\"}\").toString();\n }\n\n private void buildParamStr(StringBuilder spatialInfo, KEY key) {\n Object value = get(key);\n if (value instanceof int[]) {\n value = ArrayUtils.intArrayToString(value);\n }\n spatialInfo.append(\"\\t\\t\").append(key.getFieldName()).append(\":\").append(value).append(\"\\n\");\n }\n\n public Parameters readForNetwork(FSTObjectInput in) throws Exception {\n Parameters result = (Parameters)in.readObject(Parameters.class);\n return result;\n }\n\n public void writeForNetwork(FSTObjectOutput out) throws IOException {\n out.writeObject(this, Parameters.class);\n out.close();\n }\n\n /**\n * Usage of {@link DeepEquals} in order to ensure the same hashcode\n * for the same equal content regardless of cycles.\n */\n @Override\n public int hashCode() {\n Random rnd = (Random)paramMap.remove(KEY.RANDOM);\n int hc = DeepEquals.deepHashCode(paramMap);\n paramMap.put(KEY.RANDOM, rnd);\n \n return hc;\n \n }\n\n /**\n * This implementation skips over any native comparisons (i.e. \"==\")\n * because their hashcodes will not be equal.\n */\n @Override\n public boolean equals(Object obj) {\n if(this == obj)\n return true;\n if(obj == null)\n return false;\n if(getClass() != obj.getClass())\n return false;\n Parameters other = (Parameters)obj;\n if(paramMap == null) {\n if(other.paramMap != null)\n return false;\n } else {\n Class<?>[] classArray = new Class[] { Object.class };\n try {\n for(KEY key : paramMap.keySet()) {\n if(paramMap.get(key) == null || other.paramMap.get(key) == null) continue;\n \n Class<?> thisValueClass = paramMap.get(key).getClass();\n Class<?> otherValueClass = other.paramMap.get(key).getClass();\n boolean isSpecial = isSpecial(key, thisValueClass);\n if(!isSpecial && (thisValueClass.getMethod(\"equals\", classArray).getDeclaringClass() != thisValueClass ||\n otherValueClass.getMethod(\"equals\", classArray).getDeclaringClass() != otherValueClass)) {\n continue;\n }else if(isSpecial) {\n if(int[].class.isAssignableFrom(thisValueClass)) {\n if(!Arrays.equals((int[])paramMap.get(key), (int[])other.paramMap.get(key))) return false;\n }else if(key == KEY.FIELD_ENCODING_MAP) {\n if(!DeepEquals.deepEquals(paramMap.get(key), other.paramMap.get(key))) {\n return false;\n }\n }\n }else if(!other.paramMap.containsKey(key) || !paramMap.get(key).equals(other.paramMap.get(key))) {\n return false;\n }\n }\n }catch(Exception e) { return false; }\n }\n return true;\n }\n \n /**\n * Returns a flag indicating whether the type is an equality\n * special case.\n * @param key the {@link KEY}\n * @param klazz the class of the type being considered.\n * @return\n */\n private boolean isSpecial(KEY key, Class<?> klazz) {\n if(int[].class.isAssignableFrom(klazz) ||\n key == KEY.FIELD_ENCODING_MAP) {\n \n return true;\n }\n return false;\n }\n}", "public static enum KEY {\n /////////// Universal Parameters ///////////\n /**\n * Total number of columns\n */\n COLUMN_DIMENSIONS(\"columnDimensions\", int[].class),\n /**\n * Total number of cells per column\n */\n CELLS_PER_COLUMN(\"cellsPerColumn\", Integer.class, 1, null),\n /**\n * Learning variable\n */\n LEARN(\"learn\", Boolean.class),\n /**\n * Random Number Generator\n */\n RANDOM(\"random\", Random.class),\n /**\n * Seed for random number generator\n */\n SEED(\"seed\", Integer.class),\n\n /////////// Temporal Memory Parameters ///////////\n /**\n * If the number of active connected synapses on a segment\n * is at least this threshold, the segment is said to be active.\n */\n ACTIVATION_THRESHOLD(\"activationThreshold\", Integer.class, 0, null),\n /**\n * Radius around cell from which it can\n * sample to form distal {@link DistalDendrite} connections.\n */\n LEARNING_RADIUS(\"learningRadius\", Integer.class, 0, null),\n /**\n * If the number of synapses active on a segment is at least this\n * threshold, it is selected as the best matching\n * cell in a bursting column.\n */\n MIN_THRESHOLD(\"minThreshold\", Integer.class, 0, null),\n /**\n * The maximum number of synapses added to a segment during learning.\n */\n MAX_NEW_SYNAPSE_COUNT(\"maxNewSynapseCount\", Integer.class),\n /**\n * The maximum number of synapses that can be added to a segment.\n */\n MAX_SYNAPSES_PER_SEGMENT(\"maxSynapsesPerSegment\", Integer.class),\n /**\n * The maximum number of {@link Segment}s a {@link Cell} can have.\n */\n MAX_SEGMENTS_PER_CELL(\"maxSegmentsPerCell\", Integer.class),\n /**\n * Initial permanence of a new synapse\n */\n INITIAL_PERMANENCE(\"initialPermanence\", Double.class, 0.0, 1.0),\n /**\n * If the permanence value for a synapse\n * is greater than this value, it is said\n * to be connected.\n */\n CONNECTED_PERMANENCE(\"connectedPermanence\", Double.class, 0.0, 1.0),\n /**\n * Amount by which permanence of synapses\n * are incremented during learning.\n */\n PERMANENCE_INCREMENT(\"permanenceIncrement\", Double.class, 0.0, 1.0),\n /**\n * Amount by which permanences of synapses\n * are decremented during learning.\n */\n PERMANENCE_DECREMENT(\"permanenceDecrement\", Double.class, 0.0, 1.0),\n /**\n * Amount by which active permanences of synapses of previously \n * predicted but inactive segments are decremented.\n */\n PREDICTED_SEGMENT_DECREMENT(\"predictedSegmentDecrement\", Double.class, 0.0, 9.0),\n /** TODO: Remove this and add Logging (slf4j) */\n //TM_VERBOSITY(\"tmVerbosity\", Integer.class, 0, 10),\n \n\n /////////// Spatial Pooler Parameters ///////////\n INPUT_DIMENSIONS(\"inputDimensions\", int[].class),\n /** <b>WARNING:</b> potentialRadius **must** be set to \n * the inputWidth if using \"globalInhibition\" and if not \n * using the Network API (which sets this automatically) \n */\n POTENTIAL_RADIUS(\"potentialRadius\", Integer.class),\n /**\n * The percent of the inputs, within a column's potential radius, that a\n * column can be connected to. If set to 1, the column will be connected\n * to every input within its potential radius. This parameter is used to\n * give each column a unique potential pool when a large potentialRadius\n * causes overlap between the columns. At initialization time we choose\n * ((2*potentialRadius + 1)^(# inputDimensions) * potentialPct) input bits\n * to comprise the column's potential pool.\n */\n POTENTIAL_PCT(\"potentialPct\", Double.class), //TODO add range here?\n /**\n * If true, then during inhibition phase the winning columns are selected\n * as the most active columns from the region as a whole. Otherwise, the\n * winning columns are selected with respect to their local neighborhoods.\n * Using global inhibition boosts performance x60.\n */\n GLOBAL_INHIBITION(\"globalInhibition\", Boolean.class),\n /**\n * The inhibition radius determines the size of a column's local\n * neighborhood. A cortical column must overcome the overlap score of\n * columns in its neighborhood in order to become active. This radius is\n * updated every learning round. It grows and shrinks with the average\n * number of connected synapses per column.\n */\n INHIBITION_RADIUS(\"inhibitionRadius\", Integer.class, 0, null),\n /**\n * The desired density of active columns within a local inhibition area\n * (the size of which is set by the internally calculated inhibitionRadius,\n * which is in turn determined from the average size of the connected\n * potential pools of all columns). The inhibition logic will insure that\n * at most N columns remain ON within a local inhibition area, where\n * N = localAreaDensity * (total number of columns in inhibition area).\n */\n LOCAL_AREA_DENSITY(\"localAreaDensity\", Double.class), //TODO add range here?\n /**\n * An alternate way to control the density of the active columns. If\n * numActiveColumnsPerInhArea is specified then localAreaDensity must be\n * less than 0, and vice versa. When using numActiveColumnsPerInhArea, the\n * inhibition logic will insure that at most 'numActiveColumnsPerInhArea'\n * columns remain ON within a local inhibition area (the size of which is\n * set by the internally calculated inhibitionRadius, which is in turn\n * determined from the average size of the connected receptive fields of all\n * columns). When using this method, as columns learn and grow their\n * effective receptive fields, the inhibitionRadius will grow, and hence the\n * net density of the active columns will *decrease*. This is in contrast to\n * the localAreaDensity method, which keeps the density of active columns\n * the same regardless of the size of their receptive fields.\n */\n NUM_ACTIVE_COLUMNS_PER_INH_AREA(\"numActiveColumnsPerInhArea\", Double.class),//TODO add range here?\n /**\n * This is a number specifying the minimum number of synapses that must be\n * on in order for a columns to turn ON. The purpose of this is to prevent\n * noise input from activating columns. Specified as a percent of a fully\n * grown synapse.\n */\n STIMULUS_THRESHOLD(\"stimulusThreshold\", Double.class), //TODO add range here?\n /**\n * The amount by which an inactive synapse is decremented in each round.\n * Specified as a percent of a fully grown synapse.\n */\n SYN_PERM_INACTIVE_DEC(\"synPermInactiveDec\", Double.class, 0.0, 1.0),\n /**\n * The amount by which an active synapse is incremented in each round.\n * Specified as a percent of a fully grown synapse.\n */\n SYN_PERM_ACTIVE_INC(\"synPermActiveInc\", Double.class, 0.0, 1.0),\n /**\n * The default connected threshold. Any synapse whose permanence value is\n * above the connected threshold is a \"connected synapse\", meaning it can\n * contribute to the cell's firing.\n */\n SYN_PERM_CONNECTED(\"synPermConnected\", Double.class, 0.0, 1.0),\n /**\n * <b>WARNING:</b> This is a <i><b>derived</b><i> value, and is overwritten\n * by the SpatialPooler algorithm's initialization.\n * \n * The permanence increment amount for columns that have not been\n * recently active\n */\n SYN_PERM_BELOW_STIMULUS_INC(\"synPermBelowStimulusInc\", Double.class, 0.0, 1.0),\n /**\n * <b>WARNING:</b> This is a <i><b>derived</b><i> value, and is overwritten\n * by the SpatialPooler algorithm's initialization.\n * \n * Values below this are \"clipped\" and zero'd out.\n */\n SYN_PERM_TRIM_THRESHOLD(\"synPermTrimThreshold\", Double.class, 0.0, 1.0),\n /**\n * A number between 0 and 1.0, used to set a floor on how often a column\n * should have at least stimulusThreshold active inputs. Periodically, each\n * column looks at the overlap duty cycle of all other columns within its\n * inhibition radius and sets its own internal minimal acceptable duty cycle\n * to: minPctDutyCycleBeforeInh * max(other columns' duty cycles). On each\n * iteration, any column whose overlap duty cycle falls below this computed\n * value will get all of its permanence values boosted up by\n * synPermActiveInc. Raising all permanences in response to a sub-par duty\n * cycle before inhibition allows a cell to search for new inputs when\n * either its previously learned inputs are no longer ever active, or when\n * the vast majority of them have been \"hijacked\" by other columns.\n */\n MIN_PCT_OVERLAP_DUTY_CYCLES(\"minPctOverlapDutyCycles\", Double.class),//TODO add range here?\n /**\n * A number between 0 and 1.0, used to set a floor on how often a column\n * should be activate. Periodically, each column looks at the activity duty\n * cycle of all other columns within its inhibition radius and sets its own\n * internal minimal acceptable duty cycle to: minPctDutyCycleAfterInh *\n * max(other columns' duty cycles). On each iteration, any column whose duty\n * cycle after inhibition falls below this computed value will get its\n * internal boost factor increased.\n */\n MIN_PCT_ACTIVE_DUTY_CYCLES(\"minPctActiveDutyCycles\", Double.class),//TODO add range here?\n /**\n * The period used to calculate duty cycles. Higher values make it take\n * longer to respond to changes in boost or synPerConnectedCell. Shorter\n * values make it more unstable and likely to oscillate.\n */\n DUTY_CYCLE_PERIOD(\"dutyCyclePeriod\", Integer.class),//TODO add range here?\n /**\n * The maximum overlap boost factor. Each column's overlap gets multiplied\n * by a boost factor before it gets considered for inhibition. The actual\n * boost factor for a column is number between 1.0 and maxBoost. A boost\n * factor of 1.0 is used if the duty cycle is >= minOverlapDutyCycle,\n * maxBoost is used if the duty cycle is 0, and any duty cycle in between is\n * linearly extrapolated from these 2 endpoints.\n */\n MAX_BOOST(\"maxBoost\", Double.class), //TODO add range here?\n /**\n * Determines if inputs at the beginning and end of an input dimension should\n * be considered neighbors when mapping columns to inputs.\n */\n WRAP_AROUND(\"wrapAround\", Boolean.class),\n \n ///////////// SpatialPooler / Network Parameter(s) /////////////\n /** Number of cycles to send through the SP before forwarding data to the rest of the network. */\n SP_PRIMER_DELAY(\"sp_primer_delay\", Integer.class),\n \n ///////////// Encoder Parameters //////////////\n /** number of bits in the representation (must be &gt;= w) */\n N(\"n\", Integer.class),\n /** \n * The number of bits that are set to encode a single value - the\n * \"width\" of the output signal\n */\n W(\"w\", Integer.class),\n /** The minimum value of the input signal. */\n MIN_VAL(\"minVal\", Double.class),\n /** The maximum value of the input signal. */\n MAX_VAL(\"maxVal\", Double.class),\n /**\n * inputs separated by more than, or equal to this distance will have non-overlapping\n * representations\n */\n RADIUS(\"radius\", Double.class),\n /** inputs separated by more than, or equal to this distance will have different representations */\n RESOLUTION(\"resolution\", Double.class),\n /**\n * If true, then the input value \"wraps around\" such that minval = maxval\n * For a periodic value, the input must be strictly less than maxval,\n * otherwise maxval is a true upper bound.\n */\n PERIODIC(\"periodic\", Boolean.class),\n /** \n * if true, non-periodic inputs smaller than minval or greater\n * than maxval will be clipped to minval/maxval \n */\n CLIP_INPUT(\"clipInput\", Boolean.class),\n /** \n * If true, skip some safety checks (for compatibility reasons), default false \n * Mostly having to do with being able to set the window size &lt; 21 \n */\n FORCED(\"forced\", Boolean.class),\n /** Name of the field being encoded */\n FIELD_NAME(\"fieldName\", String.class),\n /** Primitive type of the field, used to auto-configure the type of encoder */\n FIELD_TYPE(\"fieldType\", String.class),\n /** Encoder name */\n ENCODER(\"encoderType\", String.class),\n /** Designates holder for the Multi Encoding Map */\n FIELD_ENCODING_MAP(\"fieldEncodings\", Map.class),\n CATEGORY_LIST(\"categoryList\", List.class),\n \n // Network Layer indicator for auto classifier generation\n AUTO_CLASSIFY(\"hasClassifiers\", Boolean.class),\n\n /** Maps encoder input field name to type of classifier to be used for them */\n INFERRED_FIELDS(\"inferredFields\", Map.class), // Map<String, Classifier.class>\n\n // How many bits to use if encoding the respective date fields.\n // e.g. Tuple(bits to use:int, radius:double)\n DATEFIELD_SEASON(\"season\", Tuple.class), \n DATEFIELD_DOFW(\"dayOfWeek\", Tuple.class),\n DATEFIELD_WKEND(\"weekend\", Tuple.class),\n DATEFIELD_HOLIDAY(\"holiday\", Tuple.class),\n DATEFIELD_TOFD(\"timeOfDay\", Tuple.class),\n DATEFIELD_CUSTOM(\"customDays\", Tuple.class), // e.g. Tuple(bits:int, List<String>:\"mon,tue,fri\")\n DATEFIELD_PATTERN(\"formatPattern\", String.class);\n \n\n private static final Map<String, KEY> fieldMap = new HashMap<>();\n\n static {\n for (KEY key : KEY.values()) {\n fieldMap.put(key.getFieldName(), key);\n }\n }\n\n public static KEY getKeyByFieldName(String fieldName) {\n return fieldMap.get(fieldName);\n }\n\n final private String fieldName;\n final private Class<?> fieldType;\n final private Number min;\n final private Number max;\n\n /**\n * Constructs a new KEY\n *\n * @param fieldName\n * @param fieldType\n */\n private KEY(String fieldName, Class<?> fieldType) {\n this(fieldName, fieldType, null, null);\n }\n\n /**\n * Constructs a new KEY with range check\n *\n * @param fieldName\n * @param fieldType\n * @param min\n * @param max\n */\n private KEY(String fieldName, Class<?> fieldType, Number min, Number max) {\n this.fieldName = fieldName;\n this.fieldType = fieldType;\n this.min = min;\n this.max = max;\n }\n\n public Class<?> getFieldType() {\n return fieldType;\n }\n\n public String getFieldName() {\n return fieldName;\n }\n\n public Number getMin() {\n return min;\n }\n\n public Number getMax() {\n return max;\n }\n\n public boolean checkRange(Number value) {\n if (value == null) {\n throw new IllegalArgumentException(\"checkRange argument can not be null\");\n }\n return (min == null && max == null) ||\n (min != null && max == null && value.doubleValue() >= min.doubleValue()) ||\n (max != null && min == null && value.doubleValue() <= max.doubleValue()) ||\n (min != null && value.doubleValue() >= min.doubleValue() && max != null && value.doubleValue() <= max.doubleValue());\n }\n\n}", "public class TemporalMemory implements ComputeDecorator, Serializable{\n /** simple serial version id */\n\tprivate static final long serialVersionUID = 1L;\n \n private static final double EPSILON = 0.00001;\n \n private static final int ACTIVE_COLUMNS = 1;\n \n /**\n * Uses the specified {@link Connections} object to Build the structural \n * anatomy needed by this {@code TemporalMemory} to implement its algorithms.\n * \n * The connections object holds the {@link Column} and {@link Cell} infrastructure,\n * and is used by both the {@link SpatialPooler} and {@link TemporalMemory}. Either of\n * these can be used separately, and therefore this Connections object may have its\n * Columns and Cells initialized by either the init method of the SpatialPooler or the\n * init method of the TemporalMemory. We check for this so that complete initialization\n * of both Columns and Cells occurs, without either being redundant (initialized more than\n * once). However, {@link Cell}s only get created when initializing a TemporalMemory, because\n * they are not used by the SpatialPooler.\n * \n * @param c {@link Connections} object\n */\n \n \n public static void init(Connections c) {\n SparseObjectMatrix<Column> matrix = c.getMemory() == null ?\n new SparseObjectMatrix<Column>(c.getColumnDimensions()) :\n c.getMemory();\n c.setMemory(matrix);\n \n int numColumns = matrix.getMaxIndex() + 1;\n c.setNumColumns(numColumns);\n int cellsPerColumn = c.getCellsPerColumn();\n Cell[] cells = new Cell[numColumns * cellsPerColumn];\n \n //Used as flag to determine if Column objects have been created.\n Column colZero = matrix.getObject(0);\n for(int i = 0;i < numColumns;i++) {\n Column column = colZero == null ? \n new Column(cellsPerColumn, i) : matrix.getObject(i);\n for(int j = 0;j < cellsPerColumn;j++) {\n cells[i * cellsPerColumn + j] = column.getCell(j);\n }\n //If columns have not been previously configured\n if(colZero == null) matrix.set(i, column);\n }\n //Only the TemporalMemory initializes cells so no need to test for redundancy\n c.setCells(cells);\n }\n\n\t@Override\n\tpublic ComputeCycle compute(Connections connections, int[] activeColumns, boolean learn) {\n\t ComputeCycle cycle = new ComputeCycle();\n\t\tactivateCells(connections, cycle, activeColumns, learn);\n\t\tactivateDendrites(connections, cycle, learn);\n\t\t\n\t\treturn cycle;\n\t}\n\t\n\t/**\n\t * Calculate the active cells, using the current active columns and dendrite\n * segments. Grow and reinforce synapses.\n * \n * <pre>\n * Pseudocode:\n * for each column\n * if column is active and has active distal dendrite segments\n * call activatePredictedColumn\n * if column is active and doesn't have active distal dendrite segments\n * call burstColumn\n * if column is inactive and has matching distal dendrite segments\n * call punishPredictedColumn\n * \n * </pre>\n * \n\t * @param conn \n\t * @param activeColumnIndices\n\t * @param learn\n\t */\n\t@SuppressWarnings(\"unchecked\")\n public void activateCells(Connections conn, ComputeCycle cycle, int[] activeColumnIndices, boolean learn) {\n\t \n\t ColumnData columnData = new ColumnData();\n \n Set<Cell> prevActiveCells = conn.getActiveCells();\n Set<Cell> prevWinnerCells = conn.getWinnerCells();\n \n List<Column> activeColumns = Arrays.stream(activeColumnIndices)\n .sorted()\n .mapToObj(i -> conn.getColumn(i))\n .collect(Collectors.toList());\n \n Function<Column, Column> identity = Function.identity();\n Function<DistalDendrite, Column> segToCol = segment -> segment.getParentCell().getColumn(); \n \n @SuppressWarnings({ \"rawtypes\" })\n GroupBy2<Column> grouper = GroupBy2.<Column>of(\n new Pair(activeColumns, identity),\n new Pair(new ArrayList<>(conn.getActiveSegments()), segToCol),\n new Pair(new ArrayList<>(conn.getMatchingSegments()), segToCol));\n \n double permanenceIncrement = conn.getPermanenceIncrement();\n double permanenceDecrement = conn.getPermanenceDecrement();\n \n for(Tuple t : grouper) {\n columnData = columnData.set(t);\n \n if(columnData.isNotNone(ACTIVE_COLUMNS)) {\n if(!columnData.activeSegments().isEmpty()) {\n List<Cell> cellsToAdd = activatePredictedColumn(conn, columnData.activeSegments(),\n columnData.matchingSegments(), prevActiveCells, prevWinnerCells, \n permanenceIncrement, permanenceDecrement, learn);\n \n cycle.activeCells.addAll(cellsToAdd);\n cycle.winnerCells.addAll(cellsToAdd);\n }else{\n Tuple cellsXwinnerCell = burstColumn(conn, columnData.column(), columnData.matchingSegments(), \n prevActiveCells, prevWinnerCells, permanenceIncrement, permanenceDecrement, conn.getRandom(), \n learn);\n \n cycle.activeCells.addAll((List<Cell>)cellsXwinnerCell.get(0));\n cycle.winnerCells.add((Cell)cellsXwinnerCell.get(1));\n }\n }else{\n if(learn) {\n punishPredictedColumn(conn, columnData.activeSegments(), columnData.matchingSegments(), \n prevActiveCells, prevWinnerCells, conn.getPredictedSegmentDecrement());\n }\n }\n }\n\t}\n\t\n\t/**\n\t * Calculate dendrite segment activity, using the current active cells.\n\t * \n\t * <pre>\n\t * Pseudocode:\n * for each distal dendrite segment with activity >= activationThreshold\n * mark the segment as active\n * for each distal dendrite segment with unconnected activity >= minThreshold\n * mark the segment as matching\n * </pre>\n * \n\t * @param conn the Connectivity\n\t * @param cycle Stores current compute cycle results\n\t * @param learn If true, segment activations will be recorded. This information is used\n * during segment cleanup.\n\t */\n\tpublic void activateDendrites(Connections conn, ComputeCycle cycle, boolean learn) {\n\t Activity activity = conn.computeActivity(cycle.activeCells, conn.getConnectedPermanence());\n\t \n\t List<DistalDendrite> activeSegments = IntStream.range(0, activity.numActiveConnected.length)\n\t .filter(i -> activity.numActiveConnected[i] >= conn.getActivationThreshold())\n\t .mapToObj(i -> conn.segmentForFlatIdx(i))\n\t .collect(Collectors.toList());\n\t \n\t List<DistalDendrite> matchingSegments = IntStream.range(0, activity.numActiveConnected.length)\n\t .filter(i -> activity.numActivePotential[i] >= conn.getMinThreshold())\n\t .mapToObj(i -> conn.segmentForFlatIdx(i))\n\t .collect(Collectors.toList());\n\t \n\t Collections.sort(activeSegments, conn.segmentPositionSortKey);\n\t Collections.sort(matchingSegments, conn.segmentPositionSortKey);\n\t \n\t cycle.activeSegments = activeSegments;\n\t cycle.matchingSegments = matchingSegments;\n\t \n\t conn.lastActivity = activity;\n\t conn.setActiveCells(new LinkedHashSet<>(cycle.activeCells));\n conn.setWinnerCells(new LinkedHashSet<>(cycle.winnerCells));\n conn.setActiveSegments(activeSegments);\n conn.setMatchingSegments(matchingSegments);\n // Forces generation of the predictive cells from the above active segments\n conn.clearPredictiveCells();\n conn.getPredictiveCells();\n\t \n\t if(learn) {\n\t activeSegments.stream().forEach(s -> conn.recordSegmentActivity(s));\n\t conn.startNewIteration();\n\t }\n\t}\n\t\n\t/**\n * Indicates the start of a new sequence. Clears any predictions and makes sure\n * synapses don't grow to the currently active cells in the next time step.\n */\n @Override\n public void reset(Connections connections) {\n connections.getActiveCells().clear();\n connections.getWinnerCells().clear();\n connections.getActiveSegments().clear();\n connections.getMatchingSegments().clear();\n }\n \n /**\n\t * Determines which cells in a predicted column should be added to winner cells\n * list, and learns on the segments that correctly predicted this column.\n * \n\t * @param conn the connections\n\t * @param activeSegments Active segments in the specified column\n\t * @param matchingSegments Matching segments in the specified column\n\t * @param prevActiveCells Active cells in `t-1`\n\t * @param prevWinnerCells Winner cells in `t-1`\n\t * @param learn If true, grow and reinforce synapses\n\t * \n\t * <pre>\n\t * Pseudocode:\n * for each cell in the column that has an active distal dendrite segment\n * mark the cell as active\n * mark the cell as a winner cell\n * (learning) for each active distal dendrite segment\n * strengthen active synapses\n * weaken inactive synapses\n * grow synapses to previous winner cells\n * </pre>\n * \n\t * @return A list of predicted cells that will be added to active cells and winner\n * cells.\n\t */\n\tpublic List<Cell> activatePredictedColumn(Connections conn, List<DistalDendrite> activeSegments,\n\t List<DistalDendrite> matchingSegments, Set<Cell> prevActiveCells, Set<Cell> prevWinnerCells,\n\t double permanenceIncrement, double permanenceDecrement, boolean learn) {\n\t \n\t List<Cell> cellsToAdd = new ArrayList<>();\n Cell previousCell = null;\n Cell currCell;\n for(DistalDendrite segment : activeSegments) {\n if((currCell = segment.getParentCell()) != previousCell) {\n cellsToAdd.add(currCell);\n previousCell = currCell;\n }\n \n if(learn) {\n adaptSegment(conn, segment, prevActiveCells, permanenceIncrement, permanenceDecrement);\n \n int numActive = conn.getLastActivity().numActivePotential[segment.getIndex()];\n int nGrowDesired = conn.getMaxNewSynapseCount() - numActive;\n \n if(nGrowDesired > 0) {\n growSynapses(conn, prevWinnerCells, segment, conn.getInitialPermanence(),\n nGrowDesired, conn.getRandom());\n }\n }\n }\n \n return cellsToAdd;\n\t}\n\t\n\t/**\n * Activates all of the cells in an unpredicted active column,\n * chooses a winner cell, and, if learning is turned on, either adapts or\n * creates a segment. growSynapses is invoked on this segment.\n * </p><p>\n * <b>Pseudocode:</b>\n * </p><p>\n * <pre>\n * mark all cells as active\n * if there are any matching distal dendrite segments\n * find the most active matching segment\n * mark its cell as a winner cell\n * (learning)\n * grow and reinforce synapses to previous winner cells\n * else\n * find the cell with the least segments, mark it as a winner cell\n * (learning)\n * (optimization) if there are previous winner cells\n * add a segment to this winner cell\n * grow synapses to previous winner cells\n * </pre>\n * </p>\n * \n * @param conn Connections instance for the TM\n * @param column Bursting {@link Column}\n * @param matchingSegments List of matching {@link DistalDendrite}s\n * @param prevActiveCells Active cells in `t-1`\n * @param prevWinnerCells Winner cells in `t-1`\n * @param permanenceIncrement Amount by which permanences of synapses\n * are decremented during learning\n * @param permanenceDecrement Amount by which permanences of synapses\n * are incremented during learning\n * @param random Random number generator\n * @param learn Whether or not learning is enabled\n * \n * @return Tuple containing:\n * cells list of the processed column's cells\n * bestCell the best cell\n */\n public Tuple burstColumn(Connections conn, Column column, List<DistalDendrite> matchingSegments, \n Set<Cell> prevActiveCells, Set<Cell> prevWinnerCells, double permanenceIncrement, double permanenceDecrement, \n Random random, boolean learn) {\n \n List<Cell> cells = column.getCells();\n Cell bestCell = null;\n \n if(!matchingSegments.isEmpty()) {\n int[] numPoten = conn.getLastActivity().numActivePotential;\n Comparator<DistalDendrite> cmp = (dd1,dd2) -> numPoten[dd1.getIndex()] - numPoten[dd2.getIndex()]; \n \n DistalDendrite bestSegment = matchingSegments.stream().max(cmp).get();\n bestCell = bestSegment.getParentCell();\n \n if(learn) {\n adaptSegment(conn, bestSegment, prevActiveCells, permanenceIncrement, permanenceDecrement);\n \n int nGrowDesired = conn.getMaxNewSynapseCount() - numPoten[bestSegment.getIndex()];\n \n if(nGrowDesired > 0) {\n growSynapses(conn, prevWinnerCells, bestSegment, conn.getInitialPermanence(), \n nGrowDesired, random); \n }\n }\n }else{\n bestCell = leastUsedCell(conn, cells, random);\n if(learn) {\n int nGrowExact = Math.min(conn.getMaxNewSynapseCount(), prevWinnerCells.size());\n if(nGrowExact > 0) {\n DistalDendrite bestSegment = conn.createSegment(bestCell);\n growSynapses(conn, prevWinnerCells, bestSegment, conn.getInitialPermanence(), \n nGrowExact, random);\n }\n }\n }\n \n return new Tuple(cells, bestCell);\n }\n \n /**\n * Punishes the Segments that incorrectly predicted a column to be active.\n * \n * <p>\n * <pre>\n * Pseudocode:\n * for each matching segment in the column\n * weaken active synapses\n * </pre>\n * </p>\n * \n * @param conn Connections instance for the tm\n * @param activeSegments An iterable of {@link DistalDendrite} actives\n * @param matchingSegments An iterable of {@link DistalDendrite} matching\n * for the column compute is operating on\n * that are matching; None if empty\n * @param prevActiveCells Active cells in `t-1`\n * @param prevWinnerCells Winner cells in `t-1`\n * are decremented during learning.\n * @param predictedSegmentDecrement Amount by which segments are punished for incorrect predictions\n */\n public void punishPredictedColumn(Connections conn, List<DistalDendrite> activeSegments, \n List<DistalDendrite> matchingSegments, Set<Cell> prevActiveCells, Set<Cell> prevWinnerCells,\n double predictedSegmentDecrement) {\n \n if(predictedSegmentDecrement > 0) {\n for(DistalDendrite segment : matchingSegments) {\n adaptSegment(conn, segment, prevActiveCells, -conn.getPredictedSegmentDecrement(), 0);\n }\n }\n }\n\t\n\t\n ////////////////////////////\n // Helper Methods //\n ////////////////////////////\n \n\t/**\n * Gets the cell with the smallest number of segments.\n * Break ties randomly.\n * \n * @param conn Connections instance for the tm\n * @param cells List of {@link Cell}s\n * @param random Random Number Generator\n * \n * @return the least used {@code Cell}\n */\n public Cell leastUsedCell(Connections conn, List<Cell> cells, Random random) {\n List<Cell> leastUsedCells = new ArrayList<>();\n int minNumSegments = Integer.MAX_VALUE;\n for(Cell cell : cells) {\n int numSegments = conn.numSegments(cell);\n \n if(numSegments < minNumSegments) {\n minNumSegments = numSegments;\n leastUsedCells.clear();\n }\n \n if(numSegments == minNumSegments) {\n leastUsedCells.add(cell);\n }\n }\n \n int i = random.nextInt(leastUsedCells.size());\n return leastUsedCells.get(i);\n }\n \n /**\n * Creates nDesiredNewSynapes synapses on the segment passed in if\n * possible, choosing random cells from the previous winner cells that are\n * not already on the segment.\n * <p>\n * <b>Notes:</b> The process of writing the last value into the index in the array\n * that was most recently changed is to ensure the same results that we get\n * in the c++ implementation using iter_swap with vectors.\n * </p>\n * \n * @param conn Connections instance for the tm\n * @param prevWinnerCells Winner cells in `t-1`\n * @param segment Segment to grow synapses on. \n * @param initialPermanence Initial permanence of a new synapse.\n * @param nDesiredNewSynapses Desired number of synapses to grow\n * @param random Tm object used to generate random\n * numbers\n */\n public void growSynapses(Connections conn, Set<Cell> prevWinnerCells, DistalDendrite segment, \n double initialPermanence, int nDesiredNewSynapses, Random random) {\n \n List<Cell> candidates = new ArrayList<>(prevWinnerCells);\n Collections.sort(candidates);\n \n for(Synapse synapse : conn.getSynapses(segment)) {\n Cell presynapticCell = synapse.getPresynapticCell();\n int index = candidates.indexOf(presynapticCell);\n if(index != -1) {\n candidates.remove(index);\n }\n }\n \n int candidatesLength = candidates.size();\n int nActual = nDesiredNewSynapses < candidatesLength ? nDesiredNewSynapses : candidatesLength;\n \n for(int i = 0;i < nActual;i++) {\n int rand = random.nextInt(candidates.size());\n conn.createSynapse(segment, candidates.get(rand), initialPermanence);\n candidates.remove(rand);\n }\n }\n\n /**\n * Updates synapses on segment.\n * Strengthens active synapses; weakens inactive synapses.\n * \n * @param conn {@link Connections} instance for the tm\n * @param segment {@link DistalDendrite} to adapt\n * @param prevActiveCells Active {@link Cell}s in `t-1`\n * @param permanenceIncrement Amount to increment active synapses \n * @param permanenceDecrement Amount to decrement inactive synapses\n */\n public void adaptSegment(Connections conn, DistalDendrite segment, Set<Cell> prevActiveCells, \n double permanenceIncrement, double permanenceDecrement) {\n \n // Destroying a synapse modifies the set that we're iterating through.\n List<Synapse> synapsesToDestroy = new ArrayList<>();\n \n for(Synapse synapse : conn.getSynapses(segment)) {\n double permanence = synapse.getPermanence();\n \n if(prevActiveCells.contains(synapse.getPresynapticCell())) {\n permanence += permanenceIncrement;\n }else{\n permanence -= permanenceDecrement;\n }\n \n // Keep permanence within min/max bounds\n permanence = permanence < 0 ? 0 : permanence > 1.0 ? 1.0 : permanence;\n \n // Use this to examine issues caused by subtle floating point differences\n // be careful to set the scale (1 below) to the max significant digits right of the decimal point\n // between the permanenceIncrement and initialPermanence\n //\n // permanence = new BigDecimal(permanence).setScale(1, RoundingMode.HALF_UP).doubleValue(); \n \n if(permanence < EPSILON) {\n synapsesToDestroy.add(synapse);\n }else{\n synapse.setPermanence(conn, permanence);\n }\n }\n \n for(Synapse s : synapsesToDestroy) {\n conn.destroySynapse(s);\n }\n \n if(conn.numSynapses(segment) == 0) {\n conn.destroySegment(segment);\n }\n }\n \n\t/**\n * Used in the {@link TemporalMemory#compute(Connections, int[], boolean)} method\n * to make pulling values out of the {@link GroupBy2} more readable and named.\n */\n @SuppressWarnings(\"unchecked\")\n public static class ColumnData implements Serializable {\n /** Default Serial */\n private static final long serialVersionUID = 1L;\n Tuple t;\n \n public ColumnData() {}\n \n public ColumnData(Tuple t) {\n this.t = t;\n }\n \n public Column column() { return (Column)t.get(0); }\n public List<Column> activeColumns() { return (List<Column>)t.get(1); }\n public List<DistalDendrite> activeSegments() { \n return ((List<?>)t.get(2)).get(0).equals(Slot.empty()) ? \n Collections.emptyList() :\n (List<DistalDendrite>)t.get(2); \n }\n public List<DistalDendrite> matchingSegments() {\n return ((List<?>)t.get(3)).get(0).equals(Slot.empty()) ? \n Collections.emptyList() :\n (List<DistalDendrite>)t.get(3); \n }\n \n public ColumnData set(Tuple t) { this.t = t; return this; }\n \n /**\n * Returns a boolean flag indicating whether the slot contained by the\n * tuple at the specified index is filled with the special empty\n * indicator.\n * \n * @param memberIndex the index of the tuple to assess.\n * @return true if <em><b>not</b></em> none, false if it <em><b>is none</b></em>.\n */\n public boolean isNotNone(int memberIndex) {\n return !((List<?>)t.get(memberIndex)).get(0).equals(NONE);\n }\n } \n}", "@SuppressWarnings(\"unchecked\")\npublic static class ColumnData implements Serializable {\n /** Default Serial */\n private static final long serialVersionUID = 1L;\n Tuple t;\n \n public ColumnData() {}\n \n public ColumnData(Tuple t) {\n this.t = t;\n }\n \n public Column column() { return (Column)t.get(0); }\n public List<Column> activeColumns() { return (List<Column>)t.get(1); }\n public List<DistalDendrite> activeSegments() { \n return ((List<?>)t.get(2)).get(0).equals(Slot.empty()) ? \n Collections.emptyList() :\n (List<DistalDendrite>)t.get(2); \n }\n public List<DistalDendrite> matchingSegments() {\n return ((List<?>)t.get(3)).get(0).equals(Slot.empty()) ? \n Collections.emptyList() :\n (List<DistalDendrite>)t.get(3); \n }\n \n public ColumnData set(Tuple t) { this.t = t; return this; }\n \n /**\n * Returns a boolean flag indicating whether the slot contained by the\n * tuple at the specified index is filled with the special empty\n * indicator.\n * \n * @param memberIndex the index of the tuple to assess.\n * @return true if <em><b>not</b></em> none, false if it <em><b>is none</b></em>.\n */\n public boolean isNotNone(int memberIndex) {\n return !((List<?>)t.get(memberIndex)).get(0).equals(NONE);\n }\n} ", "public class GroupBy2<R extends Comparable<R>> implements Generator<Tuple> {\n /** serial version */\n private static final long serialVersionUID = 1L;\n \n /** stores the user inputted pairs */\n private Pair<List<Object>, Function<Object, R>>[] entries;\n \n /** stores the {@link GroupBy} {@link Generator}s created from the supplied lists */\n private List<GroupBy<Object, R>> generatorList;\n \n /** the current interation's minimum key value */\n private R minKeyVal;\n \n \n ///////////////////////\n // Control Lists //\n ///////////////////////\n private boolean[] advanceList;\n private Slot<Pair<Object, R>>[] nextList;\n \n private int numEntries;\n \n /**\n * Private internally used constructor. To instantiate objects of this\n * class, please see the static factory method {@link #of(Pair...)}\n * \n * @param entries a {@link Pair} of lists and their key-producing functions\n */\n private GroupBy2(Pair<List<Object>, Function<Object, R>>[] entries) {\n this.entries = entries;\n }\n \n /**\n * <p>\n * Returns a {@code GroupBy2} instance which is used to group lists of objects\n * in ascending order using keys supplied by their associated {@link Function}s.\n * </p><p>\n * <b>Here is an example of the usage and output of this object: (Taken from {@link GroupBy2Test})</b>\n * </p>\n * <pre>\n * List<Integer> sequence0 = Arrays.asList(new Integer[] { 7, 12, 16 });\n * List<Integer> sequence1 = Arrays.asList(new Integer[] { 3, 4, 5 });\n * \n * Function<Integer, Integer> identity = Function.identity();\n * Function<Integer, Integer> times3 = x -> x * 3;\n * \n * @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n * GroupBy2<Integer> groupby2 = GroupBy2.of(\n * new Pair(sequence0, identity), \n * new Pair(sequence1, times3));\n * \n * for(Tuple tuple : groupby2) {\n * System.out.println(tuple);\n * }\n * </pre>\n * <br>\n * <b>Will output the following {@link Tuple}s:</b>\n * <pre>\n * '7':'[7]':'[NONE]'\n * '9':'[NONE]':'[3]'\n * '12':'[12]':'[4]'\n * '15':'[NONE]':'[5]'\n * '16':'[16]':'[NONE]'\n * \n * From row 1 of the output:\n * Where '7' == Tuple.get(0), 'List[7]' == Tuple.get(1), 'List[NONE]' == Tuple.get(2) == empty list with no members\n * </pre>\n * \n * <b>Note: Read up on groupby here:</b><br>\n * https://docs.python.org/dev/library/itertools.html#itertools.groupby\n * <p> \n * @param entries\n * @return a n + 1 dimensional tuple, where the first element is the\n * key of the group and the other n entries are lists of\n * objects that are a member of the current group that is being\n * iterated over in the nth list passed in. Note that this\n * is a generator and a n+1 dimensional tuple is yielded for\n * every group. If a list has no members in the current\n * group, {@link Slot#NONE} is returned in place of a generator.\n */\n @SuppressWarnings(\"unchecked\")\n public static <R extends Comparable<R>> GroupBy2<R> of(Pair<List<Object>, Function<Object, R>>... entries) {\n return new GroupBy2<>(entries);\n }\n \n /**\n * (Re)initializes the internal {@link Generator}(s). This method\n * may be used to \"restart\" the internal {@link Iterator}s and\n * reuse this object.\n */\n @SuppressWarnings(\"unchecked\")\n public void reset() {\n generatorList = new ArrayList<>();\n \n for(int i = 0;i < entries.length;i++) {\n generatorList.add(GroupBy.of(entries[i].getFirst(), entries[i].getSecond()));\n }\n \n numEntries = generatorList.size();\n \n// for(int i = 0;i < numEntries;i++) {\n// for(Pair<Object, R> p : generatorList.get(i)) {\n// System.out.println(\"generator \" + i + \": \" + p.getKey() + \", \" + p.getValue());\n// }\n// System.out.println(\"\");\n// }\n// \n// generatorList = new ArrayList<>();\n// \n// for(int i = 0;i < entries.length;i++) {\n// generatorList.add(GroupBy.of(entries[i].getKey(), entries[i].getValue()));\n// }\n \n advanceList = new boolean[numEntries];\n Arrays.fill(advanceList, true);\n nextList = new Slot[numEntries];\n Arrays.fill(nextList, Slot.NONE);\n }\n \n /**\n * {@inheritDoc}\n */\n public Iterator<Tuple> iterator() { return this; }\n \n /**\n * Returns a flag indicating that at least one {@link Generator} has\n * a matching key for the current \"smallest\" key generated.\n * \n * @return a flag indicating that at least one {@link Generator} has\n * a matching key for the current \"smallest\" key generated.\n */\n @Override\n public boolean hasNext() {\n if(generatorList == null) {\n reset();\n }\n \n advanceSequences();\n \n return nextMinKey();\n }\n \n /**\n * Returns a {@link Tuple} containing the current key in the\n * zero'th slot, and a list objects which are members of the\n * group specified by that key.\n * \n * {@inheritDoc}\n */\n @SuppressWarnings(\"unchecked\")\n @Override\n public Tuple next() {\n \n Object[] objs = IntStream\n .range(0, numEntries + 1)\n .mapToObj(i -> i==0 ? minKeyVal : new ArrayList<R>())\n .toArray();\n \n Tuple retVal = new Tuple((Object[])objs);\n \n for(int i = 0;i < numEntries;i++) {\n if(isEligibleList(i, minKeyVal)) {\n ((List<Object>)retVal.get(i + 1)).add(nextList[i].get().getFirst());\n drainKey(retVal, i, minKeyVal);\n advanceList[i] = true;\n }else{\n advanceList[i] = false;\n ((List<Object>)retVal.get(i + 1)).add(Slot.empty());\n }\n }\n \n return retVal;\n }\n \n /**\n * Internal method which advances index of the current\n * {@link GroupBy}s for each group present.\n */\n private void advanceSequences() {\n for(int i = 0;i < numEntries;i++) {\n if(advanceList[i]) {\n nextList[i] = generatorList.get(i).hasNext() ?\n Slot.of(generatorList.get(i).next()) : Slot.empty();\n }\n }\n }\n \n /**\n * Returns the next smallest generated key.\n * \n * @return the next smallest generated key.\n */\n private boolean nextMinKey() {\n return Arrays.stream(nextList)\n .filter(opt -> opt.isPresent())\n .map(opt -> opt.get().getSecond())\n .min((k, k2) -> k.compareTo(k2))\n .map(k -> { minKeyVal = k; return k; } )\n .isPresent();\n }\n \n /**\n * Returns a flag indicating whether the list currently pointed\n * to by the specified index contains a key which matches the\n * specified \"targetKey\".\n * \n * @param listIdx the index pointing to the {@link GroupBy} being\n * processed.\n * @param targetKey the specified key to match.\n * @return true if so, false if not\n */\n private boolean isEligibleList(int listIdx, Object targetKey) {\n return nextList[listIdx].isPresent() && nextList[listIdx].get().getSecond().equals(targetKey);\n }\n \n /**\n * Each input grouper may generate multiple members which match the\n * specified \"targetVal\". This method guarantees that all members \n * are added to the list residing at the specified Tuple index.\n * \n * @param retVal the Tuple being added to\n * @param listIdx the index specifying the list within the \n * tuple which will have members added to it\n * @param targetVal the value to match in order to be an added member\n */\n @SuppressWarnings(\"unchecked\")\n private void drainKey(Tuple retVal, int listIdx, R targetVal) {\n while(generatorList.get(listIdx).hasNext()) {\n if(generatorList.get(listIdx).peek().getSecond().equals(targetVal)) {\n nextList[listIdx] = Slot.of(generatorList.get(listIdx).next());\n ((List<Object>)retVal.get(listIdx + 1)).add(nextList[listIdx].get().getFirst());\n }else{\n nextList[listIdx] = Slot.empty();\n break;\n }\n }\n }\n \n /**\n * A minimal {@link Serializable} version of an {@link Slot}\n * @param <T> the value held within this {@code Slot}\n */\n public static final class Slot<T> implements Serializable {\n /** Default Serial */\n private static final long serialVersionUID = 1L;\n \n /**\n * Common instance for {@code empty()}.\n */\n public static final Slot<?> NONE = new Slot<>();\n\n /**\n * If non-null, the value; if null, indicates no value is present\n */\n private final T value;\n \n private Slot() { this.value = null; }\n \n /**\n * Constructs an instance with the value present.\n *\n * @param value the non-null value to be present\n * @throws NullPointerException if value is null\n */\n private Slot(T value) {\n this.value = Objects.requireNonNull(value);\n }\n\n /**\n * Returns an {@code Slot} with the specified present non-null value.\n *\n * @param <T> the class of the value\n * @param value the value to be present, which must be non-null\n * @return an {@code Slot} with the value present\n * @throws NullPointerException if value is null\n */\n public static <T> Slot<T> of(T value) {\n return new Slot<>(value);\n }\n\n /**\n * Returns an {@code Slot} describing the specified value, if non-null,\n * otherwise returns an empty {@code Slot}.\n *\n * @param <T> the class of the value\n * @param value the possibly-null value to describe\n * @return an {@code Slot} with a present value if the specified value\n * is non-null, otherwise an empty {@code Slot}\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> Slot<T> ofNullable(T value) {\n return value == null ? (Slot<T>)NONE : of(value);\n }\n\n /**\n * If a value is present in this {@code Slot}, returns the value,\n * otherwise throws {@code NoSuchElementException}.\n *\n * @return the non-null value held by this {@code Slot}\n * @throws NoSuchElementException if there is no value present\n *\n * @see Slot#isPresent()\n */\n public T get() {\n if (value == null) {\n throw new NoSuchElementException(\"No value present\");\n }\n return value;\n }\n \n /**\n * Returns an empty {@code Slot} instance. No value is present for this\n * Slot.\n *\n * @param <T> Type of the non-existent value\n * @return an empty {@code Slot}\n */\n public static<T> Slot<T> empty() {\n @SuppressWarnings(\"unchecked\")\n Slot<T> t = (Slot<T>) NONE;\n return t;\n }\n\n /**\n * Return {@code true} if there is a value present, otherwise {@code false}.\n *\n * @return {@code true} if there is a value present, otherwise {@code false}\n */\n public boolean isPresent() {\n return value != null;\n }\n \n /**\n * Indicates whether some other object is \"equal to\" this Slot. The\n * other object is considered equal if:\n * <ul>\n * <li>it is also an {@code Slot} and;\n * <li>both instances have no value present or;\n * <li>the present values are \"equal to\" each other via {@code equals()}.\n * </ul>\n *\n * @param obj an object to be tested for equality\n * @return {code true} if the other object is \"equal to\" this object\n * otherwise {@code false}\n */\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (!(obj instanceof Slot)) {\n return false;\n }\n\n Slot<?> other = (Slot<?>) obj;\n return Objects.equals(value, other.value);\n }\n\n /**\n * Returns the hash code value of the present value, if any, or 0 (zero) if\n * no value is present.\n *\n * @return hash code value of the present value or 0 if no value is present\n */\n @Override\n public int hashCode() {\n return Objects.hashCode(value);\n }\n\n /**\n * Returns a non-empty string representation of this Slot suitable for\n * debugging. The exact presentation format is unspecified and may vary\n * between implementations and versions.\n *\n * @implSpec If a value is present the result must include its string\n * representation in the result. Empty and present Slots must be\n * unambiguously differentiable.\n *\n * @return the string representation of this instance\n */\n @Override\n public String toString() {\n return value != null ? String.format(\"Slot[%s]\", value) : \"NONE\";\n }\n }\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.numenta.nupic.Parameters; import org.numenta.nupic.Parameters.KEY; import org.numenta.nupic.algorithms.TemporalMemory; import org.numenta.nupic.algorithms.TemporalMemory.ColumnData; import org.numenta.nupic.util.GroupBy2; import org.numenta.nupic.util.Tuple; import org.numenta.nupic.util.UniversalRandom; import chaschev.lang.Pair;
package org.numenta.nupic.model; public class ComputeCycleTest { @Test public void testConversionConstructor() { Column column = new Column(10, 0); List<Cell> cells = IntStream.range(0, 10) .mapToObj(i -> new Cell(column, i)) .collect(Collectors.toList()); Connections cnx = new Connections(); cnx.setActiveCells(new LinkedHashSet<Cell>( Arrays.asList( new Cell[] { cells.get(0), cells.get(1), cells.get(2), cells.get(3) }))); cnx.setWinnerCells(new LinkedHashSet<Cell>( Arrays.asList( new Cell[] { cells.get(1), cells.get(3), }))); ComputeCycle cc = new ComputeCycle(cnx); assertNotNull(cc.activeCells); assertEquals(4, cc.activeCells.size()); assertNotNull(cc.winnerCells); assertEquals(2, cc.winnerCells.size()); assertNotNull(cc.predictiveCells()); assertEquals(0, cc.predictiveCells().size()); ComputeCycle cc1 = new ComputeCycle(cnx); assertEquals(cc, cc1); assertEquals(cc.hashCode(), cc1.hashCode()); // Now test negative equality cnx.setWinnerCells(new LinkedHashSet<Cell>( Arrays.asList( new Cell[] { cells.get(4), cells.get(3), }))); ComputeCycle cc2 = new ComputeCycle(cnx); assertNotEquals(cc1, cc2); assertFalse(cc1.hashCode() == cc2.hashCode()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testActiveColumnsRetrievable() { TemporalMemory tm = new TemporalMemory(); Connections cn = new Connections(); Parameters p = getDefaultParameters(null, KEY.CELLS_PER_COLUMN, 1); p = getDefaultParameters(p, KEY.MIN_THRESHOLD, 1); p.apply(cn); TemporalMemory.init(cn); int[] previousActiveColumns = { 0, 1, 2, 3 }; Set<Cell> prevWinnerCells = cn.getCellSet(new int[] { 0, 1, 2, 3 }); int[] activeColumnsIndices = { 4 }; DistalDendrite matchingSegment = cn.createSegment(cn.getCell(4)); cn.createSynapse(matchingSegment, cn.getCell(0), 0.5); ComputeCycle cc = tm.compute(cn, previousActiveColumns, true); assertTrue(cc.winnerCells().equals(prevWinnerCells)); //cc = tm.compute(cn, activeColumnsIndices, true); Function<Column, Column> identity = Function.identity(); Function<DistalDendrite, Column> segToCol = segment -> segment.getParentCell().getColumn(); List<Column> activeColumns = Arrays.stream(activeColumnsIndices) .sorted() .mapToObj(i -> cn.getColumn(i)) .collect(Collectors.toList()); GroupBy2<Column> grouper = GroupBy2.<Column>of( new Pair(activeColumns, identity), new Pair(new ArrayList(cn.getActiveSegments()), segToCol), new Pair(new ArrayList(cn.getMatchingSegments()), segToCol));
ColumnData columnData = new ColumnData();
3
JamesNorris/Ablockalypse
src/com/github/jamesnorris/ablockalypse/event/bukkit/PlayerDeath.java
[ "public class Ablockalypse extends JavaPlugin {\n private static Ablockalypse instance;\n private static DataContainer data = new DataContainer();\n private static MainThread mainThread;\n private static External external;\n private static BaseCommand commandInstance;\n private static Tracker tracker;\n\n public static BaseCommand getBaseCommandInstance() {\n return commandInstance;\n }\n\n public static DataContainer getData() {\n return data;\n }\n\n public static External getExternal() {\n return external;\n }\n\n public static Ablockalypse getInstance() {\n return instance;\n }\n\n public static MainThread getMainThread() {\n return mainThread;\n }\n\n public static Tracker getTracker() {\n return tracker;\n }\n\n // Kills the plugin.\n protected static void kill() {\n Ablockalypse.instance.setEnabled(false);\n }\n\n @Override public void onDisable() {\n for (Game game : data.getObjectsOfType(Game.class)) {\n game.organizeObjects();\n PermanentAspect.save(game, external.getSavedDataFile(game.getName(), true));\n if ((Boolean) Setting.PRINT_STORAGE_DATA_TO_FILE.getSetting()) {\n try {\n PermanentAspect.printData(game);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n game.remove(false);\n }\n for (PlayerState state : PlayerJoin.toLoad) {\n PlayerQuit.playerSaves.put(state.getPlayer().getPlayer(), state);\n }\n for (Player player : PlayerQuit.playerSaves.keySet()) {\n PlayerState state = PlayerQuit.playerSaves.get(player);\n PermanentAspect.save(state, external.getSavedPlayerDataFile(player, true));\n }\n mainThread.cancel();\n }\n\n @SuppressWarnings(\"unchecked\") @Override public void onEnable() {\n Ablockalypse.instance = this;\n external = new External(this);\n tracker = new Tracker(\"Ablockalypse\", getDescription().getVersion(), \"https://github.com/JamesNorris/Ablockalypse/issues\", (Integer) Setting.MAX_FATALITY.getSetting());\n commandInstance = new BaseCommand();\n register();\n initServerThreads(false);\n try {\n for (File file : external.getSavedDataFolder().listFiles()) {\n if (file != null && !file.isDirectory()) {\n Map<String, Object> save = (Map<String, Object>) External.load(file);\n PermanentAspect.load(Game.class, save);\n }\n }\n for (File file : external.getSavedPlayerDataFolder().listFiles()) {\n if (file != null && !file.isDirectory()) {\n Map<String, Object> save = (Map<String, Object>) External.load(file);\n PlayerJoin.toLoad.add((PlayerState) PermanentAspect.load(PlayerState.class, save));\n file.delete();\n }\n }\n } catch (EOFException e) {\n // nothing, the file is empty and no data was saved\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n mainThread.run();// starts the main thread, which was told not to autorun earlier. Done to prevent NPEs with loading saves and running threads.\n }\n\n protected void initServerThreads(boolean startMain) {\n mainThread = new MainThread(startMain);\n new ServerBarrierActionTask(true);\n new ServerMobSpawnPreventionTask(360, (Boolean) Setting.CLEAR_MOBS.getSetting());\n new ServerHellhoundActionTask(20, true);\n new ServerTeleporterActionTask(20, true);\n }\n\n protected void register() {\n PluginManager pm = getServer().getPluginManager();\n /* EVENTS */\n for (Listener listener : new Listener[] {new EntityDamage(), new PlayerDeath(), new PlayerInteract(),\n new SignChange(), new EntityDeath(), new PlayerPickupItem(), new ProjectileHit(), new PlayerMove(),\n new EntityBreakDoor(), new PlayerTeleport(), new PlayerQuit(), new EntityTarget(), new PlayerRespawn(),\n new EntityExplode(), new EntityDamageByEntity(), new PlayerJoin(), new BlockBreak(),\n new PlayerDropItem(), new PlayerKick(), new BlockPlace(), new BlockRedstone(), new PlayerToggleSneak()}) {\n pm.registerEvents(listener, instance);\n }\n /* COMMANDS */\n instance.getCommand(\"za\").setExecutor(commandInstance);\n }\n}", "public class DataContainer {\n public static DataContainer fromObject(Object obj) {\n try {\n for (Field field : obj.getClass().getDeclaredFields()) {\n if (field.getType() == DataContainer.class) {\n return (DataContainer) field.get(obj);\n }\n }\n return (DataContainer) obj.getClass().getDeclaredField(\"data\").get(obj);// if a DataContainer field is not found otherwise...\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n public Material[] modifiableMaterials = new Material[] {Material.FLOWER_POT};// default materials\n public CopyOnWriteArrayList<Object> objects = new CopyOnWriteArrayList<Object>();\n\n public boolean gameExists(String gamename) {\n return getObjectsOfType(Game.class).contains(getGame(gamename, false));\n }\n\n public Barrier getBarrier(Location loc) {\n return getGameObjectByLocation(Barrier.class, loc);\n }\n\n public Claymore getClaymore(Location loc) {\n return getGameObjectByLocation(Claymore.class, loc);\n }\n\n public <O extends GameAspect> O getClosest(Class<O> type, Location loc) {\n return getClosest(type, loc, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);\n }\n\n public <O extends GameAspect> O getClosest(Class<O> type, Location loc, double distX, double distY, double distZ) {\n O object = null;\n double lowestDist = Double.MAX_VALUE;\n for (O obj : getObjectsOfType(type)) {\n if (obj.getDefiningBlocks() == null) {\n continue;\n }\n Location objLoc = obj.getDefiningBlock().getLocation();\n double xDif = Math.abs(objLoc.getX() - loc.getX());\n double yDif = Math.abs(objLoc.getY() - loc.getY());\n double zDif = Math.abs(objLoc.getZ() - loc.getZ());\n if (xDif < distX && yDif < distY && zDif < distZ && xDif + yDif + zDif < lowestDist) {\n object = obj;\n }\n }\n return object;\n }\n\n public Entity getEntityByUUID(World world, UUID uuid) {\n for (Entity entity : world.getEntities()) {\n if (entity.getUniqueId().compareTo(uuid) == 0) {\n return entity;\n }\n }\n return null;\n }\n\n public Game getGame(String name, boolean force) {\n List<Game> games = getObjectsOfType(Game.class);\n Game correctGame = null;\n for (Game game : games) {\n if (game.getName().equalsIgnoreCase(name)) {\n correctGame = game;\n }\n }\n return correctGame != null ? correctGame : force ? new Game(name) : null;\n }\n\n public <O extends GameAspect> O getGameObjectByLocation(Class<O> type, Location loc) {\n for (O obj : getObjectsOfType(type)) {\n if (obj.getDefiningBlocks() == null) {\n continue;\n }\n for (Block matchBlock : obj.getDefiningBlocks()) {\n if (BukkitUtility.locationMatch(matchBlock.getLocation(), loc)) {\n return obj;\n }\n }\n }\n return null;\n }\n\n public GameAspect getGameObjectByLocation(Location loc) {\n return getGameObjectByLocation(GameAspect.class, loc);\n }\n\n public Grenade getGrenade(Entity entity) {\n for (Grenade grenade : getObjectsOfType(Grenade.class)) {\n if (grenade.getLocation() != null && grenade.getGrenadeEntity() != null && grenade.getGrenadeEntity().getUniqueId().compareTo(entity.getUniqueId()) == 0) {\n return grenade;\n }\n }\n return null;\n }\n\n public Hellhound getHellhound(LivingEntity e) {\n return (Hellhound) getZAMobByEntity(e);\n }\n\n public Teleporter getMainframe(Location loc) {\n return getGameObjectByLocation(Teleporter.class, loc);\n }\n\n public MobSpawner getMobSpawner(Location loc) {\n return getGameObjectByLocation(MobSpawner.class, loc);\n }\n\n public MysteryBox getMysteryChest(Location loc) {\n return getGameObjectByLocation(MysteryBox.class, loc);\n }\n\n @SuppressWarnings(\"unchecked\") public <O extends Object> List<O> getObjectsOfType(Class<O> type) {\n ArrayList<O> list = new ArrayList<O>();\n for (Object obj : objects) {\n if (type.isAssignableFrom(obj.getClass())) {\n list.add((O) obj);\n }\n }\n return list;\n }\n\n public Passage getPassage(Location loc) {\n return getGameObjectByLocation(Passage.class, loc);\n }\n\n public ArrayList<MobSpawner> getSpawns(String gamename) {\n ArrayList<MobSpawner> spawners = new ArrayList<MobSpawner>();\n for (MobSpawner spawn : getObjectsOfType(MobSpawner.class)) {\n if (spawn.getGame().getName().equalsIgnoreCase(gamename)) {\n spawners.add(spawn);\n }\n }\n return spawners;\n }\n\n @SuppressWarnings(\"unchecked\") public <T extends Task> List<T> getTasksOfType(Class<T> type) {\n ArrayList<T> list = new ArrayList<T>();\n for (Task thread : getObjectsOfType(Task.class)) {\n if (thread.getClass().isInstance(type)) {\n list.add((T) thread);\n }\n }\n return list;\n }\n\n public Teleporter getTeleporter(Location loc) {\n return getGameObjectByLocation(Teleporter.class, loc);\n }\n\n public ZAMob getZAMob(LivingEntity e) {\n return getZAMobByEntity(e);\n }\n\n public ZAMob getZAMobByEntity(LivingEntity ent) {\n for (ZAMob mob : getObjectsOfType(ZAMob.class)) {\n if (mob.getEntity().getUniqueId().compareTo(ent.getUniqueId()) == 0) {\n return mob;\n }\n }\n return null;\n }\n\n public ZAPlayer getZAPlayer(Player player) {\n for (ZAPlayer zap : getObjectsOfType(ZAPlayer.class)) {\n if (zap.getPlayer().getName().equals(player.getName())) {\n return zap;\n }\n }\n return null;\n }\n\n public ZAPlayer getZAPlayer(Player player, String gamename, boolean force) {\n if (getZAPlayer(player) != null) {\n return getZAPlayer(player);\n } else if (getGame(gamename, false) != null && force) {\n return new ZAPlayer(player, getGame(gamename, false));\n } else if (force) {\n return new ZAPlayer(player, getGame(gamename, true));\n }\n return null;\n }\n\n public Zombie getZombie(LivingEntity e) {\n return (Zombie) getZAMobByEntity(e);\n }\n\n public boolean isBarrier(Location loc) {\n return getBarrier(loc) != null;\n }\n\n public boolean isClaymore(Location loc) {\n return getClaymore(loc) != null;\n }\n\n public boolean isGame(String name) {\n return getGame(name, false) != null;\n }\n\n public boolean isGameObject(Location loc) {\n return getGameObjectByLocation(loc) != null;\n }\n\n public boolean isGrenade(Entity entity) {\n return getGrenade(entity) != null;\n }\n\n public boolean isHellhound(LivingEntity e) {\n return getHellhound(e) != null;\n }\n\n public boolean isMainframe(Location loc) {\n return getMainframe(loc) != null;\n }\n\n public boolean isMobSpawner(Location loc) {\n return getMobSpawner(loc) != null;\n }\n\n public boolean isModifiable(Material type) {\n for (Material m : modifiableMaterials) {\n if (m == type) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isMysteryChest(Location loc) {\n return getMysteryChest(loc) != null;\n }\n\n public boolean isPassage(Location loc) {\n return getPassage(loc) != null;\n }\n\n public boolean isTeleporter(Location loc) {\n return getTeleporter(loc) != null;\n }\n\n public boolean isUndead(LivingEntity e) {\n return getZombie(e) != null;\n }\n\n public boolean isZAMob(LivingEntity e) {\n return getZAMob(e) != null;\n }\n\n public boolean isZAPlayer(Player player) {\n return getZAPlayer(player) != null;\n }\n\n public void setModifiableMaterials(Material[] materials) {\n modifiableMaterials = materials;\n }\n}", "public class Game extends PermanentAspect {\n private MysteryBox active;\n private MysteryBoxFakeBeaconTask beacons;\n private DataContainer data = Ablockalypse.getData();\n private int level = 0, mobcount, startpoints, spawnedInThisRound = 0;\n private Teleporter mainframe;\n private GameScoreboard scoreBoard;\n private String name;\n private NextLevelTask nlt;\n private CopyOnWriteArrayList<GameAspect> objects = new CopyOnWriteArrayList<GameAspect>();\n private HashMap<Integer, Integer> wolfLevels = new HashMap<Integer, Integer>();\n private boolean wolfRound, armorRound, paused, started;// TODO armorRound not used (should it be?)\n private Random rand = new Random();\n private UUID uuid = UUID.randomUUID();\n\n public Game(Map<String, Object> savings) {\n this((String) savings.get(\"game_name\"));\n // SerialLocation.returnLocation((SerialLocation) savings.get(\"active_chest_location\"));\n active = null;// automatically set by loading the available mystery chests\n level = (Integer) savings.get(\"level\");\n mobcount = (Integer) savings.get(\"mob_count\");\n startpoints = (Integer) savings.get(\"starting_points\");\n @SuppressWarnings(\"unchecked\") List<Map<String, Object>> savedVersions = (List<Map<String, Object>>) savings.get(\"game_objects\");\n for (Map<String, Object> save : savedVersions) {\n if (save == null) {\n continue;\n }\n try {\n PermanentAspect.load(Class.forName((String) save.get(\"saved_class_type\")), save);\n } catch (ClassNotFoundException ex) {\n Ablockalypse.getTracker().error(\"The class designated to a saved object could not be found!\", 20, ex);\n }\n }\n if (savings.get(\"mainframe_location\") != null) {\n mainframe = data.getTeleporter(SerialLocation.returnLocation((SerialLocation) savings.get(\"mainframe_location\")));\n if (mainframe != null) {\n mainframe.refresh();\n }\n }\n @SuppressWarnings(\"unchecked\") HashMap<Integer, Integer> hashMap = (HashMap<Integer, Integer>) savings.get(\"wolf_levels\");\n wolfLevels = hashMap;\n wolfRound = (Boolean) savings.get(\"wolf_round\");\n armorRound = (Boolean) savings.get(\"armor_round\");\n paused = (Boolean) savings.get(\"paused\");\n started = (Boolean) savings.get(\"started\");\n spawnedInThisRound = (Integer) savings.get(\"mobs_spawned_this_round\");\n uuid = savings.get(\"uuid\") == null ? uuid : (UUID) savings.get(\"uuid\");\n }\n\n /**\n * Creates a new instance of a game.\n * \n * @param name The name of the ZAGame\n */\n public Game(String name) {\n this.name = name;\n paused = false;\n started = false;\n @SuppressWarnings(\"unchecked\") ArrayList<String> wolfLevelsList = (ArrayList<String>) Setting.WOLF_LEVELS.getSetting();\n for (String line : wolfLevelsList.toArray(new String[wolfLevelsList.size()])) {\n for (Integer level : MathUtility.parseIntervalNotation(line)) {\n wolfLevels.put(level, MathUtility.parsePercentage(line));\n }\n }\n startpoints = (Integer) Setting.STARTING_POINTS.getSetting();\n beacons = new MysteryBoxFakeBeaconTask(this, 200, (Boolean) Setting.BEACONS.getSetting());\n scoreBoard = new GameScoreboard(this);\n data.objects.add(this);\n }\n\n /**\n * Attaches an area to this game.\n * \n * @param ga The area to load into this game\n */\n public void addObject(GameAspect obj) {\n if (obj != null && !objects.contains(obj) && !overlapsAnotherObject(obj)) {\n objects.add(obj);\n }\n }\n\n /**\n * Adds a player to the game.\n * NOTE: This does not change a players' status at all, that must be done through the ZAPlayer instance.\n * \n * @param player The player to be added to the game\n */\n public void addPlayer(Player player) {\n ZAPlayer zap = data.getZAPlayer(player, name, true);\n if (!player.isOnline() && !PlayerJoin.isQueued(zap)) {\n return;\n }\n addObject(zap);\n if (!data.isZAPlayer(player)) {\n zap.setPoints(startpoints);\n }\n if (!playerIsInGame(zap)) {\n broadcast(ChatColor.RED + player.getName() + ChatColor.GRAY + \" has joined the game!\", player);\n }\n if (paused) {\n pause(false);\n }\n if (!started) {\n start();\n }\n }\n\n /**\n * Sends a message to all players in the game.\n * \n * @param message The message to send\n * @param exception A player to be excluded from the broadcast\n */\n public void broadcast(String message, Player... exceptions) {\n for (ZAPlayer zap : getPlayers()) {\n boolean contained = false;\n if (exceptions != null) {\n for (Player except : exceptions) {\n if (zap.getPlayer() == except) {\n contained = true;\n }\n }\n }\n if (!contained) {\n zap.getPlayer().sendMessage(message);\n }\n }\n }\n\n /**\n * Sends all players in the game the points of all players.\n */\n public void broadcastPoints() {\n for (ZAPlayer zap : getPlayers()) {\n zap.showPoints();\n }\n }\n\n public void broadcastSound(ZASound sound, Player... exceptions) {\n for (ZAPlayer zap : getPlayers()) {\n boolean contained = false;\n if (exceptions != null) {\n for (Player except : exceptions) {\n if (zap.getPlayer() == except) {\n contained = true;\n }\n }\n }\n if (!contained) {\n sound.play(zap.getPlayer().getLocation());\n }\n }\n }\n\n /**\n * Ends the game, repairs all barriers, closes all areas, and removes all players.\n * @param countQueue If the player queue for offline players (see PlayerJoin.java) should be\n * checked before ending the game. If the queue is not empty, the game will then not start.\n */\n public void end(boolean countQueue) {\n if (started) {\n if (countQueue && PlayerJoin.getQueues(this).size() != 0) {\n return;\n }\n int points = 0;\n for (ZAPlayer zap : getObjectsOfType(ZAPlayer.class)) {\n points += zap.getPoints();\n }\n GameEndEvent GEE = new GameEndEvent(this, points);\n Bukkit.getPluginManager().callEvent(GEE);\n if (!GEE.isCancelled()) {\n for (GameAspect obj : objects) {\n obj.onGameEnd();\n }\n spawnedInThisRound = 0;\n paused = true;\n started = false;\n level = 1;\n if (nlt != null && nlt.isRunning()) {\n nlt.cancel();\n }\n mobcount = 0;\n }\n }\n }\n\n /**\n * Gets the currently active chest for this game.\n * \n * @return The currently active chest for this game\n */\n public MysteryBox getActiveMysteryChest() {\n return active;\n }\n\n public Player getClosestLivingPlayer(Location location) {\n if (getRemainingPlayers().size() >= 1) {\n Player closest = getRandomLivingPlayer();\n Double distanceSquared = Double.MAX_VALUE;\n for (ZAPlayer zap : getPlayers()) {\n double currentDSq = zap.getPlayer().getLocation().distanceSquared(location);\n if (!zap.getPlayer().isDead() && !zap.isInLastStand() && !zap.isInLimbo() && currentDSq < distanceSquared) {\n closest = zap.getPlayer();\n distanceSquared = currentDSq;\n }\n }\n return closest;\n }\n return null;\n }\n\n public MysteryBoxFakeBeaconTask getFakeBeaconThread() {\n return beacons;\n }\n\n public GameScoreboard getGameScoreboard() {\n return scoreBoard;\n }\n\n @Override public String getHeader() {\n return this.getClass().getSimpleName() + \" <UUID: \" + getUUID().toString() + \">\";\n }\n\n /**\n * Gets the current level that the game is on.\n * \n * @return The current level of the game\n */\n public int getLevel() {\n return level;\n }\n\n /**\n * Gets the spawn location for this game.\n * \n * @return The location of the spawn\n */\n public Teleporter getMainframe() {\n return mainframe;\n }\n\n /**\n * Gets the remaining custom mobs in the game.\n * \n * @return The amount of remaining mobs in this game\n */\n public int getMobCount() {\n return mobcount;\n }\n\n public int getMobCountSpawnedInThisRound() {\n return spawnedInThisRound;\n }\n\n /**\n * Gets all mobs spawned in this game.\n * \n * @return All mobs currently alive in this game\n */\n public List<ZAMob> getMobs() {\n return getObjectsOfType(ZAMob.class);\n }\n\n /**\n * Gets the name of this game.\n * \n * @return The name of the ZAGame\n */\n public String getName() {\n return name;\n }\n\n public CopyOnWriteArrayList<GameAspect> getObjects() {\n return objects;\n }\n\n @SuppressWarnings(\"unchecked\") public <T extends Object> List<T> getObjectsOfType(Class<T> type) {\n ArrayList<T> list = new ArrayList<T>();\n for (Object obj : objects) {\n if (obj != null && type != null) {\n if (type.isAssignableFrom(obj.getClass())) {\n list.add((T) obj);\n }\n }\n }\n return list;\n }\n\n /**\n * Returns a list of players currently in the game.\n * \n * @return A list of player names that are involved in this game\n */\n public List<ZAPlayer> getPlayers() {\n return getObjectsOfType(ZAPlayer.class);\n }\n\n /**\n * Gets a random living player.\n * Living is considered as not in limbo, last stand, respawn thread, or death.\n * \n * @return The random living player\n */\n public Player getRandomLivingPlayer() {\n if (getRemainingPlayers().size() >= 1) {\n ArrayList<ZAPlayer> zaps = new ArrayList<ZAPlayer>();\n for (ZAPlayer zap : getPlayers()) {\n if (zap.getPlayer() != null && !zap.getPlayer().isDead() && !zap.isInLastStand() && !zap.isInLimbo()) {\n zaps.add(zap);\n }\n }\n return zaps.get(rand.nextInt(zaps.size())).getPlayer();\n }\n return null;\n }\n\n /**\n * Returns a random player from this game.\n * \n * @return The random player from this game\n */\n public ZAPlayer getRandomPlayer() {\n return getPlayers().get(rand.nextInt(getPlayers().size()));\n }\n\n /**\n * Gets the players still in the game.\n * This only counts players that are living and not in last stand or limbo.\n * \n * @return How many living players are in the game\n */\n public List<ZAPlayer> getRemainingPlayers() {\n List<ZAPlayer> remaining = new ArrayList<ZAPlayer>();\n for (ZAPlayer zap : getPlayers()) {\n if (zap.getPlayer() != null && !zap.getPlayer().isDead() && !zap.isInLimbo() && !zap.isInLastStand()) {\n remaining.add(zap);\n }\n }\n return remaining;\n }\n\n @Override public Map<String, Object> getSave() {\n Map<String, Object> savings = new HashMap<String, Object>();\n savings.put(\"uuid\", getUUID());\n savings.put(\"active_chest_location\", active == null ? null : new SerialLocation(active.getLocation()));\n savings.put(\"level\", level);\n savings.put(\"mob_count\", mobcount);\n savings.put(\"starting_points\", startpoints);\n savings.put(\"mobs_spawned_this_round\", spawnedInThisRound);\n savings.put(\"mainframe_location\", mainframe == null ? null : new SerialLocation(mainframe.getLocation()));\n savings.put(\"game_name\", name);\n List<Map<String, Object>> savedVersions = new ArrayList<Map<String, Object>>();\n for (PermanentAspect aspect : getObjectsOfType(PermanentAspect.class)) {\n Map<String, Object> save = aspect.getSave();\n save.put(\"saved_class_type\", aspect.getClass().getName());\n savedVersions.add(save);\n }\n savings.put(\"game_objects\", savedVersions);\n savings.put(\"wolf_levels\", wolfLevels);\n savings.put(\"wolf_round\", wolfRound);\n savings.put(\"armor_round\", armorRound);\n savings.put(\"paused\", paused);\n savings.put(\"started\", started);\n savings.put(\"mobs_spawned_this_round\", spawnedInThisRound);\n return savings;\n }\n\n @Override public UUID getUUID() {\n return uuid;\n }\n\n public int getWolfPercentage() {\n return getWolfPercentage(level);\n }\n\n public int getWolfPercentage(int level) {\n if (!wolfLevels.containsKey(level)) {\n return 0;\n }\n return wolfLevels.get(level);\n }\n\n public boolean hasMob(ZAMob mob) {\n return getMobs().contains(mob);\n }\n\n /**\n * Returns whether or not the game has started.\n * \n * @return Whether or not the game has been started, and mobs are spawning\n */\n public boolean hasStarted() {\n return started;\n }\n\n public boolean isArmorRound() {\n return armorRound;\n }\n\n /**\n * Checks if the game is paused or not.\n * \n * @return Whether or not the game is paused\n */\n public boolean isPaused() {\n return paused;\n }\n\n /**\n * Returns true if the current round is a wolf round.\n * \n * @return Whether or not the current round is a wolf round\n */\n public boolean isWolfRound() {\n return wolfRound;\n }\n\n /**\n * Starts the next level for the game, and adds a level to all players in this game.\n * Then, spawns a wave of zombies, and starts the thread for the next level.\n */\n public void nextLevel() {\n ++level;\n int maxWave = (Integer) Setting.MAX_WAVE.getSetting();\n if (level >= maxWave && maxWave != -1) {\n end(false);\n return;\n }\n spawnedInThisRound = 0;\n mobcount = 0;\n if (!started) {\n level = 1;\n List<MysteryBox> chests = getObjectsOfType(MysteryBox.class);\n if (chests != null && chests.size() > 0) {\n MysteryBox mc = chests.get(rand.nextInt(chests.size()));\n setActiveMysteryChest(mc);\n }\n for (GameAspect obj : objects) {\n obj.onGameStart();\n }\n started = true;\n }\n if (wolfLevels != null && wolfLevels.containsKey(level)) {\n wolfRound = true;\n }\n paused = false;\n nlt = new NextLevelTask(this, true);\n spawnWave(SpawnUtility.getCurrentSpawnAmount(this) - spawnedInThisRound);\n for (GameAspect obj : objects) {\n obj.onNextLevel();\n }\n }\n\n public void organizeObjects() {\n CopyOnWriteArrayList<GameAspect> newObjects = new CopyOnWriteArrayList<GameAspect>();\n int[][] priorities = new int[objects.size()][2];\n for (int i = 0; i < priorities.length; i++) {\n GameAspect obj = objects.get(i);\n priorities[i][0] = i;\n priorities[i][1] = obj == null ? Integer.MAX_VALUE : obj.getLoadPriority();\n }\n for (int j = 1; j < priorities.length; j++) {\n int[] temp = priorities[j];\n int current = j - 1;\n while (current >= 0 && priorities[current][1] > temp[1]) {\n priorities[current + 1] = priorities[current];\n current--;\n }\n priorities[current + 1] = temp;\n }\n for (int k = 0; k < priorities.length; k++) {\n newObjects.add(objects.get(priorities[k][0]));\n }\n objects = newObjects;\n }\n\n /**\n * Sets the game to pause or not.\n * \n * @param tf Whether or not to pause or un-pause the game\n */\n public void pause(boolean tf) {\n if (tf && !paused) {\n // TODO freeze mobs, cancel damage, etc\n } else if (!tf && paused) {\n --level;\n nextLevel();\n }\n paused = tf;\n }\n\n /**\n * Ends the game, removes all attached instances, and finalizes this instance.\n */\n public void remove(boolean permanently) {\n end(false);\n for (GameAspect object : getObjects()) {\n object.remove();\n }\n if (beacons != null) {\n beacons.cancel();\n }\n File savedData = Ablockalypse.getExternal().getSavedDataFile(getName(), false);\n if (permanently && savedData != null) {\n savedData.delete();\n }\n data.objects.remove(this);\n }\n\n /**\n * Removes an area from this game.\n * \n * @param ga The area to be unloaded from this game\n */\n public void removeObject(GameAspect obj) {\n if (obj != null && objects.contains(obj)) {\n objects.remove(obj);\n }\n }\n\n /**\n * Removes a player from the game.\n * \n * @param player The player to be removed from the game\n */\n public void removePlayer(Player player) {\n ZAPlayer zap = data.getZAPlayer(player);\n if (zap != null && objects.contains(zap)) {\n objects.remove(zap);\n zap.removeFromGame();// removes zap from data.objects\n if (getPlayers().isEmpty()) {\n pause(true);\n end(true);\n }\n }\n }\n\n /**\n * Sets the active chest that can be used during this game.\n * \n * @param mc The chest to be made active\n */\n public void setActiveMysteryChest(MysteryBox mc) {\n if ((Boolean) Setting.MOVING_MYSTERY_BOXES.getSetting()) {\n active = mc;\n for (MysteryBox chest : getObjectsOfType(MysteryBox.class)) {\n chest.setActive(false);\n }\n if (!mc.isActive()) {\n mc.setActive(true);\n mc.setActiveUses(rand.nextInt(8) + 2);\n }\n }\n }\n\n public void setArmorRound(boolean tf) {\n armorRound = tf;\n }\n\n public void setFakeBeaconThread(MysteryBoxFakeBeaconTask thread) {\n beacons = thread;\n }\n\n public void setGameScoreboard(GameScoreboard scoreBoard) {\n this.scoreBoard = scoreBoard;\n }\n\n /**\n * Sets the game to the specified level.\n * \n * @param i The level the game will be set to\n */\n public void setLevel(int i) {\n level = i;\n }\n\n /**\n * Sets the spawn location and central teleporter of the game.\n * \n * @param mf The mainframe to be set for the game\n */\n public void setMainframe(Teleporter mf) {\n mainframe = mf;\n mf.refresh();\n }\n\n /**\n * Sets the mob count.\n * If raised higher than the count currently is, this will require more mobs spawned.\n * If lower than the count currently is, this will require more mob removals.\n * \n * @param i The count to set the current amount of mobs to.\n */\n public void setMobCount(int i) {\n mobcount = i;\n if (mobcount < 0) {\n mobcount = 0;\n }\n }\n\n public void setMobCountSpawnedInThisRound(int amt) {\n spawnedInThisRound = amt;\n }\n\n /**\n * Makes the game a wolf round.\n * \n * @param tf Whether or not the game should be a wolf round\n */\n public void setWolfRound(boolean tf) {\n wolfRound = tf;\n }\n\n /**\n * Spawns a wave of mobs around random living players in this game.\n * If barriers are present and acessible, spawns the mobs at the barriers.\n */\n public void spawnWave(int amount) {\n if (mainframe == null && getRandomLivingPlayer() != null) {\n Location playerLoc = getRandomLivingPlayer().getLocation();\n mainframe = new Teleporter(this, playerLoc);\n }\n SpawnUtility.spawnWave(this, amount);\n started = true;\n }\n\n public void start() {\n started = false;\n level = 0;\n nextLevel();\n }\n\n private boolean overlapsAnotherObject(GameAspect obj) {\n if (obj.getDefiningBlocks() == null) {\n return false;\n }\n for (GameAspect object : getObjects()) {\n if (object == null || object.getDefiningBlocks() == null) {\n continue;\n }\n for (Block block : object.getDefiningBlocks()) {\n if (block == null) {\n continue;\n }\n Location bLoc = block.getLocation();\n for (Block otherBlock : obj.getDefiningBlocks()) {\n if (BukkitUtility.locationMatch(otherBlock.getLocation(), bLoc)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n private boolean playerIsInGame(ZAPlayer zap) {\n for (ZAPlayer zap2 : getObjectsOfType(ZAPlayer.class)) {\n if (zap.getPlayer().getName().equalsIgnoreCase(zap2.getPlayer().getName())) {\n return true;\n }\n }\n return false;\n }\n}", "public class ZAPlayer extends ZACharacter {\r\n private Player player;\r\n private Game game;\r\n private PlayerStatus status = PlayerStatus.NORMAL;\r\n private List<ZAPerk> perks = new ArrayList<ZAPerk>();\r\n private double pointGainModifier = 1, pointLossModifier = 1;\r\n private PlayerState beforeGame, beforeLS;\r\n private int points, kills;\r\n private boolean sentIntoGame, instakill, removed;\r\n\r\n @SuppressWarnings(\"unchecked\") public ZAPlayer(Map<String, Object> savings) {\r\n super(savings);\r\n player = super.getPlayer();\r\n game = super.getGame();\r\n status = super.getStatus();\r\n Map<String, Object> beforeGameState = (Map<String, Object>) savings.get(\"before_game_state\");\r\n if (beforeGameState != null) {\r\n beforeGame = new PlayerState(beforeGameState);\r\n }\r\n Map<String, Object> beforeLSState = (Map<String, Object>) savings.get(\"before_last_stand_state\");\r\n if (beforeLSState != null) {\r\n beforeLS = new PlayerState(beforeLSState);\r\n }\r\n if (!player.isOnline()) {\r\n PlayerJoin.queuePlayer(this, SerialLocation.returnLocation((SerialLocation) savings.get(\"player_in_game_location\")), savings);\r\n return;\r\n }\r\n removed = false;\r\n loadSavedVersion(savings);\r\n }\r\n\r\n public ZAPlayer(Player player, Game game) {\r\n super(player, game);\r\n this.player = player;\r\n this.game = game;\r\n }\r\n\r\n public void addKills(int kills) {\r\n this.kills += kills;\r\n }\r\n\r\n public void addPerk(ZAPerk perk) {\r\n if (hasPerk(perk)) {\r\n return;// prevents recursion\r\n }\r\n perks.add(perk);\r\n perk.givePerk(this);\r\n }\r\n\r\n public void addPoints(int points) {\r\n this.points += points * pointGainModifier;\r\n }\r\n\r\n public void clearPerks() {\r\n for (ZAPerk perk : perks) {\r\n perk.removePerk(this);\r\n }\r\n perks.clear();\r\n }\r\n\r\n public void decrementKills() {\r\n subtractKills(1);\r\n }\r\n\r\n public int getKills() {\r\n return kills;\r\n }\r\n\r\n @Override public int getLoadPriority() {\r\n return 1;\r\n }\r\n\r\n public List<ZAPerk> getPerks() {\r\n return perks;\r\n }\r\n\r\n public double getPointGainModifier() {\r\n return pointGainModifier;\r\n }\r\n\r\n public double getPointLossModifier() {\r\n return pointLossModifier;\r\n }\r\n\r\n public int getPoints() {\r\n return points;\r\n }\r\n\r\n @Override public Map<String, Object> getSave() {\r\n Map<String, Object> savings = new HashMap<String, Object>();\r\n savings.put(\"uuid\", getUUID());\r\n savings.put(\"game_name\", game.getName());\r\n savings.put(\"points\", points);\r\n savings.put(\"kills\", kills);\r\n savings.put(\"point_gain_modifier\", pointGainModifier);\r\n savings.put(\"point_loss_modifier\", pointLossModifier);\r\n if (beforeGame != null) {\r\n savings.put(\"before_game_state\", beforeGame.getSave());\r\n }\r\n if (beforeLS != null) {\r\n savings.put(\"before_last_stand_state\", beforeLS.getSave());\r\n }\r\n List<Integer> perkIds = new ArrayList<Integer>();\r\n for (ZAPerk perk : perks) {\r\n perkIds.add(perk.getId());\r\n }\r\n savings.put(\"perk_ids\", perkIds);\r\n savings.put(\"has_been_sent_into_the_game\", sentIntoGame);\r\n savings.put(\"has_instakill\", instakill);\r\n savings.put(\"player_in_game_location\", player == null ? null : new SerialLocation(player.getLocation()));\r\n savings.putAll(super.getSave());\r\n return savings;\r\n }\r\n\r\n public void giveItem(ItemStack item) {\r\n Ablockalypse.getExternal().getItemFileManager().giveItem(player, item);\r\n }\r\n\r\n public void givePowerup(PowerupType type, Entity cause) {\r\n type.play(game, player, cause, data);\r\n }\r\n\r\n public boolean hasBeenSentIntoGame() {\r\n return sentIntoGame;\r\n }\r\n\r\n public boolean hasInstaKill() {\r\n return instakill;\r\n }\r\n\r\n public boolean hasPerk(ZAPerk perk) {\r\n return perks.contains(perk);\r\n }\r\n\r\n public void incrementKills() {\r\n addKills(1);\r\n }\r\n\r\n public boolean isInLastStand() {\r\n return status == PlayerStatus.LAST_STAND;\r\n }\r\n\r\n public boolean isInLimbo() {\r\n return status == PlayerStatus.LIMBO;\r\n }\r\n\r\n public boolean isTeleporting() {\r\n return status == PlayerStatus.TELEPORTING;\r\n }\r\n\r\n public void loadPlayerToGame(String name, boolean showMessages) {\r\n /* Use an old game to add the player to the game */\r\n if (data.isGame(name)) {\r\n Game zag = data.getGame(name, false);\r\n PlayerJoinGameEvent GPJE = new PlayerJoinGameEvent(this, zag);\r\n Bukkit.getPluginManager().callEvent(GPJE);\r\n if (!GPJE.isCancelled()) {\r\n int max = (Integer) Setting.MAX_PLAYERS.getSetting();\r\n if (zag.getPlayers().size() < max) {\r\n if (game.getMainframe() == null) {\r\n Teleporter newMainframe = new Teleporter(game, player.getLocation().clone().subtract(0, 1, 0));\r\n game.setMainframe(newMainframe);\r\n newMainframe.setBlinking(false);\r\n }\r\n removed = false;\r\n zag.addPlayer(player);\r\n prepare();\r\n sendToMainframe(showMessages ? ChatColor.GRAY + \"Teleporting to mainframe...\" : null, \"Loading player to a game\");\r\n if (showMessages) {\r\n player.sendMessage(ChatColor.GRAY + \"You have joined the game: \" + name);\r\n }\r\n return;\r\n } else {\r\n if (showMessages) {\r\n player.sendMessage(ChatColor.RED + \"This game has \" + max + \"/\" + max + \" players!\");\r\n }\r\n }\r\n }\r\n } else if (showMessages) {\r\n player.sendMessage(ChatColor.RED + \"That game does not exist!\");\r\n }\r\n }\r\n\r\n public void loadSavedVersion(Map<String, Object> savings) {\r\n points = (Integer) savings.get(\"points\");\r\n kills = (Integer) savings.get(\"kills\");\r\n pointGainModifier = (Integer) savings.get(\"point_gain_modifier\");\r\n pointLossModifier = (Integer) savings.get(\"point_loss_modifier\");\r\n List<ItemStack> stacks = new ArrayList<ItemStack>();\r\n @SuppressWarnings(\"unchecked\") List<Map<String, Object>> serialStacks = (List<Map<String, Object>>) savings.get(\"inventory\");\r\n for (Map<String, Object> serialStack : serialStacks) {\r\n stacks.add(ItemStack.deserialize(serialStack));\r\n }\r\n player.getInventory().setContents(stacks.toArray(new ItemStack[stacks.size()]));\r\n List<ZAPerk> loadedPerks = new ArrayList<ZAPerk>();\r\n @SuppressWarnings(\"unchecked\") List<Integer> perkIds = (List<Integer>) savings.get(\"perk_ids\");\r\n for (Integer id : perkIds) {\r\n loadedPerks.add(ZAPerk.getById(id));\r\n }\r\n perks = loadedPerks;\r\n sentIntoGame = (Boolean) savings.get(\"has_been_sent_into_the_game\");\r\n instakill = (Boolean) savings.get(\"has_instakill\");\r\n }\r\n\r\n @Override public void onGameEnd() {\r\n player.sendMessage(ChatColor.BOLD + \"\" + ChatColor.GRAY + \"The game has ended. You made it to level \" + game.getLevel());\r\n ZASound.END.play(player.getLocation());\r\n game.removePlayer(player);\r\n }\r\n\r\n @Override public void onLevelEnd() {\r\n ZASound.PREV_LEVEL.play(player.getLocation());\r\n //@formatter:off\r\n player.sendMessage(ChatColor.BOLD + \"Level \" + ChatColor.RESET + ChatColor.RED + game.getLevel() + ChatColor.RESET + ChatColor.BOLD \r\n + \" over... Next level: \" + ChatColor.RED + (game.getLevel() + 1) + \"\\n\" + ChatColor.RESET + ChatColor.BOLD + \"Time to next level: \"\r\n + ChatColor.RED + Setting.LEVEL_TRANSITION_TIME.getSetting() + ChatColor.RESET + ChatColor.BOLD + \" seconds.\");\r\n //@formatter:on\r\n // showPoints();//with the new scoreboard, there is not longer any need\r\n }\r\n\r\n @Override public void onNextLevel() {\r\n int level = game.getLevel();\r\n if (level != 0) {\r\n player.setLevel(level);\r\n player.sendMessage(ChatColor.BOLD + \"Level \" + ChatColor.RESET + ChatColor.RED + level + ChatColor.RESET + ChatColor.BOLD + \" has started.\");\r\n if (level != 1) {\r\n showPoints();\r\n }\r\n }\r\n }\r\n\r\n @Override public void remove() {\r\n if (removed) {\r\n return;// prevents recursion with ZAMob.kill(), which calls game.removeObject(), which calls this, which calls ZAMob.kill()... you get the idea\r\n }\r\n restoreStatus();\r\n game = null;\r\n super.remove();\r\n removed = true;\r\n }\r\n\r\n public void removeFromGame() {\r\n if (removed) {\r\n return;// prevents recursion with remove()\r\n }\r\n remove();\r\n }\r\n\r\n public void removePerk(ZAPerk perk) {\r\n if (!hasPerk(perk)) {\r\n return;// prevents recursion\r\n }\r\n perks.remove(perk);\r\n perk.removePerk(this);\r\n }\r\n\r\n @Override public void sendToMainframe(String message, String reason) {\r\n if (message != null) {\r\n player.sendMessage(message);\r\n }\r\n Location loc = game.getMainframe().getLocation().clone().add(0, 1, 0);\r\n Chunk c = loc.getChunk();\r\n if (!c.isLoaded()) {\r\n c.load();\r\n }\r\n player.teleport(loc);\r\n if (!sentIntoGame) {\r\n ZASound.START.play(loc);\r\n sentIntoGame = true;\r\n } else {\r\n ZASound.TELEPORT.play(loc);\r\n }\r\n if ((Boolean) Setting.DEBUG.getSetting()) {\r\n System.out.println(\"[Ablockalypse] [DEBUG] Mainframe TP reason: (\" + game.getName() + \") \" + reason);\r\n }\r\n }\r\n\r\n public void setInstaKill(boolean instakill) {\r\n this.instakill = instakill;\r\n }\r\n\r\n public void setKills(int kills) {\r\n this.kills = kills;\r\n }\r\n\r\n public void setPointGainModifier(double modifier) {\r\n pointGainModifier = modifier;\r\n }\r\n\r\n public void setPointLossModifier(double modifier) {\r\n pointLossModifier = modifier;\r\n }\r\n\r\n public void setPoints(int points) {\r\n double modifier = 1;\r\n if (points > this.points) {\r\n modifier = pointGainModifier;\r\n } else if (points < this.points) {\r\n modifier = pointLossModifier;\r\n }\r\n this.points = (int) Math.round(points * modifier);\r\n }\r\n\r\n public void setSentIntoGame(boolean sent) {\r\n sentIntoGame = sent;\r\n }\r\n\r\n public void showPoints() {\r\n for (ZAPlayer zap2 : game.getPlayers()) {\r\n Player p2 = zap2.getPlayer();\r\n player.sendMessage(ChatColor.RED + p2.getName() + ChatColor.RESET + \" - \" + ChatColor.GRAY + zap2.getPoints());\r\n }\r\n }\r\n\r\n public void subtractKills(int kills) {\r\n if (this.kills < kills) {\r\n this.kills = 0;\r\n return;\r\n }\r\n this.kills -= kills;\r\n }\r\n\r\n public void subtractPoints(int points) {\r\n if (this.points < points * pointLossModifier) {\r\n this.points = 0;\r\n return;\r\n }\r\n this.points -= points * pointLossModifier;\r\n }\r\n\r\n public void toggleLastStand() {\r\n if (status != PlayerStatus.LAST_STAND) {\r\n sitDown();\r\n } else {\r\n pickUp();\r\n }\r\n }\r\n\r\n private void pickUp() {\r\n LastStandEvent lse = new LastStandEvent(player, this, false);\r\n Bukkit.getServer().getPluginManager().callEvent(lse);\r\n if (!lse.isCancelled()) {\r\n beforeLS.update();\r\n player.sendMessage(ChatColor.GRAY + \"You have been picked up!\");\r\n game.broadcast(ChatColor.RED + player.getName() + ChatColor.GRAY + \" has been revived.\", player);\r\n status = PlayerStatus.NORMAL;\r\n // Breakable.setSitting(player, false);\r\n getSeat().removePassenger();\r\n getSeat().remove();\r\n player.setCanPickupItems(true);\r\n if (player.getVehicle() != null) {\r\n player.getVehicle().remove();\r\n }\r\n player.setFoodLevel(20);\r\n Entity v = player.getVehicle();\r\n if (v != null) {\r\n v.remove();\r\n }\r\n }\r\n }\r\n\r\n /* Saving the player status, so when the player is removed from the game, they are set back to where they were before. */\r\n @SuppressWarnings(\"deprecation\") private void prepare() {\r\n beforeGame = new PlayerState(player);\r\n ZASound.START.play(player.getLocation());\r\n player.setGameMode(GameMode.SURVIVAL);\r\n player.getInventory().clear();\r\n player.setLevel(game.getLevel());\r\n player.setExp(0);\r\n player.setHealth(20);\r\n player.setFoodLevel(20);\r\n player.setSaturation(0);\r\n player.getActivePotionEffects().clear();\r\n player.getInventory().setArmorContents(null);\r\n player.setSleepingIgnored(true);\r\n player.setFireTicks(0);\r\n player.setFallDistance(0F);\r\n player.setExhaustion(0F);\r\n ItemManager itemManager = Ablockalypse.getExternal().getItemFileManager();\r\n if (itemManager != null && itemManager.getStartingItemsMap() != null) {\r\n Map<Integer, BuyableItemData> startingItems = itemManager.getStartingItemsMap();\r\n for (int id : startingItems.keySet()) {\r\n itemManager.giveItem(player, startingItems.get(id).toItemStack());\r\n }\r\n }\r\n rename(\"\", player.getName(), \"0\");\r\n player.updateInventory();\r\n }\r\n\r\n /* Restoring the player status to the last saved status before the game. */\r\n private void restoreStatus() {\r\n if (status == PlayerStatus.LAST_STAND) {\r\n toggleLastStand();\r\n }\r\n for (PotionEffect pe : player.getActivePotionEffects()) {\r\n PotionEffectType pet = pe.getType();\r\n player.removePotionEffect(pet);\r\n }\r\n player.setDisplayName(player.getName());\r\n if (beforeGame != null) {\r\n beforeGame.update();\r\n }\r\n }\r\n\r\n private void sitDown() {\r\n LastStandEvent lse = new LastStandEvent(player, this, true);\r\n Bukkit.getServer().getPluginManager().callEvent(lse);\r\n if (!lse.isCancelled()) {\r\n player.sendMessage(ChatColor.GRAY + \"You have been knocked down!\");\r\n if (getGame().getRemainingPlayers().size() < 1 && (Boolean) Setting.END_ON_LAST_PLAYER_LAST_STAND.getSetting()) {\r\n removeFromGame();\r\n return;\r\n }\r\n beforeLS = new PlayerState(player);\r\n status = PlayerStatus.LAST_STAND;\r\n Entity v = player.getVehicle();\r\n if (v != null) {\r\n v.remove();\r\n }\r\n rename(\"\", player.getName(), \"[LS]\");\r\n player.setFoodLevel(0);\r\n player.setHealth((Double) Setting.LAST_STAND_HEALTH_THRESHOLD.getSetting());\r\n ZASound.LAST_STAND.play(player.getLocation());\r\n getSeat().moveLocation(player.getLocation());\r\n getSeat().sit(player);\r\n player.getInventory().clear();\r\n player.setCanPickupItems(false);\r\n game.broadcast(ChatColor.RED + player.getName() + ChatColor.GRAY + \" is down and needs revival\", player);\r\n new LastStandFallenTask(this, true);\r\n if ((Boolean) Setting.LOSE_PERKS_ON_LAST_STAND.getSetting()) {\r\n clearPerks();\r\n }\r\n }\r\n }\r\n}\r", "public enum PlayerStatus {\n LAST_STAND(1) {\n @Override public void set(ZACharacter character) {\n if (!(character instanceof ZAPlayer)) {\n return;\n }\n ZAPlayer zap = (ZAPlayer) character;\n if (!zap.isInLastStand()) {\n zap.toggleLastStand();\n }\n }\n },\n LIMBO(2) {\n @Override public void set(ZACharacter character) {\n character.setStatus(PlayerStatus.LIMBO);\n }\n },\n NORMAL(3) {\n @Override public void set(ZACharacter character) {\n if (character instanceof ZAPlayer) {\n ZAPlayer zap = (ZAPlayer) character;\n if (zap.isInLastStand()) {\n zap.toggleLastStand();\n }\n }\n character.setStatus(PlayerStatus.NORMAL);\n }\n },\n TELEPORTING(4) {\n @Override public void set(ZACharacter character) {\n character.setStatus(PlayerStatus.TELEPORTING);\n }\n };\n private final static Map<Integer, PlayerStatus> BY_ID = Maps.newHashMap();\n static {\n for (PlayerStatus status : values()) {\n BY_ID.put(status.id, status);\n }\n }\n\n public static PlayerStatus getById(int id) {\n return BY_ID.get(id);\n }\n\n private int id;\n\n PlayerStatus(int id) {\n this.id = id;\n }\n\n public int getId() {\n return id;\n }\n\n public abstract void set(ZACharacter character);\n}" ]
import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import com.github.jamesnorris.ablockalypse.Ablockalypse; import com.github.jamesnorris.ablockalypse.DataContainer; import com.github.jamesnorris.ablockalypse.aspect.Game; import com.github.jamesnorris.ablockalypse.aspect.ZAPlayer; import com.github.jamesnorris.ablockalypse.enumerated.PlayerStatus;
package com.github.jamesnorris.ablockalypse.event.bukkit; public class PlayerDeath implements Listener { private DataContainer data = Ablockalypse.getData(); /* Called when a player is killed. * * Used for respawning the player after the current level. */ @EventHandler(priority = EventPriority.HIGHEST) public void PDE(PlayerDeathEvent event) {// RespawnThread is activated by PlayerRespawn.java Player p = event.getEntity(); if (data.isZAPlayer(p)) { event.getDrops().clear(); event.setKeepLevel(true); ZAPlayer zap = data.getZAPlayer(p);
zap.setStatus(PlayerStatus.LIMBO);
4
EpicEricEE/ShopChest
src/main/java/de/epiceric/shopchest/external/listeners/GriefPreventionListener.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 Config {\n\n /**\n * The item with which a player can click a shop to retrieve information\n **/\n public static ItemStack shopInfoItem;\n\n /**\n * The default value for the custom WorldGuard flag 'create-shop'\n **/\n public static boolean wgAllowCreateShopDefault;\n\n /**\n * The default value for the custom WorldGuard flag 'use-admin-shop'\n **/\n public static boolean wgAllowUseAdminShopDefault;\n\n /**\n * The default value for the custom WorldGuard flag 'use-shop'\n **/\n public static boolean wgAllowUseShopDefault;\n\n /**\n * The types of town plots residents are allowed to create shops in\n **/\n public static List<String> townyShopPlotsResidents;\n\n /**\n * The types of town plots the mayor is allowed to create shops in\n **/\n public static List<String> townyShopPlotsMayor;\n\n /**\n * The types of town plots the king is allowed to create shops in\n **/\n public static List<String> townyShopPlotsKing;\n\n /**\n * The events of AreaShop when shops in that region should be removed\n **/\n public static List<String> areashopRemoveShopEvents;\n\n /**\n * The hostname used in ShopChest's MySQL database\n **/\n public static String databaseMySqlHost;\n\n /**\n * The port used for ShopChest's MySQL database\n **/\n public static int databaseMySqlPort;\n\n /**\n * The database used for ShopChest's MySQL database\n **/\n public static String databaseMySqlDatabase;\n\n /**\n * The username used in ShopChest's MySQL database\n **/\n public static String databaseMySqlUsername;\n\n /**\n * The password used in ShopChest's MySQL database\n **/\n public static String databaseMySqlPassword;\n\n /**\n * The prefix to be used for database tables\n */\n public static String databaseTablePrefix;\n\n /**\n * The database type used for ShopChest\n **/\n public static Database.DatabaseType databaseType;\n\n /**\n * The interval in seconds, a ping is sent to the MySQL server\n **/\n public static int databaseMySqlPingInterval;\n\n /**\n * <p>The minimum prices for certain items</p>\n * This returns a key set, which contains e.g \"STONE\", \"STONE:1\", of the <i>minimum-prices</i> section in ShopChest's config.\n * To actually retrieve the minimum price for an item, you have to get the double {@code minimum-prices.<key>}.\n **/\n public static Set<String> minimumPrices;\n\n /**\n * <p>The maximum prices for certain items</p>\n * This returns a key set, which contains e.g \"STONE\", \"STONE:1\", of the {@code maximum-prices} section in ShopChest's config.\n * To actually retrieve the maximum price for an item, you have to get the double {@code maximum-prices.<key>}.\n **/\n public static Set<String> maximumPrices;\n\n /**\n * <p>List containing items, of which players can't create a shop</p>\n * If this list contains an item (e.g \"STONE\", \"STONE:1\"), it's in the blacklist.\n **/\n public static List<String> blacklist;\n\n /**\n * Whether prices may contain decimals\n **/\n public static boolean allowDecimalsInPrice;\n\n /**\n * Whether the buy price of a shop must be greater than or equal the sell price\n **/\n public static boolean buyGreaterOrEqualSell;\n\n /**\n * Whether buys and sells must be confirmed\n **/\n public static boolean confirmShopping;\n\n /**\n * Whether the shop creation price should be refunded at removal.\n */\n public static boolean refundShopCreation;\n\n /**\n * <p>Whether the update checker should run on start and notify players on join.</p>\n * The command is not affected by this setting and will continue to check for updates.\n **/\n public static boolean enableUpdateChecker;\n\n /**\n * Whether the debug log file should be created\n **/\n public static boolean enableDebugLog;\n\n /**\n * Whether buys and sells should be logged in the database\n **/\n public static boolean enableEconomyLog;\n\n /**\n * Whether WorldGuard integration should be enabled\n **/\n public static boolean enableWorldGuardIntegration;\n\n /**\n * <p>Sets the time limit for cleaning up the economy log in days</p>\n * \n * If this equals to {@code 0}, the economy log will not be cleaned.\n **/\n public static int cleanupEconomyLogDays;\n\n /**\n * Whether Towny integration should be enabled\n **/\n public static boolean enableTownyIntegration;\n\n /**\n * Whether AuthMe integration should be enabled\n **/\n public static boolean enableAuthMeIntegration;\n\n /**\n * Whether PlotSquared integration should be enabled\n **/\n public static boolean enablePlotsquaredIntegration;\n\n /**\n * Whether uSkyBlock integration should be enabled\n **/\n public static boolean enableUSkyblockIntegration;\n\n /**\n * Whether ASkyBlock integration should be enabled\n **/\n public static boolean enableASkyblockIntegration;\n\n /**\n * Whether BentoBox integration should be enabled\n **/\n public static boolean enableBentoBoxIntegration;\n\n /**\n * Whether IslandWorld integration should be enabled\n **/\n public static boolean enableIslandWorldIntegration;\n\n /**\n * Whether GriefPrevention integration should be enabled\n **/\n public static boolean enableGriefPreventionIntegration;\n\n /**\n * Whether AreaShop integration should be enabled\n **/\n public static boolean enableAreaShopIntegration;\n\n /**\n * Whether the vendor of the shop should get messages about buys and sells\n **/\n public static boolean enableVendorMessages;\n\n /**\n * Whether the vendor of the shop should get messages on all servers about buys and sells\n **/\n public static boolean enableVendorBungeeMessages;\n\n /**\n * Whether the extension of a potion or tipped arrow (if available) should be appended to the item name.\n **/\n public static boolean appendPotionLevelToItemName;\n\n /**\n * Whether players are allowed to sell/buy broken items\n **/\n public static boolean allowBrokenItems;\n\n /**\n * Whether only the shop a player is pointing at should be shown\n **/\n public static boolean onlyShowShopsInSight;\n\n /**\n * <p>Whether shops should automatically be removed from the database if an error occurred while loading</p>\n * (e.g. when no chest is found at a shop's location)\n */\n public static boolean removeShopOnError;\n\n /**\n * Whether the item amount should be calculated to fit the available money or inventory space\n **/\n public static boolean autoCalculateItemAmount;\n\n /**\n * Whether players should be able to select an item from the creative inventory\n */\n public static boolean creativeSelectItem;\n\n /**\n * <p>Whether the mouse buttons are inverted</p>\n * <b>Default:</b><br>\n * Right-Click: Buy<br>\n * Left-Click: Sell\n **/\n public static boolean invertMouseButtons;\n\n /**\n * Whether the hologram's location should be fixed at the bottom\n **/\n public static boolean hologramFixedBottom;\n\n /**\n * Amount every hologram should be lifted\n **/\n public static double hologramLift;\n\n /**\n * The maximum distance between a player and a shop to see the hologram\n **/\n public static double maximalDistance;\n\n /**\n * The maximum distance between a player and a shop to see the shop item\n **/\n public static double maximalItemDistance;\n\n /**\n * The price a player has to pay in order to create a normal shop\n **/\n public static double shopCreationPriceNormal;\n\n /**\n * The price a player has to pay in order to create an admin shop\n **/\n public static double shopCreationPriceAdmin;\n\n /**\n * The default shop limit for players whose limit is not set via a permission\n **/\n public static int defaultLimit;\n\n /**\n * The main command of ShopChest <i>(default: shop)</i>\n **/\n public static String mainCommandName;\n\n /**\n * The language file to use (e.g <i>en_US</i>, <i>de_DE</i>)\n **/\n public static String languageFile;\n\n /**\n * The language configuration of the currently selected language file\n */\n public static LanguageConfiguration langConfig;\n\n private ShopChest plugin;\n\n public Config(ShopChest plugin) {\n this.plugin = plugin;\n\n plugin.saveDefaultConfig();\n\n reload(true, true, true);\n }\n\n /**\n * <p>Set a configuration value</p>\n * <i>Config is automatically reloaded</i>\n *\n * @param property Property to change\n * @param value Value to set\n */\n public void set(String property, String value) {\n boolean langChange = (property.equalsIgnoreCase(\"language-file\"));\n try {\n int intValue = Integer.parseInt(value);\n plugin.getConfig().set(property, intValue);\n\n plugin.saveConfig();\n reload(false, langChange, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not an integer */ }\n\n try {\n double doubleValue = Double.parseDouble(value);\n plugin.getConfig().set(property, doubleValue);\n\n plugin.saveConfig();\n reload(false, langChange, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not a double */ }\n\n if (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"false\")) {\n boolean boolValue = Boolean.parseBoolean(value);\n plugin.getConfig().set(property, boolValue);\n } else {\n plugin.getConfig().set(property, value);\n }\n\n plugin.saveConfig();\n\n reload(false, langChange, false);\n }\n\n /**\n * Add a value to a list in the config.yml.\n * If the list does not exist, a new list with the given value will be created\n *\n * @param property Location of the list\n * @param value Value to add\n */\n public void add(String property, String value) {\n List list = (plugin.getConfig().getList(property) == null) ? new ArrayList<>() : plugin.getConfig().getList(property);\n\n try {\n int intValue = Integer.parseInt(value);\n list.add(intValue);\n\n plugin.saveConfig();\n reload(false, false, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not an integer */ }\n\n try {\n double doubleValue = Double.parseDouble(value);\n list.add(doubleValue);\n\n plugin.saveConfig();\n reload(false, false, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not a double */ }\n\n if (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"false\")) {\n boolean boolValue = Boolean.parseBoolean(value);\n list.add(boolValue);\n } else {\n list.add(value);\n }\n\n plugin.saveConfig();\n\n reload(false, false, false);\n }\n\n public void remove(String property, String value) {\n List list = (plugin.getConfig().getList(property) == null) ? new ArrayList<>() : plugin.getConfig().getList(property);\n\n try {\n int intValue = Integer.parseInt(value);\n list.remove(intValue);\n\n plugin.saveConfig();\n reload(false, false, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not an integer */ }\n\n try {\n double doubleValue = Double.parseDouble(value);\n list.remove(doubleValue);\n\n plugin.saveConfig();\n reload(false, false, false);\n\n return;\n } catch (NumberFormatException e) { /* Value not a double */ }\n\n if (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"false\")) {\n boolean boolValue = Boolean.parseBoolean(value);\n list.remove(boolValue);\n } else {\n list.remove(value);\n }\n\n plugin.saveConfig();\n\n reload(false, false, false);\n }\n\n /**\n * Reload the configuration values from config.yml\n * @param firstLoad Whether the config values have not been loaded before\n * @param langReload Whether the language configuration should be reloaded\n * @param showMessages Whether console (error) messages should be shown\n */\n public void reload(boolean firstLoad, boolean langReload, boolean showMessages) {\n plugin.reloadConfig();\n\n shopInfoItem = ItemUtils.getItemStack(plugin.getConfig().getString(\"shop-info-item\"));\n wgAllowCreateShopDefault = plugin.getConfig().getBoolean(\"worldguard-default-flag-values.create-shop\");\n wgAllowUseAdminShopDefault = plugin.getConfig().getBoolean(\"worldguard-default-flag-values.use-admin-shop\");\n wgAllowUseShopDefault = plugin.getConfig().getBoolean(\"worldguard-default-flag-values.use-shop\");\n townyShopPlotsResidents = plugin.getConfig().getStringList(\"towny-shop-plots.residents\");\n townyShopPlotsMayor = plugin.getConfig().getStringList(\"towny-shop-plots.mayor\");\n townyShopPlotsKing = plugin.getConfig().getStringList(\"towny-shop-plots.king\");\n areashopRemoveShopEvents = plugin.getConfig().getStringList(\"areashop-remove-shops\");\n databaseMySqlPingInterval = plugin.getConfig().getInt(\"database.mysql.ping-interval\");\n databaseMySqlHost = plugin.getConfig().getString(\"database.mysql.hostname\");\n databaseMySqlPort = plugin.getConfig().getInt(\"database.mysql.port\");\n databaseMySqlDatabase = plugin.getConfig().getString(\"database.mysql.database\");\n databaseMySqlUsername = plugin.getConfig().getString(\"database.mysql.username\");\n databaseMySqlPassword = plugin.getConfig().getString(\"database.mysql.password\");\n databaseTablePrefix = plugin.getConfig().getString(\"database.table-prefix\");\n databaseType = Database.DatabaseType.valueOf(plugin.getConfig().getString(\"database.type\"));\n minimumPrices = (plugin.getConfig().getConfigurationSection(\"minimum-prices\") == null) ? new HashSet<String>() : plugin.getConfig().getConfigurationSection(\"minimum-prices\").getKeys(true);\n maximumPrices = (plugin.getConfig().getConfigurationSection(\"maximum-prices\") == null) ? new HashSet<String>() : plugin.getConfig().getConfigurationSection(\"maximum-prices\").getKeys(true);\n allowDecimalsInPrice = plugin.getConfig().getBoolean(\"allow-decimals-in-price\");\n allowBrokenItems = plugin.getConfig().getBoolean(\"allow-broken-items\");\n autoCalculateItemAmount = (allowDecimalsInPrice && plugin.getConfig().getBoolean(\"auto-calculate-item-amount\"));\n creativeSelectItem = plugin.getConfig().getBoolean(\"creative-select-item\");\n blacklist = (plugin.getConfig().getStringList(\"blacklist\") == null) ? new ArrayList<String>() : plugin.getConfig().getStringList(\"blacklist\");\n buyGreaterOrEqualSell = plugin.getConfig().getBoolean(\"buy-greater-or-equal-sell\");\n confirmShopping = plugin.getConfig().getBoolean(\"confirm-shopping\");\n refundShopCreation = plugin.getConfig().getBoolean(\"refund-shop-creation\");\n enableUpdateChecker = plugin.getConfig().getBoolean(\"enable-update-checker\");\n enableDebugLog = plugin.getConfig().getBoolean(\"enable-debug-log\");\n enableEconomyLog = plugin.getConfig().getBoolean(\"enable-economy-log\");\n cleanupEconomyLogDays = plugin.getConfig().getInt(\"cleanup-economy-log-days\");\n enableWorldGuardIntegration = plugin.getConfig().getBoolean(\"enable-worldguard-integration\");\n enableTownyIntegration = plugin.getConfig().getBoolean(\"enable-towny-integration\");\n enableAuthMeIntegration = plugin.getConfig().getBoolean(\"enable-authme-integration\");\n enablePlotsquaredIntegration = plugin.getConfig().getBoolean(\"enable-plotsquared-integration\");\n enableUSkyblockIntegration = plugin.getConfig().getBoolean(\"enable-uskyblock-integration\");\n enableASkyblockIntegration = plugin.getConfig().getBoolean(\"enable-askyblock-integration\");\n enableBentoBoxIntegration = plugin.getConfig().getBoolean(\"enable-bentobox-integration\");\n enableIslandWorldIntegration = plugin.getConfig().getBoolean(\"enable-islandworld-integration\");\n enableGriefPreventionIntegration = plugin.getConfig().getBoolean(\"enable-griefprevention-integration\");\n enableAreaShopIntegration = plugin.getConfig().getBoolean(\"enable-areashop-integration\");\n enableVendorMessages = plugin.getConfig().getBoolean(\"enable-vendor-messages\");\n enableVendorBungeeMessages = plugin.getConfig().getBoolean(\"enable-vendor-bungee-messages\");\n onlyShowShopsInSight = plugin.getConfig().getBoolean(\"only-show-shops-in-sight\");\n appendPotionLevelToItemName = plugin.getConfig().getBoolean(\"append-potion-level-to-item-name\");\n removeShopOnError = plugin.getConfig().getBoolean(\"remove-shop-on-error\");\n invertMouseButtons = plugin.getConfig().getBoolean(\"invert-mouse-buttons\");\n hologramFixedBottom = plugin.getConfig().getBoolean(\"hologram-fixed-bottom\");\n hologramLift = plugin.getConfig().getDouble(\"hologram-lift\");\n maximalDistance = plugin.getConfig().getDouble(\"maximal-distance\");\n maximalItemDistance = plugin.getConfig().getDouble(\"maximal-item-distance\");\n shopCreationPriceNormal = plugin.getConfig().getDouble(\"shop-creation-price.normal\");\n shopCreationPriceAdmin = plugin.getConfig().getDouble(\"shop-creation-price.admin\");\n defaultLimit = plugin.getConfig().getInt(\"shop-limits.default\");\n mainCommandName = plugin.getConfig().getString(\"main-command-name\");\n languageFile = plugin.getConfig().getString(\"language-file\");\n\n if (firstLoad || langReload) loadLanguageConfig(showMessages);\n if (!firstLoad && langReload) LanguageUtils.load();\n }\n\n /**\n * @return ShopChest's {@link LanguageConfiguration}\n */\n public LanguageConfiguration getLanguageConfig() {\n return langConfig;\n }\n\n private Reader getTextResource(String file, boolean showMessages) {\n try {\n return (Reader) plugin.getClass().getDeclaredMethod(\"getTextResource\", String.class).invoke(plugin, file);\n } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {\n if (showMessages) plugin.getLogger().severe(\"Failed to get file from jar: \" + file);\n plugin.debug(\"Failed to get file from jar: \" + file);\n plugin.debug(e);\n }\n\n return null;\n }\n\n private void loadLanguageConfig(boolean showMessages) {\n langConfig = new LanguageConfiguration(plugin, showMessages);\n File langFolder = new File(plugin.getDataFolder(), \"lang\");\n\n String legacy = Utils.getMajorVersion() < 13 ? \"-legacy\" : \"\";\n\n if (!(new File(langFolder, \"en_US\" + legacy + \".lang\")).exists())\n plugin.saveResource(\"lang/en_US\" + legacy + \".lang\", false);\n \n if (!(new File(langFolder, \"de_DE\" + legacy + \".lang\")).exists())\n plugin.saveResource(\"lang/de_DE\" + legacy + \".lang\", false);\n\n File langConfigFile = new File(langFolder, languageFile + legacy + \".lang\");\n File langDefaultFile = new File(langFolder, \"en_US\" + legacy + \".lang\");\n\n if (!langConfigFile.exists()) {\n if (!langDefaultFile.exists()) {\n try {\n Reader r = getTextResource(\"lang/\" + langConfigFile.getName(), showMessages);\n\n if (r == null) {\n r = getTextResource(\"lang/en_US\" + legacy + \".lang\", showMessages);\n if (showMessages) plugin.getLogger().info(\"Using locale \\\"en_US\" + legacy + \"\\\" (Streamed from jar file)\");\n } else {\n if (showMessages)\n plugin.getLogger().info(\"Using locale \\\"\" + langConfigFile.getName().substring(0, langConfigFile.getName().length() - 5) + \"\\\" (Streamed from jar file)\");\n }\n\n if (r == null) {\n if (showMessages) plugin.getLogger().warning(\"Using default language values\");\n plugin.debug(\"Using default language values (#1)\");\n }\n\n BufferedReader br = new BufferedReader(r);\n\n StringBuilder sb = new StringBuilder();\n String line = br.readLine();\n\n while (line != null) {\n sb.append(line);\n sb.append(\"\\n\");\n line = br.readLine();\n }\n\n langConfig.loadFromString(sb.toString());\n } catch (IOException | InvalidConfigurationException e) {\n if (showMessages) {\n plugin.getLogger().warning(\"Using default language values\");\n }\n\n plugin.debug(\"Using default language values (#2)\");\n plugin.debug(e);\n }\n } else {\n try {\n langConfig.load(langDefaultFile);\n if (showMessages) plugin.getLogger().info(\"Using locale \\\"en_US\" + legacy + \"\\\"\");\n } catch (IOException | InvalidConfigurationException e) {\n if (showMessages) {\n plugin.getLogger().warning(\"Using default language values\");\n }\n\n plugin.debug(\"Using default language values (#3)\");\n plugin.debug(e);\n }\n }\n } else {\n try {\n if (showMessages)\n plugin.getLogger().info(\"Using locale \\\"\" + langConfigFile.getName().substring(0, langConfigFile.getName().length() - 5) + \"\\\"\");\n langConfig.load(langConfigFile);\n } catch (IOException | InvalidConfigurationException e) {\n if (showMessages) {\n plugin.getLogger().warning(\"Using default language values\");\n }\n\n plugin.debug(\"Using default language values (#4)\");\n plugin.debug(e);\n }\n }\n }\n\n}", "public class ShopCreateEvent extends ShopEvent implements Cancellable {\n private double creationPrice;\n private boolean cancelled;\n\n public ShopCreateEvent(Player player, Shop shop, double creationPrice) {\n super(player, shop);\n this.creationPrice = creationPrice;\n }\n /**\n * @return The price the player has to pay in order to create the shop (only if the event is not cancelled)\n */\n public double getCreationPrice() {\n return creationPrice;\n }\n\n @Override\n public boolean isCancelled() {\n return cancelled;\n }\n\n @Override\n public void setCancelled(boolean cancel) {\n cancelled = cancel;\n }\n\n}", "public class ShopExtendEvent extends ShopEvent implements Cancellable {\n private boolean cancelled;\n private Location newChestLocation;\n\n public ShopExtendEvent(Player player, Shop shop, Location newChest) {\n super(player, shop);\n this.newChestLocation = newChest;\n }\n\n /**\n * @return Location of the placed chest\n */\n public Location getNewChestLocation() {\n return newChestLocation;\n }\n\n @Override\n public boolean isCancelled() {\n return cancelled;\n }\n\n @Override\n public void setCancelled(boolean cancel) {\n cancelled = cancel;\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.util.Set; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import de.epiceric.shopchest.ShopChest; import de.epiceric.shopchest.config.Config; import de.epiceric.shopchest.event.ShopCreateEvent; import de.epiceric.shopchest.event.ShopExtendEvent; import de.epiceric.shopchest.utils.Utils; import me.ryanhamshire.GriefPrevention.Claim; import me.ryanhamshire.GriefPrevention.GriefPrevention;
package de.epiceric.shopchest.external.listeners; public class GriefPreventionListener implements Listener { private final ShopChest plugin; private final GriefPrevention griefPrevention; public GriefPreventionListener(ShopChest plugin) { this.plugin = plugin; this.griefPrevention = plugin.getGriefPrevention(); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onCreateShop(ShopCreateEvent e) {
2
tomasbjerre/git-changelog-lib
src/main/java/se/bjurr/gitchangelog/api/model/Issue.java
[ "public static <T> T checkNotNull(final T it, final String string) {\n if (it == null) {\n throw new IllegalStateException(string);\n }\n return it;\n}", "public static void checkState(final boolean b, final String string) {\n if (!b) {\n throw new IllegalStateException(string);\n }\n}", "public static boolean isNullOrEmpty(final String it) {\n return it == null || it.isEmpty();\n}", "public static String nullToEmpty(final String it) {\n if (it == null) {\n return \"\";\n }\n return it;\n}", "public interface IAuthors {\n List<Author> getAuthors();\n}", "public interface ICommits {\n List<Commit> getCommits();\n}", "public enum SettingsIssueType {\n NOISSUE,\n CUSTOM,\n JIRA,\n GITHUB,\n GITLAB,\n REDMINE\n}" ]
import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.CUSTOM; import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.GITHUB; import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.GITLAB; import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.JIRA; import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.NOISSUE; import static se.bjurr.gitchangelog.internal.settings.SettingsIssueType.REDMINE; import static se.bjurr.gitchangelog.internal.util.Preconditions.checkNotNull; import static se.bjurr.gitchangelog.internal.util.Preconditions.checkState; import static se.bjurr.gitchangelog.internal.util.Preconditions.isNullOrEmpty; import static se.bjurr.gitchangelog.internal.util.Preconditions.nullToEmpty; import java.io.Serializable; import java.util.List; import se.bjurr.gitchangelog.api.model.interfaces.IAuthors; import se.bjurr.gitchangelog.api.model.interfaces.ICommits; import se.bjurr.gitchangelog.internal.settings.SettingsIssueType;
package se.bjurr.gitchangelog.api.model; public class Issue implements ICommits, IAuthors, Serializable { private static final long serialVersionUID = -7571341639024417199L; private final List<Commit> commits; private final List<Author> authors; /** Like JIRA, or GitHub. */ private final String name; /** Like the title of a Jira. */ private final String title; private final boolean hasTitle; /** Like the actual Jira, JIR-ABC. */ private final String issue; private final boolean hasIssue; /** A link to the issue, http://..... */ private final String link; private final boolean hasLink; /** Type of issue, perhaps Story, Bug and etc */ private final String type; private final boolean hasType; private final boolean hasDescription; private final String description; /** Labels on the issue, for GitHub it may be bug, enhancement, ... */ private final List<String> labels; private final boolean hasLabels; private final boolean hasLinkedIssues; private final SettingsIssueType issueType; private final List<String> linkedIssues; public Issue( final List<Commit> commits, final List<Author> authors, final String name, final String title, final String issue, final SettingsIssueType issueType, final String description, final String link, final String type, final List<String> linkedIssues, final List<String> labels) { checkState(!commits.isEmpty(), "commits"); this.commits = commits;
this.authors = checkNotNull(authors, "authors");
0
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/ImplementationExecutor.java
[ "public interface InfluxDBDao<Measurement extends Serializable> {\n\t/**\n\t * 插入一条数据\n\t * \n\t * @param measurement\n\t */\n\tvoid insert(Measurement measurement);\n\n\t/**\n\t * 批量插入\n\t * \n\t * @param measurement\n\t */\n\tvoid batchInsert(Collection<Measurement> measurement);\n\n\t/**\n\t * 查询所有\n\t * \n\t * @return\n\t * @deprecated 使用{@link #select(Map)}方法查询\n\t */\n\t@Deprecated\n\tList<Measurement> selectAll();\n\n\t/**\n\t * 按条件查询\n\t * \n\t * @param tagCondition\n\t * tagField查询条件\n\t * @return\n\t */\n\tList<Measurement> select(Map<String, Object> tagCondition);\n\n\t/**\n\t * 按时间范围查询\n\t * \n\t * @param timeStart\n\t * 起始时间, 可以为空\n\t * @param timeEnd\n\t * 结束时间, 可以为空\n\t * @param tagCondition\n\t * tagField查询条件\n\t * @return\n\t */\n\tList<Measurement> selectBetween(Date timeStart, Date timeEnd, Map<String, Object> tagCondition);\n\n\t/**\n\t * 查询{@code time}之后的数据\n\t * \n\t * @param time\n\t * @param tagCondition\n\t * tagField查询条件\n\t * @return\n\t */\n\tList<Measurement> selectAfter(Date time, Map<String, Object> tagCondition);\n\n\t/**\n\t * 查询{@code time}之前的数据\n\t * \n\t * @param time\n\t * @param tagCondition\n\t * tagField查询条件\n\t * @return\n\t */\n\tList<Measurement> selectBefore(Date time, Map<String, Object> tagCondition);\n}", "public class InfluxDBException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -4410268653794610252L;\n\n\tpublic InfluxDBException() {\n\t\tsuper();\n\t}\n\n\tpublic InfluxDBException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic InfluxDBException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic InfluxDBException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n}", "public class MapperMethod {\n\tprivate final Executor executor;\n\tprivate final ParameterProducer producer;\n\tprivate final MethodSignature methodSignature;\n\tprivate final MapperInterface mapperInterface;\n\tprivate final InfluxDBRepository repository;\n\n\tpublic MapperMethod(Class<?> mapperInterface, InfluxDBRepository repository, MethodSignature signature) {\n\t\tthis.mapperInterface = new MapperInterface(mapperInterface);\n\t\tthis.repository = repository;\n\t\tthis.methodSignature = signature;\n\t\tthis.executor = ExecutorFactory.getInstance().executorOf(signature, repository);\n\n\t\tfinal Collection<ParameterProducer> parameterProducers = new LinkedList<>();\n\t\tparameterProducers.add(new AnnotationParameterProducer(signature.getMethod()));\n\t\tparameterProducers.add(new J8ParameterProducer(signature.getMethod()));\n\t\tthis.producer = new BatchParameterProducer(parameterProducers);\n\t}\n\n\tpublic Executor getExecutor() {\n\t\treturn executor;\n\t}\n\n\tpublic ParameterProducer getProducer() {\n\t\treturn producer;\n\t}\n\n\tpublic MethodSignature getMethodSignature() {\n\t\treturn methodSignature;\n\t}\n\n\tpublic MapperInterface getMapperInterface() {\n\t\treturn mapperInterface;\n\t}\n\n\t@CoberturaIgnore\n\tpublic InfluxDBRepository getRepository() {\n\t\treturn repository;\n\t}\n\n\t@Override\n\t@CoberturaIgnore\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((methodSignature == null) ? 0 : methodSignature.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\t@CoberturaIgnore\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tMapperMethod other = (MapperMethod) obj;\n\t\tif (methodSignature == null) {\n\t\t\tif (other.methodSignature != null)\n\t\t\t\treturn false;\n\t\t} else if (!methodSignature.equals(other.methodSignature))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}", "public class MethodSignature {\n\tprivate final boolean returnsMany;\n\tprivate final boolean returnsMap;\n\tprivate final boolean returnsVoid;\n\tprivate final boolean returnsBoolean;\n\tprivate final Class<?> returnType;\n\tprivate final Method method;\n\tprivate final Annotation[] annotations;\n\tprivate final Parameter[] parameters;\n\n\tpublic MethodSignature(Class<?> mapperInterface, Method method) {\n\t\tType resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);\n\t\tif (resolvedReturnType instanceof Class<?>) {\n\t\t\tthis.returnType = (Class<?>) resolvedReturnType;\n\t\t} else if (resolvedReturnType instanceof ParameterizedType) {\n\t\t\tthis.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();\n\t\t} else {\n\t\t\tthis.returnType = method.getReturnType();\n\t\t}\n\t\tthis.returnsVoid = void.class.isAssignableFrom(returnType);\n\t\tthis.returnsMany = Collection.class.isAssignableFrom(returnType) || returnType.isArray();\n\t\tthis.returnsMap = Map.class.isAssignableFrom(returnType);\n\t\tthis.returnsBoolean = Boolean.class == returnType || boolean.class == returnType;\n\t\tthis.method = method;\n\t\tannotations = method.getDeclaredAnnotations();\n\t\tparameters = method.getParameters();\n\t}\n\n\tpublic boolean returnsBoolean() {\n\t\treturn returnsBoolean;\n\t}\n\n\tpublic boolean returnsMany() {\n\t\treturn returnsMany;\n\t}\n\n\tpublic boolean returnsMap() {\n\t\treturn returnsMap;\n\t}\n\n\tpublic boolean returnsVoid() {\n\t\treturn returnsVoid;\n\t}\n\n\tpublic Class<?> getReturnType() {\n\t\treturn returnType;\n\t}\n\n\tpublic Method getMethod() {\n\t\treturn method;\n\t}\n\n\tpublic Annotation[] getAnnotations() {\n\t\treturn annotations;\n\t}\n\n\tpublic <T extends Annotation> T getAnnotation(Class<T> annotationClass) {\n\t\treturn method.getAnnotation(annotationClass);\n\t}\n\n\tpublic Parameter[] getParameters() {\n\t\treturn parameters;\n\t}\n\n\t@Override\n\t@CoberturaIgnore\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((method == null) ? 0 : method.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\t@CoberturaIgnore\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tMethodSignature other = (MethodSignature) obj;\n\t\tif (method == null) {\n\t\t\tif (other.method != null)\n\t\t\t\treturn false;\n\t\t} else if (!method.equals(other.method))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}", "public class MeasurementClassMetadata {\n\n\tprivate final String measurementName;\n\tprivate final String retentionPolicy;\n\n\tprivate final Class<? extends Serializable> measurementClass;\n\tprivate final PropertyDescriptor shardingFieldDescriptor;\n\tprivate final PropertyDescriptor timeFieldDescriptor;\n\t/**\n\t * map<数据库名称, java字段名称>\n\t */\n\tprivate final Map<String, String> tagColumnJavaFieldNameMap;\n\t/**\n\t * map<数据库字段名称, java字段名称>\n\t */\n\tprivate final Map<String, String> fieldColumnJavaFieldNameMap;\n\t/**\n\t * map<数据库字段名称, PropertyDescriptor>\n\t */\n\tprivate final Map<String, PropertyDescriptor> tagColumnDescriptors;\n\t/**\n\t * map<数据库字段名称, PropertyDescriptor>\n\t */\n\tprivate final Map<String, PropertyDescriptor> fieldColumnDescriptors;\n\n\tprivate boolean isJavaUtilDateTimeField;\n\tprivate boolean isNumberTimeField;\n\tprivate boolean isStringTimeField;\n\tprivate String[] datetimePatterns;\n\tprivate final int _hashcode;\n\n\tpublic MeasurementClassMetadata(Class<? extends Serializable> measurementClass, String defaultRetentionPolicy) {\n\t\tthis.measurementClass = measurementClass;\n\t\ttagColumnJavaFieldNameMap = new HashMap<>();\n\t\tfieldColumnJavaFieldNameMap = new HashMap<>();\n\t\ttagColumnDescriptors = new HashMap<>();\n\t\tfieldColumnDescriptors = new HashMap<>();\n\n\t\tMap<String, PropertyDescriptor> descriptorsMap = descriptorsMap(measurementClass);\n\n\t\ttimeFieldDescriptor = descriptorsMap.get(\"time\");\n\t\tassertTimeFieldDescriptorNotNull();\n\n\t\tClass<?> timeFieldType = timeFieldDescriptor.getPropertyType();\n\n\t\tisJavaUtilDateTimeField = Date.class.isAssignableFrom(timeFieldType);\n\t\tisNumberTimeField = Number.class.isAssignableFrom(timeFieldType);\n\t\tisStringTimeField = CharSequence.class.isAssignableFrom(timeFieldType);\n\n\t\tif (!isJavaUtilDateTimeField && !isNumberTimeField && !isStringTimeField) {\n\t\t\tthrow new InfluxDBException(\"Unsupported time field type: \" + timeFieldType);\n\t\t}\n\n\t\tInfluxDBMeasurement annotation = measurementClass.getAnnotation(InfluxDBMeasurement.class);\n\t\tassertMeasurementAnnotationNotNull(annotation);\n\n\t\tthis.measurementName = annotation.value();\n\t\tthis.retentionPolicy = StringUtils.isBlank(annotation.retentionPolicy()) ? defaultRetentionPolicy : annotation.retentionPolicy();\n\t\tthis.shardingFieldDescriptor = descriptorsMap.get(annotation.shardingField());\n\t\tthis.datetimePatterns = annotation.datetimePatterns();\n\n\t\tfindFields(descriptorsMap);\n\t\tfindTags(descriptorsMap);\n\t\t_hashcode = hash();\n\t}\n\n\tprivate void assertTimeFieldDescriptorNotNull() {\n\t\tif (timeFieldDescriptor == null) {\n\t\t\tthrow new InfluxDBException(\"Invalid measurement class: time field not found!\");\n\t\t}\n\t}\n\n\tprivate void assertMeasurementAnnotationNotNull(InfluxDBMeasurement annotation) {\n\t\tif (annotation == null) {\n\t\t\tthrow new InfluxDBException(\"Invalid measurement class: must annotated by @InfluxDBMeasurement\");\n\t\t}\n\t}\n\n\tprivate void findTags(Map<String, PropertyDescriptor> descriptorsMap) {\n\n\t\tfor (Map.Entry<String, PropertyDescriptor> entry : descriptorsMap.entrySet()) {\n\n\t\t\tPropertyDescriptor descriptor = entry.getValue();\n\t\t\tString fieldName = descriptor.getName();\n\t\t\tField field = ReflectionUtils.findField(this.measurementClass, fieldName);\n\n\t\t\tTagColumn tagAnnotation = field.getAnnotation(TagColumn.class);\n\n\t\t\tif (tagAnnotation != null) {\n\t\t\t\ttagColumnJavaFieldNameMap.put(tagAnnotation.value(), fieldName);\n\t\t\t\ttagColumnDescriptors.put(fieldName, descriptor);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void findFields(Map<String, PropertyDescriptor> descriptorsMap) {\n\n\t\tfor (Map.Entry<String, PropertyDescriptor> entry : descriptorsMap.entrySet()) {\n\n\t\t\tPropertyDescriptor descriptor = entry.getValue();\n\t\t\tString fieldName = descriptor.getName();\n\t\t\tField field = ReflectionUtils.findField(this.measurementClass, fieldName);\n\n\t\t\tFieldColumn fieldAnnotation = field.getAnnotation(FieldColumn.class);\n\n\t\t\tif (fieldAnnotation != null) {\n\t\t\t\tfieldColumnJavaFieldNameMap.put(fieldAnnotation.value(), fieldName);\n\t\t\t\tfieldColumnDescriptors.put(fieldName, descriptor);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static final Map<String, PropertyDescriptor> descriptorsMap(Class<?> measurementClass) {\n\t\ttry {\n\t\t\tBeanInfo beanInfo = Introspector.getBeanInfo(measurementClass);\n\t\t\tPropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\t\t\tMap<String, PropertyDescriptor> descriptorsMap = new HashMap<>();\n\t\t\tfor (int i = 0; i < propertyDescriptors.length; i++) {\n\t\t\t\tString name = propertyDescriptors[i].getName();\n\t\t\t\tdescriptorsMap.put(name, propertyDescriptors[i]);\n\t\t\t}\n\t\t\tdescriptorsMap.remove(\"class\");\n\t\t\treturn descriptorsMap;\n\t\t} catch (IntrospectionException e) {\n\t\t\tthrow new InfluxDBException(e);\n\t\t}\n\t}\n\n\tpublic boolean isJavaUtilDateTimeField() {\n\t\treturn isJavaUtilDateTimeField;\n\t}\n\n\tpublic boolean isNumberTimeField() {\n\t\treturn isNumberTimeField;\n\t}\n\n\tpublic boolean isStringTimeField() {\n\t\treturn isStringTimeField;\n\t}\n\n\tpublic String[] getDatetimePatterns() {\n\t\treturn datetimePatterns;\n\t}\n\n\tpublic Class<? extends Serializable> getMeasurementClass() {\n\t\treturn measurementClass;\n\t}\n\n\tpublic String getMeasurementName() {\n\t\treturn measurementName;\n\t}\n\n\tpublic String getRetentionPolicy() {\n\t\treturn retentionPolicy;\n\t}\n\n\tpublic PropertyDescriptor getShardingFieldDescriptor() {\n\t\treturn shardingFieldDescriptor;\n\t}\n\n\tpublic Map<String, String> getTagColumnJavaFieldNameMap() {\n\t\treturn tagColumnJavaFieldNameMap;\n\t}\n\n\tpublic Map<String, String> getFieldColumnJavaFieldNameMap() {\n\t\treturn fieldColumnJavaFieldNameMap;\n\t}\n\n\tpublic PropertyDescriptor getTimeFieldDescriptor() {\n\t\treturn timeFieldDescriptor;\n\t}\n\n\tpublic Map<String, PropertyDescriptor> getTagColumnDescriptors() {\n\t\treturn tagColumnDescriptors;\n\t}\n\n\tpublic Map<String, PropertyDescriptor> getFieldColumnDescriptors() {\n\t\treturn fieldColumnDescriptors;\n\t}\n\n\tprivate int hash() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((measurementClass == null) ? 0 : measurementClass.hashCode());\n\t\tresult = prime * result + ((measurementName == null) ? 0 : measurementName.hashCode());\n\t\tresult = prime * result + ((retentionPolicy == null) ? 0 : retentionPolicy.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn _hashcode;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tMeasurementClassMetadata other = (MeasurementClassMetadata) obj;\n\t\tif (measurementClass == null) {\n\t\t\tif (other.measurementClass != null)\n\t\t\t\treturn false;\n\t\t} else if (!measurementClass.equals(other.measurementClass))\n\t\t\treturn false;\n\t\tif (measurementName == null) {\n\t\t\tif (other.measurementName != null)\n\t\t\t\treturn false;\n\t\t} else if (!measurementName.equals(other.measurementName))\n\t\t\treturn false;\n\t\tif (retentionPolicy == null) {\n\t\t\tif (other.retentionPolicy != null)\n\t\t\t\treturn false;\n\t\t} else if (!retentionPolicy.equals(other.retentionPolicy))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}", "public class ParameterValue {\n\tprivate final Object value;\n\tprivate final ParameterSignature signature;\n\n\tpublic ParameterValue(Object value, ParameterSignature signature) {\n\t\tsuper();\n\t\tthis.value = value;\n\t\tthis.signature = signature;\n\t}\n\n\tpublic Object getValue() {\n\t\treturn value;\n\t}\n\n\tpublic ParameterSignature getSignature() {\n\t\treturn signature;\n\t}\n\n}", "public class InfluxDBRepository {\n\n\tprivate static final Logger logger = Logger.getLogger(InfluxDBRepository.class.getCanonicalName());\n\n\tpublic static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n\tprivate final InfluxDB influxDB;\n\tprivate final String databaseName;\n\n\t/**\n\t * map<classname, metadata>\n\t */\n\tprivate final Map<String, MeasurementClassMetadata> classmetadata;\n\t/**\n\t * map<key{measurementName, retentionPolicy}, metadata>\n\t */\n\tprivate final Map<MeasurementKey, MeasurementClassMetadata> classmetadataMapByKey;\n\n\tprivate final TypeConverterSupport typeConverter;\n\n\tprivate final InfluxQLMapper qlMapper;\n\n\tpublic InfluxDBRepository(final InfluxDB influxDB, final String databaseName, final Map<String, MeasurementClassMetadata> classmetadata,\n\t\t\tInfluxQLMapper qlMapper) {\n\t\tsuper();\n\t\tthis.influxDB = influxDB;\n\t\tthis.databaseName = databaseName;\n\t\tthis.classmetadata = classmetadata;\n\t\tthis.qlMapper = qlMapper;\n\t\tthis.classmetadataMapByKey = new HashMap<>();\n\t\tthis.typeConverter = new SimpleTypeConverter();\n\n\t\tthis.typeConverter.registerCustomEditor(Date.class, new DatePropertyEditor());\n\n\t\ttransform(classmetadata, classmetadataMapByKey);\n\n\t\tscanAndRegisterEnumTypeEditors(this.typeConverter, classmetadata);\n\t}\n\n\tprivate void scanAndRegisterEnumTypeEditors(TypeConverterSupport typeConverter, Map<String, MeasurementClassMetadata> classmetadatas) {\n\t\tfor(MeasurementClassMetadata classMetadata: classmetadatas.values()) {\n\t\t\tcheckAndRegisterEnumTypeEditors(typeConverter, classMetadata.getTagColumnDescriptors().values());\n\t\t\tcheckAndRegisterEnumTypeEditors(typeConverter, classMetadata.getFieldColumnDescriptors().values());\n\t\t}\n\t}\n\n\tprivate void checkAndRegisterEnumTypeEditors(TypeConverterSupport typeConverter, Collection<PropertyDescriptor> values) {\n\t\tfor(PropertyDescriptor dspr: values) {\n\t\t\tClass propertyType = dspr.getReadMethod().getReturnType();\n\t\t\tif(!EnumType.class.isAssignableFrom(propertyType)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(!typeConverter.hasCustomEditorForElement(propertyType, null)) {\n\t\t\t\ttypeConverter.registerCustomEditor(propertyType, new EnumsValuePropertyEditor(propertyType));\n\t\t\t}\n\t\t}\n\t}\n\n\n\tpublic void execute(String command, final Map<String, ParameterValue> parameters) {\n\t\tcommand = CommandUtils.parseCommand(command, parameters);\n\t\tif (logger.isLoggable(Level.INFO)) {\n\t\t\tlogger.info(\"execute → \" + command);\n\t\t}\n\t\tfinal Query query = new Query(command, databaseName);\n\t\tinfluxDB.query(query, DEFAULT_TIME_UNIT);\n\t}\n\n\tpublic ResultContext query(String command, final Map<String, ParameterValue> parameters) {\n\t\tcommand = CommandUtils.parseCommand(command, parameters);\n\t\tif (logger.isLoggable(Level.INFO)) {\n\t\t\tlogger.info(\"query → \" + command);\n\t\t}\n\t\tfinal Query query = new Query(command, databaseName);\n\t\tfinal QueryResult queryResult = influxDB.query(query, DEFAULT_TIME_UNIT);\n\t\treturn new NativeResultContext(queryResult);\n\t}\n\n\tpublic void insert(final Object entity) {\n\t\tif (entity == null) {\n\t\t\treturn;\n\t\t}\n\t\tfinal String entityClassName = entity.getClass().getName();\n\t\tfinal MeasurementClassMetadata classMetadata = getClassMetadata(entityClassName);\n\t\tif (classMetadata == null) {\n\t\t\tthrow new InfluxDBException(\"Class not mapped: \" + entityClassName);\n\t\t}\n\t\tfinal Point point = buildPoint(entity, classMetadata);\n\t\tinfluxDB.write(databaseName, classMetadata.getRetentionPolicy(), point);\n\t}\n\n\tpublic void batchInsert(final Collection<Object> entities) {\n\t\tif (CollectionUtils.isEmpty(entities)) {\n\t\t\treturn;\n\t\t}\n\t\tfinal Map<MeasurementKey, Collection<Object>> entitiesGrouped = new HashMap<>();\n\t\tfor (final Object entity : entities) {\n\t\t\tif (entity == null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinal String entityClassName = entity.getClass().getName();\n\t\t\tfinal MeasurementClassMetadata classMetadata = getClassMetadata(entityClassName);\n\t\t\tif (classMetadata == null) {\n\t\t\t\tthrow new InfluxDBException(\"Class not mapped: \" + entityClassName);\n\t\t\t}\n\t\t\tfinal MeasurementKey key = new MeasurementKey(classMetadata.getMeasurementName(), classMetadata.getRetentionPolicy());\n\n\t\t\tCollection<Object> gEntities = entitiesGrouped.get(key);\n\t\t\tif (gEntities == null) {\n\t\t\t\tgEntities = new LinkedList<>();\n\t\t\t\tentitiesGrouped.put(key, gEntities);\n\t\t\t}\n\t\t\tgEntities.add(entity);\n\t\t}\n\t\tfor (final Map.Entry<MeasurementKey, Collection<Object>> entry : entitiesGrouped.entrySet()) {\n\t\t\tbatchInsert(entry.getKey(), entry.getValue());\n\t\t}\n\t}\n\n\tprivate static void transform(final Map<String, MeasurementClassMetadata> classmetadata,\n\t\t\tfinal Map<MeasurementKey, MeasurementClassMetadata> classmetadataMapByKey) {\n\t\tfor (final MeasurementClassMetadata metadata : classmetadata.values()) {\n\t\t\tclassmetadataMapByKey.put(new MeasurementKey(metadata.getMeasurementName(), metadata.getRetentionPolicy()), metadata);\n\t\t}\n\t}\n\n\tprivate void batchInsert(final MeasurementKey key, final Collection<Object> entities) {\n\t\tif (CollectionUtils.isEmpty(entities)) {\n\t\t\treturn;\n\t\t}\n\t\tfinal MeasurementClassMetadata classMetadata = getClassMetadata(key);\n\n\t\tfinal BatchPoints.Builder batchPointsBuilder = BatchPoints //\n\t\t\t\t.database(databaseName) //\n\t\t\t\t.retentionPolicy(key.retentionPolicy);\n\t\tfor (final Object entity : entities) {\n\t\t\tif (entity == null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinal Point point = buildPoint(entity, classMetadata);\n\t\t\tbatchPointsBuilder.point(point);\n\t\t}\n\t\tinfluxDB.write(batchPointsBuilder.build());\n\t}\n\n\tprivate Point buildPoint(final Object entity, final MeasurementClassMetadata classMetadata) {\n\t\tfinal String measurementName = getShardingMeasurementName(classMetadata, entity);\n\t\tfinal Point.Builder pointBuilder = Point.measurement(measurementName);\n\n\t\tfinal Date time = readTimeField(classMetadata, entity);\n\t\tpointBuilder.time(DEFAULT_TIME_UNIT.toNanos(time.getTime()), TimeUnit.NANOSECONDS);\n\n\t\tresolveMeasurementTags(entity, classMetadata, pointBuilder);\n\t\tresolveMeasurementFields(entity, classMetadata, pointBuilder);\n\t\tfinal Point point = pointBuilder.build();\n\t\treturn point;\n\t}\n\n\tprivate Date readTimeField(final MeasurementClassMetadata classMetadata, final Object entity) {\n\t\tfinal Method readMethod = classMetadata.getTimeFieldDescriptor().getReadMethod();\n\t\ttry {\n\t\t\tfinal Object result = readMethod.invoke(entity);\n\n\t\t\tif (classMetadata.isJavaUtilDateTimeField()) {\n\t\t\t\treturn (Date) result;\n\t\t\t} else if (classMetadata.isNumberTimeField()) {\n\t\t\t\treturn new Date(((Number) result).longValue());\n\t\t\t} else if (classMetadata.isStringTimeField()) {\n\t\t\t\treturn DateUtils.parseDate(result.toString(), classMetadata.getDatetimePatterns());\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | ParseException e) {\n\t\t\tthrow new InfluxDBException(\"An error occurred while read time field value\", e);\n\t\t}\n\t}\n\n\tprivate void resolveMeasurementFields(final Object entity, final MeasurementClassMetadata classMetadata, final Builder pointBuilder) {\n\t\tfinal Map<String, PropertyDescriptor> fieldColumnDescriptors = classMetadata.getFieldColumnDescriptors();\n\t\tMap<String, Object> fields = new HashMap<>(fieldColumnDescriptors.size());\n\n\t\tfor (final Map.Entry<String, PropertyDescriptor> entry : fieldColumnDescriptors.entrySet()) {\n\t\t\tfinal String fieldName = entry.getKey();\n\t\t\tfinal PropertyDescriptor valueDescriptor = entry.getValue();\n\t\t\tfinal Method readMethod = valueDescriptor.getReadMethod();\n\t\t\tfinal Object value = valueOfField(readMethod, entity);\n\n\t\t\tClass<?> fieldJavaType = readMethod.getReturnType();\n\n\t\t\tObject convertedValue = convertFieldValue(value, fieldJavaType);\n\n\t\t\tfields.put(fieldName, convertedValue);\n\t\t}\n\t\tpointBuilder.fields(fields);\n\t}\n\n\tprivate Object convertFieldValue(Object value, Class<?> fieldJavaType) {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t}\n\t\tObject convertedValue = null;\n\t\tif (fieldJavaType.isPrimitive()) {\n\t\t\tconvertedValue = value;\n\t\t} else if (Number.class.isAssignableFrom(fieldJavaType)) {\n\t\t\tconvertedValue = ((Number) value).doubleValue();\n\t\t} else {\n\t\t\tconvertedValue = this.typeConverter.convertIfNecessary(value, String.class);\n\t\t}\n\t\tif (convertedValue == null && value != null) {\n\t\t\tthrow new InfluxDBException(\"cannot convert type \\\"\" + fieldJavaType + \"\\\" to String\");\n\t\t}\n\t\treturn convertedValue;\n\t}\n\n\tprivate void resolveMeasurementTags(final Object entity, final MeasurementClassMetadata classMetadata, final Builder pointBuilder) {\n\t\tfinal Map<String, PropertyDescriptor> tagColumnDescriptors = classMetadata.getTagColumnDescriptors();\n\t\tfor (final Map.Entry<String, PropertyDescriptor> entry : tagColumnDescriptors.entrySet()) {\n\t\t\tfinal String tagName = entry.getKey();\n\t\t\tfinal PropertyDescriptor valueDescriptor = entry.getValue();\n\t\t\tfinal Method readMethod = valueDescriptor.getReadMethod();\n\t\t\tfinal Object value = valueOfTag(readMethod, entity);\n\t\t\tfinal String converted = this.typeConverter.convertIfNecessary(value, String.class);\n\t\t\tif (converted == null && value != null) {\n\t\t\t\tthrow new InfluxDBException(\"cannot convert type \\\"\" + readMethod.getReturnType() + \"\\\" to String\");\n\t\t\t}\n\t\t\tpointBuilder.tag(tagName, converted);\n\t\t}\n\t}\n\n\tprivate Object valueOfField(final Method readMethod, final Object entity) {\n\t\ttry {\n\t\t\treturn readMethod.invoke(entity);\n\t\t} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\n\t\t\tthrow new InfluxDBException(\"An error occorred while reading field value\", e);\n\t\t}\n\t}\n\n\tprivate Object valueOfTag(final Method readMethod, final Object entity) {\n\t\ttry {\n\t\t\treturn readMethod.invoke(entity);\n\t\t} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\n\t\t\tthrow new InfluxDBException(\"An error occorred while reading tag field value\", e);\n\t\t}\n\t}\n\n\tpublic String getShardingMeasurementName(final MeasurementClassMetadata metadata, final Object entity) {\n\t\tfinal PropertyDescriptor shardingFieldDescriptor = metadata.getShardingFieldDescriptor();\n\t\tif (shardingFieldDescriptor == null) {\n\t\t\treturn metadata.getMeasurementName();\n\t\t}\n\t\tfinal Method readMethod = shardingFieldDescriptor.getReadMethod();\n\t\ttry {\n\t\t\tfinal Object value = readMethod.invoke(entity);\n\t\t\treturn new StringBuilder() //\n\t\t\t\t\t.append(metadata.getMeasurementName()) //\n\t\t\t\t\t.append('_') //\n\t\t\t\t\t.append(value) //\n\t\t\t\t\t.toString();\n\t\t} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {\n\t\t\tthrow new InfluxDBException(\"An error occurred while reading shard field value\", e);\n\t\t}\n\t}\n\n\tpublic InfluxDB getInfluxDB() {\n\t\treturn influxDB;\n\t}\n\n\tpublic InfluxQLStatement getStatement(String name) {\n\t\treturn qlMapper.getStatement(name);\n\t}\n\n\tpublic MeasurementClassMetadata getClassMetadata(final String measurementClassName) {\n\t\treturn classmetadata.get(measurementClassName);\n\t}\n\n\tpublic MeasurementClassMetadata getClassMetadata(final String measurementName, final String retentionPolicy) {\n\t\treturn classmetadataMapByKey.get(new MeasurementKey(measurementName, retentionPolicy));\n\t}\n\n\tprivate MeasurementClassMetadata getClassMetadata(final MeasurementKey key) {\n\t\treturn classmetadataMapByKey.get(key);\n\t}\n\n\tpublic MeasurementClassMetadata getClassMetadataByMeasurementName(final String measurementName) {\n\t\treturn classmetadataMapByKey.get(new MeasurementKey(measurementName));\n\t}\n\n\tpublic MeasurementClassMetadata getClassMetadata(final Class<?> measurementClass) {\n\t\treturn getClassMetadata(measurementClass.getName());\n\t}\n\n\tpublic Map<String, MeasurementClassMetadata> getAllClassMetadata() {\n\t\treturn classmetadata;\n\t}\n\n\tpublic <T> T convert(Map<String, Object> map, Class<T> targetType) {\n\t\tMeasurementClassMetadata classMetadata = getClassMetadata(targetType);\n\t\tif (classMetadata != null) {\n\t\t\treturn BeanConvertUtils.convert(map, classMetadata, this.typeConverter);\n\t\t}\n\t\treturn BeanConvertUtils.convert(map, targetType, this.typeConverter);\n\t}\n\n\tpublic <T> T convert(Object source, Class<T> targetType) {\n\t\treturn this.typeConverter.convertIfNecessary(source, targetType);\n\t}\n\n\tprivate static final class MeasurementKey {\n\t\tprivate final String measurementName;\n\t\tprivate final String retentionPolicy;\n\t\tprivate final int _hash;\n\n\t\tpublic MeasurementKey(final String measurementName, final String retentionPolicy) {\n\t\t\tsuper();\n\t\t\tthis.measurementName = measurementName;\n\t\t\tthis.retentionPolicy = retentionPolicy;\n\t\t\tthis._hash = hash();\n\t\t}\n\n\t\tpublic MeasurementKey(final String measurementName) {\n\t\t\tthis(measurementName, \"autogen\");\n\t\t}\n\n\t\tprivate int hash() {\n\t\t\tfinal int prime = 31;\n\t\t\tint result = 1;\n\t\t\tresult = prime * result + ((measurementName == null) ? 0 : measurementName.hashCode());\n\t\t\tresult = prime * result + ((retentionPolicy == null) ? 0 : retentionPolicy.hashCode());\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn _hash;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(final Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tfinal MeasurementKey other = (MeasurementKey) obj;\n\t\t\tif (measurementName == null) {\n\t\t\t\tif (other.measurementName != null)\n\t\t\t\t\treturn false;\n\t\t\t} else if (!measurementName.equals(other.measurementName))\n\t\t\t\treturn false;\n\t\t\tif (retentionPolicy == null) {\n\t\t\t\tif (other.retentionPolicy != null)\n\t\t\t\t\treturn false;\n\t\t\t} else if (!retentionPolicy.equals(other.retentionPolicy))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\n\t}\n}", "public interface ResultContext {\n\tpublic static final ResultContext VOID = VoidResultContext.INSTANCE;\n\n\tpublic boolean hasResult();\n\n\tpublic boolean hasError();\n\n\tpublic String getErrorMessage();\n\n\tpublic Object getValue();\n}", "public class WrapperResultContext implements ResultContext {\n\n\tprivate final Object value;\n\n\tprivate final boolean hasResult;\n\n\tpublic WrapperResultContext() {\n\t\tvalue = null;\n\t\thasResult = false;\n\t}\n\n\tpublic WrapperResultContext(Object value) {\n\t\tthis.value = value;\n\t\thasResult = true;\n\t}\n\n\t@Override\n\tpublic boolean hasResult() {\n\t\treturn hasResult;\n\t}\n\n\t@Override\n\tpublic boolean hasError() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String getErrorMessage() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Object getValue() {\n\t\treturn value;\n\t}\n\n}" ]
import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import org.springframework.util.CollectionUtils; import com.vgerbot.orm.influxdb.InfluxDBDao; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.binding.MapperMethod; import com.vgerbot.orm.influxdb.binding.MethodSignature; import com.vgerbot.orm.influxdb.metadata.MeasurementClassMetadata; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.repo.InfluxDBRepository; import com.vgerbot.orm.influxdb.result.ResultContext; import com.vgerbot.orm.influxdb.result.WrapperResultContext;
package com.vgerbot.orm.influxdb.exec; public class ImplementationExecutor extends Executor { private ConcurrentMap<MeasurementClassMetadata, InfluxDBDao<Serializable>> implementationCache = new ConcurrentHashMap<>(); public ImplementationExecutor(InfluxDBRepository repository) { super(repository); } @Override public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) {
MethodSignature methodSignature = method.getMethodSignature();
3
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/GraphEditor.java
[ "public interface GConnection extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Source</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Source</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Source</em>' reference.\n\t * @see #setSource(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Source()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getSource();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getSource <em>Source</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Source</em>' reference.\n\t * @see #getSource()\n\t * @generated\n\t */\n\tvoid setSource(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Target</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Target</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Target</em>' reference.\n\t * @see #setTarget(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Target()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getTarget();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getTarget <em>Target</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Target</em>' reference.\n\t * @see #getTarget()\n\t * @generated\n\t */\n\tvoid setTarget(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Joints</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GJoint}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GJoint#getConnection <em>Connection</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Joints</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Joints</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Joints()\n\t * @see de.tesis.dynaware.grapheditor.model.GJoint#getConnection\n\t * @model opposite=\"connection\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GJoint> getJoints();\n\n} // GConnection", "public interface GModel extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Nodes</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GNode}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Nodes</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Nodes</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Nodes()\n\t * @model containment=\"true\"\n\t * @generated\n\t */\n\tEList<GNode> getNodes();\n\n\t/**\n\t * Returns the value of the '<em><b>Connections</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnection}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connections</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connections</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Connections()\n\t * @model containment=\"true\"\n\t * @generated\n\t */\n\tEList<GConnection> getConnections();\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Content Width</b></em>' attribute.\n\t * The default value is <code>\"3000\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Content Width</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Content Width</em>' attribute.\n\t * @see #setContentWidth(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_ContentWidth()\n\t * @model default=\"3000\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getContentWidth();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getContentWidth <em>Content Width</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Content Width</em>' attribute.\n\t * @see #getContentWidth()\n\t * @generated\n\t */\n\tvoid setContentWidth(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Content Height</b></em>' attribute.\n\t * The default value is <code>\"2250\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Content Height</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Content Height</em>' attribute.\n\t * @see #setContentHeight(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_ContentHeight()\n\t * @model default=\"2250\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getContentHeight();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getContentHeight <em>Content Height</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Content Height</em>' attribute.\n\t * @see #getContentHeight()\n\t * @generated\n\t */\n\tvoid setContentHeight(double value);\n\n} // GModel", "public interface GNode extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_X()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Y()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Width</b></em>' attribute.\n\t * The default value is <code>\"151\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Width</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Width</em>' attribute.\n\t * @see #setWidth(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Width()\n\t * @model default=\"151\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getWidth();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getWidth <em>Width</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Width</em>' attribute.\n\t * @see #getWidth()\n\t * @generated\n\t */\n\tvoid setWidth(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Height</b></em>' attribute.\n\t * The default value is <code>\"101\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Height</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Height</em>' attribute.\n\t * @see #setHeight(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Height()\n\t * @model default=\"101\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getHeight();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getHeight <em>Height</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Height</em>' attribute.\n\t * @see #getHeight()\n\t * @generated\n\t */\n\tvoid setHeight(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connectors</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnector}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GConnector#getParent <em>Parent</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connectors</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connectors</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Connectors()\n\t * @see de.tesis.dynaware.grapheditor.model.GConnector#getParent\n\t * @model opposite=\"parent\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GConnector> getConnectors();\n\n} // GNode", "public class GraphEditorProperties implements GraphEventManager\n{\n\n /**\n * The default max width of the editor region, set on startup.\n */\n public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE;\n /**\n * The default max height of the editor region, set on startup.\n */\n public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE;\n\n public static final double DEFAULT_BOUND_VALUE = 15;\n public static final double DEFAULT_GRID_SPACING = 12;\n\n // The distance from the editor edge at which the objects should stop when dragged / resized.\n private double northBoundValue = DEFAULT_BOUND_VALUE;\n private double southBoundValue = DEFAULT_BOUND_VALUE;\n private double eastBoundValue = DEFAULT_BOUND_VALUE;\n private double westBoundValue = DEFAULT_BOUND_VALUE;\n\n // Off by default.\n private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, \"gridVisible\"); //$NON-NLS-1$\n private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, \"snapToGrid\"); //$NON-NLS-1$\n private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, \"gridSpacing\", DEFAULT_GRID_SPACING); //$NON-NLS-1$\n\n private final Map<EditorElement, BooleanProperty> readOnly = new EnumMap<>(EditorElement.class);\n\n private final ObservableMap<String, String> customProperties = FXCollections.observableHashMap();\n\n private final GraphEventManager eventManager = new GraphEventManagerImpl();\n\n /**\n * Creates a new editor properties instance containing a set of default\n * properties.\n */\n public GraphEditorProperties()\n {\n }\n\n /**\n * Copy constructor.\n *\n * <p>\n * Creates a new editor properties instance with all values copied over from\n * an existing instance.\n * </p>\n *\n * @param editorProperties\n * an existing {@link GraphEditorProperties} instance\n */\n public GraphEditorProperties(final GraphEditorProperties editorProperties)\n {\n northBoundValue = editorProperties.getNorthBoundValue();\n southBoundValue = editorProperties.getSouthBoundValue();\n eastBoundValue = editorProperties.getEastBoundValue();\n westBoundValue = editorProperties.getWestBoundValue();\n\n gridVisible.set(editorProperties.isGridVisible());\n snapToGrid.set(editorProperties.isSnapToGridOn());\n gridSpacing.set(editorProperties.getGridSpacing());\n\n for (final Map.Entry<EditorElement, BooleanProperty> entry : editorProperties.readOnly.entrySet())\n {\n readOnly.computeIfAbsent(entry.getKey(), k -> new SimpleBooleanProperty()).set(entry.getValue().get());\n }\n\n customProperties.putAll(editorProperties.getCustomProperties());\n }\n\n /**\n * Gets the value of the north bound.\n *\n * @return the value of the north bound\n */\n public double getNorthBoundValue()\n {\n return northBoundValue;\n }\n\n /**\n * Sets the value of the north bound.\n *\n * @param pNorthBoundValue\n * the value of the north bound\n */\n public void setNorthBoundValue(final double pNorthBoundValue)\n {\n northBoundValue = pNorthBoundValue;\n }\n\n /**\n * Gets the value of the south bound.\n *\n * @return the value of the south bound\n */\n public double getSouthBoundValue()\n {\n return southBoundValue;\n }\n\n /**\n * Sets the value of the south bound.\n *\n * @param pSouthBoundValue\n * the value of the south bound\n */\n public void setSouthBoundValue(final double pSouthBoundValue)\n {\n southBoundValue = pSouthBoundValue;\n }\n\n /**\n * Gets the value of the east bound.\n *\n * @return the value of the east bound\n */\n public double getEastBoundValue()\n {\n return eastBoundValue;\n }\n\n /**\n * Sets the value of the east bound.\n *\n * @param pEastBoundValue\n * the value of the east bound\n */\n public void setEastBoundValue(final double pEastBoundValue)\n {\n eastBoundValue = pEastBoundValue;\n }\n\n /**\n * Gets the value of the west bound.\n *\n * @return the value of the west bound\n */\n public double getWestBoundValue()\n {\n return westBoundValue;\n }\n\n /**\n * Sets the value of the west bound.\n *\n * @param pWestBoundValue\n * the value of the west bound\n */\n public void setWestBoundValue(final double pWestBoundValue)\n {\n westBoundValue = pWestBoundValue;\n }\n\n /**\n * Checks if the background grid is visible.\n *\n * @return {@code true} if the background grid is visible, {@code false} if\n * not\n */\n public boolean isGridVisible()\n {\n return gridVisible.get();\n }\n\n /**\n * Sets whether the background grid should be visible or not.\n *\n * @param pGridVisible\n * {@code true} if the background grid should be visible,\n * {@code false} if not\n */\n public void setGridVisible(final boolean pGridVisible)\n {\n gridVisible.set(pGridVisible);\n }\n\n /**\n * Gets the grid-visible property.\n *\n * @return a {@link BooleanProperty} tracking whether the grid is visible or\n * not\n */\n public BooleanProperty gridVisibleProperty()\n {\n return gridVisible;\n }\n\n /**\n * Checks if snap-to-grid is on.\n *\n * @return {@code true} if snap-to-grid is on, {@code false} if not\n */\n public boolean isSnapToGridOn()\n {\n return snapToGrid.get();\n }\n\n /**\n * Sets whether snap-to-grid should be on.\n *\n * @param pSnapToGrid\n * {@code true} if snap-to-grid should be on, {@code false} if\n * not\n */\n public void setSnapToGrid(final boolean pSnapToGrid)\n {\n snapToGrid.set(pSnapToGrid);\n }\n\n /**\n * Gets the snap-to-grid property.\n *\n * @return a {@link BooleanProperty} tracking whether snap-to-grid is on or\n * off\n */\n public BooleanProperty snapToGridProperty()\n {\n return snapToGrid;\n }\n\n /**\n * Gets the current grid spacing in pixels.\n *\n * @return the current grid spacing\n */\n public double getGridSpacing()\n {\n return gridSpacing.get();\n }\n\n /**\n * Sets the grid spacing to be used if the grid is visible and/or\n * snap-to-grid is enabled.\n *\n * <p>\n * Integer values are recommended to avoid sub-pixel positioning effects.\n * </p>\n *\n * @param pGridSpacing\n * the grid spacing to be used\n */\n public void setGridSpacing(final double pGridSpacing)\n {\n gridSpacing.set(pGridSpacing);\n }\n\n /**\n * Gets the grid spacing property.\n *\n * @return the grid spacing {@link DoubleProperty}.\n */\n public DoubleProperty gridSpacingProperty()\n {\n return gridSpacing;\n }\n\n /**\n * Gets the read only property\n *\n * @param pType\n * {@link EditorElement}\n * @return read only {@link BooleanProperty}\n */\n public BooleanProperty readOnlyProperty(final EditorElement pType)\n {\n Objects.requireNonNull(pType, \"ElementType may not be null!\");\n return readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty());\n }\n\n /**\n * Returns whether or not the graph is in read only state.\n *\n * @param pType\n * {@link EditorElement}\n * @return whether or not the graph is in read only state.\n */\n public boolean isReadOnly(final EditorElement pType)\n {\n return pType != null && readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty()).get();\n }\n\n /**\n * @param pType\n * {@link EditorElement}\n * @param pReadOnly\n * {@code true} to set the graph editor in read only state or {@code false} (default) for edit state.\n */\n public void setReadOnly(final EditorElement pType, final boolean pReadOnly)\n {\n if (pType != null)\n {\n readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty()).set(pReadOnly);\n }\n }\n\n /**\n * Additional properties that may be added and referred to in custom skin\n * implementations.\n *\n * @return a map of custom properties\n */\n public ObservableMap<String, String> getCustomProperties()\n {\n return customProperties;\n }\n\n @Override\n public boolean activateGesture(GraphInputGesture pGesture, Event pEvent, Object pOwner)\n {\n return eventManager.activateGesture(pGesture, pEvent, pOwner);\n }\n\n @Override\n public boolean finishGesture(GraphInputGesture pExpected, Object pOwner)\n {\n return eventManager.finishGesture(pExpected, pOwner);\n }\n}", "public final class RemoveContext\n{\n\n private final Collection<EObject> objectsToDelete = new HashSet<>();\n\n /**\n * Constructor\n *\n * @since 15.02.2019\n */\n public RemoveContext()\n {\n // Auto-generated constructor stub\n }\n\n /**\n * @param pToCheck\n * {@link EObject} to check\n * @return {@code true} if no other involved party has created a delete\n * command for the given object otherwise {@code false}\n * @since 15.02.2019\n */\n public boolean canRemove(final EObject pToCheck)\n {\n return objectsToDelete.add(pToCheck);\n }\n\n /**\n * @param pToCheck\n * {@link EObject} to check\n * @return {@code true} any involved party has created a delete command for\n * the given object otherwise {@code false}\n * @since 15.02.2019\n */\n public boolean contains(final EObject pToCheck)\n {\n return objectsToDelete.contains(pToCheck);\n }\n}" ]
import java.util.Collection; import java.util.function.BiFunction; import java.util.function.Function; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.ecore.EObject; import de.tesis.dynaware.grapheditor.model.GConnection; import de.tesis.dynaware.grapheditor.model.GModel; import de.tesis.dynaware.grapheditor.model.GNode; import de.tesis.dynaware.grapheditor.utils.GraphEditorProperties; import de.tesis.dynaware.grapheditor.utils.RemoveContext; import javafx.beans.property.ObjectProperty; import javafx.scene.layout.Region;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor; /** * Provides functionality for displaying and editing graph-like diagrams in * JavaFX. * * <p> * Example: * * <pre> * <code>GModel model = GraphFactory.eINSTANCE.createGModel(); * * GraphEditor graphEditor = new DefaultGraphEditor(); * graphEditor.setModel(model); * * Region view = graphEditor.getView();</code> * </pre> * * The view is a {@link Region} and can be added to the JavaFX scene graph in * the usual way. For large graphs, the editor can be put inside a pannable * container (see module core) instead. * </p> * * <p> * The editor updates its underlying model via EMF commands. This means any user * action should be undoable. Helper methods for common operations are provided * in the {@link Commands} class, such as: * * <ul> * <li>Add Node</li> * <li>Clear All</li> * <li>Undo</li> * <li>Redo</li> * </ul> * * </p> * * <p> * Look and feel can be customised by setting custom skin classes. The default * skins can also be customised to some extent via CSS. See <b>defaults.css</b> * in the core module for more information. * </p> */ public interface GraphEditor extends GraphEditorSkins { /** * Sets a custom connector validator. * * <p> * This will be used to decide which connections are allowed / forbidden during drag and drop events in the editor. * </p> * * @param validator a custom validator implements {@link GConnectorValidator}, or null to use the default validator */ void setConnectorValidator(final GConnectorValidator validator); /** * Sets the graph model to be edited. * * @param model the {@link GModel} to be edited */ void setModel(final GModel model); /** * Gets the graph model that is currently being edited. * * @return the {@link GModel} being edited, or {@code null} if no model was ever set */ GModel getModel(); /** * Reloads the graph model currently being edited. * * <p> * <b>Note: </b><br> * If the model is updated via EMF commands, as is recommended, it should rarely be necessary to call this method. * The model will be reloaded automatically via a command-stack listener. * </p> */ void reload(); /** * The property containing the graph model being edited. * * @return a property containing the {@link GModel} being edited */ ObjectProperty<GModel> modelProperty(); /** * Gets the view where the graph is displayed and edited. * * <p> * The view is a JavaFX {@link Region}. It should be added to the scene * graph in the usual way. * </p> * * @return the {@link Region} where the graph is displayed and edited */ Region getView(); /** * Gets the properties of the editor. * * <p> * This provides access to global properties such as: * * <ul> * <li>Show/hide alignment grid.</li> * <li>Toggle snap-to-grid on/off.</li> * <li>Toggle editor bounds on/off.</li> * </ul> * * </p> * * @return an {@link GraphEditorProperties} instance containing the properties of the editor */ GraphEditorProperties getProperties(); /** * Gets the skin lookup. * * <p> * The skin lookup is used to get any skin instance associated to a model element instance. * </p> * * @return a {@link SkinLookup} used to lookup skins */ SkinLookup getSkinLookup(); /** * Gets the selection manager. * * <p> * The selection manager keeps track of the selected nodes, connections, * etc. * </p> * * @return the {@link SelectionManager} */ SelectionManager getSelectionManager(); /** * Sets a method to be called when a connection is created in the editor. * * <p> * This can be used to append additional commands to the one that created the connection. * </p> * * @param consumer a consumer to append additional commands */ void setOnConnectionCreated(Function<GConnection, Command> consumer); /** * Sets a method to be called when a connection is removed in the editor. * * <p> * This can be used to create additional commands to the one that removed * the connection. * </p> * * @param pOnConnectionRemoved * a {@link BiFunction} creating the additional command */
void setOnConnectionRemoved(BiFunction<RemoveContext, GConnection, Command> pOnConnectionRemoved);
4
rapidpro/surveyor
app/src/main/java/io/rapidpro/surveyor/data/Submission.java
[ "public class Logger {\n\n private static final String TAG = \"Surveyor\";\n\n public static void e(String message, Throwable t) {\n Log.e(TAG, message, t);\n }\n\n public static void w(String message) {\n Log.w(TAG, message);\n }\n\n public static void d(String message) {\n Log.d(TAG, message);\n }\n}", "public class SurveyorApplication extends Application {\n\n /**\n * The singleton instance of this application\n */\n private static SurveyorApplication s_this;\n\n /**\n * Service for network operations\n */\n private TembaService tembaService = null;\n\n /**\n * Service for local org operations\n */\n private OrgService orgService = null;\n\n /**\n * Service for local submission operations\n */\n private SubmissionService submissionService = null;\n\n /**\n * Gets the singleton instance of this application\n *\n * @return the instance\n */\n public static SurveyorApplication get() {\n return s_this;\n }\n\n @Override\n public void onCreate() {\n Logger.d(\"Creating Surveyor application...\");\n\n super.onCreate();\n\n Logger.d(\"External storage dir=\" + Environment.getExternalStorageDirectory() + \" state=\" + Environment.getExternalStorageState() + \" emulated=\" + Environment.isExternalStorageEmulated());\n\n s_this = this;\n\n tembaService = new TembaService(getTembaHost());\n\n try {\n orgService = new OrgService(getOrgsDirectory());\n submissionService = new SubmissionService(getSubmissionsDirectory());\n } catch (IOException e) {\n Logger.e(\"Unable to create directory based services\", e);\n }\n }\n\n /**\n * Gets the name of the preferences file\n *\n * @return the name of the preferences\n */\n public String getPreferencesName() {\n return \"default\";\n }\n\n /**\n * Gets the shared preferences for this application\n *\n * @return the preferences\n */\n public SharedPreferences getPreferences() {\n return s_this.getSharedPreferences(getPreferencesName(), Context.MODE_PRIVATE);\n }\n\n /**\n * Saves a string shared preference for this application\n *\n * @param key the preference key\n * @param value the preference value\n */\n public void setPreference(String key, String value) {\n getPreferences().edit().putString(key, value).apply();\n }\n\n /**\n * Saves a string-set shared preference for this application\n *\n * @param key the preference key\n * @param values the preference value\n */\n public void setPreference(String key, Set<String> values) {\n getPreferences().edit().putStringSet(key, values).apply();\n }\n\n /**\n * Clears a shared preference for this application\n *\n * @param key the preference key\n */\n public void clearPreference(String key) {\n getPreferences().edit().remove(key).apply();\n }\n\n /**\n * Gets the base URL of the Temba instance we're connected to\n *\n * @return the base URL\n */\n public String getTembaHost() {\n String host = getPreferences().getString(SurveyorPreferences.HOST, getString(R.string.pref_default_host));\n\n // strip any trailing slash\n if (host.endsWith(\"/\")) {\n host = host.substring(0, host.length() - 1);\n }\n\n return host;\n }\n\n /**\n * Called when our host setting has changed\n */\n public void onTembaHostChanged() {\n String newHost = getTembaHost();\n\n Logger.d(\"Host changed to \" + newHost);\n\n clearPreference(SurveyorPreferences.AUTH_USERNAME);\n clearPreference(SurveyorPreferences.AUTH_ORGS);\n try {\n getSubmissionService().clearAll();\n } catch (IOException e) {\n Logger.e(\"Unable to clear submissions\", e);\n }\n\n tembaService = new TembaService(newHost);\n }\n\n /**\n * Returns the Temba API service\n *\n * @return the service\n */\n public TembaService getTembaService() {\n return tembaService;\n }\n\n /**\n * Returns the local orgs service\n *\n * @return the service\n */\n public OrgService getOrgService() {\n return orgService;\n }\n\n /**\n * Returns the local submissions service\n *\n * @return the service\n */\n public SubmissionService getSubmissionService() {\n return submissionService;\n }\n\n /**\n * Gets the directory for org configurations\n *\n * @return the directory\n */\n public File getOrgsDirectory() throws IOException {\n return SurveyUtils.mkdir(getFilesDir(), \"orgs\");\n }\n\n /**\n * Gets the directory for user collected data\n *\n * @return the directory\n */\n public File getUserDirectory() {\n return getExternalFilesDir(null);\n }\n\n /**\n * Gets the submissions storage directory\n *\n * @return the directory\n */\n protected File getSubmissionsDirectory() throws IOException {\n return SurveyUtils.mkdir(getUserDirectory(), \"submissions\");\n }\n\n /**\n * Gets the URI for the given file using our application's file provider\n *\n * @param file the file\n * @return the URI\n */\n public Uri getUriForFile(File file) {\n return FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + \".provider\", file);\n }\n\n /**\n * Generate dump of the Android log\n *\n * @return the URI of the dump file\n */\n public Uri generateLogDump() throws IOException {\n // log our build and device details\n Logger.d(\"Version: \" + BuildConfig.VERSION_NAME + \"; \" + BuildConfig.VERSION_CODE);\n Logger.d(\"OS: \" + System.getProperty(\"os.version\") + \" (API \" + Build.VERSION.SDK_INT + \")\");\n Logger.d(\"Model: \" + android.os.Build.MODEL + \" (\" + android.os.Build.DEVICE + \")\");\n\n // dump log to file and return URI\n File outputFile = new File(getUserDirectory(), \"bug-report.txt\");\n Runtime.getRuntime().exec(\"logcat -d -f \" + outputFile.getAbsolutePath() + \" \\\"Surveyor:* *:E\\\"\");\n return getUriForFile(outputFile);\n }\n}", "public class EngineException extends SurveyorException {\n public EngineException(Exception e) {\n super(e.getMessage(), e);\n }\n}", "public class Session {\n private com.nyaruka.goflow.mobile.Session target;\n\n /**\n * Creates a new session\n */\n Session(com.nyaruka.goflow.mobile.Session target) {\n this.target = target;\n }\n\n /**\n * Resumes this session with a resume\n *\n * @param resume the resume\n * @return the events\n */\n public Sprint resume(Resume resume) throws EngineException {\n try {\n return Sprint.fromNative(target.resume(resume));\n } catch (Exception e) {\n throw new EngineException(e);\n }\n }\n\n /**\n * Gets the assets used by this session\n *\n * @return the assets\n */\n public SessionAssets getAssets() {\n return target.assets();\n }\n\n /**\n * Gets the status of this session\n *\n * @return the status\n */\n public String getStatus() {\n return target.status();\n }\n\n /**\n * Gets whether this session is waiting for input\n *\n * @return true if session is waiting\n */\n public boolean isWaiting() {\n return getStatus().equals(\"waiting\");\n }\n\n public Wait getWait() {\n return target.getWait();\n }\n\n /**\n * Marshals this session to JSON\n *\n * @return the JSON\n */\n public String toJSON() throws EngineException {\n try {\n return target.toJSON();\n } catch (Exception e) {\n throw new EngineException(e);\n }\n }\n}", "public class TembaException extends SurveyorException {\n public TembaException(String message) {\n super(message);\n }\n\n public TembaException(String message, Exception e) {\n super(message, e);\n }\n}", "public class SubmissionPayload {\n private RawJson session;\n private List<RawJson> modifiers;\n private List<RawJson> events;\n\n public SubmissionPayload(RawJson session, List<RawJson> modifiers, List<RawJson> events) {\n this.session = session;\n this.modifiers = modifiers;\n this.events = events;\n }\n\n public RawJson getSession() {\n return session;\n }\n\n public List<RawJson> getModifiers() {\n return modifiers;\n }\n\n public List<RawJson> getEvents() {\n return events;\n }\n}", "public class RawJson {\n private String data;\n\n public RawJson(String data) {\n this.data = data;\n }\n\n @Override\n public String toString() {\n return this.data;\n }\n\n /**\n * Type adapter to tell Gson how to use fields of this type\n */\n public static class Adapter extends TypeAdapter<RawJson> {\n @Override\n public void write(JsonWriter out, RawJson value) throws IOException {\n out.jsonValue(value.toString());\n }\n\n @Override\n public RawJson read(JsonReader in) throws IOException {\n // TODO ideally this wouldn't parse the entire tree into memory\n // see https://github.com/google/gson/issues/1368\n JsonElement parsed = new JsonParser().parse(in);\n\n return new RawJson(parsed.toString());\n }\n }\n}", "public class SurveyUtils {\n /**\n * Creates a nested directory\n *\n * @param root the root directory\n * @param folders the nested directory names\n * @return the directory\n * @throws IOException if any directory couldn't be created\n */\n public static File mkdir(File root, String... folders) throws IOException {\n File current = root;\n for (String folder : folders) {\n current = new File(current, folder);\n\n if (!current.exists() && !current.mkdirs()) {\n throw new IOException(\"Unable to create directory: \" + current.getAbsolutePath());\n }\n }\n return current;\n }\n}" ]
import android.net.Uri; import com.nyaruka.goflow.mobile.Event; import com.nyaruka.goflow.mobile.Modifier; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import io.rapidpro.surveyor.Logger; import io.rapidpro.surveyor.SurveyorApplication; import io.rapidpro.surveyor.engine.EngineException; import io.rapidpro.surveyor.engine.Session; import io.rapidpro.surveyor.net.TembaException; import io.rapidpro.surveyor.net.requests.SubmissionPayload; import io.rapidpro.surveyor.utils.RawJson; import io.rapidpro.surveyor.utils.SurveyUtils;
package io.rapidpro.surveyor.data; public class Submission { private static final String SESSION_FILE = "session.json"; private static final String MODIFIERS_FILE = "modifiers.jsonl"; private static final String EVENTS_FILE = "events.jsonl"; private static final String COMPLETION_FILE = ".completed"; private static final String MEDIA_DIR = "media"; private Org org; private File directory; /** * Creates a new submission for the given org in the given directory * * @param org the org * @param directory the directory */ public Submission(Org org, File directory) { this.org = org; this.directory = directory; } /** * Gets the UUID of this org (i.e. the name of its directory) * * @return the UUID */ public String getUuid() { return directory.getName(); } /** * Gets the org this submission belongs to * * @return the org */ public Org getOrg() { return org; } /** * Get's the directory this submission is stored in * * @return the directory */ public File getDirectory() { return directory; } /** * Get's the directory this submission's media is stored in * * @return the directory */ public File getMediaDirectory() throws IOException { return SurveyUtils.mkdir(directory, MEDIA_DIR); } /** * Gets whether this submission is complete * * @return true if complete */ public boolean isCompleted() { return new File(directory, COMPLETION_FILE).exists(); } /** * Saves the current session * * @param session the current session */ public void saveSession(Session session) throws IOException, EngineException { FileUtils.writeStringToFile(new File(directory, SESSION_FILE), session.toJSON()); } /** * Saves new modifiers to this submission * * @param modifiers the modifiers to save */ public void saveNewModifiers(List<Modifier> modifiers) throws IOException { File file = new File(directory, MODIFIERS_FILE); BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); for (Modifier mod : modifiers) { writer.write(mod.payload()); writer.newLine(); } writer.close(); } /** * Saves new events to this submission * * @param events the events to save */ public void saveNewEvents(List<Event> events) throws IOException { File file = new File(directory, EVENTS_FILE); BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); for (Event event : events) { writer.write(event.payload()); writer.newLine(); } writer.close(); } /** * Saves a new media file to this submission * * @param data the media data * @param extension the file extension * @return the URI of the saved file */ public Uri saveMedia(byte[] data, String extension) throws IOException { File file = new File(getMediaDirectory(), UUID.randomUUID().toString() + "." + extension); FileUtils.writeByteArrayToFile(file, data); return SurveyorApplication.get().getUriForFile(file); } /** * Saves a new media file to this submission * * @param src the file to copy * @return the URI of the saved file */ public Uri saveMedia(File src) throws IOException { String extension = FilenameUtils.getExtension(src.getName()); File file = new File(getMediaDirectory(), UUID.randomUUID().toString() + "." + extension); FileUtils.copyFile(src, file); return SurveyorApplication.get().getUriForFile(file); } /** * Marks this submission as completed */ public void complete() throws IOException { FileUtils.writeStringToFile(new File(directory, COMPLETION_FILE), ""); } /** * Deletes this submission from the file system */ public void delete() { try { FileUtils.deleteDirectory(directory); directory = null; } catch (IOException e) { Logger.e("Unable to delete submission " + directory.getAbsolutePath(), e); } }
public void submit() throws IOException, TembaException {
4
TonnyL/Espresso
app/src/main/java/io/github/marktony/espresso/service/ReminderService.java
[ "public class AppWidgetProvider extends android.appwidget.AppWidgetProvider {\n\n private static final String REFRESH_ACTION = \"io.github.marktony.espresso.appwidget.action.REFRESH\";\n\n public static Intent getRefreshBroadcastIntent(Context context) {\n return new Intent(REFRESH_ACTION)\n .setComponent(new ComponentName(context, AppWidgetProvider.class));\n }\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {\n for (int appWidgetId : appWidgetIds) {\n RemoteViews remoteViews = updateWidgetListView(context, appWidgetId);\n appWidgetManager.updateAppWidget(appWidgetId, remoteViews);\n }\n super.onUpdate(context, appWidgetManager, appWidgetIds);\n }\n\n private RemoteViews updateWidgetListView(Context context, int id) {\n RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.launcher_list_widget);\n\n Intent intent = new Intent(context, AppWidgetService.class);\n intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);\n intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));\n\n remoteViews.setRemoteAdapter(R.id.listViewWidget, intent);\n remoteViews.setEmptyView(R.id.listViewWidget, R.id.emptyView);\n\n Intent tempIntent = new Intent(context, PackageDetailsActivity.class);\n tempIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n remoteViews.setPendingIntentTemplate(R.id.listViewWidget,\n PendingIntent.getActivity(context, 0, tempIntent, PendingIntent.FLAG_CANCEL_CURRENT));\n\n return remoteViews;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n super.onReceive(context, intent);\n String action = intent.getAction();\n if (REFRESH_ACTION.equals(action)) {\n AppWidgetManager manager = AppWidgetManager.getInstance(context);\n ComponentName name = new ComponentName(context, AppWidgetProvider.class);\n manager.notifyAppWidgetViewDataChanged(manager.getAppWidgetIds(name), R.id.listViewWidget);\n }\n }\n\n}", "public class Package extends RealmObject {\n\n public static final int STATUS_FAILED = 2, STATUS_NORMAL = 0,\n STATUS_ON_THE_WAY = 5, STATUS_DELIVERED = 3,\n STATUS_RETURNED = 4, STATUS_RETURNING = 6,\n STATUS_OTHER = 1;\n\n @Expose\n @SerializedName(\"message\")\n private String message;\n @Expose\n @SerializedName(\"nu\")\n @PrimaryKey\n private String number;\n @Expose\n @SerializedName(\"ischeck\")\n private String isCheck;\n @Expose\n @SerializedName(\"condition\")\n private String condition;\n @Expose\n @SerializedName(\"com\")\n private String company;\n @Expose\n @SerializedName(\"status\")\n private String status;\n @Expose\n @SerializedName(\"state\")\n private String state;\n @Expose\n @SerializedName(\"data\")\n private RealmList<PackageStatus> data;\n\n @Expose\n private boolean pushable = false;\n @Expose\n private boolean readable = false;\n @Expose\n private String name;\n @Expose\n private String companyChineseName;\n @Expose\n private int colorAvatar;\n @Expose\n private long timestamp;\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public String getNumber() {\n return number;\n }\n\n public void setNumber(String number) {\n this.number = number;\n }\n\n public String getIsCheck() {\n return isCheck;\n }\n\n public void setIsCheck(String isCheck) {\n this.isCheck = isCheck;\n }\n\n public String getCondition() {\n return condition;\n }\n\n public void setCondition(String condition) {\n this.condition = condition;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public RealmList<PackageStatus> getData() {\n return data;\n }\n\n public void setData(RealmList<PackageStatus> data) {\n this.data = data;\n }\n\n public boolean isReadable() {\n return readable;\n }\n\n public void setReadable(boolean readable) {\n this.readable = readable;\n }\n\n public String getCompany() {\n return company;\n }\n\n public void setCompany(String company) {\n this.company = company;\n }\n\n public boolean isPushable() {\n return pushable;\n }\n\n public void setPushable(boolean pushable) {\n this.pushable = pushable;\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 getCompanyChineseName() {\n return companyChineseName;\n }\n\n public void setCompanyChineseName(String companyChineseName) {\n this.companyChineseName = companyChineseName;\n }\n\n public void setColorAvatar(int colorAvatar) {\n this.colorAvatar = colorAvatar;\n }\n\n public int getColorAvatar() {\n return colorAvatar;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n @Override\n public String toString() {\n return new Gson().toJson(this);\n }\n}", "public class PackageDetailsActivity extends AppCompatActivity{\n\n private PackageDetailsFragment fragment;\n\n public static final String PACKAGE_ID = \"PACKAGE_ID\";\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.container);\n\n // Set the navigation bar color\n if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(\"navigation_bar_tint\", true)) {\n getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));\n }\n\n // Restore the status.\n if (savedInstanceState != null) {\n fragment = (PackageDetailsFragment) getSupportFragmentManager().getFragment(savedInstanceState, \"PackageDetailsFragment\");\n } else {\n fragment = PackageDetailsFragment.newInstance();\n }\n\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.view_pager, fragment)\n .commit();\n\n // Create the presenter.\n new PackageDetailsPresenter(\n getIntent().getStringExtra(PACKAGE_ID),\n PackagesRepository.getInstance(\n PackagesRemoteDataSource.getInstance(),\n PackagesLocalDataSource.getInstance()),\n fragment);\n\n }\n\n // Save the fragment state to bundle.\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n getSupportFragmentManager().putFragment(outState, \"PackageDetailsFragment\", fragment);\n }\n\n}", "public class RealmHelper {\n\n public static final String DATABASE_NAME = \"Espresso.realm\";\n\n public static Realm newRealmInstance() {\n return Realm.getInstance(new RealmConfiguration.Builder()\n .deleteRealmIfMigrationNeeded()\n .name(RealmHelper.DATABASE_NAME)\n .build());\n }\n\n}", "public class RetrofitClient {\n\n private RetrofitClient() {}\n\n private static class ClientHolder {\n private static Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(Api.API_BASE)\n .addCallAdapterFactory(RxJava2CallAdapterFactory.create())\n .addConverterFactory(GsonConverterFactory.create())\n .build();\n }\n\n public static Retrofit getInstance() {\n return ClientHolder.retrofit;\n }\n\n}", "public interface RetrofitService {\n\n @GET(Api.COMPANY_QUERY)\n Observable<CompanyRecognition> query(@Query(\"text\") String number);\n\n @GET(Api.PACKAGE_STATE)\n Observable<Package> getPackageState(@Query(\"type\") String type, @Query(\"postid\") String postId);\n\n}", "public class NetworkUtil {\n\n // whether connect to internet\n public static boolean networkConnected(Context context){\n\n if (context != null){\n ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo info = manager.getActiveNetworkInfo();\n if (info != null)\n return info.isAvailable();\n }\n\n return false;\n }\n\n}", "public class PushUtil {\n\n public static final String TAG = PushUtil.class.getSimpleName();\n\n public static void startAlarmService(Context context, Class<?> service, long interval) {\n\n boolean alert = PreferenceManager.getDefaultSharedPreferences(context)\n .getBoolean(SettingsUtil.KEY_ALERT, true);\n\n if (alert) {\n AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, service);\n PendingIntent pendingIntent = PendingIntent.getService(context, 10000, intent, PendingIntent.FLAG_CANCEL_CURRENT);\n manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, pendingIntent);\n Log.d(TAG, \"startAlarmService\");\n }\n }\n\n public static void stopAlarmService(Context context, Class<?> service) {\n AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, service);\n PendingIntent pendingIntent = PendingIntent.getService(context, 10000, intent, PendingIntent.FLAG_CANCEL_CURRENT);\n manager.cancel(pendingIntent);\n Log.d(TAG, \"stopAlarmService\");\n }\n\n public static void startReminderService(Context context) {\n // Default value is 30 minutes\n int intervalTime = getIntervalTime(Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(context)\n .getString(SettingsUtil.KEY_NOTIFICATION_INTERVAL, \"1\")));\n if (intervalTime > -1) {\n startAlarmService(context, ReminderService.class, intervalTime);\n Log.d(TAG, \"startReminderService: interval time \" + intervalTime);\n }\n }\n\n public static void stopReminderService(Context context) {\n stopAlarmService(context, ReminderService.class);\n }\n\n public static void restartReminderService(Context context) {\n stopReminderService(context);\n startReminderService(context);\n }\n\n public static boolean isInDisturbTime(Context context, Calendar calendar) {\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n int startHour = sp.getInt(SettingsUtil.KEY_DO_NOT_DISTURB_MODE_START_HOUR, 23);\n int startMinute = sp.getInt(SettingsUtil.KEY_DO_NOT_DISTURB_MODE_START_MINUTE, 0);\n int endHour = sp.getInt(SettingsUtil.KEY_DO_NOT_DISTURB_MODE_END_HOUR, 6);\n int endMinute = sp.getInt(SettingsUtil.KEY_DO_NOT_DISTURB_MODE_END_MINUTE, 0);\n int nowHour = calendar.get(Calendar.HOUR_OF_DAY);\n int nowMinute = calendar.get(Calendar.MINUTE);\n return (nowHour >= startHour && nowMinute >= startMinute) && (nowHour <= endHour && nowMinute <= endMinute);\n }\n\n public static int getIntervalTime(int id) {\n switch (id) {\n case 0:\n return 10 * 60 * 1000; // 10 minutes\n case 1:\n return 30 * 60 * 1000; // 30 minutes\n case 2:\n return 60 * 60 * 1000; // 1 hour\n case 3:\n return 90 * 60 * 1000; // 1.5 hours\n case 4:\n return 120 * 60 * 1000; // 2 hours\n default:\n return -1;\n }\n }\n\n}", "public class SettingsUtil {\n\n public static final String KEY_ALERT = \"alert\";\n public static final String KEY_DO_NOT_DISTURB_MODE = \"do_not_disturb_mode\";\n public static final String KEY_DO_NOT_DISTURB_MODE_START_HOUR = \"do_not_disturb_mode_start_hour\";\n public static final String KEY_DO_NOT_DISTURB_MODE_START_MINUTE = \"do_not_disturb_mode_start_minute\";\n public static final String KEY_DO_NOT_DISTURB_MODE_END_HOUR = \"do_not_disturb_mode_end_hour\";\n public static final String KEY_DO_NOT_DISTURB_MODE_END_MINUTE = \"do_not_disturb_mode_end_minute\";\n public static final String KEY_NOTIFICATION_INTERVAL = \"notification_interval\";\n\n public static final String KEY_FIRST_LAUNCH = \"first_launch\";\n\n public static final String KEY_CUSTOM_TABS = \"chrome_custom_tabs\";\n\n public static final String KEY_NIGHT_MODE = \"night_mode\";\n\n}" ]
import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.RingtoneManager; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.NotificationCompat; import android.support.v7.preference.PreferenceManager; import android.util.Log; import java.util.Calendar; import java.util.List; import io.github.marktony.espresso.R; import io.github.marktony.espresso.appwidget.AppWidgetProvider; import io.github.marktony.espresso.data.Package; import io.github.marktony.espresso.mvp.packagedetails.PackageDetailsActivity; import io.github.marktony.espresso.realm.RealmHelper; import io.github.marktony.espresso.retrofit.RetrofitClient; import io.github.marktony.espresso.retrofit.RetrofitService; import io.github.marktony.espresso.util.NetworkUtil; import io.github.marktony.espresso.util.PushUtil; import io.github.marktony.espresso.util.SettingsUtil; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import io.realm.Realm;
/* * Copyright(c) 2017 lizhaotailang * * 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.github.marktony.espresso.service; /** * Created by lizhaotailang on 2017/3/8. * Background service to build notifications and send them to user. */ public class ReminderService extends IntentService { private SharedPreferences preference; private CompositeDisposable compositeDisposable; public static final String TAG = ReminderService.class.getSimpleName(); /** * Creates an IntentService. Invoked by your subclass's constructor. */ public ReminderService() { super(TAG); } @Override public void onCreate() { super.onCreate(); preference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); compositeDisposable = new CompositeDisposable(); Log.d(TAG, "onCreate: "); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override protected void onHandleIntent(@Nullable Intent intent) { Log.d(TAG, "onHandleIntent: "); boolean isDisturbMode = preference.getBoolean(SettingsUtil.KEY_DO_NOT_DISTURB_MODE, true); // The alert mode is off // or DO-NOT-DISTURB-MODE is off // or time now is not in the DO-NOT-DISTURB-MODE range. if (isDisturbMode && PushUtil.isInDisturbTime(this, Calendar.getInstance())) { return; } Realm rlm = RealmHelper.newRealmInstance(); List<Package> results = rlm.copyFromRealm( rlm.where(Package.class) .notEqualTo("state", String.valueOf(Package.STATUS_DELIVERED)) .findAll()); for (int i = 0; i < results.size(); i++){ Package p = results.get(i); // Avoid repeated pushing if (p.isPushable()) { Realm realm = RealmHelper.newRealmInstance(); p.setPushable(false); pushNotification(i + 1001, setNotifications(i, p)); realm.beginTransaction(); realm.copyToRealmOrUpdate(p); realm.commitTransaction(); realm.close(); } else if (NetworkUtil.networkConnected(getApplicationContext())) { refreshPackage(i, results.get(i)); } } rlm.close(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand: "); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); compositeDisposable.clear(); Log.d(TAG, "onDestroy: "); } private static Notification buildNotification(Context context, String title, String subject, String longText, String time, int icon, int color, PendingIntent contentIntent, PendingIntent deleteIntent) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setContentTitle(title); builder.setContentText(subject); builder.setPriority(NotificationCompat.PRIORITY_MAX); builder.setStyle(new NotificationCompat.BigTextStyle(builder).bigText(longText)); builder.setSmallIcon(icon); builder.setShowWhen(true); builder.setWhen(System.currentTimeMillis()); builder.setContentIntent(contentIntent); builder.setSubText(time); builder.setAutoCancel(true); builder.setColor(color); return builder.build(); } /** * Set the details like title, subject, etc. of notifications. * @param position Position. * @param pkg The package. * @return The notification. */ private Notification setNotifications(int position, Package pkg) { if (pkg != null) {
Intent i = new Intent(getApplicationContext(), PackageDetailsActivity.class);
2
WetABQ/Nukkit-AntiCheat
src/main/java/top/dreamcity/AntiCheat/AntiCheat.java
[ "public class Report extends AsyncTask {\r\n protected Player player;\r\n\r\n public Report(Player player) {\r\n this.player = player;\r\n }\r\n\r\n public void onRun() {\r\n\r\n }\r\n}\r", "public class CheckChatThread extends AsyncTask {\r\n\r\n private static HashMap<String, Integer> playerChat = new HashMap<>();\r\n\r\n public CheckChatThread() {\r\n Server.getInstance().getScheduler().scheduleAsyncTask(AntiCheatAPI.getInstance(), this);\r\n }\r\n\r\n public void onRun() {\r\n while (true) {\r\n try {\r\n for (Player player : Server.getInstance().getOnlinePlayers().values()) {\r\n if (playerChat.containsKey(player.getName())) {\r\n if (playerChat.get(player.getName()) > 0) {\r\n playerChat.put(player.getName(), playerChat.get(player.getName()) - 1);\r\n } else {\r\n playerChat.remove(player.getName());\r\n }\r\n }\r\n }\r\n Thread.sleep(1000);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n public static void addPlayer(String name) {\r\n playerChat.put(name, AntiCheatAPI.getInstance().getMasterConfig().getChatSec());\r\n }\r\n\r\n public static boolean hasPlayer(String name) {\r\n return playerChat.containsKey(name);\r\n }\r\n\r\n}\r", "public class AntiFlyThread extends AsyncTask {\r\n\r\n\r\n private HashSet<String> playerThread = new HashSet<>();\r\n //private HashMap<String,Integer> Flycount = new HashMap<>();\r\n\r\n public AntiFlyThread() {\r\n Server.getInstance().getScheduler().scheduleAsyncTask(AntiCheatAPI.getInstance(), this);\r\n }\r\n\r\n public void onRun() {\r\n while (true) {\r\n try {\r\n Map<UUID, Player> players = new HashMap<>(Server.getInstance().getOnlinePlayers());\r\n for (Player player : players.values()) {\r\n if (player.isOnline() && !player.isOp() && player.getGamemode() == 0) {\r\n if (!playerThread.contains(player.getName())) {\r\n new AntiFlyPlayerThread(player);\r\n playerThread.add(player.getName());\r\n }\r\n }\r\n }\r\n for (String name : playerThread) {\r\n if (Server.getInstance().getPlayerExact(name) == null) {\r\n playerThread.remove(name);\r\n }\r\n }\r\n Thread.sleep(1000);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\r\n }\r\n }\r\n}\r", "public class AntiSpeedThread extends AsyncTask {\r\n\r\n //private static HashMap<String,HashMap<Integer,Float>> moveSpeed = new HashMap<>();\r\n private static HashMap<String, Float> finalSpeed = new HashMap<>();\r\n public static HashMap<String, Position> positionHashMap = new HashMap<>();\r\n private static HashMap<String, Long> timeCheck = new HashMap<>();\r\n private static HashMap<String, Integer> highJump = new HashMap<>();\r\n\r\n public AntiSpeedThread() {\r\n Server.getInstance().getScheduler().scheduleAsyncTask(AntiCheatAPI.getInstance(), this);\r\n }\r\n\r\n public void onRun() {\r\n while (true) {\r\n try {\r\n Map<UUID, Player> players = new HashMap<>(Server.getInstance().getOnlinePlayers());\r\n for (Player player : players.values()) {\r\n for (String name : highJump.keySet()) {\r\n if (Server.getInstance().getPlayerExact(name) == null) {\r\n highJump.remove(name);\r\n }\r\n }\r\n if (positionHashMap.containsKey(player.getName())) {\r\n if (!EventListener.tp.containsKey(player.getName())) {\r\n Position from = positionHashMap.get(player.getName());\r\n Position to = player.getPosition();\r\n float move = ((float) Math.sqrt(Math.pow((int) from.x - (int) to.x, 2) + Math.pow((int) from.z - (int) to.z, 2))) - (float) 0.1 * (System.currentTimeMillis() - timeCheck.get(player.getName()) - 1000);\r\n //putMove(player.getName(),move);\r\n if (player.hasEffect(1)) {\r\n Effect speed = player.getEffect(1);\r\n if (speed.getAmplifier() > 0) {\r\n int i = speed.getAmplifier() + 1;\r\n if (i <= 2) {\r\n double fsp = (double) i * 0.2D;\r\n move = move - (float) fsp;\r\n } else {\r\n double fsp = (double) i * 0.4D;\r\n move = move - (float) fsp;\r\n }\r\n }\r\n }\r\n if (move < 0) {\r\n move = 0;\r\n }\r\n setFinalMove(player.getName(), move);\r\n positionHashMap.put(player.getName(), player.getPosition());\r\n timeCheck.put(player.getName(), System.currentTimeMillis());\r\n } else {\r\n if (EventListener.tp.get(player.getName()) > 0) {\r\n EventListener.tp.put(player.getName(), EventListener.tp.get(player.getName()) - 1);\r\n setFinalMove(player.getName(), 0);\r\n positionHashMap.put(player.getName(), player.getPosition());\r\n timeCheck.put(player.getName(), System.currentTimeMillis());\r\n } else {\r\n EventListener.tp.remove(player.getName());\r\n }\r\n }\r\n } else {\r\n //putMove(player.getName(),0F);\r\n setFinalMove(player.getName(), 0F);\r\n timeCheck.put(player.getName(), System.currentTimeMillis());\r\n positionHashMap.put(player.getName(), player.getPosition());\r\n }\r\n if (!player.hasEffect(3)) {\r\n MobEffectPacket pk = new MobEffectPacket();\r\n pk.eid = player.getId();\r\n pk.effectId = 3;\r\n pk.eventId = 3;\r\n player.dataPacket(pk);\r\n }\r\n if (EventListener.AntiTower.containsKey(player.getName())) {\r\n double y = EventListener.AntiTower.get(player.getName()).y;\r\n double jumpY = 1.45D;\r\n if (player.hasEffect(Effect.JUMP)) {\r\n jumpY = Math.pow((player.getEffect(Effect.JUMP).getAmplifier() + 4.2), 2) / 16D;\r\n jumpY = jumpY + 0.1;\r\n }\r\n BigDecimal b1 = new BigDecimal(Double.toString(player.y));\r\n BigDecimal b2 = new BigDecimal(Double.toString(y));\r\n double dY = b1.subtract(b2).doubleValue();\r\n if (dY > jumpY) {\r\n int groundY = 1;\r\n while (player.getLevel().getBlockIdAt((int) player.x, (int) player.y - groundY, (int) player.z) == 0 && player.isOnline()) {\r\n groundY++;\r\n }\r\n groundY -= 1;\r\n if (groundY > 1) {\r\n //System.out.println(\"high Jump!!!\");\r\n player.setMotion(new Vector3(0, 0 - groundY, 0));\r\n player.sendMessage(TextFormat.colorize(\"&cYou suspected to use HighJump cheat, please stop your behavior &eCheck: AntiCheat\"));\r\n if (highJump.containsKey(player.getName())) {\r\n highJump.put(player.getName(), highJump.get(player.getName()) + 1);\r\n if (highJump.get(player.getName()) >= 10) {\r\n Server.getInstance().broadcastMessage(TextFormat.colorize(\"&dPlayer &b\" + player.getName() + \" &6suspected to use high jump cheats kicked by AntiCheat!\"));\r\n player.kick(TextFormat.colorize(\"&cYou suspected to use high jump cheats kicked out by anti-cheat\\n&eIf you misjudge the following information to the administrator\\nCheck: AntiCheat[HighJump] HighJump:\" + highJump.get(player.getName()) + \" Speed:\" + AntiSpeedThread.getMove(player.getName())) + \" onGround:\" + player.isOnGround() + \" inAirTick:\" + player.getInAirTicks());\r\n }\r\n } else {\r\n highJump.put(player.getName(), 1);\r\n }\r\n }\r\n }\r\n EventListener.AntiTower.remove(player.getName());\r\n }\r\n //player.sendTip(TextFormat.GREEN+\" Speed: \"+getMove(player.getName()));\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getAntiSpeed()) {\r\n AntiSpeed antiSpeed = new AntiSpeed(player);\r\n if (antiSpeed.isCheat()) {\r\n AntiCheatAPI.getInstance().addRecord(player, antiSpeed.getCheatType());\r\n if (!EventListener.tp.containsKey(player.getName())) {\r\n player.sendMessage(TextFormat.RED + \"We detected that you used to accelerate. Perhaps this is a misjudgment.\");\r\n player.setMotion(new Vector3(0, 0, 0));\r\n }\r\n }\r\n }\r\n }\r\n Thread.sleep(1000);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n public static void setFinalMove(String name, float speed) {\r\n finalSpeed.put(name, speed);\r\n }\r\n\r\n public static float getMove(String name) {\r\n return finalSpeed.get(name);\r\n //return 0;\r\n }\r\n\r\n /*private void putMove(String name,float speed){\r\n HashMap<Integer,Float> move = new HashMap<>();\r\n if(moveSpeed.containsKey(name)){\r\n move = moveSpeed.get(name);\r\n if(move.get(1) < 0){\r\n move.put(1,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(2) < 0){\r\n move.put(2,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(3) < 0){\r\n move.put(3,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(4) < 0){\r\n move.put(4,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(5) < 0){\r\n move.put(5,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(6) < 0){\r\n move.put(6,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(7) < 0){\r\n move.put(7,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n if(move.get(8) < 0){\r\n move.put(8,speed);\r\n moveSpeed.put(name,move);\r\n return;\r\n }\r\n float fs = (move.get(1) +move.get(2) + move.get(3)+move.get(4)+move.get(5)+move.get(6)+move.get(7)+move.get(8));\r\n fs = fs / 8;\r\n fs = fs*10;\r\n finalSpeed.put(name,fs);\r\n //Server.getInstance().getPlayer(name).sendPopup(TextFormat.GREEN+\"Speed:\"+ fs+\" \\n\\n\\n\");\r\n move.put(1,-1F);\r\n move.put(2,-1F);\r\n move.put(3,-1F);\r\n move.put(4,-1F);\r\n move.put(5,-1F);\r\n move.put(6,-1F);\r\n move.put(7,-1F);\r\n move.put(8,-1F);\r\n moveSpeed.put(name,move);\r\n }else{\r\n move.put(1,-1F);\r\n move.put(2,-1F);\r\n move.put(3,-1F);\r\n move.put(4,-1F);\r\n move.put(5,-1F);\r\n move.put(6,-1F);\r\n move.put(7,-1F);\r\n move.put(8,-1F);\r\n moveSpeed.put(name,move);\r\n finalSpeed.put(name,0F);\r\n }\r\n }*/\r\n\r\n}\r", "public class AntiWaterWalkThread extends AsyncTask {\r\n\r\n public AntiWaterWalkThread() {\r\n Server.getInstance().getScheduler().scheduleAsyncTask(AntiCheatAPI.getInstance(), this);\r\n }\r\n\r\n public void onRun() {\r\n while (true) {\r\n try {\r\n Map<UUID, Player> players = new HashMap<>(Server.getInstance().getOnlinePlayers());\r\n for (Player player : players.values()) {\r\n if (player.isOnline() && !player.isOp() && player.getGamemode() == 0) {\r\n new AntiWaterWalkPlayerThread(player, player.isOnGround());\r\n }\r\n }\r\n Thread.sleep(7500);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\r\n }\r\n }\r\n\r\n}\r", "public class ReportCommand extends Command {\r\n\r\n public ReportCommand() {\r\n super(\"report\");\r\n this.setDescription(\"Report to the system to cheat players!\");\r\n this.setAliases(new String[]{\r\n \"r\"\r\n });\r\n this.setUsage(\"/r or /report <Player Name> <Cheat Type>\");\r\n this.setCommandParameters(new HashMap<String, CommandParameter[]>() {\r\n {\r\n put(\"1arg\", new CommandParameter[]{\r\n new CommandParameter(\"Player Name\", CommandParameter.ARG_TYPE_PLAYER, false),\r\n new CommandParameter(\"Cheat Type\", CommandParameter.ARG_TYPE_RAW_TEXT, false)\r\n });\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public boolean execute(CommandSender sender, String s, String[] args) {\r\n if (sender instanceof Player) {\r\n if (args.length != 2) {\r\n return false;\r\n }\r\n Player p = Server.getInstance().getPlayer(args[0]);\r\n if (p == null) {\r\n sender.sendMessage(TextFormat.RED + \"Player isn't online\");\r\n return true;\r\n }\r\n int type = -1;\r\n switch (args[1].toLowerCase()) {\r\n case \"加速\":\r\n case \"速度\":\r\n case \"speed\":\r\n case \"s\":\r\n case \"sp\":\r\n type = 0;\r\n break;\r\n case \"飞行\":\r\n case \"f\":\r\n case \"fly\":\r\n type = 1;\r\n break;\r\n }\r\n AntiCheat.CheatType cheatType = null;\r\n switch (type) {\r\n case 0:\r\n cheatType = AntiCheat.CheatType.SPEED;\r\n break;\r\n case 1:\r\n cheatType = AntiCheat.CheatType.FLY;\r\n break;\r\n default:\r\n sender.sendMessage(TextFormat.RED + \"Unknown type! For example: fly f 飞行 s sp speed 速度 加速\");\r\n return true;\r\n }\r\n if (AntiCheatAPI.getInstance().reportPlayer.containsKey(p.getName())) {\r\n sender.sendMessage(TextFormat.GREEN + \"Please do not repeat the report\");\r\n return true;\r\n }\r\n AntiCheatAPI.getInstance().reportPlayer.put(p.getName(), cheatType);\r\n Server.getInstance().getLogger().warning(\"Player \" + sender.getName() + \" report \" + p.getName() + \" cheat type:\" + cheatType.getTypeName());\r\n sender.sendMessage(TextFormat.GREEN + \"You successfully reported the player \" + p.getName() + \" cheat type \" + cheatType.getTypeName());\r\n addReportThread(p, cheatType);\r\n } else {\r\n sender.sendMessage(TextFormat.RED + \"You must run in game!\");\r\n }\r\n return true;\r\n }\r\n\r\n\r\n private void addReportThread(Player player, AntiCheat.CheatType type) {\r\n switch (type.getTypeName()) {\r\n case \"fly\":\r\n AntiCheatAPI.getInstance().reportThread.put(player.getName(), new ReportFlyThread(player));\r\n break;\r\n case \"speed\":\r\n AntiCheatAPI.getInstance().reportThread.put(player.getName(), new ReportSpeedThread(player));\r\n break;\r\n default:\r\n AntiCheatAPI.getInstance().reportThread.put(player.getName(), new ReportFlyThread(player));\r\n AntiCheatAPI.getInstance().reportThread.put(player.getName(), new ReportSpeedThread(player));\r\n break;\r\n }\r\n }\r\n\r\n}\r", "public class MasterConfig {\r\n\r\n private ConfigSection config;\r\n\r\n private Boolean isEmpty;\r\n\r\n private Boolean antiSpeed;\r\n\r\n private Boolean checkBB;\r\n\r\n private Boolean antiFly;\r\n\r\n private Boolean checkChat;\r\n\r\n private Boolean checkChatWord;\r\n\r\n private Boolean antiKillAura;\r\n\r\n private Boolean antiAutoAim;\r\n\r\n private Boolean antiSpeedPingCheck;\r\n\r\n private float maxMoveSpeed;\r\n\r\n private int pingNoCheckValue;\r\n\r\n private int inAirTimeCheck;\r\n\r\n private int chatSec;\r\n\r\n private int checkKillAuraCPS;\r\n\r\n private ArrayList<String> SensitiveWords;\r\n\r\n private String SkinPath;\r\n\r\n\r\n public MasterConfig(ConfigSection configSection) {\r\n config = configSection;\r\n isEmpty = config.isEmpty();\r\n init();\r\n }\r\n\r\n public void init() {\r\n if (!isEmpty) {\r\n antiSpeed = config.getBoolean(\"antiSpeed\");\r\n checkBB = config.getBoolean(\"checkBB\");\r\n antiFly = config.getBoolean(\"antiFly \");\r\n checkChat = config.getBoolean(\"checkChat\");\r\n checkChatWord = config.getBoolean(\"checkChatWord\");\r\n antiKillAura = config.getBoolean(\"antiKillAura\");\r\n antiAutoAim = config.getBoolean(\"antiAutoAim\");\r\n antiSpeedPingCheck = config.getBoolean(\"antiSpeedPingCheck\");\r\n maxMoveSpeed = (float) config.getDouble(\"maxMoveSpeed\");\r\n pingNoCheckValue = config.getInt(\"pingNoCheckValue\");\r\n inAirTimeCheck = config.getInt(\"inAirTimeCheck\");\r\n chatSec = config.getInt(\"chatSec\");\r\n checkKillAuraCPS = config.getInt(\"checkKillAuraCPS\");\r\n SensitiveWords = (ArrayList) config.get(\"SensitiveWords\");\r\n SkinPath = config.getString(\"RobotSkinPath\");\r\n } else {\r\n spawnDefaultConfig();\r\n }\r\n }\r\n\r\n public void spawnDefaultConfig() {\r\n AntiCheat.getInstance().getLogger().notice(\"Start spawning default config.\");\r\n antiSpeed = true;\r\n checkBB = true;\r\n antiFly = true;\r\n checkChat = true;\r\n checkChatWord = true;\r\n antiKillAura = true;\r\n antiAutoAim = true;\r\n antiSpeedPingCheck = true;\r\n maxMoveSpeed = 10F;\r\n pingNoCheckValue = 25;\r\n inAirTimeCheck = 5;\r\n chatSec = 2;\r\n checkKillAuraCPS = 3;\r\n SensitiveWords = new ArrayList<>();\r\n SensitiveWords.add(\"fuck\");\r\n SensitiveWords.add(\"shit\");\r\n SkinPath = AntiCheatAPI.getInstance().getDataFolder() + \"/Steve.png\";\r\n save();\r\n }\r\n\r\n public void save() {\r\n try {\r\n config.put(\"antiSpeed\", antiSpeed);\r\n config.put(\"antiSpeedPingCheck\", antiSpeedPingCheck);\r\n config.put(\"pingNoCheckValue\", pingNoCheckValue);\r\n config.put(\"maxMoveSpeed\", maxMoveSpeed);\r\n config.put(\"checkBB\", checkBB);\r\n config.put(\"antiFly\", antiFly);\r\n config.put(\"inAirTimeCheck\", inAirTimeCheck);\r\n config.put(\"checkChat\", checkChat);\r\n config.put(\"chatSec\", chatSec);\r\n config.put(\"checkChatWord\", checkChatWord);\r\n config.put(\"SensitiveWords\", SensitiveWords);\r\n config.put(\"antiKillAura\", antiKillAura);\r\n config.put(\"antiAutoAim\", antiAutoAim);\r\n config.put(\"checkKillAuraCPS\", checkKillAuraCPS);\r\n config.put(\"RobotSkinPath\", SkinPath);\r\n Config c = new Config(AntiCheat.getInstance().getDataFolder() + \"/config.yml\", Config.YAML);\r\n c.setAll(config);\r\n c.save();\r\n } catch (NullPointerException e) {\r\n spawnDefaultConfig();\r\n save();\r\n }\r\n }\r\n\r\n public boolean isEmpty() {\r\n return isEmpty;\r\n }\r\n\r\n public int getChatSec() {\r\n return chatSec;\r\n }\r\n\r\n public int getCheckKillAuraCPS() {\r\n return checkKillAuraCPS;\r\n }\r\n\r\n public int getInAirTimeCheck() {\r\n return inAirTimeCheck;\r\n }\r\n\r\n public int getPingNoCheckValue() {\r\n return pingNoCheckValue;\r\n }\r\n\r\n public ArrayList<String> getSensitiveWords() {\r\n return SensitiveWords;\r\n }\r\n\r\n public Boolean getAntiAutoAim() {\r\n return antiAutoAim;\r\n }\r\n\r\n public Boolean getAntiFly() {\r\n return antiFly;\r\n }\r\n\r\n public Boolean getAntiSpeed() {\r\n return antiSpeed;\r\n }\r\n\r\n public Boolean getAntiSpeedPingCheck() {\r\n return antiSpeedPingCheck;\r\n }\r\n\r\n public Boolean getCheckBB() {\r\n return checkBB;\r\n }\r\n\r\n public Boolean getCheckChat() {\r\n return checkChat;\r\n }\r\n\r\n public Boolean getCheckChatWord() {\r\n return checkChatWord;\r\n }\r\n\r\n public Boolean getAntiKillAura() {\r\n return antiKillAura;\r\n }\r\n\r\n public float getMaxMoveSpeed() {\r\n return maxMoveSpeed;\r\n }\r\n\r\n public String getSkinPath() {\r\n return SkinPath;\r\n }\r\n\r\n}\r", "public class PlayerCheatRecord {\r\n\r\n private ConfigSection config;\r\n\r\n public PlayerCheatRecord(ConfigSection configSection) {\r\n config = configSection;\r\n }\r\n\r\n public void addRecord(Player player, top.dreamcity.AntiCheat.Cheat.AntiCheat.CheatType cheatType) {\r\n int id = config.size() + 1;\r\n Date date = new Date();\r\n DateFormat format = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\r\n String time = format.format(date);\r\n config.put(\"#\" + id + \"|Time:\" + time, \"Player \" + player.getName() + \"(\" + player.getLocation().toString() + \")[HP:\" + player.getHealth() + \"/\" + player.getMaxHealth() + \"] try cheating(Type:\" + cheatType.getTypeName() + \").\");\r\n save();\r\n }\r\n\r\n private void save() {\r\n Config c = new Config(AntiCheat.getInstance().getDataFolder() + \"/record.yml\", Config.YAML);\r\n c.setAll(config);\r\n c.save();\r\n }\r\n\r\n}\r", "public class EventListener implements Listener {\r\n\r\n private HashMap<String, AntiAutoAim> AntiAutoAim = new HashMap<>();\r\n public static HashMap<String, Position> AntiTower = new HashMap<>();\r\n public static HashMap<String, Integer> tp = new HashMap<>();\r\n\r\n\r\n @EventHandler\r\n public void onDataPacket(DataPacketReceiveEvent event) {\r\n if (event.getPacket() instanceof PlayerActionPacket) {\r\n /*\r\n * That maybe can't AntiTower,because JavaScript Tower can't send packet;\r\n * But this can AntiFly?\r\n */\r\n if (((PlayerActionPacket) event.getPacket()).action == PlayerActionPacket.ACTION_JUMP) {\r\n Player player = event.getPlayer();\r\n if (!AntiTower.containsKey(event.getPlayer().getName())) {\r\n AntiTower.put(event.getPlayer().getName(), event.getPlayer().getPosition());\r\n } else {\r\n if (player.getLevel().getBlockIdAt((int) player.x, (int) player.y - 1, (int) player.z) == 0 &&\r\n player.getLevel().getBlockIdAt((int) player.x, (int) player.y - 1, (int) player.z - 1) == 0 &&\r\n player.getLevel().getBlockIdAt((int) player.x, (int) player.y - 1, (int) player.z + 1) == 0 &&\r\n player.getLevel().getBlockIdAt((int) player.x + 1, (int) player.y - 1, (int) player.z) == 0 &&\r\n player.getLevel().getBlockIdAt((int) player.x - 1, (int) player.y - 1, (int) player.z) == 0) {\r\n int groundY = 1;\r\n while (player.getLevel().getBlockIdAt((int) player.x, (int) player.y - groundY, (int) player.z) == 0) {\r\n groundY++;\r\n }\r\n groundY -= 1;\r\n if (groundY > 2) {\r\n player.teleport(new Vector3(player.x, player.y - groundY, player.z));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n\r\n @EventHandler(priority = EventPriority.HIGHEST)\r\n public void onChat(PlayerChatEvent event) {\r\n Player player = event.getPlayer();\r\n String msg = event.getMessage();\r\n CheckChat checkChat = new CheckChat(player, msg);\r\n CheckWords checkWords = new CheckWords(player, msg);\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getCheckChat() && checkChat.isCheat()) {\r\n AntiCheatAPI.getInstance().addRecord(player, checkChat.getCheatType());\r\n player.sendMessage(TextFormat.RED + \"You chat faster than predetermined value.\");\r\n event.setCancelled();\r\n }\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getCheckChatWord() && checkWords.isCheat()) {\r\n event.setMessage(checkWords.ChangeMessage());\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.LOWEST)\r\n public void onJoin(PlayerJoinEvent event) {\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getAntiAutoAim()) {\r\n AntiAutoAim.put(event.getPlayer().getName(), new AntiAutoAim(event.getPlayer()));\r\n event.getPlayer().sendMessage(TextFormat.GOLD + \"The server enable AntiAutoAim!\");\r\n }\r\n }\r\n\r\n @EventHandler\r\n public void onMove(PlayerMoveEvent event) {\r\n Player player = event.getPlayer();\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getCheckBB()) {\r\n CheckBB checkBB = new CheckBB(player);\r\n if (checkBB.isCheat()) {\r\n AntiCheatAPI.getInstance().addRecord(player, checkBB.getCheatType());\r\n //player.sendMessage(TextFormat.RED+\"We detected that you used to accelerate. Perhaps this is a misjudgment.\");\r\n //player.teleport(player.getLocation().add(0,1.5,0));\r\n event.setCancelled();\r\n }\r\n }\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getAntiAutoAim() && AntiAutoAim.containsKey(player.getName())) {\r\n AntiAutoAim.get(event.getPlayer().getName()).move(event.getPlayer());\r\n }\r\n }\r\n\r\n @EventHandler\r\n public void onQuit(PlayerQuitEvent event) {\r\n if (AntiCheatAPI.getInstance().getMasterConfig().getAntiAutoAim() && AntiAutoAim.containsKey(event.getPlayer().getName())) {\r\n AntiAutoAim.get(event.getPlayer().getName()).getNpc().close();\r\n }\r\n }\r\n\r\n @EventHandler\r\n public void onBlockPlace(BlockPlaceEvent event) {\r\n Reach reach = new Reach(event.getPlayer(), event.getBlock());\r\n if (reach.isCheat()) {\r\n event.getPlayer().sendMessage(TextFormat.RED + \"Maybe you used Reach!!!\");\r\n event.setCancelled();\r\n }\r\n }\r\n\r\n @EventHandler(priority = EventPriority.HIGHEST)\r\n public void onBlockBreak(BlockBreakEvent event) {\r\n /*Player player = event.getPlayer();\r\n double breakTime = event.getBlock().getBreakTime(event.getPlayer().getInventory().getItemInHand(), event.getPlayer());\r\n if (player.isCreative() && breakTime > 0.15D) {\r\n breakTime = 0.15D;\r\n }\r\n\r\n if (player.hasEffect(3)) {\r\n breakTime *= 1.0D - 0.2D * (double)(player.getEffect(3).getAmplifier() + 1);\r\n }\r\n\r\n if (player.hasEffect(4)) {\r\n breakTime *= 1.0D - 0.3D * (double)(player.getEffect(4).getAmplifier() + 1);\r\n }\r\n\r\n Enchantment eff = event.getPlayer().getInventory().getItemInHand().getEnchantment(15);\r\n if (eff != null && eff.getLevel() > 0) {\r\n breakTime *= 1.0D - 0.3D * (double)eff.getLevel();\r\n }\r\n if((double)player.lastBreak - (double)System.currentTimeMillis() < (breakTime - 1)*1000D){\r\n //event.setCancelled();\r\n }*/\r\n\r\n }\r\n\r\n public void onEntitDamage(EntityDamageByEntityEvent event) {\r\n if (event.getDamager() instanceof Player) {\r\n Reach reach = new Reach((Player) event.getDamager(), event.getEntity());\r\n if (reach.isCheat() && !event.getCause().equals(EntityDamageByEntityEvent.DamageCause.PROJECTILE)) {\r\n ((Player) event.getDamager()).sendMessage(TextFormat.RED + \"Maybe you used Reach!!!\");\r\n event.setCancelled();\r\n }\r\n event.setKnockBack(0.25F); // Nukkit KnockBack is so ‘long’\r\n }\r\n if (event.getEntity() instanceof NPC || event.getEntity().getNameTag().equals(\"'\")) {\r\n event.setCancelled();\r\n }\r\n }\r\n\r\n\r\n @EventHandler\r\n public void PlayerCheatingEvent(PlayerCheating event) {\r\n if (event.getPlayer() != null && !event.getCheatType().getTypeName().equals(\"bb\")) {\r\n Server.getInstance().getLogger().warning(\"Player \" + event.getPlayer().getName() + \" cheating,type: \" + event.getCheatType().getTypeName());\r\n }\r\n }\r\n\r\n}\r" ]
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.plugin.PluginBase; import cn.nukkit.utils.Config; import top.dreamcity.AntiCheat.Cheat.Report; import top.dreamcity.AntiCheat.Cheat.chat.CheckChatThread; import top.dreamcity.AntiCheat.Cheat.move.AntiFlyThread; import top.dreamcity.AntiCheat.Cheat.move.AntiSpeedThread; import top.dreamcity.AntiCheat.Cheat.move.AntiWaterWalkThread; import top.dreamcity.AntiCheat.Command.ReportCommand; import top.dreamcity.AntiCheat.Config.MasterConfig; import top.dreamcity.AntiCheat.Config.PlayerCheatRecord; import top.dreamcity.AntiCheat.Event.Listener.EventListener; import java.util.HashMap; import java.util.HashSet;
package top.dreamcity.AntiCheat; /** * Copyright © 2017 WetABQ&DreamCityAdminGroup All right reserved. * Welcome to DreamCity Server Address:dreamcity.top:19132 * Created by WetABQ(Administrator) on 2017/10/8. * ||| || |||| || |||||||| ||||||| * ||| ||| ||| || || | ||| || ||| ||| * ||| ||| || |||||| |||||||| || || || |||| ||| || * || ||||| || ||| || |||| ||| ||||| |||||||| | || * || || || || || || | |||||||| || || ||| || || * |||| |||| || || || || ||| ||| |||| ||| |||||||| * || ||| ||||||| ||||| ||| |||| |||||||| ||||| | * |||| */ public class AntiCheat extends PluginBase implements AntiCheatAPI { private static AntiCheat instance;
private static MasterConfig masterConfig;
6
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/inventory/container/ContainerAbilityContainer.java
[ "public class RegistryEntries {\n\n @ObjectHolder(\"everlastingabilities:ability_bottle\")\n public static final Item ITEM_ABILITY_BOTTLE = null;\n @ObjectHolder(\"everlastingabilities:ability_totem\")\n public static final Item ITEM_ABILITY_TOTEM = null;\n\n @ObjectHolder(\"everlastingabilities:ability_container\")\n public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null;\n\n @ObjectHolder(\"everlastingabilities:crafting_special_totem_recycle\")\n public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null;\n\n}", "public class AbilityHelpers {\n\n /**\n * This value is synced with {@link GeneralConfig#maxPlayerAbilities} from the server.\n * This is to ensure that clients can not hack around the ability limit.\n */\n public static int maxPlayerAbilitiesClient = -1;\n\n public static final int[] RARITY_COLORS = new int[] {\n Helpers.RGBToInt(255, 255, 255),\n Helpers.RGBToInt(255, 255, 0),\n Helpers.RGBToInt(0, 255, 255),\n Helpers.RGBToInt(255, 0, 255),\n };\n\n public static int getExperienceForLevel(int level) {\n if (level == 0) {\n return 0;\n } else if (level < 16) {\n return (int) (Math.pow(level, 2) + 6 * level);\n } else if (level < 31) {\n return (int) (2.5 * Math.pow(level, 2) - 40.5 * level + 360);\n } else {\n return (int) (4.5 * Math.pow(level, 2) - 162.5 * level + 2220);\n }\n }\n\n public static int getLevelForExperience(int experience) {\n int i = 0;\n int newXp, lastXp = -1;\n while ((newXp = getExperienceForLevel(i)) <= experience) {\n if (newXp <= lastXp) break; // Avoid infinite loops when the MC level is too high, resulting in an xp overflow. See https://github.com/CyclopsMC/EverlastingAbilities/issues/27\n i++;\n lastXp = newXp;\n }\n return i - 1;\n }\n\n public static Predicate<IAbilityType> createRarityPredicate(Rarity rarity) {\n return abilityType -> abilityType.getRarity() == rarity;\n }\n\n public static List<IAbilityType> getAbilityTypes(Predicate<IAbilityType> abilityFilter) {\n return AbilityTypes.REGISTRY.getValues()\n .stream()\n .filter(abilityFilter)\n .collect(Collectors.toList());\n }\n\n public static List<IAbilityType> getAbilityTypesPlayerSpawn() {\n return getAbilityTypes(IAbilityType::isObtainableOnPlayerSpawn);\n }\n\n public static List<IAbilityType> getAbilityTypesMobSpawn() {\n return getAbilityTypes(IAbilityType::isObtainableOnMobSpawn);\n }\n\n public static List<IAbilityType> getAbilityTypesCrafting() {\n return getAbilityTypes(IAbilityType::isObtainableOnCraft);\n }\n\n public static List<IAbilityType> getAbilityTypesLoot() {\n return getAbilityTypes(IAbilityType::isObtainableOnLoot);\n }\n\n public static void onPlayerAbilityChanged(PlayerEntity player, IAbilityType abilityType, int oldLevel, int newLevel) {\n abilityType.onChangedLevel(player, oldLevel, newLevel);\n }\n\n public static int getMaxPlayerAbilities(World world) {\n return world.isRemote() ? maxPlayerAbilitiesClient : GeneralConfig.maxPlayerAbilities;\n }\n\n /**\n * Add the given ability.\n * @param player The player.\n * @param ability The ability.\n * @param doAdd If the addition should actually be done.\n * @param modifyXp Whether to require player to have enough XP before adding\n * @return The ability part that was added.\n */\n @NonNull\n public static Ability addPlayerAbility(PlayerEntity player, Ability ability, boolean doAdd, boolean modifyXp) {\n return player.getCapability(MutableAbilityStoreConfig.CAPABILITY)\n .map(abilityStore -> {\n int oldLevel = abilityStore.hasAbilityType(ability.getAbilityType())\n ? abilityStore.getAbility(ability.getAbilityType()).getLevel() : 0;\n\n // Check max ability count\n if (getMaxPlayerAbilities(player.getEntityWorld()) >= 0 && oldLevel == 0\n && getMaxPlayerAbilities(player.getEntityWorld()) <= abilityStore.getAbilities().size()) {\n return Ability.EMPTY;\n }\n\n Ability result = abilityStore.addAbility(ability, doAdd);\n int currentXp = player.experienceTotal;\n if (result != null && modifyXp && getExperience(result) > currentXp) {\n int maxLevels = player.experienceTotal / result.getAbilityType().getBaseXpPerLevel();\n if (maxLevels == 0) {\n result = Ability.EMPTY;\n } else {\n result = new Ability(result.getAbilityType(), maxLevels);\n }\n }\n if (doAdd && !result.isEmpty()) {\n player.experienceTotal -= getExperience(result);\n // Fix xp bar\n player.experienceLevel = getLevelForExperience(player.experienceTotal);\n int xpForLevel = getExperienceForLevel(player.experienceLevel);\n player.experience = (float)(player.experienceTotal - xpForLevel) / (float)player.xpBarCap();\n\n int newLevel = abilityStore.getAbility(result.getAbilityType()).getLevel();\n onPlayerAbilityChanged(player, result.getAbilityType(), oldLevel, newLevel);\n }\n return result;\n })\n .orElse(Ability.EMPTY);\n }\n\n /**\n * Remove the given ability.\n * @param player The player.\n * @param ability The ability.\n * @param doRemove If the removal should actually be done.\n * @param modifyXp Whether to refund XP cost of ability\n * @return The ability part that was removed.\n */\n @NonNull\n public static Ability removePlayerAbility(PlayerEntity player, Ability ability, boolean doRemove, boolean modifyXp) {\n return player.getCapability(MutableAbilityStoreConfig.CAPABILITY, null)\n .map(abilityStore -> {\n int oldLevel = abilityStore.hasAbilityType(ability.getAbilityType())\n ? abilityStore.getAbility(ability.getAbilityType()).getLevel() : 0;\n Ability result = abilityStore.removeAbility(ability, doRemove);\n if (modifyXp && !result.isEmpty()) {\n player.giveExperiencePoints(getExperience(result));\n int newLevel = abilityStore.hasAbilityType(result.getAbilityType())\n ? abilityStore.getAbility(result.getAbilityType()).getLevel() : 0;\n onPlayerAbilityChanged(player, result.getAbilityType(), oldLevel, newLevel);\n }\n return result;\n })\n .orElse(Ability.EMPTY);\n }\n\n public static int getExperience(@NonNull Ability ability) {\n if (ability.isEmpty()) {\n return 0;\n }\n return ability.getAbilityType().getBaseXpPerLevel() * ability.getLevel();\n }\n\n public static void setPlayerAbilities(ServerPlayerEntity player, Map<IAbilityType, Integer> abilityTypes) {\n player.getCapability(MutableAbilityStoreConfig.CAPABILITY)\n .ifPresent(abilityStore -> abilityStore.setAbilities(abilityTypes));\n }\n\n public static boolean canInsert(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n Ability added = mutableAbilityStore.addAbility(ability, false);\n return added.getLevel() == ability.getLevel();\n }\n\n public static boolean canExtract(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n Ability added = mutableAbilityStore.removeAbility(ability, false);\n return added.getLevel() == ability.getLevel();\n }\n\n public static boolean canInsertToPlayer(Ability ability, PlayerEntity player) {\n Ability added = addPlayerAbility(player, ability, false, true);\n return added.getLevel() == ability.getLevel();\n }\n\n public static Ability insert(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n return mutableAbilityStore.addAbility(ability, true);\n }\n\n public static Ability extract(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n return mutableAbilityStore.removeAbility(ability, true);\n }\n\n public static Optional<IAbilityType> getRandomAbility(List<IAbilityType> abilityTypes, Random random, Rarity rarity) {\n List<IAbilityType> filtered = abilityTypes.stream().filter(createRarityPredicate(rarity)).collect(Collectors.toList());\n if (filtered.size() > 0) {\n return Optional.of(filtered.get(random.nextInt(filtered.size())));\n }\n return Optional.empty();\n }\n\n public static Optional<IAbilityType> getRandomAbilityUntilRarity(List<IAbilityType> abilityTypes, Random random, Rarity rarity, boolean inclusive) {\n NavigableSet<Rarity> validRarities = AbilityHelpers.getValidAbilityRarities(abilityTypes).headSet(rarity, inclusive);\n Iterator<Rarity> it = validRarities.descendingIterator();\n while (it.hasNext()) {\n Optional<IAbilityType> optional = getRandomAbility(abilityTypes, random, it.next());\n if (optional.isPresent()) {\n return optional;\n }\n }\n return Optional.empty();\n }\n\n public static Optional<ItemStack> getRandomTotem(List<IAbilityType> abilityTypes, Rarity rarity, Random rand) {\n return getRandomAbility(abilityTypes, rand, rarity).flatMap(\n abilityType -> Optional.of(ItemAbilityTotem.getTotem(new Ability(abilityType, 1))));\n }\n \n\n public static Rarity getRandomRarity(List<IAbilityType> abilityTypes, Random rand) {\n int chance = rand.nextInt(50);\n Rarity rarity;\n if (chance >= 49) {\n rarity = Rarity.EPIC;\n } else if (chance >= 40) {\n rarity = Rarity.RARE;\n } else if (chance >= 25) {\n rarity = Rarity.UNCOMMON;\n } else {\n rarity = Rarity.COMMON;\n }\n\n // Fallback to a random selection of a rarity that is guaranteed to exist in the registered abilities\n if (!hasRarityAbilities(abilityTypes, rarity)) {\n int size = abilityTypes.size();\n if (size == 0) {\n throw new IllegalStateException(\"No abilities were registered, at least one ability must be enabled for this mod to function correctly.\");\n }\n rarity = Iterables.get(abilityTypes, rand.nextInt(size)).getRarity();\n }\n\n return rarity;\n }\n\n public static boolean hasRarityAbilities(List<IAbilityType> abilityTypes, Rarity rarity) {\n return abilityTypes.stream().anyMatch(createRarityPredicate(rarity));\n }\n\n public static NavigableSet<Rarity> getValidAbilityRarities(List<IAbilityType> abilityTypes) {\n NavigableSet<Rarity> rarities = Sets.newTreeSet();\n for (Rarity rarity : Rarity.values()) {\n if (hasRarityAbilities(abilityTypes, rarity)) {\n rarities.add(rarity);\n }\n }\n return rarities;\n }\n\n public static Triple<Integer, Integer, Integer> getAverageRarityColor(IAbilityStore abilityStore) {\n int r = 0;\n int g = 0;\n int b = 0;\n int count = 1;\n for (IAbilityType abilityType : abilityStore.getAbilityTypes()) {\n Triple<Float, Float, Float> color = Helpers.intToRGB(AbilityHelpers.RARITY_COLORS\n [Math.min(AbilityHelpers.RARITY_COLORS.length - 1, abilityType.getRarity().ordinal())]);\n r += color.getLeft() * 255;\n g += color.getMiddle() * 255;\n b += color.getRight() * 255;\n count++;\n }\n return Triple.of(r / count, g / count, b / count);\n }\n\n public static Supplier<Rarity> getSafeRarity(Supplier<Integer> rarityGetter) {\n return () -> {\n Integer rarity = rarityGetter.get();\n return rarity < 0 ? Rarity.COMMON : (rarity >= Rarity.values().length ? Rarity.EPIC : Rarity.values()[rarity]);\n };\n }\n\n}", "public class Ability implements Comparable<Ability> {\n\n public static final Ability EMPTY = new Ability(new AbilityType(\"\", \"\", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0);\n\n private final IAbilityType abilityType;\n private final int level;\n\n public Ability(@Nonnull IAbilityType abilityType, int level) {\n this.abilityType = Objects.requireNonNull(abilityType);\n this.level = level;\n }\n\n public IAbilityType getAbilityType() {\n return abilityType;\n }\n\n public int getLevel() {\n return level;\n }\n\n @Override\n public String toString() {\n return String.format(\"[%s @ %s]\", abilityType.getTranslationKey(), level);\n }\n\n @Override\n public int compareTo(Ability other) {\n return this.toString().compareTo(other.toString());\n }\n\n public ITextComponent getTextComponent() {\n return new StringTextComponent(\"[\")\n .append(new TranslationTextComponent(abilityType.getTranslationKey()))\n .appendString(\" @ \" + level + \"]\");\n }\n\n public boolean isEmpty() {\n return getLevel() <= 0;\n }\n\n}", "public interface IMutableAbilityStore extends IAbilityStore {\n\n /**\n * Add the given ability.\n * @param ability The ability.\n * @param doAdd If the addition should actually be done.\n * @return The ability part that was added.\n */\n @NonNull\n public Ability addAbility(Ability ability, boolean doAdd);\n\n /**\n * Remove the given ability.\n * @param ability The ability.\n * @param doRemove If the removal should actually be done.\n * @return The ability part that was removed.\n */\n @NonNull\n public Ability removeAbility(Ability ability, boolean doRemove);\n\n}", "public class MutableAbilityStoreConfig extends CapabilityConfig {\n\n /**\n * The unique instance.\n */\n public static MutableAbilityStoreConfig _instance;\n\n @CapabilityInject(IMutableAbilityStore.class)\n public static Capability<IMutableAbilityStore> CAPABILITY = null;\n\n /**\n * Make a new instance.\n */\n public MutableAbilityStoreConfig() {\n super(EverlastingAbilities._instance,\n \"mutableAbilityStore\",\n IMutableAbilityStore.class,\n new AbilityStoreStorage(),\n DefaultMutableAbilityStore::new);\n }\n}", "public class ContainerScreenAbilityContainer extends ContainerScreenExtended<ContainerAbilityContainer> {\n\n private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation(\"textures/misc/enchanted_item_glint.png\");\n protected static final int ABILITY_LIST_SIZE = 6;\n protected static final int ABILITY_BOX_HEIGHT = 18;\n protected static final int ABILITY_BOX_WIDTH = 63;\n\n private final PlayerEntity player;\n\n protected int startIndexPlayer = 0;\n protected int startIndexItem = 0;\n\n protected int absoluteSelectedIndexPlayer = -1;\n protected int absoluteSelectedIndexItem = -1;\n\n protected ButtonArrow buttonUp1;\n protected ButtonArrow buttonDown1;\n protected ButtonArrow buttonUp2;\n protected ButtonArrow buttonDown2;\n protected ButtonArrow buttonLeft;\n protected ButtonArrow buttonRight;\n\n public ContainerScreenAbilityContainer(ContainerAbilityContainer container, PlayerInventory inventory, ITextComponent title) {\n super(container, inventory, title);\n this.player = inventory.player;\n container.setGui(this);\n }\n\n @Override\n protected ResourceLocation constructGuiTexture() {\n return new ResourceLocation(Reference.MOD_ID, \"textures/gui/ability_totem.png\");\n }\n\n @Override\n public void init() {\n super.init();\n\n addButton(buttonUp1 = new ButtonArrow(this.guiLeft + 73, this.guiTop + 83, new TranslationTextComponent(\"gui.cyclopscore.up\"), button -> {\n if (startIndexPlayer > 0) startIndexPlayer--;\n }, ButtonArrow.Direction.NORTH));\n addButton(buttonDown1 = new ButtonArrow(this.guiLeft + 73, this.guiTop + 174, new TranslationTextComponent(\"gui.cyclopscore.down\"), button -> {\n if (startIndexPlayer + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getPlayerAbilitiesCount())) startIndexPlayer++;\n }, ButtonArrow.Direction.SOUTH));\n addButton(buttonUp2 = new ButtonArrow(this.guiLeft + 88, this.guiTop + 83, new TranslationTextComponent(\"gui.cyclopscore.up\"), button -> {\n if (startIndexItem > 0) startIndexItem--;\n }, ButtonArrow.Direction.NORTH));\n addButton(buttonDown2 = new ButtonArrow(this.guiLeft + 88, this.guiTop + 174, new TranslationTextComponent(\"gui.cyclopscore.down\"), button -> {\n if (startIndexItem + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getItemAbilitiesCount())) startIndexItem++;\n }, ButtonArrow.Direction.SOUTH));\n\n addButton(buttonLeft = new ButtonArrow(this.guiLeft + 76, this.guiTop + 130, new TranslationTextComponent(\"gui.cyclopscore.left\"), button -> {\n if (canMoveToPlayer()) {\n EverlastingAbilities._instance.getPacketHandler().sendToServer(\n new MoveAbilityPacket(getSelectedItemAbilitySingle(), MoveAbilityPacket.Movement.TO_PLAYER));\n moveToPlayer();\n }\n }, ButtonArrow.Direction.WEST));\n addButton(buttonRight = new ButtonArrow(this.guiLeft + 90, this.guiTop + 130, new TranslationTextComponent(\"gui.cyclopscore.right\"), button -> {\n if (canMoveFromPlayer()) {\n EverlastingAbilities._instance.getPacketHandler().sendToServer(\n new MoveAbilityPacket(getSelectedPlayerAbilitySingle(), MoveAbilityPacket.Movement.FROM_PLAYER));\n moveFromPlayer();\n }\n }, ButtonArrow.Direction.EAST));\n }\n\n @Override\n protected int getBaseYSize() {\n return 219;\n }\n\n @Override\n protected void drawGuiContainerForegroundLayer(MatrixStack matrixStack, int mouseX, int mouseY) {\n if (getContainer().getItemStack(player) == null) {\n return;\n }\n\n this.font.drawString(matrixStack, player.getDisplayName().getString(), 8, 6, -1);\n this.font.func_238407_a_(matrixStack, getContainer().getItemStack(player).getDisplayName().func_241878_f(), 102, 6, -1);\n\n // Draw abilities\n drawAbilitiesTooltip(8, 83, getPlayerAbilities(), startIndexPlayer, mouseX, mouseY);\n drawAbilitiesTooltip(105, 83, getItemAbilities(), startIndexItem, mouseX, mouseY);\n }\n\n protected List<Ability> getPlayerAbilities() {\n List<Ability> abilities = getContainer().getPlayerAbilities();\n Collections.sort(abilities);\n return abilities;\n }\n\n protected List<Ability> getItemAbilities() {\n List<Ability> abilities = getContainer().getItemAbilities();\n Collections.sort(abilities);\n return abilities;\n }\n\n protected IMutableAbilityStore getPlayerAbilityStore() {\n return getContainer().getPlayerAbilityStore().orElse(null);\n }\n\n protected IMutableAbilityStore getItemAbilityStore() {\n return getContainer().getItemAbilityStore().orElse(null);\n }\n\n protected int getPlayerAbilitiesCount() {\n return getPlayerAbilities().size();\n }\n\n protected int getItemAbilitiesCount() {\n return getItemAbilities().size();\n }\n\n @Override\n protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int mouseX, int mouseY) {\n if (getContainer().getItemStack(player) == null) {\n return;\n }\n\n buttonUp1.active = startIndexPlayer > 0;\n buttonDown1.active = startIndexPlayer + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getPlayerAbilitiesCount());\n buttonUp2.active = startIndexItem > 0;\n buttonDown2.active = startIndexItem + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getItemAbilitiesCount());\n\n buttonLeft.active = canMoveToPlayer();\n buttonRight.active = canMoveFromPlayer();\n buttonRight.active = canMoveFromPlayerByItem();\n\n super.drawGuiContainerBackgroundLayer(matrixStack, partialTicks, mouseX, mouseY);\n\n int i = this.guiLeft;\n int j = this.guiTop;\n drawFancyBackground(i + 8, j + 17, 66, 61, getPlayerAbilityStore());\n InventoryScreen.drawEntityOnScreen(i + 41, j + 74, 30, (float)(i + 41) - mouseX, (float)(j + 76 - 50) - mouseY, this.getMinecraft().player);\n drawXp(matrixStack, i + 67, j + 70);\n RenderHelpers.drawScaledCenteredString(matrixStack, font, \"\" + player.experienceTotal, i + 62, j + 73, 0, 0.5F, Helpers.RGBToInt(40, 215, 40));\n drawFancyBackground(i + 102, j + 17, 66, 61, getItemAbilityStore());\n drawItemOnScreen(i + 134, j + 46, 50, (float)(i + 134) - mouseX, (float)(j + 46 - 30) - mouseY, getContainer().getItemStack(this.getMinecraft().player));\n\n // Draw abilities\n drawAbilities(matrixStack, this.guiLeft + 8, this.guiTop + 83, getPlayerAbilities(), startIndexPlayer, Integer.MAX_VALUE, absoluteSelectedIndexPlayer, mouseX, mouseY, canMoveFromPlayerByItem());\n drawAbilities(matrixStack, this.guiLeft + 105, this.guiTop + 83, getItemAbilities(), startIndexItem, player.experienceTotal, absoluteSelectedIndexItem, mouseX, mouseY, true);\n }\n\n public void drawFancyBackground(int x, int y, int width, int height, IAbilityStore abilityStore) {\n int r = 140;\n int g = 140;\n int b = 140;\n if (abilityStore != null) {\n if (abilityStore.getAbilityTypes().isEmpty()) return;\n Triple<Integer, Integer, Integer> color = AbilityHelpers.getAverageRarityColor(abilityStore);\n r = color.getLeft();\n g = color.getMiddle();\n b = color.getRight();\n }\n\n RenderSystem.depthMask(false);\n RenderSystem.depthFunc(514);\n RenderSystem.disableLighting();\n RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_COLOR, GlStateManager.DestFactor.ONE);\n RenderHelpers.bindTexture(RES_ITEM_GLINT);\n RenderSystem.matrixMode(5890);\n RenderSystem.pushMatrix();\n RenderSystem.scalef(8.0F, 8.0F, 8.0F);\n float f = (float)(Util.milliTime() % 3000L) / 3000.0F / 8.0F;\n RenderSystem.translatef(f, 0.0F, 0.0F);\n RenderSystem.rotatef(-50.0F, 0.0F, 0.0F, 1.0F);\n RenderSystem.enableBlend();\n drawTexturedModalRectColor(x, y, 0, 0, width, height, r, g, b, 255);\n RenderSystem.popMatrix();\n RenderSystem.pushMatrix();\n RenderSystem.scalef(8.0F, 8.0F, 8.0F);\n float f1 = (float)(Util.milliTime() % 4873L) / 4873.0F / 8.0F;\n RenderSystem.translatef(-f1, 0.0F, 0.0F);\n RenderSystem.rotatef(10.0F, 0.0F, 0.0F, 1.0F);\n float rotation = ((float) (Util.milliTime() / 100 % 3600)) / 10F;\n RenderSystem.rotatef(rotation, 1.0F, 0.5F, 1.0F);\n drawTexturedModalRectColor(x, y, 0, 0, width, height, r, g, b, 255);\n RenderSystem.popMatrix();\n RenderSystem.matrixMode(5888);\n RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);\n //GlStateManager.enableLighting();\n RenderSystem.depthFunc(515);\n RenderSystem.depthMask(true);\n RenderSystem.disableBlend();\n RenderHelpers.bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE);\n\n RenderSystem.color4f(1, 1, 1, 1);\n }\n\n protected void drawXp(MatrixStack matrixStack, int x, int y) {\n RenderHelpers.bindTexture(texture);\n blit(matrixStack, x, y, 0, 219, 5, 5);\n }\n\n private void drawAbilities(MatrixStack matrixStack, int x, int y, List<Ability> abilities, int startIndex, int playerXp,\n int currentSelectedIndex, int mouseX, int mouseY, boolean canEdit) {\n int maxI = Math.min(ABILITY_LIST_SIZE, abilities.size() - startIndex);\n for (int i = 0; i < maxI; i++) {\n int boxY = y + i * ABILITY_BOX_HEIGHT;\n Ability ability = abilities.get(i + startIndex);\n\n // select box (+hover)\n if (canEdit) {\n boolean active = currentSelectedIndex == i + startIndex;\n boolean showActive = active || isPointInRegion(new Rectangle(x - this.guiLeft, boxY - this.guiTop, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT), new Point(mouseX, mouseY));\n if (showActive) {\n drawFancyBackground(x, boxY - 1, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT, null);\n }\n }\n\n // Name\n RenderHelpers.drawScaledCenteredString(matrixStack, font,\n new TranslationTextComponent(ability.getAbilityType().getTranslationKey())\n .setStyle(Style.EMPTY.setColor(Color.fromTextFormatting(ability.getAbilityType().getRarity().color)))\n .getString(),\n x + 27, boxY + 7, 0, 1.0F, 50, -1);\n\n // Level\n RenderHelpers.drawScaledCenteredString(matrixStack, font,\n \"\" + ability.getLevel(),\n x + 58, boxY + 5, 0, 0.8F, -1);\n\n // XP\n int requiredXp = ability.getAbilityType().getBaseXpPerLevel();\n if (playerXp < requiredXp) {\n GlStateManager.color4f(0.3F, 0.3F, 0.3F, 1);\n } else {\n GlStateManager.color4f(1, 1, 1, 1);\n }\n drawXp(matrixStack, x + 57, boxY + 10);\n RenderHelpers.drawScaledCenteredString(matrixStack, font,\n \"\" + requiredXp,\n x + 53, boxY + 13, 0, 0.5F, Helpers.RGBToInt(40, 215, 40));\n }\n GlStateManager.color4f(1, 1, 1, 1);\n }\n\n private void drawAbilitiesTooltip(int x, int y, List<Ability> abilities, int startIndex, int mouseX, int mouseY) {\n int maxI = Math.min(ABILITY_LIST_SIZE, abilities.size() - startIndex);\n for (int i = 0; i < maxI; i++) {\n int boxY = y + i * ABILITY_BOX_HEIGHT;\n if(isPointInRegion(new Rectangle(x, boxY, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT), new Point(mouseX, mouseY))) {\n Ability ability = abilities.get(i + startIndex);\n List<ITextComponent> lines = Lists.newLinkedList();\n\n // Name\n lines.add(new TranslationTextComponent(ability.getAbilityType().getTranslationKey())\n .setStyle(Style.EMPTY.setColor(Color.fromTextFormatting(ability.getAbilityType().getRarity().color))));\n\n // Level\n lines.add(new TranslationTextComponent(\"general.everlastingabilities.level\", ability.getLevel(),\n ability.getAbilityType().getMaxLevel() == -1 ? \"Inf\" : ability.getAbilityType().getMaxLevel()));\n\n // Description\n lines.add(new TranslationTextComponent(ability.getAbilityType().getUnlocalizedDescription())\n .setStyle(Style.EMPTY.createStyleFromFormattings(IInformationProvider.INFO_PREFIX_STYLES)));\n\n // Xp\n lines.add(new TranslationTextComponent(\"general.everlastingabilities.xp\",\n ability.getAbilityType().getBaseXpPerLevel(),\n AbilityHelpers.getLevelForExperience(ability.getAbilityType().getBaseXpPerLevel()))\n .setStyle(Style.EMPTY.setColor(Color.fromTextFormatting(TextFormatting.DARK_GREEN))));\n\n drawTooltip(lines, mouseX - this.guiLeft, mouseY - this.guiTop);\n }\n }\n }\n\n public void drawTexturedModalRectColor(int x, int y, int textureX, int textureY, int width, int height, int r, int g, int b, int a) {\n float f = 0.00390625F;\n float f1 = 0.00390625F;\n Tessellator tessellator = Tessellator.getInstance();\n BufferBuilder vertexbuffer = tessellator.getBuffer();\n vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);\n vertexbuffer.pos(x + 0, y + height, this.getBlitOffset()).tex((textureX + 0) * f, (textureY + height) * f1).color(r, g, b, a).endVertex();\n vertexbuffer.pos(x + width, y + height, this.getBlitOffset()).tex((textureX + width) * f, (textureY + height) * f1).color(r, g, b, a).endVertex();\n vertexbuffer.pos(x + width, y + 0,this.getBlitOffset()).tex((textureX + width) * f, (textureY + 0) * f1).color(r, g, b, a).endVertex();\n vertexbuffer.pos(x + 0, y + 0, this.getBlitOffset()).tex((textureX + 0) * f, (textureY + 0) * f1).color(r, g, b, a).endVertex();\n tessellator.draw();\n }\n\n public static void drawItemOnScreen(int posX, int posY, int scale, float mouseX, float mouseY, ItemStack itemStack) {\n float lvt_6_1_ = (float)Math.atan((double)(mouseX / 40.0F));\n float lvt_7_1_ = (float)Math.atan((double)(mouseY / 40.0F));\n RenderSystem.pushMatrix();\n RenderSystem.translatef((float)posX, (float)posY, 1050.0F);\n RenderSystem.scalef(1.0F, 1.0F, -1.0F);\n MatrixStack matrixStack = new MatrixStack();\n matrixStack.translate(0.0D, 0.0D, 1000.0D);\n matrixStack.scale((float)scale, (float)scale, (float)scale);\n Quaternion rotation = Vector3f.ZP.rotationDegrees(180.0F);\n Quaternion cameraOrientationY = Vector3f.YP.rotationDegrees(- lvt_6_1_ * 40.0F);\n Quaternion cameraOrientationX = Vector3f.XP.rotationDegrees(lvt_7_1_ * 20.0F);\n rotation.multiply(cameraOrientationY);\n rotation.multiply(cameraOrientationX);\n matrixStack.rotate(rotation);\n IRenderTypeBuffer.Impl renderTypeBuffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();\n RenderHelper.enableStandardItemLighting();\n Minecraft.getInstance().getItemRenderer().renderItem(itemStack, ItemCameraTransforms.TransformType.FIXED, 15728880, OverlayTexture.NO_OVERLAY, matrixStack, renderTypeBuffer);\n RenderHelper.disableStandardItemLighting();\n renderTypeBuffer.finish();\n RenderSystem.popMatrix();\n }\n\n @Override\n public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {\n int newSelectedPlayer = canMoveFromPlayerByItem() ? clickAbilities(8, 83, getPlayerAbilities(), startIndexPlayer, absoluteSelectedIndexPlayer, mouseX, mouseY) : -2;\n int newSelectedItem = clickAbilities(105, 83, getItemAbilities(), startIndexItem, absoluteSelectedIndexItem, mouseX, mouseY);\n\n if (newSelectedPlayer >= -1) {\n absoluteSelectedIndexPlayer = newSelectedPlayer;\n }\n if (newSelectedItem >= -1) {\n absoluteSelectedIndexItem = newSelectedItem;\n }\n\n if (newSelectedPlayer < 0 && newSelectedItem < 0) {\n super.mouseClicked(mouseX, mouseY, mouseButton);\n }\n\n return true;\n }\n \n @Override\n public boolean mouseScrolled(double mouseX, double mouseY, double scrollAmount) {\n if (isPointInRegion(8, 83, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT * ABILITY_LIST_SIZE, mouseX, mouseY)) {\n if (scrollAmount > 0) {\n if (startIndexPlayer > 0)\n startIndexPlayer--;\n } else if (scrollAmount < 0) {\n if (startIndexPlayer + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getPlayerAbilitiesCount()))\n startIndexPlayer++;\n }\n return true;\n } else if (isPointInRegion(105, 83, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT * ABILITY_LIST_SIZE, mouseX, mouseY)) {\n if (scrollAmount > 0) {\n if (startIndexItem > 0)\n startIndexItem--;\n } else if (scrollAmount < 0) {\n if (startIndexItem + ABILITY_LIST_SIZE < Math.max(ABILITY_LIST_SIZE, getItemAbilitiesCount()))\n startIndexItem++;\n }\n return true;\n }\n \n return false;\n }\n \n private int clickAbilities(int x, int y, List<Ability> abilities, int startIndex, int currentSelectedIndex,\n double mouseX, double mouseY) {\n int maxI = Math.min(ABILITY_LIST_SIZE, abilities.size() - startIndex);\n for (int i = 0; i < maxI; i++) {\n int boxY = y + i * ABILITY_BOX_HEIGHT;\n if (isPointInRegion(new Rectangle(x, boxY, ABILITY_BOX_WIDTH, ABILITY_BOX_HEIGHT), new Point((int) mouseX, (int) mouseY))) {\n int absoluteIndex = startIndex + i;\n if (currentSelectedIndex == absoluteIndex) {\n return -1;\n } else {\n return absoluteIndex;\n }\n }\n }\n return -2;\n }\n\n public Ability getSelectedPlayerAbilitySingle() {\n Ability ability = getSelectedPlayerAbility();\n if (!ability.isEmpty()) {\n ability = new Ability(ability.getAbilityType(), 1);\n }\n return ability;\n }\n\n public Ability getSelectedItemAbilitySingle() {\n Ability ability = getSelectedItemAbility();\n if (!ability.isEmpty()) {\n ability = new Ability(ability.getAbilityType(), 1);\n }\n return ability;\n }\n\n public Ability getSelectedPlayerAbility() {\n List<Ability> abilities = getPlayerAbilities();\n if (absoluteSelectedIndexPlayer >= 0 && absoluteSelectedIndexPlayer < abilities.size()) {\n return abilities.get(absoluteSelectedIndexPlayer);\n }\n return Ability.EMPTY;\n }\n\n public Ability getSelectedItemAbility() {\n List<Ability> abilities = getItemAbilities();\n if (absoluteSelectedIndexItem >= 0 && absoluteSelectedIndexItem < abilities.size()) {\n return abilities.get(absoluteSelectedIndexItem);\n }\n return Ability.EMPTY;\n }\n\n public boolean canMoveFromPlayer(Ability ability, PlayerEntity player, IMutableAbilityStore target) {\n return !ability.isEmpty() && AbilityHelpers.canInsert(ability, target);\n }\n\n public boolean canMoveToPlayer(Ability ability, PlayerEntity player) {\n return !ability.isEmpty() && AbilityHelpers.canInsertToPlayer(ability, player);\n }\n\n public boolean canMoveFromPlayerByItem() {\n return getContainer().getItem().canMoveFromPlayer();\n }\n\n public boolean canMoveFromPlayer() {\n if (!canMoveFromPlayerByItem()) {\n return false;\n }\n Ability playerAbility = getSelectedPlayerAbilitySingle();\n return canMoveFromPlayer(playerAbility, player, getItemAbilityStore());\n }\n\n public boolean canMoveToPlayer() {\n Ability itemAbility = getSelectedItemAbilitySingle();\n return canMoveToPlayer(itemAbility, player);\n }\n\n public void moveFromPlayer() {\n getContainer().moveFromPlayer(getSelectedPlayerAbilitySingle());\n }\n\n public void moveToPlayer() {\n getContainer().moveToPlayer(getSelectedItemAbilitySingle());\n }\n}", "public abstract class ItemGuiAbilityContainer extends ItemGui {\n\n protected ItemGuiAbilityContainer(Properties properties) {\n super(properties);\n }\n\n @Override\n public Class<? extends Container> getContainerClass(World world, PlayerEntity playerEntity, ItemStack itemStack) {\n return ContainerAbilityContainer.class;\n }\n\n @Nullable\n @Override\n public INamedContainerProvider getContainer(World world, PlayerEntity playerEntity, int itemIndex, Hand hand, ItemStack itemStack) {\n return new NamedContainerProviderItem(itemIndex, hand, itemStack.getDisplayName(), ContainerAbilityContainer::new);\n }\n\n @Override\n public void addInformation(ItemStack itemStack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {\n super.addInformation(itemStack, worldIn, tooltip, flagIn);\n\n itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null).ifPresent(abilityStore -> {\n List<Ability> abilities = new ArrayList<Ability>(abilityStore.getAbilities());\n Collections.sort(abilities);\n\n // Display each ability in store, one line at a time\n // Or display \"none\" string if list is empty\n boolean empty = true;\n for (Ability ability : abilities) {\n empty = false;\n tooltip.add(new TranslationTextComponent(ability.getAbilityType().getTranslationKey())\n .appendString(\" \" + ability.getLevel())\n .setStyle(Style.EMPTY\n .setColor(Color.fromTextFormatting(TextFormatting.YELLOW))));\n }\n if (empty) {\n tooltip.add(new TranslationTextComponent(\"general.everlastingabilities.empty\")\n .setStyle(Style.EMPTY\n .setColor(Color.fromTextFormatting(TextFormatting.GRAY))\n .setItalic(true)));\n }\n });\n }\n\n @Override\n public ICapabilityProvider initCapabilities(ItemStack stack, CompoundNBT nbt) {\n // TODO: restore when Forge fixed that bug (backwards compat is already taken care of, because data is stored twice (in stacktag and capdata))\n //return new SerializableCapabilityProvider<IMutableAbilityStore>(MutableAbilityStoreConfig.CAPABILITY,\n // new DefaultMutableAbilityStore());\n return new DefaultCapabilityProvider<>(() -> MutableAbilityStoreConfig.CAPABILITY,\n new ItemStackMutableAbilityStore(stack));\n }\n\n public abstract boolean canMoveFromPlayer();\n\n @Override\n public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {\n return oldStack == null || newStack == null || oldStack.getItem() != newStack.getItem();\n }\n\n}" ]
import com.google.common.collect.Lists; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Hand; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.util.LazyOptional; import org.cyclops.cyclopscore.helper.InventoryHelpers; import org.cyclops.cyclopscore.inventory.container.ItemInventoryContainer; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.ability.AbilityHelpers; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.capability.IMutableAbilityStore; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import org.cyclops.everlastingabilities.client.gui.ContainerScreenAbilityContainer; import org.cyclops.everlastingabilities.item.ItemGuiAbilityContainer; import java.util.Collections; import java.util.List;
package org.cyclops.everlastingabilities.inventory.container; /** * Container for the labeller. * @author rubensworks */ public class ContainerAbilityContainer extends ItemInventoryContainer<ItemGuiAbilityContainer> { @OnlyIn(Dist.CLIENT)
private ContainerScreenAbilityContainer gui;
5
linheimx/LChart
app/src/main/java/com/linheimx/app/lchart/NullEntityActivity.java
[ "public class DefaultValueAdapter implements IValueAdapter {\n\n\n private DecimalFormat _formatter;\n protected int _digits = 0;\n\n public DefaultValueAdapter(int digits) {\n _digits = digits;\n\n StringBuffer b = new StringBuffer();\n for (int i = 0; i < _digits; i++) {\n if (i == 0)\n b.append(\".\");\n b.append(\"0\");\n }\n\n _formatter = new DecimalFormat(\"###,###,###,##0\" + b.toString());\n }\n\n @Override\n public String value2String(double value) {\n return _formatter.format(value);\n }\n\n}", "public interface IValueAdapter {\n String value2String(double value);\n}", "public class LineChart extends Chart {\n\n MappingManager _MappingManager;\n\n Lines _lines;\n\n //////////////////////////// listener ///////////////////////////\n IDragListener _dragListener;\n\n ////////////////////////// function //////////////////////////\n boolean isHighLightEnabled = true;\n boolean isTouchEnabled = true;\n boolean isDragable = true;\n boolean isScaleable = true;\n ChartMode _ChartMode;\n CursorMode _CursorMode = CursorMode.cursor1;// 默认使用光标1\n\n ///////////////////////////////// parts ////////////////////////////////\n XAxis _XAxis;\n YAxis _YAxis;\n HighLight _HighLight1;// 光标1\n HighLight _HighLight2;// 光标2\n\n ////////////////////////////////// render /////////////////////////////\n NoDataRender _NoDataRender;\n XAxisRender _XAxisRender;\n YAxisRender _YAxisRender;\n LineRender _LineRender;\n HighLightRender _HighLightRender1;// 光标1\n HighLightRender _HighLightRender2;// 光标2\n GodRender _GodRender;\n\n\n ////////////////////////////// touch /////////////////////////////\n TouchListener _TouchListener;\n GodTouchListener _GodTouchListener;\n\n //////////////////////////// 区域 ///////////////////////////\n RectF _MainPlotRect;// 主要的绘图区域\n\n float _paddingLeft = 40;\n float _paddingRight = 5;\n float _paddingTop = 17;\n float _paddingBottom = 15;\n\n RectF _GodRect;//\n\n ////////////////////////////// animator ////////////////////////////\n LAnimator _LAnimator;\n\n\n public LineChart(Context context) {\n super(context);\n }\n\n public LineChart(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public LineChart(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n @Override\n protected void init(Context context, AttributeSet attributeSet) {\n super.init(context, attributeSet);\n\n TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.LineChart);\n boolean isGodMode = typedArray.getBoolean(R.styleable.LineChart_god_mode, false);\n _ChartMode = isGodMode ? ChartMode.God : ChartMode.Normal;\n typedArray.recycle();\n\n // animator\n _LAnimator = new LAnimator(this);\n\n // init v\n _MainPlotRect = new RectF();\n _MappingManager = new MappingManager(_MainPlotRect);\n _GodRect = new RectF();\n\n // models\n _XAxis = new XAxis();\n _YAxis = new YAxis();\n _HighLight1 = new HighLight();\n _HighLight2 = new HighLight();\n\n // render\n _NoDataRender = new NoDataRender(_MainPlotRect, _MappingManager);\n _XAxisRender = new XAxisRender(_MainPlotRect, _MappingManager, _XAxis);\n _YAxisRender = new YAxisRender(_MainPlotRect, _MappingManager, _YAxis);\n _LineRender = new LineRender(_MainPlotRect, _MappingManager, _lines, this);\n _HighLightRender1 = new HighLightRender(this, HighLightRender.H1, _MainPlotRect, _MappingManager, _HighLight1);\n _HighLightRender2 = new HighLightRender(this, HighLightRender.H2, _MainPlotRect, _MappingManager, _HighLight2);\n\n _GodRender = new GodRender(_MainPlotRect, _MappingManager, _GodRect);\n\n // touch listener\n _TouchListener = new TouchListener(this);\n _GodTouchListener = new GodTouchListener(this);\n\n // other\n _paddingLeft = Utils.dp2px(_paddingLeft);\n _paddingRight = Utils.dp2px(_paddingRight);\n _paddingTop = Utils.dp2px(_paddingTop);\n _paddingBottom = Utils.dp2px(_paddingBottom);\n }\n\n\n @Override\n public void computeScroll() {\n super.computeScroll();\n\n if (_ChartMode == ChartMode.Normal) {\n _TouchListener.computeScroll();\n }\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n\n if (_lines == null) {\n return false;\n }\n if (!isTouchEnabled) {\n return false;\n }\n\n if (_ChartMode == ChartMode.Normal) {\n return _TouchListener.onTouch(this, event);\n } else if (_ChartMode == ChartMode.God) {\n return _GodTouchListener.onTouch(this, event);\n }\n\n return false;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // 1. render no data\n if (_lines == null || _lines.getLines() == null || _lines.getLines().size() == 0) {\n _NoDataRender.render(canvas);\n return;\n }\n\n // 计算轴线上的数值\n Line line = _lines.getLines().get(0);\n double xmin = getVisiableMinX();\n double xmax = getVisiableMaxX();\n double ymin = getVisiableMinY();\n double ymax = getVisiableMaxY();\n _XAxis.calValues(xmin, xmax, line, xmin, xmax);\n _YAxis.calValues(ymin, ymax, line, xmin, xmax);\n\n // render grid line\n _XAxisRender.renderGridline(canvas);\n _YAxisRender.renderGridline(canvas);\n\n // render line\n _LineRender.render(canvas);\n // render high light\n _HighLightRender1.render(canvas);// 光标1\n _HighLightRender2.render(canvas);// 光标2\n\n // render god\n if (_ChartMode == ChartMode.God) {\n _GodRender.render(canvas);\n }\n\n // render warn line\n _XAxisRender.renderWarnLine(canvas);\n _YAxisRender.renderWarnLine(canvas);\n\n // render Axis\n _XAxisRender.renderAxisLine(canvas);\n _YAxisRender.renderAxisLine(canvas);\n\n // render labels\n _XAxisRender.renderLabels(canvas);\n _YAxisRender.renderLabels(canvas);\n\n // render unit\n _XAxisRender.renderUnit(canvas);\n _YAxisRender.renderUnit(canvas);\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n\n _LineRender.onChartSizeChanged(w, h);\n notifyDataChanged();\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n\n _lines = null;\n }\n\n /**\n * 通知数据改变\n */\n public void notifyDataChanged() {\n\n limitMainPlotArea();\n\n if (_lines == null) {\n return;\n }\n _lines.calMinMax();\n\n prepareMap();\n\n // 2. onDataChanged\n _LineRender.onDataChanged(_lines);\n }\n\n /**\n * 限制 主绘图区域的边界\n */\n private void limitMainPlotArea() {\n\n _MainPlotRect.setEmpty();\n _MainPlotRect.right += _MainPlotRect.left + getWidth();\n _MainPlotRect.bottom += _MainPlotRect.top + getHeight();\n\n // 0. padding\n offsetPadding();\n // 1. 计算label,unit的宽高\n offsetArea();\n\n if (_ChartMode == ChartMode.God) {\n _GodRect.set(_MainPlotRect);\n _GodRect.right = _GodRect.right / 3;\n\n // 设置预览窗口\n _GodTouchListener.changeViewPort(0, 0);\n }\n }\n\n private void offsetPadding() {\n\n // 考虑图例\n if (_lines != null) {\n int h = 0;\n for (Line line : _lines.getLines()) {\n if (line.getLegendHeight() > h) {\n h = line.getLegendHeight();\n }\n }\n\n if (h > 0) {\n _paddingTop = h;\n }\n }\n\n _MainPlotRect.left += _paddingLeft;\n _MainPlotRect.top += _paddingTop;\n _MainPlotRect.right -= _paddingRight;\n _MainPlotRect.bottom -= _paddingBottom;\n }\n\n private void offsetArea() {\n\n _YAxisRender.paint_label();\n _YAxisRender.paint_unit();\n Paint paintLabel = _YAxisRender.get_PaintLabel();\n Paint paintUnit = _YAxisRender.get_PaintUnit();\n\n /******************************* 取一堆label中的head middle tail 中的最大值 ***********************************/\n float labelDimen = _YAxis.getLabelDimen();\n\n if (_lines != null && _lines.getLines().size() > 0) {\n Line line = _lines.getLines().get(0);\n\n if (line.getEntries().size() > 0) {\n List<Entry> entryList = line.getEntries();\n\n Entry head = entryList.get(0);\n Entry tail = entryList.get(entryList.size() - 1);\n Entry middle = entryList.get((0 + entryList.size() - 1) / 2);\n\n IValueAdapter yAdapter = _YAxis.get_ValueAdapter();\n String s1 = yAdapter.value2String(head.getY());\n float w1 = Utils.textWidth(paintLabel, s1);\n if (labelDimen < w1) {\n labelDimen = w1;\n }\n\n String s2 = yAdapter.value2String(middle.getY());\n float w2 = Utils.textWidth(paintLabel, s2);\n if (labelDimen < w2) {\n labelDimen = w2;\n }\n\n String s3 = yAdapter.value2String(tail.getY());\n float w3 = Utils.textWidth(paintLabel, s3);\n if (labelDimen < w3) {\n labelDimen = w3;\n }\n }\n\n }\n\n // 考虑y label和unit\n _MainPlotRect.left += _YAxis.offsetLeft(labelDimen, Utils.textHeight(paintUnit));\n // 考虑x label和unit\n _MainPlotRect.bottom -= _XAxis.offsetBottom(Utils.textHeight(paintLabel), Utils.textHeight(paintUnit));\n }\n\n\n /**\n * 准备映射关系\n */\n private void prepareMap() {\n\n double xMin = _lines.getmXMin();\n double xMax = _lines.getmXMax();\n double yMin = _lines.getmYMin();\n double yMax = _lines.getmYMax();\n\n _MappingManager.prepareRelation(xMin, xMax, yMin, yMax);\n }\n\n /**\n * 设置数据源\n *\n * @param lines\n */\n public void setLines(Lines lines) {\n _lines = lines;\n\n notifyDataChanged();\n postInvalidate();\n }\n\n public Lines getlines() {\n return _lines;\n }\n\n /**\n * 清空数据\n */\n public void clearData() {\n _lines = null;\n invalidate();\n }\n\n\n private void A______________________________________________() {\n\n }\n\n /**\n * Y方向进行动画\n */\n @UiThread\n public void animateY() {\n _LAnimator.animateY(1000);\n }\n\n /**\n * Y方向进行动画\n */\n @UiThread\n public void animateY(long duration) {\n _LAnimator.animateY(duration);\n }\n\n /**\n * X方向进行动画\n */\n @UiThread\n public void animateX() {\n _LAnimator.animateX(1000);\n }\n\n /**\n * X方向进行动画\n */\n @UiThread\n public void animateX(long duration) {\n _LAnimator.animateX(duration);\n }\n\n /**\n * X,Y方向进行动画\n */\n @UiThread\n public void animateXY() {\n _LAnimator.animateXY(1000);\n }\n\n /**\n * X,Y方向进行动画\n */\n @UiThread\n public void animateXY(long duration) {\n _LAnimator.animateXY(duration);\n }\n\n public LAnimator get_LAnimator() {\n return _LAnimator;\n }\n\n public void set_LAnimator(LAnimator _LAnimator) {\n this._LAnimator = _LAnimator;\n }\n\n\n private void B_________________________________________________() {\n\n }\n\n private void a______________________________________________() {\n\n }\n\n public boolean isCanX_drag() {\n return _TouchListener.isCanX_drag();\n }\n\n /**\n * 设置x方向是否可拖动\n *\n * @param canX_drag\n */\n public void setCanX_drag(boolean canX_drag) {\n _TouchListener.setCanX_drag(canX_drag);\n }\n\n public boolean isCanY_drag() {\n return _TouchListener.isCanY_drag();\n }\n\n /**\n * 设置y方向是否可拖动\n *\n * @param canY_drag\n */\n public void setCanY_drag(boolean canY_drag) {\n _TouchListener.setCanY_drag(canY_drag);\n }\n\n public boolean isZoom_alone() {\n return _TouchListener.isZoom_alone();\n }\n\n /**\n * 设置x,y方向是否可以独立缩放\n *\n * @param zoom_independent\n */\n public void setZoom_alone(boolean zoom_independent) {\n _TouchListener.setZoom_alone(zoom_independent);\n }\n\n public boolean isCanX_zoom() {\n return _TouchListener.isCanX_zoom();\n }\n\n /**\n * 设置x方向是否可以缩放\n *\n * @param canX_zoom\n */\n public void setCanX_zoom(boolean canX_zoom) {\n _TouchListener.setCanX_zoom(canX_zoom);\n }\n\n public boolean isCanY_zoom() {\n return _TouchListener.isCanY_zoom();\n }\n\n /**\n * 设置y方向是否可以缩放\n *\n * @param canY_zoom\n */\n public void setCanY_zoom(boolean canY_zoom) {\n _TouchListener.setCanY_zoom(canY_zoom);\n }\n\n public boolean isDragable() {\n return isDragable;\n }\n\n public void setDragable(boolean dragable) {\n isDragable = dragable;\n }\n\n public boolean isScaleable() {\n return isScaleable;\n }\n\n public void setScaleable(boolean scaleable) {\n isScaleable = scaleable;\n }\n\n public IDragListener get_dragListener() {\n return _dragListener;\n }\n\n public void set_dragListener(IDragListener _dragListener) {\n this._dragListener = _dragListener;\n }\n\n private void b______________________________________________() {\n\n }\n\n public float get_paddingLeft() {\n return _paddingLeft;\n }\n\n public void set_paddingLeft(float _paddingLeft) {\n this._paddingLeft = _paddingLeft;\n }\n\n public float get_paddingRight() {\n return _paddingRight;\n }\n\n public void set_paddingRight(float _paddingRight) {\n this._paddingRight = _paddingRight;\n }\n\n public float get_paddingTop() {\n return _paddingTop;\n }\n\n public void set_paddingTop(float _paddingTop) {\n this._paddingTop = _paddingTop;\n }\n\n public float get_paddingBottom() {\n return _paddingBottom;\n }\n\n public void set_paddingBottom(float _paddingBottom) {\n this._paddingBottom = _paddingBottom;\n }\n\n private void c______________________________________________() {\n\n }\n\n public double getVisiableMinX() {\n float px = _MainPlotRect.left;\n SingleD_XY xy = _MappingManager.getValueByPx(px, 0);\n return xy.getX();\n }\n\n public double getVisiableMaxX() {\n float px = _MainPlotRect.right;\n SingleD_XY xy = _MappingManager.getValueByPx(px, 0);\n return xy.getX();\n }\n\n public double getVisiableMinY() {\n float py = _MainPlotRect.bottom;\n SingleD_XY xy = _MappingManager.getValueByPx(0, py);\n return xy.getY();\n }\n\n public double getVisiableMaxY() {\n float py = _MainPlotRect.top;\n SingleD_XY xy = _MappingManager.getValueByPx(0, py);\n return xy.getY();\n }\n\n public RectD get_currentViewPort() {\n return _MappingManager.get_currentViewPort();\n }\n\n public void set_currentViewPort(RectD currentViewPort) {\n _MappingManager.set_currentViewPort(currentViewPort);\n }\n\n /**\n * 设置y轴的范围\n *\n * @param yMin\n * @param yMax\n */\n public void setYMax_Min(double yMin, double yMax) {\n if (_lines != null) {\n _lines.setYCustomMaxMin(true);\n _lines.setmYMin(yMin);\n _lines.setmYMax(yMax);\n postInvalidate();\n } else {\n LogUtil.e(\"setAxisMaxMin: 请在lines设置后,调用此方法!\");\n }\n }\n\n /**\n * 设置轴线的范围\n *\n * @param xMin\n * @param xMax\n */\n public void setXAix_MaxMin(double xMin, double xMax) {\n if (_lines != null) {\n _lines.setXCustomMaxMin(true);\n _lines.setmXMin(xMin);\n _lines.setmXMax(xMax);\n postInvalidate();\n } else {\n LogUtil.e(\"setAxisMaxMin: 请在lines设置后,调用此方法!\");\n }\n }\n\n private void d______________________________________________() {\n\n }\n\n /**\n * 获取映射管家\n *\n * @return\n */\n public MappingManager get_MappingManager() {\n return _MappingManager;\n }\n\n\n //////////////////////////////// 便捷的方法 //////////////////////////////////\n\n\n public CursorMode get_CursorMode() {\n return _CursorMode;\n }\n\n /**\n * 设置使用哪一个光标\n * ---------------------\n * 第一个?\n * 第二个?\n *\n * @param _CursorMode\n */\n public void set_CursorMode(CursorMode _CursorMode) {\n this._CursorMode = _CursorMode;\n }\n\n public void highLight_PixXY(float px, float py) {\n SingleD_XY xy = _MappingManager.getValueByPx(px, py);\n highLight_ValueXY(xy.getX(), xy.getY());\n }\n\n public void highLight_ValueXY(double x, double y) {\n\n if (_CursorMode == CursorMode.cursor1) {\n _HighLightRender1.highLight_ValueXY(x, y);\n } else if (_CursorMode == CursorMode.cursor2) {\n _HighLightRender2.highLight_ValueXY(x, y);\n }\n\n invalidate();\n }\n\n public void highLightLeft() {\n\n if (_CursorMode == CursorMode.cursor1) {\n _HighLightRender1.highLightLeft();\n } else if (_CursorMode == CursorMode.cursor2) {\n _HighLightRender2.highLightLeft();\n }\n\n invalidate();\n }\n\n public void highLightRight() {\n\n if (_CursorMode == CursorMode.cursor1) {\n _HighLightRender1.highLightRight();\n } else if (_CursorMode == CursorMode.cursor2) {\n _HighLightRender2.highLightRight();\n }\n\n invalidate();\n }\n\n public HighLight get_HighLight1() {\n return _HighLight1;\n }\n\n public HighLight get_HighLight2() {\n return _HighLight2;\n }\n\n public HighLightRender get_HighLightRender1() {\n return _HighLightRender1;\n }\n\n public HighLightRender get_HighLightRender2() {\n return _HighLightRender2;\n }\n\n public XAxis get_XAxis() {\n return _XAxis;\n }\n\n public YAxis get_YAxis() {\n return _YAxis;\n }\n\n public RectF get_GodRect() {\n return _GodRect;\n }\n\n public void set_GodRect(RectF _GodRect) {\n this._GodRect = _GodRect;\n }\n\n public RectF get_MainPlotRect() {\n return _MainPlotRect;\n }\n\n public void set_MainPlotRect(RectF _MainPlotRect) {\n this._MainPlotRect = _MainPlotRect;\n }\n\n public ChartMode get_ChartMode() {\n return _ChartMode;\n }\n\n public LineChart set_ChartMode(ChartMode _ChartMode) {\n this._ChartMode = _ChartMode;\n return this;\n }\n\n LineChart _ob_linechart;\n\n public void registObserver(LineChart lineChartOb) {\n this._ob_linechart = lineChartOb;\n\n notifyDataChanged_FromOb(lineChartOb);\n }\n\n public void notifyDataChanged_FromOb(LineChart lineChartOb) {\n\n // x,y轴上的单位\n XAxis xAxis = lineChartOb.get_XAxis();\n this.get_XAxis().set_unit(xAxis.get_unit());\n\n YAxis yAxis = lineChartOb.get_YAxis();\n this.get_YAxis().set_unit(yAxis.get_unit());\n\n this.setLines(lineChartOb.getlines());\n }\n\n public void notifyOB_ViewportChanged(RectD _currentViewPort) {\n _ob_linechart.set_CurrentViewPort(_currentViewPort);\n _ob_linechart.invalidate();\n }\n\n public LineChart set_CurrentViewPort(RectD _currentViewPort) {\n _MappingManager.set_currentViewPort(_currentViewPort);\n return this;\n }\n\n\n public enum ChartMode {\n Normal, God\n }\n\n public enum CursorMode {\n cursor1, cursor2\n }\n\n\n}", "public class Entry {\n\n double x;\n double y;\n\n boolean isNull_Y = false;\n\n public Entry(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n\n public double getX() {\n return x;\n }\n\n public Entry setX(double x) {\n this.x = x;\n return this;\n }\n\n public double getY() {\n return y;\n }\n\n public Entry setY(double y) {\n this.y = y;\n return this;\n }\n\n public boolean isNull_Y() {\n return isNull_Y;\n }\n\n public Entry setNull_Y() {\n isNull_Y = true;\n return this;\n }\n\n @Override\n public String toString() {\n return \"entry x:\" + x + \" y:\" + y;\n }\n}", "public class Line {\n\n private List<Entry> entries = new ArrayList<>();\n\n\n private double mYMax = Double.MIN_VALUE;\n private double mYMin = Double.MAX_VALUE;\n private double mXMax = Double.MIN_VALUE;\n private double mXMin = Double.MAX_VALUE;\n\n private int lineColor = Color.BLACK;\n private int lineWidth = 1;\n private int circleColor = Color.RED;\n private int circleR = 4;\n\n private boolean isFilled = false;\n private int lineAlpha = 50;\n\n private boolean isEnable = true;\n private boolean isDrawCircle = true;\n private boolean isDrawLegend = false;\n private int legendWidth = 50;\n private int legendHeight = 17;\n private int legendTextSize = 8;\n private String name = \"line\";\n\n private CallBack_OnEntryClick onEntryClick;\n\n public Line() {\n this(null);\n }\n\n public Line(List<Entry> entries) {\n\n circleR = (int) Utils.dp2px(circleR);\n legendWidth = (int) Utils.dp2px(legendWidth);\n legendTextSize = (int) Utils.dp2px(legendTextSize);\n legendHeight = (int) Utils.dp2px(legendHeight);\n\n if (entries != null) {\n setEntries(entries);\n }\n }\n\n private void calMinMax(List<Entry> entries) {\n\n mYMax = -Double.MAX_VALUE;\n mYMin = Double.MAX_VALUE;\n mXMax = -Double.MAX_VALUE;\n mXMin = Double.MAX_VALUE;\n\n for (Entry entry : entries) {\n\n if (entry.getX() < mXMin) {\n mXMin = entry.getX();\n }\n if (entry.getX() > mXMax) {\n mXMax = entry.getX();\n }\n\n if (entry.getY() < mYMin) {\n mYMin = entry.getY();\n }\n if (entry.getY() > mYMax) {\n mYMax = entry.getY();\n }\n }\n }\n\n /**\n * 在数组的前面添加数据\n *\n * @param entry\n */\n public void addEntryInHead(Entry entry) {\n if (entries == null) {\n entries = new ArrayList<>();\n }\n entries.add(0, entry);\n\n // 计算最大最小\n if (entry.getX() < mXMin) {\n mXMin = entry.getX();\n }\n if (entry.getX() > mXMax) {\n mXMax = entry.getX();\n }\n\n if (entry.getY() < mYMin) {\n mYMin = entry.getY();\n }\n if (entry.getY() > mYMax) {\n mYMax = entry.getY();\n }\n }\n\n public void addEntry(Entry entry) {\n if (entries == null) {\n entries = new ArrayList<>();\n }\n entries.add(entry);\n\n // 计算最大最小\n if (entry.getX() < mXMin) {\n mXMin = entry.getX();\n }\n if (entry.getX() > mXMax) {\n mXMax = entry.getX();\n }\n\n if (entry.getY() < mYMin) {\n mYMin = entry.getY();\n }\n if (entry.getY() > mYMax) {\n mYMax = entry.getY();\n }\n }\n\n public List<Entry> getEntries() {\n return entries;\n }\n\n public void setEntries(List<Entry> entries) {\n // check\n if (entries == null) {\n throw new IllegalArgumentException(\"entries must be no null\");\n }\n\n this.entries = entries;\n\n calMinMax(entries);\n }\n\n\n /**\n * 根据提供的 x数值,找出list中离它最近的数,返回其下标。\n * --------------\n * 考虑到性能的原因,采用二分查找法。(速度很快,不错!)\n *\n * @param entries\n * @param hitValue\n * @param rounding\n * @return\n */\n public static int getEntryIndex(List<Entry> entries, double hitValue, Rounding rounding) {\n\n if (entries == null || entries.isEmpty())\n return -1;\n\n int low = 0;\n int high = entries.size() - 1;\n int closet = low;\n\n while (low < high) {\n int m = (low + high) / 2;\n\n double fm = entries.get(m).getX();// middle\n double fr = entries.get(m + 1).getX();// right\n\n if (hitValue >= fm && hitValue <= fr) {\n\n // 中_右\n double d1 = Math.abs(hitValue - fm);\n double d2 = Math.abs(hitValue - fr);\n\n if (d1 <= d2) {\n closet = m;\n } else {\n closet = m + 1;\n }\n\n low = high = closet;\n break;\n\n } else if (hitValue < fm) {\n\n if (m >= 1) {\n double fl = entries.get(m - 1).getX();// left\n\n if (hitValue >= fl && hitValue <= fm) {\n // 中_左\n double d0 = Math.abs(hitValue - fl);\n double d1 = Math.abs(hitValue - fm);\n\n if (d0 <= d1) {\n closet = m - 1;\n } else {\n closet = m;\n }\n\n low = high = closet;\n break;\n }\n }\n\n high = m - 1;\n closet = high;\n } else if (hitValue > fr) {\n low = m + 1;\n closet = low;\n }\n }\n\n // trick\n high++;\n low--;\n closet = Math.min(Math.max(closet, 0), entries.size() - 1);\n\n int result = low;\n if (rounding == Rounding.UP) {\n result = Math.min(high, entries.size() - 1);//多一个\n } else if (rounding == Rounding.DOWN) {\n result = Math.max(low, 0);//少一个\n } else if (rounding == Rounding.CLOSEST) {\n result = closet;\n }\n return result;\n }\n\n\n public double getmYMax() {\n return mYMax;\n }\n\n public void setmYMax(double mYMax) {\n this.mYMax = mYMax;\n }\n\n public double getmYMin() {\n return mYMin;\n }\n\n public void setmYMin(double mYMin) {\n this.mYMin = mYMin;\n }\n\n public double getmXMax() {\n return mXMax;\n }\n\n public void setmXMax(double mXMax) {\n this.mXMax = mXMax;\n }\n\n public double getmXMin() {\n return mXMin;\n }\n\n public void setmXMin(double mXMin) {\n this.mXMin = mXMin;\n }\n\n public int getLineColor() {\n return lineColor;\n }\n\n public void setLineColor(int lineColor) {\n this.lineColor = lineColor;\n }\n\n public int getLineWidth() {\n return lineWidth;\n }\n\n public void setLineWidth(int lineWidth) {\n this.lineWidth = lineWidth;\n }\n\n public boolean isEnable() {\n return isEnable;\n }\n\n public void setEnable(boolean enable) {\n isEnable = enable;\n }\n\n public boolean isDrawCircle() {\n return isDrawCircle;\n }\n\n public void setDrawCircle(boolean drawCircle) {\n isDrawCircle = drawCircle;\n }\n\n public int getLegendHeight() {\n return legendHeight;\n }\n\n public void setLegendHeight(int legendHeight) {\n this.legendHeight = legendHeight;\n }\n\n public int getLegendTextSize() {\n return legendTextSize;\n }\n\n public void setLegendTextSize(int legendTextSize) {\n this.legendTextSize = legendTextSize;\n }\n\n public int getLegendWidth() {\n return legendWidth;\n }\n\n public void setLegendWidth(int legendWidth) {\n this.legendWidth = legendWidth;\n }\n\n public boolean isDrawLegend() {\n return isDrawLegend;\n }\n\n public void setDrawLegend(boolean drawLegend) {\n isDrawLegend = drawLegend;\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 getCircleR() {\n return circleR;\n }\n\n public void setCircleR(int circleR) {\n this.circleR = circleR;\n }\n\n public int getCircleColor() {\n return circleColor;\n }\n\n public void setCircleColor(int circleColor) {\n this.circleColor = circleColor;\n }\n\n public CallBack_OnEntryClick getOnEntryClick() {\n return onEntryClick;\n }\n\n public void setOnEntryClick(CallBack_OnEntryClick onEntryClick) {\n this.onEntryClick = onEntryClick;\n }\n\n public boolean isFilled() {\n return isFilled;\n }\n\n public void setFilled(boolean filled) {\n isFilled = filled;\n }\n\n public int getLineAlpha() {\n return lineAlpha;\n }\n\n public void setLineAlpha(int lineAlpha) {\n this.lineAlpha = lineAlpha;\n }\n\n public enum Rounding {\n UP,\n DOWN,\n CLOSEST,\n }\n\n public interface CallBack_OnEntryClick {\n void onEntry(Line line, Entry entry);\n }\n\n}", "public class Lines {\n\n private List<Line> lines = new ArrayList<>();\n\n /************************ x,y的范围 **********************/\n private double mYMax;\n private double mYMin;\n private double mXMax;\n private double mXMin;\n\n /**\n * 是否使用 设置的最小最大值\n */\n private boolean isYCustomMaxMin = false;\n /**\n * 是否使用 设置的最小最大值\n */\n private boolean isXCustomMaxMin = false;\n\n public Lines() {\n }\n\n public Lines(List<Line> lines) {\n setLines(lines);\n }\n\n public List<Line> getLines() {\n return lines;\n }\n\n public void setLines(List<Line> lines) {\n this.lines = lines;\n calMinMax(lines);\n }\n\n public void addLine(Line line) {\n lines.add(line);\n calMinMax(lines);\n }\n\n private void calMinMax(List<Line> lines) {\n\n if (!isXCustomMaxMin) {\n mXMax = Double.MIN_VALUE;\n mXMin = Double.MAX_VALUE;\n }\n\n if (!isYCustomMaxMin) {\n mYMax = Double.MIN_VALUE;\n mYMin = Double.MAX_VALUE;\n }\n\n for (Line line : lines) {\n\n if (!isXCustomMaxMin) {\n if (line.getmXMin() < mXMin) {\n mXMin = line.getmXMin();\n }\n if (line.getmXMax() > mXMax) {\n mXMax = line.getmXMax();\n }\n }\n\n if (!isYCustomMaxMin) {\n if (line.getmYMin() < mYMin) {\n mYMin = line.getmYMin();\n }\n if (line.getmYMax() > mYMax) {\n mYMax = line.getmYMax();\n }\n }\n }\n\n // 考虑到只有一个点的问题\n if (mXMax == mXMin) {\n double half = Math.abs(mXMax) / 2;\n mXMax += half;\n mXMin -= half;\n }\n\n if (mYMax == mYMin) {\n double half = Math.abs(mYMax) / 2;\n mYMax += half;\n mYMin -= half;\n }\n }\n\n public void calMinMax() {\n\n if (lines != null) {\n calMinMax(lines);\n }\n }\n\n\n public double getmYMax() {\n return mYMax;\n }\n\n public void setmYMax(double mYMax) {\n this.mYMax = mYMax;\n }\n\n public double getmYMin() {\n return mYMin;\n }\n\n public void setmYMin(double mYMin) {\n this.mYMin = mYMin;\n }\n\n public double getmXMax() {\n return mXMax;\n }\n\n public void setmXMax(double mXMax) {\n this.mXMax = mXMax;\n }\n\n public double getmXMin() {\n return mXMin;\n }\n\n public void setmXMin(double mXMin) {\n this.mXMin = mXMin;\n }\n\n public boolean isYCustomMaxMin() {\n return isYCustomMaxMin;\n }\n\n public void setYCustomMaxMin(boolean customMaxMin) {\n isYCustomMaxMin = customMaxMin;\n }\n\n public boolean isXCustomMaxMin() {\n return isXCustomMaxMin;\n }\n\n public void setXCustomMaxMin(boolean XCustomMaxMin) {\n isXCustomMaxMin = XCustomMaxMin;\n }\n}", "public class HighLight {\n\n public static final float D_HIGHLIGHT_WIDTH = 1;\n public static final float D_HINT_TEXT_SIZE = 15;\n\n //////////////////////// high light ////////////////////////\n int highLightColor = Color.RED;\n float highLightWidth;\n\n //////////////////////// hint ////////////////////////\n int hintColor = Color.BLACK;\n float hintTextSize;\n\n boolean enable = false;\n boolean isDrawHighLine = true;\n boolean isDrawHint = true;\n\n protected IValueAdapter xValueAdapter;// 高亮时,x应该如何显示?\n protected IValueAdapter yValueAdapter;// 高亮时,y应该如何显示?\n\n\n public HighLight() {\n\n highLightWidth = Utils.dp2px(D_HIGHLIGHT_WIDTH);\n hintTextSize = Utils.dp2px(D_HINT_TEXT_SIZE);\n\n xValueAdapter = new DefaultHighLightValueAdapter();\n yValueAdapter = new DefaultHighLightValueAdapter();\n }\n\n public HighLight(IValueAdapter xValueAdapter, IValueAdapter yValueAdapter) {\n this.xValueAdapter = xValueAdapter;\n this.yValueAdapter = yValueAdapter;\n }\n\n public int getHighLightColor() {\n return highLightColor;\n }\n\n public void setHighLightColor(int highLightColor) {\n this.highLightColor = highLightColor;\n }\n\n public float getHighLightWidth() {\n return highLightWidth;\n }\n\n public void setHighLightWidth(float highLightWidth) {\n this.highLightWidth = highLightWidth;\n }\n\n public int getHintColor() {\n return hintColor;\n }\n\n public void setHintColor(int hintColor) {\n this.hintColor = hintColor;\n }\n\n public float getHintTextSize() {\n return hintTextSize;\n }\n\n public void setHintTextSize(float hintTextSize) {\n this.hintTextSize = hintTextSize;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public boolean isDrawHighLine() {\n return isDrawHighLine;\n }\n\n public void setDrawHighLine(boolean drawHighLine) {\n isDrawHighLine = drawHighLine;\n }\n\n public boolean isDrawHint() {\n return isDrawHint;\n }\n\n public void setDrawHint(boolean drawHint) {\n isDrawHint = drawHint;\n }\n\n public IValueAdapter getxValueAdapter() {\n return xValueAdapter;\n }\n\n public HighLight setxValueAdapter(IValueAdapter xValueAdapter) {\n this.xValueAdapter = xValueAdapter;\n return this;\n }\n\n public IValueAdapter getyValueAdapter() {\n return yValueAdapter;\n }\n\n public HighLight setyValueAdapter(IValueAdapter yValueAdapter) {\n this.yValueAdapter = yValueAdapter;\n return this;\n }\n}", "public class XAxis extends Axis {\n\n public static final float AREA_UNIT = 14;// unit 区域的高\n public static final float AREA_LABEL = 14;// label 区域的高\n\n\n public XAxis() {\n super();\n\n labelDimen = Utils.dp2px(AREA_LABEL);\n unitDimen = Utils.dp2px(AREA_UNIT);\n }\n}", "public class YAxis extends Axis {\n\n public static final float AREA_UNIT = 14;// unit 区域的高\n public static final float AREA_LABEL = 14;// label 区域的高\n\n\n public YAxis() {\n super();\n\n labelDimen = Utils.dp2px(AREA_LABEL);\n unitDimen = Utils.dp2px(AREA_UNIT);\n }\n\n}" ]
import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.linheimx.app.library.adapter.DefaultValueAdapter; import com.linheimx.app.library.adapter.IValueAdapter; import com.linheimx.app.library.charts.LineChart; import com.linheimx.app.library.data.Entry; import com.linheimx.app.library.data.Line; import com.linheimx.app.library.data.Lines; import com.linheimx.app.library.model.HighLight; import com.linheimx.app.library.model.XAxis; import com.linheimx.app.library.model.YAxis; import java.util.ArrayList; import java.util.List;
package com.linheimx.app.lchart; public class NullEntityActivity extends AppCompatActivity { LineChart _lineChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_null_entity); _lineChart = (LineChart) findViewById(R.id.chart); setChartData(_lineChart); } private void setChartData(LineChart lineChart) { // lineChart.get_MappingManager().setFatFactor(1f);//设置 可见视图与原始数据视图的比例 // lineChart.setCanY_zoom(false);//设置只能y方向是否能缩放! // 高亮 HighLight highLight = lineChart.get_HighLight1(); highLight.setEnable(true);// 启用高亮显示 默认为启用状态 highLight.setxValueAdapter(new IValueAdapter() { @Override public String value2String(double value) { return "X:" + value; } }); highLight.setyValueAdapter(new IValueAdapter() { @Override public String value2String(double value) { return "Y:" + value; } }); // x,y轴上的单位 XAxis xAxis = lineChart.get_XAxis(); // xAxis.setCalWay(Axis.CalWay.every); // 轴线上label的计算方式 xAxis.set_unit("单位:s"); xAxis.set_ValueAdapter(new DefaultValueAdapter(1));
YAxis yAxis = lineChart.get_YAxis();
8
romelo333/notenoughwands
src/main/java/romelo333/notenoughwands/Items/GenericWand.java
[ "public class Config {\n public static String CATEGORY_WANDS = \"wands\";\n public static String CATEGORY_MOVINGBLACKLIST = \"movingblacklist\";\n\n public static void init(Configuration cfg) {\n GenericWand.setupConfig(cfg);\n }\n}", "public class ModItems {\n public static WandCore wandCore;\n public static AdvancedWandCore advancedWandCore;\n public static SwappingWand swappingWand;\n public static TeleportationWand teleportationWand;\n public static CapturingWand capturingWand;\n public static BuildingWand buildingWand;\n public static IlluminationWand illuminationWand;\n public static MovingWand movingWand;\n public static ProtectionWand protectionWand;\n public static ProtectionWand masterProtectionWand;\n public static DisplacementWand displacementWand;\n public static AccelerationWand accelerationWand;\n\n public static void init() {\n wandCore = new WandCore(\"WandCore\", \"wandCore\");\n advancedWandCore = new AdvancedWandCore(\"AdvancedWandCore\", \"advancedWandCore\");\n swappingWand = new SwappingWand();\n teleportationWand = new TeleportationWand();\n capturingWand = new CapturingWand();\n buildingWand = new BuildingWand();\n illuminationWand = new IlluminationWand();\n movingWand = new MovingWand();\n protectionWand = new ProtectionWand(false);\n masterProtectionWand = new ProtectionWand(true);\n displacementWand = new DisplacementWand();\n accelerationWand = new AccelerationWand();\n }\n}", "@Mod(modid = NotEnoughWands.MODID, name=\"Not Enough Wands\", dependencies =\n \"required-after:Forge@[\"+ NotEnoughWands.MIN_FORGE_VER+\",)\",\n version = NotEnoughWands.VERSION)\npublic class NotEnoughWands {\n public static final String MODID = \"NotEnoughWands\";\n public static final String VERSION = \"1.2.3\";\n public static final String MIN_FORGE_VER = \"10.13.2.1291\";\n\n @SidedProxy(clientSide=\"romelo333.notenoughwands.proxy.ClientProxy\", serverSide=\"romelo333.notenoughwands.proxy.ServerProxy\")\n public static CommonProxy proxy;\n\n @Mod.Instance(\"NotEnoughWands\")\n public static NotEnoughWands instance;\n public static Logger logger;\n public static File mainConfigDir;\n public static File modConfigDir;\n public static Configuration config;\n\n public static CreativeTabs tabNew = new CreativeTabs(\"NotEnoughWands\") {\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return ModItems.teleportationWand;\n }\n };\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 logger = e.getModLog();\n mainConfigDir = e.getModConfigurationDirectory();\n modConfigDir = new File(mainConfigDir.getPath());\n config = new Configuration(new File(modConfigDir, \"notenoughwands.cfg\"));\n proxy.preInit(e);\n\n// FMLInterModComms.sendMessage(\"Waila\", \"register\", \"mcjty.wailasupport.WailaCompatibility.load\");\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 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 proxy.postInit(e);\n }\n}", "public class ProtectedBlocks extends WorldSavedData{\n public static final String NAME = \"NEWProtectedBlocks\";\n private static ProtectedBlocks instance;\n\n // Persisted data\n private Map<GlobalCoordinate, Integer> blocks = new HashMap<GlobalCoordinate, Integer>(); // Map from coordinate -> ID\n private Map<Integer,Integer> counter = new HashMap<Integer, Integer>(); // Keep track of number of protected blocks per ID\n private int lastId = 1;\n\n public ProtectedBlocks(String name) {\n super(name);\n }\n\n public void save (World world){\n world.mapStorage.setData(NAME, this);\n markDirty();\n }\n\n public static ProtectedBlocks getProtectedBlocks (World world){\n if (world.isRemote){\n return null;\n }\n if (instance != null){\n return instance;\n }\n instance = (ProtectedBlocks)world.mapStorage.loadData(ProtectedBlocks.class,NAME);\n if (instance == null){\n instance = new ProtectedBlocks(NAME);\n }\n return instance;\n }\n\n public int getNewId(World world) {\n lastId++;\n save(world);\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, int x, int y, int z, int id) {\n GlobalCoordinate key = new GlobalCoordinate(x, y, z, world.provider.dimensionId);\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 incrementProtection(id);\n\n save(world);\n return true;\n }\n\n public boolean unprotect(EntityPlayer player, World world, int x, int y, int z, int id) {\n GlobalCoordinate key = new GlobalCoordinate(x, y, z, world.provider.dimensionId);\n if (!blocks.containsKey(key)) {\n Tools.error(player, \"This block is not prorected!\");\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 save(world);\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 }\n counter.put(id, 0);\n\n save(world);\n return cnt;\n }\n\n public boolean isProtected(World world, int x, int y, int z){\n return blocks.containsKey(new GlobalCoordinate(x, y, z, world.provider.dimensionId));\n }\n\n public boolean hasProtections() {\n return !blocks.isEmpty();\n }\n\n public void fetchProtectedBlocks(Set<Coordinate> 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.getDim() == world.provider.dimensionId) {\n float sqdist = (x - block.getX()) * (x - block.getX()) + (y - block.getY()) * (y - block.getY()) + (z - block.getZ()) * (z - block.getZ());\n if (sqdist < radius) {\n coordinates.add(block);\n }\n }\n }\n }\n }\n\n @Override\n public void readFromNBT(NBTTagCompound tagCompound) {\n lastId = tagCompound.getInteger(\"lastId\");\n blocks.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(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 void 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.getX());\n tc.setInteger(\"y\", block.getY());\n tc.setInteger(\"z\", block.getZ());\n tc.setInteger(\"dim\", block.getDim());\n tc.setInteger(\"id\", entry.getValue());\n list.appendTag(tc);\n }\n tagCompound.setTag(\"blocks\",list);\n }\n}", "public class Coordinate {\n private final int x;\n private final int y;\n private final int z;\n\n public Coordinate(int x, int y, int z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n public Coordinate add(ForgeDirection dir) {\n return new Coordinate(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ);\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public int getZ() {\n return z;\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 Coordinate that = (Coordinate) o;\n\n if (x != that.x) return false;\n if (y != that.y) return false;\n return z == that.z;\n\n }\n\n @Override\n public int hashCode() {\n int result = x;\n result = 31 * result + y;\n result = 31 * result + z;\n return result;\n }\n}", "public class Tools {\n public static void error(EntityPlayer player, String msg) {\n player.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.RED + msg));\n }\n\n public static void notify(EntityPlayer player, String msg) {\n player.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.GREEN + msg));\n }\n\n public static boolean consumeInventoryItem(Item item, int meta, InventoryPlayer inv, EntityPlayer player) {\n if (player.capabilities.isCreativeMode) {\n return true;\n }\n int i = finditem(item, meta, inv);\n\n if (i < 0) {\n return false;\n } else {\n if (--inv.mainInventory[i].stackSize <= 0) {\n inv.mainInventory[i] = null;\n }\n\n return true;\n }\n }\n\n public static void giveItem(World world, EntityPlayer player, Block block, int meta, int cnt, int x, int y, int z) {\n ItemStack oldStack = new ItemStack(block, cnt, meta);\n if (!player.inventory.addItemStackToInventory(oldStack)) {\n // Not enough room. Spawn item in world.\n EntityItem entityItem = new EntityItem(world, x, y, z, oldStack);\n world.spawnEntityInWorld(entityItem);\n }\n }\n\n public static int finditem(Item item, int meta, InventoryPlayer inv) {\n for (int i = 0; i < inv.mainInventory.length; ++i) {\n if (inv.mainInventory[i] != null && inv.mainInventory[i].getItem() == item && meta == inv.mainInventory[i].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 S29PacketSoundEffect soundEffect = new S29PacketSoundEffect(soundName, 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 ChunkCoordinates chunkcoordinates = entityplayermp.getPlayerCoordinates();\n double d7 = x - chunkcoordinates.posX;\n double d8 = y - chunkcoordinates.posY;\n double d9 = z - chunkcoordinates.posZ;\n double d10 = d7 * d7 + d8 * d8 + d9 * d9;\n\n if (d10 <= 256.0D) {\n entityplayermp.playerNetServerHandler.sendPacket(soundEffect);\n }\n }\n }\n\n}" ]
import cofh.api.energy.IEnergyContainerItem; import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.ChestGenHooks; import net.minecraftforge.common.config.Configuration; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import romelo333.notenoughwands.Config; import romelo333.notenoughwands.ModItems; import romelo333.notenoughwands.NotEnoughWands; import romelo333.notenoughwands.ProtectedBlocks; import romelo333.notenoughwands.varia.Coordinate; import romelo333.notenoughwands.varia.Tools; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set;
package romelo333.notenoughwands.Items; @Optional.InterfaceList({ @Optional.Interface(iface = "cofh.api.energy.IEnergyContainerItem", modid = "CoFHAPI")}) public class GenericWand extends Item implements IEnergyContainerItem { protected int needsxp = 0; protected int needsrf = 0; protected int maxrf = 0; protected int availability = AVAILABILITY_NORMAL; protected int lootRarity = 10; public static int AVAILABILITY_NOT = 0; public static int AVAILABILITY_CREATIVE = 1; public static int AVAILABILITY_ADVANCED = 2; public static int AVAILABILITY_NORMAL = 3; private static List<GenericWand> wands = new ArrayList<GenericWand>(); // Check if a given block can be picked up. public static double checkPickup(EntityPlayer player, World world, int x, int y, int z, Block block, float maxHardness, Map<String, Double> blacklisted) { float hardness = block.getBlockHardness(world, x, y, z); if (hardness > maxHardness){ Tools.error(player, "This block is to hard to take!"); return -1.0f; } if (!block.canEntityDestroy(world, x, y, z, player)){ Tools.error(player, "You are not allowed to take this block!"); return -1.0f; } ProtectedBlocks protectedBlocks = ProtectedBlocks.getProtectedBlocks(world); if (protectedBlocks.isProtected(world, x, y, z)) { Tools.error(player, "This block is protected. You cannot take it!"); return -1.0f; } double cost = 1.0f; String unlocName = block.getUnlocalizedName(); if (blacklisted.containsKey(unlocName)) { cost = blacklisted.get(unlocName); } if (cost <= 0.001f) { Tools.error(player, "It is illegal to take this block"); return -1.0f; } return cost; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { super.addInformation(stack, player, list, b); if (needsrf > 0) { list.add(EnumChatFormatting.GREEN+"Energy: " + getEnergyStored(stack) + " / " + getMaxEnergyStored(stack)); } } protected GenericWand setup(String name, String texture) { if (availability > 0) { setMaxStackSize(1); setNoRepair(); setUnlocalizedName(name);
setCreativeTab(NotEnoughWands.tabNew);
2
ogarcia/opensudoku
app/src/main/java/org/moire/opensudoku/gui/inputmethod/IMNumpad.java
[ "public class Cell {\n private final Object mCellCollectionLock = new Object();\n // if cell is included in collection, here are some additional information\n // about collection and cell's position in it\n private CellCollection mCellCollection;\n private int mRowIndex = -1;\n private int mColumnIndex = -1;\n private CellGroup mSector; // sector containing this cell\n private CellGroup mRow; // row containing this cell\n private CellGroup mColumn; // column containing this cell\n\n private int mValue;\n private CellNote mNote;\n private boolean mEditable;\n private boolean mValid;\n\n /**\n * Creates empty editable cell.\n */\n public Cell() {\n this(0, new CellNote(), true, true);\n }\n\n /**\n * Creates empty editable cell containing given value.\n *\n * @param value Value of the cell.\n */\n public Cell(int value) {\n this(value, new CellNote(), true, true);\n }\n\n private Cell(int value, CellNote note, boolean editable, boolean valid) {\n if (value < 0 || value > 9) {\n throw new IllegalArgumentException(\"Value must be between 0-9.\");\n }\n\n mValue = value;\n mNote = note;\n mEditable = editable;\n mValid = valid;\n }\n\n /**\n * Creates instance from given <code>StringTokenizer</code>.\n *\n * @param data\n * @return\n */\n public static Cell deserialize(StringTokenizer data, int version) {\n Cell cell = new Cell();\n cell.setValue(Integer.parseInt(data.nextToken()));\n cell.setNote(CellNote.deserialize(data.nextToken(), version));\n cell.setEditable(data.nextToken().equals(\"1\"));\n\n return cell;\n }\n\n /**\n * Creates instance from given string (string which has been\n * created by {@link #serialize(StringBuilder)} or {@link #serialize()} method).\n * earlier.\n *\n * @param cellData\n */\n public static Cell deserialize(String cellData) {\n StringTokenizer data = new StringTokenizer(cellData, \"|\");\n return deserialize(data, CellCollection.DATA_VERSION);\n }\n\n /**\n * Gets cell's row index within {@link CellCollection}.\n *\n * @return Cell's row index within CellCollection.\n */\n public int getRowIndex() {\n return mRowIndex;\n }\n\n /**\n * Gets cell's column index within {@link CellCollection}.\n *\n * @return Cell's column index within CellCollection.\n */\n public int getColumnIndex() {\n return mColumnIndex;\n }\n\n /**\n * Called when <code>Cell</code> is added to {@link CellCollection}.\n *\n * @param rowIndex Cell's row index within collection.\n * @param colIndex Cell's column index within collection.\n * @param sector Reference to sector group in which cell is included.\n * @param row Reference to row group in which cell is included.\n * @param column Reference to column group in which cell is included.\n */\n protected void initCollection(CellCollection cellCollection, int rowIndex, int colIndex,\n CellGroup sector, CellGroup row, CellGroup column) {\n synchronized (mCellCollectionLock) {\n mCellCollection = cellCollection;\n }\n\n mRowIndex = rowIndex;\n mColumnIndex = colIndex;\n mSector = sector;\n mRow = row;\n mColumn = column;\n\n sector.addCell(this);\n row.addCell(this);\n column.addCell(this);\n }\n\n /**\n * Returns sector containing this cell. Sector is 3x3 group of cells.\n *\n * @return Sector containing this cell.\n */\n public CellGroup getSector() {\n return mSector;\n }\n\n /**\n * Returns row containing this cell.\n *\n * @return Row containing this cell.\n */\n public CellGroup getRow() {\n return mRow;\n }\n\n /**\n * Returns column containing this cell.\n *\n * @return Column containing this cell.\n */\n public CellGroup getColumn() {\n return mColumn;\n }\n\n /**\n * Gets cell's value. Value can be 1-9 or 0 if cell is empty.\n *\n * @return Cell's value. Value can be 1-9 or 0 if cell is empty.\n */\n public int getValue() {\n return mValue;\n }\n\n /**\n * Sets cell's value. Value can be 1-9 or 0 if cell should be empty.\n *\n * @param value 1-9 or 0 if cell should be empty.\n */\n public void setValue(int value) {\n if (value < 0 || value > 9) {\n throw new IllegalArgumentException(\"Value must be between 0-9.\");\n }\n mValue = value;\n onChange();\n }\n\n /**\n * Gets note attached to the cell.\n *\n * @return Note attached to the cell.\n */\n public CellNote getNote() {\n return mNote;\n }\n\n /**\n * Sets note attached to the cell\n *\n * @param note Note attached to the cell\n */\n public void setNote(CellNote note) {\n mNote = note;\n onChange();\n }\n\n /**\n * Returns whether cell can be edited.\n *\n * @return True if cell can be edited.\n */\n public boolean isEditable() {\n return mEditable;\n }\n\n /**\n * Sets whether cell can be edited.\n *\n * @param editable True, if cell should allow editing.\n */\n public void setEditable(Boolean editable) {\n mEditable = editable;\n onChange();\n }\n\n /**\n * Returns true, if cell contains valid value according to sudoku rules.\n *\n * @return True, if cell contains valid value according to sudoku rules.\n */\n public boolean isValid() {\n return mValid;\n }\n\n /**\n * Sets whether cell contains valid value according to sudoku rules.\n *\n * @param valid\n */\n public void setValid(Boolean valid) {\n mValid = valid;\n onChange();\n }\n\n /**\n * Appends string representation of this object to the given <code>StringBuilder</code>\n * in a given data format version.\n * You can later recreate object from this string by calling {@link #deserialize}.\n *\n * @see CellCollection#serialize(StringBuilder, int) for supported data format versions.\n *\n * @param data A <code>StringBuilder</code> where to write data.\n */\n public void serialize(StringBuilder data, int dataVersion) {\n if (dataVersion == CellCollection.DATA_VERSION_PLAIN) {\n data.append(mValue);\n } else {\n data.append(mValue).append(\"|\");\n if (mNote == null || mNote.isEmpty()) {\n data.append(\"0\").append(\"|\");\n } else {\n mNote.serialize(data);\n }\n data.append(mEditable ? \"1\" : \"0\").append(\"|\");\n }\n }\n\n /**\n * Returns a string representation of this object in a default data format version.\n *\n * @see #serialize(StringBuilder, int)\n *\n * @return A string representation of this object.\n */\n public String serialize() {\n StringBuilder sb = new StringBuilder();\n serialize(sb, CellCollection.DATA_VERSION);\n return sb.toString();\n }\n\n /**\n * Returns a string representation of this object in a given data format version.\n *\n * @see #serialize(StringBuilder, int)\n *\n * @param dataVersion A version of data format.\n * @return A string representation of this object.\n */\n public String serialize(int dataVersion) {\n StringBuilder sb = new StringBuilder();\n serialize(sb, dataVersion);\n return sb.toString();\n }\n\n /**\n * Notify CellCollection that something has changed.\n */\n private void onChange() {\n synchronized (mCellCollectionLock) {\n if (mCellCollection != null) {\n mCellCollection.onChange();\n }\n\n }\n }\n}", "public class CellCollection {\n\n public static final int SUDOKU_SIZE = 9;\n\n /**\n * String is expected to be in format \"00002343243202...\", where each number represents\n * cell value, no other information can be set using this method.\n */\n public static int DATA_VERSION_PLAIN = 0;\n\n /**\n * See {@link #DATA_PATTERN_VERSION_1} and {@link #serialize()}.\n * Notes stored as an array of numbers\n */\n public static int DATA_VERSION_1 = 1;\n\n /**\n * Notes stored as a single number.\n */\n public static int DATA_VERSION_2 = 2;\n\n /**\n * There was a bug in the version 2. Notes stored with an additional bar character |.\n * So, it was impossible to get the import regex matched.\n * The V2 regex was modified to allow double bar symbols\n * Bug was fixed, but version has to be changed\n */\n public static int DATA_VERSION_3 = 3;\n\n public static int DATA_VERSION = DATA_VERSION_3;\n private static Pattern DATA_PATTERN_VERSION_PLAIN = Pattern.compile(\"^\\\\d{81}$\");\n private static Pattern DATA_PATTERN_VERSION_1 = Pattern.compile(\"^version: 1\\\\n((?#value)\\\\d\\\\|(?#note)((\\\\d,)+|-)\\\\|(?#editable)[01]\\\\|){0,81}$\");\n private static Pattern DATA_PATTERN_VERSION_2 = Pattern.compile(\"^version: 2\\\\n((?#value)\\\\d\\\\|(?#note)(\\\\d){1,3}\\\\|{1,2}(?#editable)[01]\\\\|){0,81}$\");\n private static Pattern DATA_PATTERN_VERSION_3 = Pattern.compile(\"^version: 3\\\\n((?#value)\\\\d\\\\|(?#note)(\\\\d){1,3}\\\\|(?#editable)[01]\\\\|){0,81}$\");\n private final List<OnChangeListener> mChangeListeners = new ArrayList<>();\n // TODO: An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects\n // Cell's data.\n private Cell[][] mCells;\n // Helper arrays, contains references to the groups of cells, which should contain unique\n // numbers.\n private CellGroup[] mSectors;\n private CellGroup[] mRows;\n private CellGroup[] mColumns;\n private boolean mOnChangeEnabled = true;\n\n /**\n * Wraps given array in this object.\n *\n * @param cells\n */\n private CellCollection(Cell[][] cells) {\n\n mCells = cells;\n initCollection();\n }\n\n /**\n * Creates empty sudoku.\n *\n * @return\n */\n public static CellCollection createEmpty() {\n Cell[][] cells = new Cell[SUDOKU_SIZE][SUDOKU_SIZE];\n\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n cells[r][c] = new Cell();\n }\n }\n\n return new CellCollection(cells);\n }\n\n /**\n * Generates debug game.\n *\n * @return\n */\n public static CellCollection createDebugGame() {\n CellCollection debugGame = new CellCollection(new Cell[][]{\n {new Cell(), new Cell(), new Cell(), new Cell(4), new Cell(5), new Cell(6), new Cell(7), new Cell(8), new Cell(9),},\n {new Cell(), new Cell(), new Cell(), new Cell(7), new Cell(8), new Cell(9), new Cell(1), new Cell(2), new Cell(3),},\n {new Cell(), new Cell(), new Cell(), new Cell(1), new Cell(2), new Cell(3), new Cell(4), new Cell(5), new Cell(6),},\n {new Cell(2), new Cell(3), new Cell(4), new Cell(), new Cell(), new Cell(), new Cell(8), new Cell(9), new Cell(1),},\n {new Cell(5), new Cell(6), new Cell(7), new Cell(), new Cell(), new Cell(), new Cell(2), new Cell(3), new Cell(4),},\n {new Cell(8), new Cell(9), new Cell(1), new Cell(), new Cell(), new Cell(), new Cell(5), new Cell(6), new Cell(7),},\n {new Cell(3), new Cell(4), new Cell(5), new Cell(6), new Cell(7), new Cell(8), new Cell(9), new Cell(1), new Cell(2),},\n {new Cell(6), new Cell(7), new Cell(8), new Cell(9), new Cell(1), new Cell(2), new Cell(3), new Cell(4), new Cell(5),},\n {new Cell(9), new Cell(1), new Cell(2), new Cell(3), new Cell(4), new Cell(5), new Cell(6), new Cell(7), new Cell(8),},\n });\n debugGame.markFilledCellsAsNotEditable();\n return debugGame;\n }\n\n /**\n * Creates instance from given <code>StringTokenizer</code>.\n *\n * @param data\n * @return\n */\n public static CellCollection deserialize(StringTokenizer data, int version) {\n Cell[][] cells = new Cell[SUDOKU_SIZE][SUDOKU_SIZE];\n\n int r = 0, c = 0;\n while (data.hasMoreTokens() && r < 9) {\n cells[r][c] = Cell.deserialize(data, version);\n c++;\n\n if (c == 9) {\n r++;\n c = 0;\n }\n }\n\n return new CellCollection(cells);\n }\n\n /**\n * Creates instance from given string (string which has been\n * created by {@link #serialize(StringBuilder)} or {@link #serialize()} method).\n * earlier.\n *\n * @param note\n */\n public static CellCollection deserialize(String data) {\n // TODO: use DATA_PATTERN_VERSION_1 to validate and extract puzzle data\n String[] lines = data.split(\"\\n\");\n if (lines.length == 0) {\n throw new IllegalArgumentException(\"Cannot deserialize Sudoku, data corrupted.\");\n }\n\n String line = lines[0];\n if (line.startsWith(\"version:\")) {\n String[] kv = line.split(\":\");\n int version = Integer.parseInt(kv[1].trim());\n StringTokenizer st = new StringTokenizer(lines[1], \"|\");\n return deserialize(st, version);\n } else {\n return fromString(data);\n }\n }\n\n /**\n * Creates collection instance from given string. String is expected\n * to be in format \"00002343243202...\", where each number represents\n * cell value, no other information can be set using this method.\n *\n * @param data\n * @return\n */\n public static CellCollection fromString(String data) {\n // TODO: validate\n\n Cell[][] cells = new Cell[SUDOKU_SIZE][SUDOKU_SIZE];\n\n int pos = 0;\n for (int r = 0; r < CellCollection.SUDOKU_SIZE; r++) {\n for (int c = 0; c < CellCollection.SUDOKU_SIZE; c++) {\n int value = 0;\n while (pos < data.length()) {\n pos++;\n if (data.charAt(pos - 1) >= '0'\n && data.charAt(pos - 1) <= '9') {\n // value=Integer.parseInt(data.substring(pos-1, pos));\n value = data.charAt(pos - 1) - '0';\n break;\n }\n }\n Cell cell = new Cell();\n cell.setValue(value);\n cell.setEditable(value == 0);\n cells[r][c] = cell;\n }\n }\n\n return new CellCollection(cells);\n }\n\n /**\n * Returns true, if given <code>data</code> conform to format of given data version.\n *\n * @param data\n * @param dataVersion\n * @return\n */\n public static boolean isValid(String data, int dataVersion) {\n if (dataVersion == DATA_VERSION_PLAIN) {\n return DATA_PATTERN_VERSION_PLAIN.matcher(data).matches();\n } else if (dataVersion == DATA_VERSION_1) {\n return DATA_PATTERN_VERSION_1.matcher(data).matches();\n } else if (dataVersion == DATA_VERSION_2) {\n return DATA_PATTERN_VERSION_2.matcher(data).matches();\n } else if (dataVersion == DATA_VERSION_3) {\n return DATA_PATTERN_VERSION_3.matcher(data).matches();\n } else {\n throw new IllegalArgumentException(\"Unknown version: \" + dataVersion);\n }\n }\n\n /**\n * Returns true, if given <code>data</code> conform to format of any version.\n *\n * @param data\n * @return\n */\n public static boolean isValid(String data) {\n return (DATA_PATTERN_VERSION_PLAIN.matcher(data).matches() ||\n DATA_PATTERN_VERSION_1.matcher(data).matches() ||\n DATA_PATTERN_VERSION_2.matcher(data).matches() ||\n DATA_PATTERN_VERSION_3.matcher(data).matches()\n );\n }\n\n /**\n * Return true, if no value is entered in any of cells.\n *\n * @return\n */\n public boolean isEmpty() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n if (cell.getValue() != 0)\n return false;\n }\n }\n return true;\n }\n\n public Cell[][] getCells() {\n return mCells;\n }\n\n /**\n * Gets cell at given position.\n *\n * @param rowIndex\n * @param colIndex\n * @return\n */\n public Cell getCell(int rowIndex, int colIndex) {\n return mCells[rowIndex][colIndex];\n }\n\n public Cell findFirstCell(int val) {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n if (cell.getValue() == val)\n return cell;\n }\n }\n return null;\n }\n\n public void markAllCellsAsValid() {\n mOnChangeEnabled = false;\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n mCells[r][c].setValid(true);\n }\n }\n mOnChangeEnabled = true;\n onChange();\n }\n\n /**\n * Validates numbers in collection according to the sudoku rules. Cells with invalid\n * values are marked - you can use getInvalid method of cell to find out whether cell\n * contains valid value.\n *\n * @return True if validation is successful.\n */\n public boolean validate() {\n\n boolean valid = true;\n\n // first set all cells as valid\n markAllCellsAsValid();\n\n mOnChangeEnabled = false;\n // run validation in groups\n for (CellGroup row : mRows) {\n if (!row.validate()) {\n valid = false;\n }\n }\n for (CellGroup column : mColumns) {\n if (!column.validate()) {\n valid = false;\n }\n }\n for (CellGroup sector : mSectors) {\n if (!sector.validate()) {\n valid = false;\n }\n }\n\n mOnChangeEnabled = true;\n onChange();\n\n return valid;\n }\n\n public boolean isCompleted() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n if (cell.getValue() == 0 || !cell.isValid()) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Marks all cells as editable.\n */\n public void markAllCellsAsEditable() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n cell.setEditable(true);\n }\n }\n }\n\n /**\n * Marks all filled cells (cells with value other than 0) as not editable.\n */\n public void markFilledCellsAsNotEditable() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n cell.setEditable(cell.getValue() == 0);\n }\n }\n }\n\n /**\n * Fills in all valid notes for all cells based on the values in each row, column, and sector.\n * This is a destructive operation in that the existing notes are overwritten.\n */\n public void fillInNotes() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = getCell(r, c);\n cell.setNote(new CellNote());\n\n CellGroup row = cell.getRow();\n CellGroup column = cell.getColumn();\n CellGroup sector = cell.getSector();\n for (int i = 1; i <= SUDOKU_SIZE; i++) {\n if (row.DoesntContain(i) && column.DoesntContain(i) && sector.DoesntContain(i)) {\n cell.setNote(cell.getNote().addNumber(i));\n }\n }\n }\n }\n }\n\n /**\n * Fills in notes with all values for all cells.\n * This is a destructive operation in that the existing notes are overwritten.\n */\n public void fillInNotesWithAllValues() {\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = getCell(r, c);\n cell.setNote(new CellNote());\n for (int i = 1; i <= SUDOKU_SIZE; i++) {\n cell.setNote(cell.getNote().addNumber(i));\n }\n }\n }\n }\n\n public void removeNotesForChangedCell(Cell cell, int number) {\n if (number < 1 || number > 9) {\n return;\n }\n\n CellGroup row = cell.getRow();\n CellGroup column = cell.getColumn();\n CellGroup sector = cell.getSector();\n for (int i = 0; i < SUDOKU_SIZE; i++) {\n row.getCells()[i].setNote(row.getCells()[i].getNote().removeNumber(number));\n column.getCells()[i].setNote(column.getCells()[i].getNote().removeNumber(number));\n sector.getCells()[i].setNote(sector.getCells()[i].getNote().removeNumber(number));\n }\n }\n\n /**\n * Returns how many times each value is used in <code>CellCollection</code>.\n * Returns map with entry for each value.\n *\n * @return\n */\n public Map<Integer, Integer> getValuesUseCount() {\n Map<Integer, Integer> valuesUseCount = new HashMap<>();\n for (int value = 1; value <= CellCollection.SUDOKU_SIZE; value++) {\n valuesUseCount.put(value, 0);\n }\n\n for (int r = 0; r < CellCollection.SUDOKU_SIZE; r++) {\n for (int c = 0; c < CellCollection.SUDOKU_SIZE; c++) {\n int value = getCell(r, c).getValue();\n if (value != 0) {\n valuesUseCount.put(value, valuesUseCount.get(value) + 1);\n }\n }\n }\n\n return valuesUseCount;\n }\n\n /**\n * Initializes collection, initialization has two steps:\n * 1) Groups of cells which must contain unique numbers are created.\n * 2) Row and column index for each cell is set.\n */\n private void initCollection() {\n mRows = new CellGroup[SUDOKU_SIZE];\n mColumns = new CellGroup[SUDOKU_SIZE];\n mSectors = new CellGroup[SUDOKU_SIZE];\n\n for (int i = 0; i < SUDOKU_SIZE; i++) {\n mRows[i] = new CellGroup();\n mColumns[i] = new CellGroup();\n mSectors[i] = new CellGroup();\n }\n\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n\n cell.initCollection(this, r, c,\n mSectors[((c / 3) * 3) + (r / 3)],\n mRows[c],\n mColumns[r]\n );\n }\n }\n }\n\n /**\n * Returns a string representation of this collection in a default\n * ({@link #DATA_PATTERN_VERSION_3}) format version.\n *\n * @see #serialize(StringBuilder, int)\n *\n * @return A string representation of this collection.\n */\n public String serialize() {\n StringBuilder sb = new StringBuilder();\n serialize(sb, DATA_VERSION);\n return sb.toString();\n }\n\n /**\n * Returns a string representation of this collection in a given data format version.\n *\n * @see #serialize(StringBuilder, int)\n *\n * @return A string representation of this collection.\n */\n public String serialize(int dataVersion) {\n StringBuilder sb = new StringBuilder();\n serialize(sb, dataVersion);\n return sb.toString();\n }\n\n /**\n * Writes collection to given <code>StringBuilder</code> in a default\n * ({@link #DATA_PATTERN_VERSION_3}) data format version.\n *\n * @see #serialize(StringBuilder, int)\n */\n public void serialize(StringBuilder data) {\n serialize(data, DATA_VERSION);\n }\n\n /**\n * Writes collection to given <code>StringBuilder</code> in a given data format version.\n * You can later recreate object instance by calling {@link #deserialize(String)} method.\n *\n * Supports only {@link #DATA_PATTERN_VERSION_PLAIN} and {@link #DATA_PATTERN_VERSION_3} formats.\n * All the other data format versions are ignored and treated as\n * {@link #DATA_PATTERN_VERSION_3} format.\n *\n * @see #DATA_PATTERN_VERSION_PLAIN\n * @see #DATA_PATTERN_VERSION_3\n *\n * @param data A <code>StringBuilder</code> where to write data.\n * @param dataVersion A version of data format.\n */\n public void serialize(StringBuilder data, int dataVersion) {\n if (dataVersion > DATA_VERSION_PLAIN) {\n data.append(\"version: \");\n data.append(dataVersion);\n data.append(\"\\n\");\n }\n for (int r = 0; r < SUDOKU_SIZE; r++) {\n for (int c = 0; c < SUDOKU_SIZE; c++) {\n Cell cell = mCells[r][c];\n cell.serialize(data, dataVersion);\n }\n }\n }\n\n public void addOnChangeListener(OnChangeListener listener) {\n if (listener == null) {\n throw new IllegalArgumentException(\"The listener is null.\");\n }\n synchronized (mChangeListeners) {\n if (mChangeListeners.contains(listener)) {\n throw new IllegalStateException(\"Listener \" + listener + \"is already registered.\");\n }\n mChangeListeners.add(listener);\n }\n }\n\n public void removeOnChangeListener(OnChangeListener listener) {\n if (listener == null) {\n throw new IllegalArgumentException(\"The listener is null.\");\n }\n synchronized (mChangeListeners) {\n if (!mChangeListeners.contains(listener)) {\n throw new IllegalStateException(\"Listener \" + listener + \" was not registered.\");\n }\n mChangeListeners.remove(listener);\n }\n }\n\n /**\n * Returns whether change notification is enabled.\n * <p>\n * If true, change notifications are distributed to the listeners\n * registered by {@link #addOnChangeListener(OnChangeListener)}.\n *\n * @return\n */\n/*\n public boolean isOnChangeEnabled() {\n return mOnChangeEnabled;\n }\n\n /***\n * Enables or disables change notifications, that are distributed to the listeners\n * registered by {@link #addOnChangeListener(OnChangeListener)}.\n *\n * @param onChangeEnabled\n *\\/\n public void setOnChangeEnabled(boolean onChangeEnabled) {\n mOnChangeEnabled = onChangeEnabled;\n }\n*/\n\n /**\n * Notify all registered listeners that something has changed.\n */\n protected void onChange() {\n if (mOnChangeEnabled) {\n synchronized (mChangeListeners) {\n for (OnChangeListener l : mChangeListeners) {\n l.onChange();\n }\n }\n }\n }\n\n public interface OnChangeListener {\n /**\n * Called when anything in the collection changes (cell's value, note, etc.)\n */\n void onChange();\n }\n}", "public interface OnChangeListener {\n /**\n * Called when anything in the collection changes (cell's value, note, etc.)\n */\n void onChange();\n}", "public class CellNote {\n\n public static final CellNote EMPTY = new CellNote();\n private final short mNotedNumbers;\n\n public CellNote() {\n mNotedNumbers = 0;\n }\n\n private CellNote(short notedNumbers) {\n mNotedNumbers = notedNumbers;\n }\n\n /**\n * Creates instance from given string (string which has been\n * created by {@link #serialize(StringBuilder)} or {@link #serialize()} method).\n * earlier.\n *\n * @param note\n */\n public static CellNote deserialize(String note) {\n return deserialize(note, CellCollection.DATA_VERSION);\n }\n\n public static CellNote deserialize(String note, int version) {\n\n int noteValue = 0;\n if (note != null && !note.equals(\"\") && !note.equals(\"-\")) {\n if (version == CellCollection.DATA_VERSION_1) {\n StringTokenizer tokenizer = new StringTokenizer(note, \",\");\n while (tokenizer.hasMoreTokens()) {\n String value = tokenizer.nextToken();\n if (!value.equals(\"-\")) {\n int number = Integer.parseInt(value);\n noteValue |= (1 << (number - 1));\n }\n }\n } else {\n //CellCollection.DATA_VERSION_2\n noteValue = Integer.parseInt(note);\n }\n }\n\n return new CellNote((short) noteValue);\n }\n\n\n /**\n * Creates note instance from given <code>int</code> array.\n *\n * @param notedNums Array of integers, which should be part of note.\n * @return New note instance.\n */\n public static CellNote fromIntArray(Integer[] notedNums) {\n int notedNumbers = 0;\n\n for (Integer n : notedNums) {\n notedNumbers = (short) (notedNumbers | (1 << (n - 1)));\n }\n\n return new CellNote((short) notedNumbers);\n }\n\n\n /**\n * Appends string representation of this object to the given <code>StringBuilder</code>.\n * You can later recreate object from this string by calling {@link #deserialize(String)}.\n *\n * @param data\n */\n public void serialize(StringBuilder data) {\n data.append(mNotedNumbers);\n data.append(\"|\");\n }\n\n public String serialize() {\n StringBuilder sb = new StringBuilder();\n serialize(sb);\n return sb.toString();\n }\n\n /**\n * Returns numbers currently noted in cell.\n *\n * @return\n */\n public List<Integer> getNotedNumbers() {\n\n List<Integer> result = new ArrayList<>();\n int c = 1;\n for (int i = 0; i < 9; i++) {\n if ((mNotedNumbers & (short) c) != 0) {\n result.add(i + 1);\n }\n c = (c << 1);\n }\n\n return result;\n }\n\n /**\n * Toggles noted number: if number is already noted, it will be removed otherwise it will be added.\n *\n * @param number Number to toggle.\n * @return New CellNote instance with changes.\n */\n public CellNote toggleNumber(int number) {\n if (number < 1 || number > 9)\n throw new IllegalArgumentException(\"Number must be between 1-9.\");\n\n return new CellNote((short) (mNotedNumbers ^ (1 << (number - 1))));\n }\n\n /**\n * Adds number to the cell's note (if not present already).\n *\n * @param number\n * @return\n */\n public CellNote addNumber(int number) {\n if (number < 1 || number > 9)\n throw new IllegalArgumentException(\"Number must be between 1-9.\");\n\n return new CellNote((short) (mNotedNumbers | (1 << (number - 1))));\n }\n\n /**\n * Removes number from the cell's note.\n *\n * @param number\n * @return\n */\n public CellNote removeNumber(int number) {\n if (number < 1 || number > 9)\n throw new IllegalArgumentException(\"Number must be between 1-9.\");\n\n return new CellNote((short) (mNotedNumbers & ~(1 << (number - 1))));\n }\n\n public boolean hasNumber(int number) {\n if (number < 1 || number > 9) {\n return false;\n }\n\n return (mNotedNumbers & (1 << (number - 1))) != 0;\n }\n\n public CellNote clear() {\n return new CellNote();\n }\n\n /**\n * Returns true, if note is empty.\n *\n * @return True if note is empty.\n */\n public boolean isEmpty() {\n return mNotedNumbers == 0;\n }\n\n}", "public class SudokuGame {\n\n public static final int GAME_STATE_PLAYING = 0;\n public static final int GAME_STATE_NOT_STARTED = 1;\n public static final int GAME_STATE_COMPLETED = 2;\n\n private long mId;\n private long mCreated;\n private int mState;\n private long mTime;\n private long mLastPlayed;\n private String mNote;\n private CellCollection mCells;\n private SudokuSolver mSolver;\n private boolean mUsedSolver = false;\n private boolean mRemoveNotesOnEntry = false;\n\n private OnPuzzleSolvedListener mOnPuzzleSolvedListener;\n private CommandStack mCommandStack;\n // Time when current activity has become active.\n private long mActiveFromTime = -1;\n\n public SudokuGame() {\n mTime = 0;\n mLastPlayed = 0;\n mCreated = 0;\n\n mState = GAME_STATE_NOT_STARTED;\n }\n\n public static SudokuGame createEmptyGame() {\n SudokuGame game = new SudokuGame();\n game.setCells(CellCollection.createEmpty());\n // set creation time\n game.setCreated(System.currentTimeMillis());\n return game;\n }\n\n public void saveState(Bundle outState) {\n outState.putLong(\"id\", mId);\n outState.putString(\"note\", mNote);\n outState.putLong(\"created\", mCreated);\n outState.putInt(\"state\", mState);\n outState.putLong(\"time\", mTime);\n outState.putLong(\"lastPlayed\", mLastPlayed);\n outState.putString(\"cells\", mCells.serialize());\n outState.putString(\"command_stack\", mCommandStack.serialize());\n }\n\n public void restoreState(Bundle inState) {\n mId = inState.getLong(\"id\");\n mNote = inState.getString(\"note\");\n mCreated = inState.getLong(\"created\");\n mState = inState.getInt(\"state\");\n mTime = inState.getLong(\"time\");\n mLastPlayed = inState.getLong(\"lastPlayed\");\n mCells = CellCollection.deserialize(inState.getString(\"cells\"));\n mCommandStack = CommandStack.deserialize(inState.getString(\"command_stack\"), mCells);\n\n validate();\n }\n\n\n public void setOnPuzzleSolvedListener(OnPuzzleSolvedListener l) {\n mOnPuzzleSolvedListener = l;\n }\n\n public String getNote() {\n return mNote;\n }\n\n public void setNote(String note) {\n mNote = note;\n }\n\n public long getCreated() {\n return mCreated;\n }\n\n public void setCreated(long created) {\n mCreated = created;\n }\n\n public int getState() {\n return mState;\n }\n\n public void setState(int state) {\n mState = state;\n }\n\n /**\n * Gets time of game-play in milliseconds.\n *\n * @return\n */\n public long getTime() {\n if (mActiveFromTime != -1) {\n return mTime + SystemClock.uptimeMillis() - mActiveFromTime;\n } else {\n return mTime;\n }\n }\n\n /**\n * Sets time of play in milliseconds.\n *\n * @param time\n */\n public void setTime(long time) {\n mTime = time;\n }\n\n public long getLastPlayed() {\n return mLastPlayed;\n }\n\n public void setLastPlayed(long lastPlayed) {\n mLastPlayed = lastPlayed;\n }\n\n public CellCollection getCells() {\n return mCells;\n }\n\n public void setCells(CellCollection cells) {\n mCells = cells;\n validate();\n mCommandStack = new CommandStack(mCells);\n }\n\n public long getId() {\n return mId;\n }\n\n public void setId(long id) {\n mId = id;\n }\n\n public CommandStack getCommandStack() {\n return mCommandStack;\n }\n\n public void setCommandStack(CommandStack commandStack) {\n mCommandStack = commandStack;\n }\n\n public void setRemoveNotesOnEntry(boolean removeNotesOnEntry) {\n mRemoveNotesOnEntry = removeNotesOnEntry;\n }\n\n /**\n * Sets value for the given cell. 0 means empty cell.\n *\n * @param cell\n * @param value\n */\n public void setCellValue(Cell cell, int value) {\n if (cell == null) {\n throw new IllegalArgumentException(\"Cell cannot be null.\");\n }\n if (value < 0 || value > 9) {\n throw new IllegalArgumentException(\"Value must be between 0-9.\");\n }\n\n if (cell.isEditable()) {\n if (mRemoveNotesOnEntry) {\n executeCommand(new SetCellValueAndRemoveNotesCommand(cell, value));\n } else {\n executeCommand(new SetCellValueCommand(cell, value));\n }\n\n validate();\n if (isCompleted()) {\n finish();\n if (mOnPuzzleSolvedListener != null) {\n mOnPuzzleSolvedListener.onPuzzleSolved();\n }\n }\n }\n }\n\n /**\n * Sets note attached to the given cell.\n *\n * @param cell\n * @param note\n */\n public void setCellNote(Cell cell, CellNote note) {\n if (cell == null) {\n throw new IllegalArgumentException(\"Cell cannot be null.\");\n }\n if (note == null) {\n throw new IllegalArgumentException(\"Note cannot be null.\");\n }\n\n if (cell.isEditable()) {\n executeCommand(new EditCellNoteCommand(cell, note));\n }\n }\n\n private void executeCommand(AbstractCommand c) {\n mCommandStack.execute(c);\n }\n\n /**\n * Undo last command.\n */\n public void undo() {\n mCommandStack.undo();\n }\n\n public boolean hasSomethingToUndo() {\n return mCommandStack.hasSomethingToUndo();\n }\n\n public void setUndoCheckpoint() {\n mCommandStack.setCheckpoint();\n }\n\n public void undoToCheckpoint() {\n mCommandStack.undoToCheckpoint();\n }\n\n public boolean hasUndoCheckpoint() {\n return mCommandStack.hasCheckpoint();\n }\n\n public void undoToBeforeMistake() {\n mCommandStack.undoToSolvableState();\n }\n\n @Nullable\n public Cell getLastChangedCell() {\n return mCommandStack.getLastChangedCell();\n }\n\n /**\n * Start game-play.\n */\n public void start() {\n mState = GAME_STATE_PLAYING;\n resume();\n }\n\n public void resume() {\n // reset time we have spent playing so far, so time when activity was not active\n // will not be part of the game play time\n mActiveFromTime = SystemClock.uptimeMillis();\n }\n\n /**\n * Pauses game-play (for example if activity pauses).\n */\n public void pause() {\n // save time we have spent playing so far - it will be reseted after resuming\n mTime += SystemClock.uptimeMillis() - mActiveFromTime;\n mActiveFromTime = -1;\n\n setLastPlayed(System.currentTimeMillis());\n }\n\n /**\n * Checks if a solution to the puzzle exists\n */\n public boolean isSolvable() {\n mSolver = new SudokuSolver();\n mSolver.setPuzzle(mCells);\n ArrayList<int[]> finalValues = mSolver.solve();\n return !finalValues.isEmpty();\n }\n\n /**\n * Solves puzzle from original state\n */\n public void solve() {\n mUsedSolver = true;\n mSolver = new SudokuSolver();\n mSolver.setPuzzle(mCells);\n ArrayList<int[]> finalValues = mSolver.solve();\n for (int[] rowColVal : finalValues) {\n int row = rowColVal[0];\n int col = rowColVal[1];\n int val = rowColVal[2];\n Cell cell = mCells.getCell(row, col);\n this.setCellValue(cell, val);\n }\n }\n\n public boolean usedSolver() {\n return mUsedSolver;\n }\n\n /**\n * Solves puzzle and fills in correct value for selected cell\n */\n public void solveCell(Cell cell) {\n mSolver = new SudokuSolver();\n mSolver.setPuzzle(mCells);\n ArrayList<int[]> finalValues = mSolver.solve();\n\n int row = cell.getRowIndex();\n int col = cell.getColumnIndex();\n for (int[] rowColVal : finalValues) {\n if (rowColVal[0] == row && rowColVal[1] == col) {\n int val = rowColVal[2];\n this.setCellValue(cell, val);\n }\n }\n }\n\n /**\n * Finishes game-play. Called when puzzle is solved.\n */\n private void finish() {\n pause();\n mState = GAME_STATE_COMPLETED;\n }\n\n /**\n * Resets game.\n */\n public void reset() {\n for (int r = 0; r < CellCollection.SUDOKU_SIZE; r++) {\n for (int c = 0; c < CellCollection.SUDOKU_SIZE; c++) {\n Cell cell = mCells.getCell(r, c);\n if (cell.isEditable()) {\n cell.setValue(0);\n cell.setNote(new CellNote());\n }\n }\n }\n mCommandStack = new CommandStack(mCells);\n validate();\n setTime(0);\n setLastPlayed(0);\n mState = GAME_STATE_NOT_STARTED;\n mUsedSolver = false;\n }\n\n /**\n * Returns true, if puzzle is solved. In order to know the current state, you have to\n * call validate first.\n *\n * @return\n */\n public boolean isCompleted() {\n return mCells.isCompleted();\n }\n\n public void clearAllNotes() {\n executeCommand(new ClearAllNotesCommand());\n }\n\n /**\n * Fills in possible values which can be entered in each cell.\n */\n public void fillInNotes() {\n executeCommand(new FillInNotesCommand());\n }\n\n /**\n * Fills in all values which can be entered in each cell.\n */\n public void fillInNotesWithAllValues() { executeCommand(new FillInNotesWithAllValuesCommand()); }\n\n public void validate() {\n mCells.validate();\n }\n\n public interface OnPuzzleSolvedListener {\n /**\n * Occurs when puzzle is solved.\n *\n * @return\n */\n void onPuzzleSolved();\n }\n}", "public class HintsQueue {\n private static final String PREF_FILE_NAME = \"hints\";\n // TODO: should be persisted in activity's state\n private final Queue<Message> mMessages;\n private final AlertDialog mHintDialog;\n private Context mContext;\n private SharedPreferences mPrefs;\n private boolean mOneTimeHintsEnabled;\n\n public HintsQueue(Context context) {\n mContext = context;\n mPrefs = mContext.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);\n\n SharedPreferences gameSettings = PreferenceManager.getDefaultSharedPreferences(context);\n gameSettings.registerOnSharedPreferenceChangeListener((sharedPreferences, key) -> {\n if (key.equals(\"show_hints\")) {\n mOneTimeHintsEnabled = sharedPreferences.getBoolean(\"show_hints\", true);\n }\n });\n mOneTimeHintsEnabled = gameSettings.getBoolean(\"show_hints\", true);\n\n //processQueue();\n OnClickListener mHintClosed = (dialog, which) -> {\n //processQueue();\n };\n mHintDialog = new AlertDialog.Builder(context)\n .setIcon(R.drawable.ic_info)\n .setTitle(R.string.hint)\n .setMessage(\"\")\n .setPositiveButton(R.string.close, mHintClosed).create();\n\n mHintDialog.setOnDismissListener(dialog -> processQueue());\n\n mMessages = new LinkedList<>();\n }\n\n private void addHint(Message hint) {\n synchronized (mMessages) {\n mMessages.add(hint);\n }\n\n synchronized (mHintDialog) {\n if (!mHintDialog.isShowing()) {\n processQueue();\n }\n }\n }\n\n private void processQueue() {\n Message hint;\n\n synchronized (mMessages) {\n hint = mMessages.poll();\n }\n\n if (hint != null) {\n showHintDialog(hint);\n }\n }\n\n private void showHintDialog(Message hint) {\n synchronized (mHintDialog) {\n mHintDialog.setTitle(mContext.getString(hint.titleResID));\n mHintDialog.setMessage(mContext.getText(hint.messageResID));\n mHintDialog.show();\n }\n }\n\n public void showHint(int titleResID, int messageResID, Object... args) {\n Message hint = new Message();\n hint.titleResID = titleResID;\n hint.messageResID = messageResID;\n //hint.args = args;\n addHint(hint);\n }\n\n public void showOneTimeHint(String key, int titleResID, int messageResID, Object... args) {\n if (mOneTimeHintsEnabled) {\n\n // FIXME: remove in future versions\n // Before 1.0.0, hintKey was created from messageResID. This ID has in 1.0.0 changed.\n // From 1.0.0, hintKey is based on key, to be backward compatible, check for old\n // hint keys.\n if (legacyHintsWereDisplayed()) {\n return;\n }\n\n String hintKey = \"hint_\" + key;\n if (!mPrefs.getBoolean(hintKey, false)) {\n showHint(titleResID, messageResID, args);\n Editor editor = mPrefs.edit();\n editor.putBoolean(hintKey, true);\n editor.apply();\n }\n }\n\n }\n\n public boolean legacyHintsWereDisplayed() {\n return mPrefs.getBoolean(\"hint_2131099727\", false) &&\n mPrefs.getBoolean(\"hint_2131099730\", false) &&\n mPrefs.getBoolean(\"hint_2131099726\", false) &&\n mPrefs.getBoolean(\"hint_2131099729\", false) &&\n mPrefs.getBoolean(\"hint_2131099728\", false);\n }\n\n public void resetOneTimeHints() {\n Editor editor = mPrefs.edit();\n editor.clear();\n editor.apply();\n }\n\n /**\n * This should be called when activity is paused.\n */\n public void pause() {\n // get rid of WindowLeakedException in logcat\n if (mHintDialog != null) {\n mHintDialog.cancel();\n }\n }\n\n private static class Message {\n int titleResID;\n int messageResID;\n //Object[] args;\n }\n\n}", "public class SudokuBoardView extends View {\n\n public static final int DEFAULT_BOARD_SIZE = 100;\n\n /**\n * \"Color not set\" value. (In relation to {@link Color}, it is in fact black color with\n * alpha channel set to 0 => that means it is completely transparent).\n */\n private static final int NO_COLOR = 0;\n\n private float mCellWidth;\n private float mCellHeight;\n\n private Cell mTouchedCell;\n // TODO: should I synchronize access to mSelectedCell?\n private Cell mSelectedCell;\n private int mHighlightedValue = 0;\n private boolean mReadonly = false;\n private boolean mHighlightWrongVals = true;\n private boolean mHighlightTouchedCell = true;\n private boolean mAutoHideTouchedCellHint = true;\n private HighlightMode mHighlightSimilarCells = HighlightMode.NONE;\n\n private SudokuGame mGame;\n private CellCollection mCells;\n private OnCellTappedListener mOnCellTappedListener;\n private OnCellSelectedListener mOnCellSelectedListener;\n private Paint mLinePaint;\n private Paint mSectorLinePaint;\n private Paint mCellValuePaint;\n private Paint mCellValueReadonlyPaint;\n private Paint mCellNotePaint;\n private int mNumberLeft;\n private int mNumberTop;\n private float mNoteTop;\n private int mSectorLineWidth;\n private Paint mBackgroundColorSecondary;\n private Paint mBackgroundColorReadOnly;\n private Paint mBackgroundColorTouched;\n private Paint mBackgroundColorSelected;\n private Paint mBackgroundColorHighlighted;\n private Paint mCellValueInvalidPaint;\n\n public SudokuBoardView(Context context) {\n this(context, null);\n }\n\n // TODO: do I need an defStyle?\n public SudokuBoardView(Context context, AttributeSet attrs/*, int defStyle*/) {\n super(context, attrs/*, defStyle*/);\n\n setFocusable(true);\n setFocusableInTouchMode(true);\n\n mLinePaint = new Paint();\n mSectorLinePaint = new Paint();\n mCellValuePaint = new Paint();\n mCellValueReadonlyPaint = new Paint();\n mCellValueInvalidPaint = new Paint();\n mCellNotePaint = new Paint();\n mBackgroundColorSecondary = new Paint();\n mBackgroundColorReadOnly = new Paint();\n mBackgroundColorTouched = new Paint();\n mBackgroundColorSelected = new Paint();\n mBackgroundColorHighlighted = new Paint();\n\n mCellValuePaint.setAntiAlias(true);\n mCellValueReadonlyPaint.setAntiAlias(true);\n mCellValueInvalidPaint.setAntiAlias(true);\n mCellNotePaint.setAntiAlias(true);\n mCellValueInvalidPaint.setColor(Color.RED);\n\n TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SudokuBoardView/*, defStyle, 0*/);\n\n setLineColor(a.getColor(R.styleable.SudokuBoardView_lineColor, Color.BLACK));\n setSectorLineColor(a.getColor(R.styleable.SudokuBoardView_sectorLineColor, Color.BLACK));\n setTextColor(a.getColor(R.styleable.SudokuBoardView_textColor, Color.BLACK));\n setTextColorReadOnly(a.getColor(R.styleable.SudokuBoardView_textColorReadOnly, Color.BLACK));\n setTextColorNote(a.getColor(R.styleable.SudokuBoardView_textColorNote, Color.BLACK));\n setBackgroundColor(a.getColor(R.styleable.SudokuBoardView_backgroundColor, Color.WHITE));\n setBackgroundColorSecondary(a.getColor(R.styleable.SudokuBoardView_backgroundColorSecondary, NO_COLOR));\n setBackgroundColorReadOnly(a.getColor(R.styleable.SudokuBoardView_backgroundColorReadOnly, NO_COLOR));\n setBackgroundColorTouched(a.getColor(R.styleable.SudokuBoardView_backgroundColorTouched, Color.rgb(50, 50, 255)));\n setBackgroundColorSelected(a.getColor(R.styleable.SudokuBoardView_backgroundColorSelected, Color.YELLOW));\n setBackgroundColorHighlighted(a.getColor(R.styleable.SudokuBoardView_backgroundColorHighlighted, Color.GREEN));\n\n a.recycle();\n }\n\n //\tpublic SudokuBoardView(Context context, AttributeSet attrs) {\n //\t\tthis(context, attrs, R.attr.sudokuBoardViewStyle);\n //\t}\n\n public int getLineColor() {\n return mLinePaint.getColor();\n }\n\n public void setLineColor(int color) {\n mLinePaint.setColor(color);\n }\n\n public int getSectorLineColor() {\n return mSectorLinePaint.getColor();\n }\n\n public void setSectorLineColor(int color) {\n mSectorLinePaint.setColor(color);\n }\n\n public int getTextColor() {\n return mCellValuePaint.getColor();\n }\n\n public void setTextColor(int color) {\n mCellValuePaint.setColor(color);\n }\n\n public int getTextColorReadOnly() {\n return mCellValueReadonlyPaint.getColor();\n }\n\n public void setTextColorReadOnly(int color) {\n mCellValueReadonlyPaint.setColor(color);\n }\n\n public int getTextColorNote() {\n return mCellNotePaint.getColor();\n }\n\n public void setTextColorNote(int color) {\n mCellNotePaint.setColor(color);\n }\n\n public int getBackgroundColorSecondary() {\n return mBackgroundColorSecondary.getColor();\n }\n\n public void setBackgroundColorSecondary(int color) {\n mBackgroundColorSecondary.setColor(color);\n }\n\n public int getBackgroundColorReadOnly() {\n return mBackgroundColorReadOnly.getColor();\n }\n\n public void setBackgroundColorReadOnly(int color) {\n mBackgroundColorReadOnly.setColor(color);\n }\n\n public int getBackgroundColorTouched() {\n return mBackgroundColorTouched.getColor();\n }\n\n public void setBackgroundColorTouched(int color) {\n mBackgroundColorTouched.setColor(color);\n }\n\n public int getBackgroundColorSelected() {\n return mBackgroundColorSelected.getColor();\n }\n\n public void setBackgroundColorSelected(int color) {\n mBackgroundColorSelected.setColor(color);\n }\n\n public int getBackgroundColorHighlighted() {\n return mBackgroundColorHighlighted.getColor();\n }\n\n public void setBackgroundColorHighlighted(int color) {\n mBackgroundColorHighlighted.setColor(color);\n }\n\n public void setGame(SudokuGame game) {\n mGame = game;\n setCells(game.getCells());\n }\n\n public CellCollection getCells() {\n return mCells;\n }\n\n public void setCells(CellCollection cells) {\n mCells = cells;\n\n if (mCells != null) {\n if (!mReadonly) {\n mSelectedCell = mCells.getCell(0, 0); // first cell will be selected by default\n onCellSelected(mSelectedCell);\n }\n\n mCells.addOnChangeListener(this::postInvalidate);\n }\n\n postInvalidate();\n }\n\n public Cell getSelectedCell() {\n return mSelectedCell;\n }\n\n public boolean isReadOnly() {\n return mReadonly;\n }\n\n public void setReadOnly(boolean readonly) {\n mReadonly = readonly;\n postInvalidate();\n }\n\n public boolean getHighlightWrongVals() {\n return mHighlightWrongVals;\n }\n\n public void setHighlightWrongVals(boolean highlightWrongVals) {\n mHighlightWrongVals = highlightWrongVals;\n postInvalidate();\n }\n\n public boolean getHighlightTouchedCell() {\n return mHighlightTouchedCell;\n }\n\n public void setHighlightTouchedCell(boolean highlightTouchedCell) {\n mHighlightTouchedCell = highlightTouchedCell;\n }\n\n public boolean getAutoHideTouchedCellHint() {\n return mAutoHideTouchedCellHint;\n }\n\n public void setAutoHideTouchedCellHint(boolean autoHideTouchedCellHint) {\n mAutoHideTouchedCellHint = autoHideTouchedCellHint;\n }\n\n public void setHighlightSimilarCell(HighlightMode highlightSimilarCell) {\n mHighlightSimilarCells = highlightSimilarCell;\n }\n\n public int getHighlightedValue() {\n return mHighlightedValue;\n }\n\n public void setHighlightedValue(int value) {\n mHighlightedValue = value;\n }\n\n /**\n * Registers callback which will be invoked when user taps the cell.\n *\n * @param l\n */\n public void setOnCellTappedListener(OnCellTappedListener l) {\n mOnCellTappedListener = l;\n }\n\n protected void onCellTapped(Cell cell) {\n if (mOnCellTappedListener != null) {\n mOnCellTappedListener.onCellTapped(cell);\n }\n }\n\n /**\n * Registers callback which will be invoked when cell is selected. Cell selection\n * can change without user interaction.\n *\n * @param l\n */\n public void setOnCellSelectedListener(OnCellSelectedListener l) {\n mOnCellSelectedListener = l;\n }\n\n public void hideTouchedCellHint() {\n mTouchedCell = null;\n postInvalidate();\n }\n\n protected void onCellSelected(Cell cell) {\n if (mOnCellSelectedListener != null) {\n mOnCellSelectedListener.onCellSelected(cell);\n }\n }\n\n public void invokeOnCellSelected() {\n onCellSelected(mSelectedCell);\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int widthMode = MeasureSpec.getMode(widthMeasureSpec);\n int widthSize = MeasureSpec.getSize(widthMeasureSpec);\n int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n int heightSize = MeasureSpec.getSize(heightMeasureSpec);\n\n\n// Log.d(TAG, \"widthMode=\" + getMeasureSpecModeString(widthMode));\n// Log.d(TAG, \"widthSize=\" + widthSize);\n// Log.d(TAG, \"heightMode=\" + getMeasureSpecModeString(heightMode));\n// Log.d(TAG, \"heightSize=\" + heightSize);\n\n int width, height;\n if (widthMode == MeasureSpec.EXACTLY) {\n width = widthSize;\n } else {\n width = DEFAULT_BOARD_SIZE;\n if (widthMode == MeasureSpec.AT_MOST && width > widthSize) {\n width = widthSize;\n }\n }\n if (heightMode == MeasureSpec.EXACTLY) {\n height = heightSize;\n } else {\n height = DEFAULT_BOARD_SIZE;\n if (heightMode == MeasureSpec.AT_MOST && height > heightSize) {\n height = heightSize;\n }\n }\n\n if (widthMode != MeasureSpec.EXACTLY) {\n width = height;\n }\n\n if (heightMode != MeasureSpec.EXACTLY) {\n height = width;\n }\n\n if (widthMode == MeasureSpec.AT_MOST && width > widthSize) {\n width = widthSize;\n }\n if (heightMode == MeasureSpec.AT_MOST && height > heightSize) {\n height = heightSize;\n }\n\n mCellWidth = (width - getPaddingLeft() - getPaddingRight()) / 9.0f;\n mCellHeight = (height - getPaddingTop() - getPaddingBottom()) / 9.0f;\n\n setMeasuredDimension(width, height);\n\n float cellTextSize = mCellHeight * 0.75f;\n mCellValuePaint.setTextSize(cellTextSize);\n mCellValueReadonlyPaint.setTextSize(cellTextSize);\n mCellValueInvalidPaint.setTextSize(cellTextSize);\n // compute offsets in each cell to center the rendered number\n mNumberLeft = (int) ((mCellWidth - mCellValuePaint.measureText(\"9\")) / 2);\n mNumberTop = (int) ((mCellHeight - mCellValuePaint.getTextSize()) / 2);\n\n // add some offset because in some resolutions notes are cut-off in the top\n mNoteTop = mCellHeight / 50.0f;\n mCellNotePaint.setTextSize((mCellHeight - mNoteTop * 2) / 3.0f);\n\n computeSectorLineWidth(width, height);\n }\n\n private void computeSectorLineWidth(int widthInPx, int heightInPx) {\n int sizeInPx = Math.min(widthInPx, heightInPx);\n float dipScale = getContext().getResources().getDisplayMetrics().density;\n float sizeInDip = sizeInPx / dipScale;\n\n float sectorLineWidthInDip = 2.0f;\n\n if (sizeInDip > 150) {\n sectorLineWidthInDip = 3.0f;\n }\n\n mSectorLineWidth = (int) (sectorLineWidthInDip * dipScale);\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // some notes:\n // Drawable has its own draw() method that takes your Canvas as an argument\n\n // TODO: I don't get this, why do I need to substract padding only from one side?\n int width = getWidth() - getPaddingRight();\n int height = getHeight() - getPaddingBottom();\n\n int paddingLeft = getPaddingLeft();\n int paddingTop = getPaddingTop();\n\n // draw secondary background\n if (mBackgroundColorSecondary.getColor() != NO_COLOR) {\n canvas.drawRect(3 * mCellWidth, 0, 6 * mCellWidth, 3 * mCellWidth, mBackgroundColorSecondary);\n canvas.drawRect(0, 3 * mCellWidth, 3 * mCellWidth, 6 * mCellWidth, mBackgroundColorSecondary);\n canvas.drawRect(6 * mCellWidth, 3 * mCellWidth, 9 * mCellWidth, 6 * mCellWidth, mBackgroundColorSecondary);\n canvas.drawRect(3 * mCellWidth, 6 * mCellWidth, 6 * mCellWidth, 9 * mCellWidth, mBackgroundColorSecondary);\n }\n\n // draw cells\n int cellLeft, cellTop;\n if (mCells != null) {\n\n boolean hasBackgroundColorReadOnly = mBackgroundColorReadOnly.getColor() != NO_COLOR;\n\n float numberAscent = mCellValuePaint.ascent();\n float noteAscent = mCellNotePaint.ascent();\n float noteWidth = mCellWidth / 3f;\n\n for (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n Cell cell = mCells.getCell(row, col);\n\n cellLeft = Math.round((col * mCellWidth) + paddingLeft);\n cellTop = Math.round((row * mCellHeight) + paddingTop);\n\n // draw read-only field background\n if (!cell.isEditable() && hasBackgroundColorReadOnly &&\n (mSelectedCell == null || mSelectedCell != cell)) {\n if (mBackgroundColorReadOnly.getColor() != NO_COLOR) {\n canvas.drawRect(\n cellLeft, cellTop,\n cellLeft + mCellWidth, cellTop + mCellHeight,\n mBackgroundColorReadOnly);\n }\n }\n\n // highlight similar cells\n boolean cellIsNotAlreadySelected = (mSelectedCell == null || mSelectedCell != cell);\n boolean highlightedValueIsValid = mHighlightedValue != 0;\n boolean shouldHighlightCell = false;\n\n switch (mHighlightSimilarCells) {\n default:\n case NONE: {\n shouldHighlightCell = false;\n break;\n }\n\n case NUMBERS: {\n shouldHighlightCell =\n cellIsNotAlreadySelected &&\n highlightedValueIsValid &&\n mHighlightedValue == cell.getValue();\n break;\n }\n\n case NUMBERS_AND_NOTES: {\n shouldHighlightCell =\n cellIsNotAlreadySelected &&\n highlightedValueIsValid &&\n (mHighlightedValue == cell.getValue() ||\n (cell.getNote().getNotedNumbers().contains(mHighlightedValue)) &&\n cell.getValue() == 0);\n }\n }\n\n if (shouldHighlightCell) {\n if (mBackgroundColorHighlighted.getColor() != NO_COLOR) {\n canvas.drawRect(\n cellLeft, cellTop,\n cellLeft + mCellWidth, cellTop + mCellHeight,\n mBackgroundColorHighlighted);\n }\n }\n }\n }\n\n // highlight selected cell\n if (!mReadonly && mSelectedCell != null) {\n cellLeft = Math.round(mSelectedCell.getColumnIndex() * mCellWidth) + paddingLeft;\n cellTop = Math.round(mSelectedCell.getRowIndex() * mCellHeight) + paddingTop;\n canvas.drawRect(\n cellLeft, cellTop,\n cellLeft + mCellWidth, cellTop + mCellHeight,\n mBackgroundColorSelected);\n }\n\n // visually highlight cell under the finger (to cope with touch screen\n // imprecision)\n if (mHighlightTouchedCell && mTouchedCell != null) {\n cellLeft = Math.round(mTouchedCell.getColumnIndex() * mCellWidth) + paddingLeft;\n cellTop = Math.round(mTouchedCell.getRowIndex() * mCellHeight) + paddingTop;\n canvas.drawRect(\n cellLeft, paddingTop,\n cellLeft + mCellWidth, height,\n mBackgroundColorTouched);\n canvas.drawRect(\n paddingLeft, cellTop,\n width, cellTop + mCellHeight,\n mBackgroundColorTouched);\n }\n\n for (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n Cell cell = mCells.getCell(row, col);\n\n cellLeft = Math.round((col * mCellWidth) + paddingLeft);\n cellTop = Math.round((row * mCellHeight) + paddingTop);\n\n // draw cell Text\n int value = cell.getValue();\n if (value != 0) {\n Paint cellValuePaint = cell.isEditable() ? mCellValuePaint : mCellValueReadonlyPaint;\n\n if (mHighlightWrongVals && !cell.isValid()) {\n cellValuePaint = mCellValueInvalidPaint;\n }\n\n canvas.drawText(Integer.toString(value),\n cellLeft + mNumberLeft,\n cellTop + mNumberTop - numberAscent,\n cellValuePaint);\n } else {\n if (!cell.getNote().isEmpty()) {\n Collection<Integer> numbers = cell.getNote().getNotedNumbers();\n for (Integer number : numbers) {\n int n = number - 1;\n int c = n % 3;\n int r = n / 3;\n canvas.drawText(Integer.toString(number), cellLeft + c * noteWidth + 2, cellTop + mNoteTop - noteAscent + r * noteWidth - 1, mCellNotePaint);\n }\n }\n }\n }\n }\n }\n\n // draw vertical lines\n for (int c = 0; c <= 9; c++) {\n float x = (c * mCellWidth) + paddingLeft;\n canvas.drawLine(x, paddingTop, x, height, mLinePaint);\n }\n\n // draw horizontal lines\n for (int r = 0; r <= 9; r++) {\n float y = r * mCellHeight + paddingTop;\n canvas.drawLine(paddingLeft, y, width, y, mLinePaint);\n }\n\n int sectorLineWidth1 = mSectorLineWidth / 2;\n int sectorLineWidth2 = sectorLineWidth1 + (mSectorLineWidth % 2);\n\n // draw sector (thick) lines\n for (int c = 0; c <= 9; c = c + 3) {\n float x = (c * mCellWidth) + paddingLeft;\n canvas.drawRect(x - sectorLineWidth1, paddingTop, x + sectorLineWidth2, height, mSectorLinePaint);\n }\n\n for (int r = 0; r <= 9; r = r + 3) {\n float y = r * mCellHeight + paddingTop;\n canvas.drawRect(paddingLeft, y - sectorLineWidth1, width, y + sectorLineWidth2, mSectorLinePaint);\n }\n\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n\n if (!mReadonly) {\n int x = (int) event.getX();\n int y = (int) event.getY();\n\n switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n case MotionEvent.ACTION_MOVE:\n mTouchedCell = getCellAtPoint(x, y);\n break;\n case MotionEvent.ACTION_UP:\n mSelectedCell = getCellAtPoint(x, y);\n invalidate(); // selected cell has changed, update board as soon as you can\n\n if (mSelectedCell != null) {\n onCellTapped(mSelectedCell);\n onCellSelected(mSelectedCell);\n }\n\n if (mAutoHideTouchedCellHint) {\n mTouchedCell = null;\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n mTouchedCell = null;\n break;\n }\n postInvalidate();\n }\n\n return !mReadonly;\n }\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (!mReadonly) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_DPAD_UP:\n return moveCellSelection(0, -1);\n case KeyEvent.KEYCODE_DPAD_RIGHT:\n return moveCellSelection(1, 0);\n case KeyEvent.KEYCODE_DPAD_DOWN:\n return moveCellSelection(0, 1);\n case KeyEvent.KEYCODE_DPAD_LEFT:\n return moveCellSelection(-1, 0);\n case KeyEvent.KEYCODE_0:\n case KeyEvent.KEYCODE_SPACE:\n case KeyEvent.KEYCODE_DEL:\n // clear value in selected cell\n // TODO: I'm not really sure that this is thread-safe\n if (mSelectedCell != null) {\n if (event.isShiftPressed() || event.isAltPressed()) {\n setCellNote(mSelectedCell, CellNote.EMPTY);\n } else {\n setCellValue(mSelectedCell, 0);\n moveCellSelectionRight();\n }\n }\n return true;\n case KeyEvent.KEYCODE_DPAD_CENTER:\n if (mSelectedCell != null) {\n onCellTapped(mSelectedCell);\n }\n return true;\n }\n\n if (keyCode >= KeyEvent.KEYCODE_1 && keyCode <= KeyEvent.KEYCODE_9 && mSelectedCell != null) {\n int selNumber = keyCode - KeyEvent.KEYCODE_0;\n Cell cell = mSelectedCell;\n\n if (event.isShiftPressed() || event.isAltPressed()) {\n // add or remove number in cell's note\n setCellNote(cell, cell.getNote().toggleNumber(selNumber));\n } else {\n // enter number in cell\n setCellValue(cell, selNumber);\n moveCellSelectionRight();\n }\n return true;\n }\n }\n\n\n return false;\n }\n\n /**\n * Moves selected cell by one cell to the right. If edge is reached, selection\n * skips on beginning of another line.\n */\n public void moveCellSelectionRight() {\n if (!moveCellSelection(1, 0)) {\n int selRow = mSelectedCell.getRowIndex();\n selRow++;\n if (!moveCellSelectionTo(selRow, 0)) {\n moveCellSelectionTo(0, 0);\n }\n }\n postInvalidate();\n }\n\n private void setCellValue(Cell cell, int value) {\n if (cell.isEditable()) {\n if (mGame != null) {\n mGame.setCellValue(cell, value);\n } else {\n cell.setValue(value);\n }\n }\n }\n\n private void setCellNote(Cell cell, CellNote note) {\n if (cell.isEditable()) {\n if (mGame != null) {\n mGame.setCellNote(cell, note);\n } else {\n cell.setNote(note);\n }\n }\n }\n\n /**\n * Moves selected by vx cells right and vy cells down. vx and vy can be negative. Returns true,\n * if new cell is selected.\n *\n * @param vx Horizontal offset, by which move selected cell.\n * @param vy Vertical offset, by which move selected cell.\n */\n private boolean moveCellSelection(int vx, int vy) {\n int newRow = 0;\n int newCol = 0;\n\n if (mSelectedCell != null) {\n newRow = mSelectedCell.getRowIndex() + vy;\n newCol = mSelectedCell.getColumnIndex() + vx;\n }\n\n return moveCellSelectionTo(newRow, newCol);\n }\n\n /**\n * Moves selection to the cell given by row and column index.\n *\n * @param row Row index of cell which should be selected.\n * @param col Columnd index of cell which should be selected.\n * @return True, if cell was successfuly selected.\n */\n public boolean moveCellSelectionTo(int row, int col) {\n if (col >= 0 && col < CellCollection.SUDOKU_SIZE\n && row >= 0 && row < CellCollection.SUDOKU_SIZE) {\n mSelectedCell = mCells.getCell(row, col);\n onCellSelected(mSelectedCell);\n\n postInvalidate();\n return true;\n }\n\n return false;\n }\n\n public void clearCellSelection() {\n mSelectedCell = null;\n onCellSelected(mSelectedCell);\n postInvalidate();\n }\n\n /**\n * Returns cell at given screen coordinates. Returns null if no cell is found.\n *\n * @param x\n * @param y\n * @return\n */\n private Cell getCellAtPoint(int x, int y) {\n // take into account padding\n int lx = x - getPaddingLeft();\n int ly = y - getPaddingTop();\n\n int row = (int) (ly / mCellHeight);\n int col = (int) (lx / mCellWidth);\n\n if (col >= 0 && col < CellCollection.SUDOKU_SIZE\n && row >= 0 && row < CellCollection.SUDOKU_SIZE) {\n return mCells.getCell(row, col);\n } else {\n return null;\n }\n }\n\n public enum HighlightMode {\n NONE,\n NUMBERS,\n NUMBERS_AND_NOTES\n }\n\n /**\n * Occurs when user tap the cell.\n *\n * @author romario\n */\n public interface OnCellTappedListener {\n void onCellTapped(Cell cell);\n }\n\n /**\n * Occurs when user selects the cell.\n *\n * @author romario\n */\n public interface OnCellSelectedListener {\n void onCellSelected(Cell cell);\n }\n\n//\tprivate String getMeasureSpecModeString(int mode) {\n//\t\tString modeString = null;\n//\t\tswitch (mode) {\n//\t\tcase MeasureSpec.AT_MOST:\n//\t\t\tmodeString = \"MeasureSpec.AT_MOST\";\n//\t\t\tbreak;\n//\t\tcase MeasureSpec.EXACTLY:\n//\t\t\tmodeString = \"MeasureSpec.EXACTLY\";\n//\t\t\tbreak;\n//\t\tcase MeasureSpec.UNSPECIFIED:\n//\t\t\tmodeString = \"MeasureSpec.UNSPECIFIED\";\n//\t\t\tbreak;\n//\t\t}\n//\n//\t\tif (modeString == null)\n//\t\t\tmodeString = new Integer(mode).toString();\n//\n//\t\treturn modeString;\n//\t}\n\n}", "public static class StateBundle {\n\n private final SharedPreferences mPreferences;\n private final Editor mPrefEditor;\n private final String mPrefix;\n private final boolean mEditable;\n\n public StateBundle(SharedPreferences preferences, String prefix,\n boolean editable) {\n mPreferences = preferences;\n mPrefix = prefix;\n mEditable = editable;\n\n if (mEditable) {\n mPrefEditor = preferences.edit();\n } else {\n mPrefEditor = null;\n }\n }\n\n public boolean getBoolean(String key, boolean defValue) {\n return mPreferences.getBoolean(mPrefix + key, defValue);\n }\n\n public float getFloat(String key, float defValue) {\n return mPreferences.getFloat(mPrefix + key, defValue);\n }\n\n public int getInt(String key, int defValue) {\n return mPreferences.getInt(mPrefix + key, defValue);\n }\n\n public String getString(String key, String defValue) {\n return mPreferences.getString(mPrefix + key, defValue);\n }\n\n public void putBoolean(String key, boolean value) {\n if (!mEditable) {\n throw new IllegalStateException(\"StateBundle is not editable\");\n }\n mPrefEditor.putBoolean(mPrefix + key, value);\n }\n\n public void putFloat(String key, float value) {\n if (!mEditable) {\n throw new IllegalStateException(\"StateBundle is not editable\");\n }\n mPrefEditor.putFloat(mPrefix + key, value);\n }\n\n public void putInt(String key, int value) {\n if (!mEditable) {\n throw new IllegalStateException(\"StateBundle is not editable\");\n }\n mPrefEditor.putInt(mPrefix + key, value);\n }\n\n public void putString(String key, String value) {\n if (!mEditable) {\n throw new IllegalStateException(\"StateBundle is not editable\");\n }\n mPrefEditor.putString(mPrefix + key, value);\n }\n\n public void commit() {\n if (!mEditable) {\n throw new IllegalStateException(\"StateBundle is not editable\");\n }\n mPrefEditor.commit();\n }\n\n}", "public class ThemeUtils {\n\n private static final int[] MATERIAL_COLORS = {\n 0xfffde0dc,\n 0xfff9bdbb,\n 0xfff69988,\n 0xfff36c60,\n 0xffe84e40,\n 0xffe51c23,\n 0xffdd191d,\n 0xffd01716,\n 0xffc41411,\n 0xffb0120a,\n 0xffff7997,\n 0xffff5177,\n 0xffff2d6f,\n 0xffe00032,\n 0xfffce4ec,\n 0xfff8bbd0,\n 0xfff48fb1,\n 0xfff06292,\n 0xffec407a,\n 0xffe91e63,\n 0xffd81b60,\n 0xffc2185b,\n 0xffad1457,\n 0xff880e4f,\n 0xffff80ab,\n 0xffff4081,\n 0xfff50057,\n 0xffc51162,\n 0xfff3e5f5,\n 0xffe1bee7,\n 0xffce93d8,\n 0xffba68c8,\n 0xffab47bc,\n 0xff9c27b0,\n 0xff8e24aa,\n 0xff7b1fa2,\n 0xff6a1b9a,\n 0xff4a148c,\n 0xffea80fc,\n 0xffe040fb,\n 0xffd500f9,\n 0xffaa00ff,\n 0xffede7f6,\n 0xffd1c4e9,\n 0xffb39ddb,\n 0xff9575cd,\n 0xff7e57c2,\n 0xff673ab7,\n 0xff5e35b1,\n 0xff512da8,\n 0xff4527a0,\n 0xff311b92,\n 0xffb388ff,\n 0xff7c4dff,\n 0xff651fff,\n 0xff6200ea,\n 0xffe8eaf6,\n 0xffc5cae9,\n 0xff9fa8da,\n 0xff7986cb,\n 0xff5c6bc0,\n 0xff3f51b5,\n 0xff3949ab,\n 0xff303f9f,\n 0xff283593,\n 0xff1a237e,\n 0xff8c9eff,\n 0xff536dfe,\n 0xff3d5afe,\n 0xff304ffe,\n 0xffe7e9fd,\n 0xffd0d9ff,\n 0xffafbfff,\n 0xff91a7ff,\n 0xff738ffe,\n 0xff5677fc,\n 0xff4e6cef,\n 0xff455ede,\n 0xff3b50ce,\n 0xff2a36b1,\n 0xffa6baff,\n 0xff6889ff,\n 0xff4d73ff,\n 0xff4d69ff,\n 0xffe1f5fe,\n 0xffb3e5fc,\n 0xff81d4fa,\n 0xff4fc3f7,\n 0xff29b6f6,\n 0xff03a9f4,\n 0xff039be5,\n 0xff0288d1,\n 0xff0277bd,\n 0xff01579b,\n 0xff80d8ff,\n 0xff40c4ff,\n 0xff00b0ff,\n 0xff0091ea,\n 0xffe0f7fa,\n 0xffb2ebf2,\n 0xff80deea,\n 0xff4dd0e1,\n 0xff26c6da,\n 0xff00bcd4,\n 0xff00acc1,\n 0xff0097a7,\n 0xff00838f,\n 0xff006064,\n 0xff84ffff,\n 0xff18ffff,\n 0xff00e5ff,\n 0xff00b8d4,\n 0xffe0f2f1,\n 0xffb2dfdb,\n 0xff80cbc4,\n 0xff4db6ac,\n 0xff26a69a,\n 0xff009688,\n 0xff00897b,\n 0xff00796b,\n 0xff00695c,\n 0xff004d40,\n 0xffa7ffeb,\n 0xff64ffda,\n 0xff1de9b6,\n 0xff00bfa5,\n 0xffd0f8ce,\n 0xffa3e9a4,\n 0xff72d572,\n 0xff42bd41,\n 0xff2baf2b,\n 0xff259b24,\n 0xff0a8f08,\n 0xff0a7e07,\n 0xff056f00,\n 0xff0d5302,\n 0xffa2f78d,\n 0xff5af158,\n 0xff14e715,\n 0xff12c700,\n 0xfff1f8e9,\n 0xffdcedc8,\n 0xffc5e1a5,\n 0xffaed581,\n 0xff9ccc65,\n 0xff8bc34a,\n 0xff7cb342,\n 0xff689f38,\n 0xff558b2f,\n 0xff33691e,\n 0xffccff90,\n 0xffb2ff59,\n 0xff76ff03,\n 0xff64dd17,\n 0xfff9fbe7,\n 0xfff0f4c3,\n 0xffe6ee9c,\n 0xffdce775,\n 0xffd4e157,\n 0xffcddc39,\n 0xffc0ca33,\n 0xffafb42b,\n 0xff9e9d24,\n 0xff827717,\n 0xfff4ff81,\n 0xffeeff41,\n 0xffc6ff00,\n 0xffaeea00,\n 0xfffffde7,\n 0xfffff9c4,\n 0xfffff59d,\n 0xfffff176,\n 0xffffee58,\n 0xffffeb3b,\n 0xfffdd835,\n 0xfffbc02d,\n 0xfff9a825,\n 0xfff57f17,\n 0xffffff8d,\n 0xffffff00,\n 0xffffea00,\n 0xffffd600,\n 0xfffff8e1,\n 0xffffecb3,\n 0xffffe082,\n 0xffffd54f,\n 0xffffca28,\n 0xffffc107,\n 0xffffb300,\n 0xffffa000,\n 0xffff8f00,\n 0xffff6f00,\n 0xffffe57f,\n 0xffffd740,\n 0xffffc400,\n 0xffffab00,\n 0xfffff3e0,\n 0xffffe0b2,\n 0xffffcc80,\n 0xffffb74d,\n 0xffffa726,\n 0xffff9800,\n 0xfffb8c00,\n 0xfff57c00,\n 0xffef6c00,\n 0xffe65100,\n 0xffffd180,\n 0xffffab40,\n 0xffff9100,\n 0xffff6d00,\n 0xfffbe9e7,\n 0xffffccbc,\n 0xffffab91,\n 0xffff8a65,\n 0xffff7043,\n 0xffff5722,\n 0xfff4511e,\n 0xffe64a19,\n 0xffd84315,\n 0xffbf360c,\n 0xffff9e80,\n 0xffff6e40,\n 0xffff3d00,\n 0xffdd2c00,\n 0xffefebe9,\n 0xffd7ccc8,\n 0xffbcaaa4,\n 0xffa1887f,\n 0xff8d6e63,\n 0xff795548,\n 0xff6d4c41,\n 0xff5d4037,\n 0xff4e342e,\n 0xff3e2723,\n 0xfffafafa,\n 0xfff5f5f5,\n 0xffeeeeee,\n 0xffe0e0e0,\n 0xffbdbdbd,\n 0xff9e9e9e,\n 0xff757575,\n 0xff616161,\n 0xff424242,\n 0xff212121,\n 0xff000000,\n 0xffffffff,\n 0xffeceff1,\n 0xffcfd8dc,\n 0xffb0bec5,\n 0xff90a4ae,\n 0xff78909c,\n 0xff607d8b,\n 0xff546e7a,\n 0xff455a64,\n 0xff37474f,\n 0xff263238\n };\n public static long sTimestampOfLastThemeUpdate = 0;\n\n public static int getThemeResourceIdFromString(String theme) {\n switch (theme) {\n case \"default\":\n return R.style.Theme_Default;\n case \"amoled\":\n return R.style.Theme_AMOLED;\n case \"latte\":\n return R.style.Theme_Latte;\n case \"espresso\":\n return R.style.Theme_Espresso;\n case \"sunrise\":\n return R.style.Theme_Sunrise;\n case \"honeybee\":\n return R.style.Theme_HoneyBee;\n case \"crystal\":\n return R.style.Theme_Crystal;\n case \"midnight_blue\":\n return R.style.Theme_MidnightBlue;\n case \"emerald\":\n return R.style.Theme_Emerald;\n case \"forest\":\n return R.style.Theme_Forest;\n case \"amethyst\":\n return R.style.Theme_Amethyst;\n case \"ruby\":\n return R.style.Theme_Ruby;\n case \"paper\":\n return R.style.Theme_Paper;\n case \"graphpaper\":\n return R.style.Theme_GraphPaper;\n case \"light\":\n return R.style.Theme_Light;\n case \"paperlight\":\n return R.style.Theme_PaperLight;\n case \"graphpaperlight\":\n return R.style.Theme_GraphPaperLight;\n case \"highcontrast\":\n return R.style.Theme_HighContrast;\n case \"invertedhighcontrast\":\n return R.style.Theme_InvertedHighContrast;\n case \"custom\":\n return R.style.Theme_AppCompat;\n case \"custom_light\":\n return R.style.Theme_AppCompat_Light;\n case \"opensudoku\":\n default:\n return R.style.Theme_OpenSudoku;\n }\n }\n\n public static boolean isLightTheme(String theme) {\n switch (theme) {\n case \"default\":\n case \"amoled\":\n case \"espresso\":\n case \"honeybee\":\n case \"midnight_blue\":\n case \"forest\":\n case \"ruby\":\n case \"paper\":\n case \"graphpaper\":\n case \"highcontrast\":\n case \"custom\":\n return false;\n case \"opensudoku\":\n case \"latte\":\n case \"sunrise\":\n case \"crystal\":\n case \"emerald\":\n case \"amethyst\":\n case \"light\":\n case \"paperlight\":\n case \"graphpaperlight\":\n case \"invertedhighcontrast\":\n case \"custom_light\":\n default:\n return true;\n }\n }\n\n public static String getCurrentThemeFromPreferences(Context context) {\n SharedPreferences gameSettings = PreferenceManager.getDefaultSharedPreferences(context);\n return gameSettings.getString(\"theme\", \"opensudoku\");\n }\n\n public static int getThemeResourceIdFromPreferences(Context context) {\n return getThemeResourceIdFromString(getCurrentThemeFromPreferences(context));\n }\n\n public static void setThemeFromPreferences(Context context) {\n String theme = getCurrentThemeFromPreferences(context);\n context.setTheme(getThemeResourceIdFromString(theme));\n\n if (theme.equals(\"custom\") || theme.equals(\"custom_light\")) {\n Resources.Theme themeResource = context.getTheme();\n SharedPreferences gameSettings = PreferenceManager.getDefaultSharedPreferences(context);\n themeResource.applyStyle(getPrimaryColorResourceId(context, gameSettings.getInt(\"custom_theme_colorPrimary\", 0xff49B7AC)), true);\n themeResource.applyStyle(getDarkPrimaryColorResourceId(context, gameSettings.getInt(\"custom_theme_colorPrimaryDark\", 0xff009587)), true);\n themeResource.applyStyle(getAccentColorResourceId(context, gameSettings.getInt(\"custom_theme_colorAccent\", 0xff656565)), true);\n themeResource.applyStyle(getButtonColorResourceId(context, gameSettings.getInt(\"custom_theme_colorButtonNormal\", 0xff656565)), true);\n }\n }\n\n public static int getCurrentThemeColor(Context context, int colorAttribute) {\n int[] attributes = {colorAttribute};\n TypedArray themeColors = context.getTheme().obtainStyledAttributes(attributes);\n return themeColors.getColor(0, Color.BLACK);\n }\n\n public static int getCurrentThemeStyle(Context context, int styleAttribute) {\n int[] attributes = {styleAttribute};\n TypedArray themeStyles = context.getTheme().obtainStyledAttributes(attributes);\n return themeStyles.getResourceId(0, 0);\n }\n\n public static void applyIMButtonStateToView(TextView view, IMButtonStyle style) {\n switch (style) {\n case DEFAULT:\n view.getBackground().setColorFilter(null);\n view.setTextColor(getCurrentThemeColor(view.getContext(), android.R.attr.textColorPrimary));\n break;\n\n case ACCENT:\n view.getBackground().setColorFilter(new PorterDuffColorFilter(\n getCurrentThemeColor(view.getContext(), android.R.attr.colorAccent), PorterDuff.Mode.SRC_ATOP));\n view.setTextColor(getCurrentThemeColor(view.getContext(), android.R.attr.textColorPrimaryInverse));\n break;\n\n case ACCENT_HIGHCONTRAST:\n view.getBackground().setColorFilter(new PorterDuffColorFilter(\n getCurrentThemeColor(view.getContext(), android.R.attr.textColorPrimaryInverse), PorterDuff.Mode.SRC_ATOP));\n view.setTextColor(getCurrentThemeColor(view.getContext(), android.R.attr.textColorPrimary));\n break;\n }\n }\n\n public static void applyCustomThemeToSudokuBoardViewFromContext(SudokuBoardView board, Context context) {\n SharedPreferences gameSettings = PreferenceManager.getDefaultSharedPreferences(context);\n board.setLineColor(gameSettings.getInt(\"custom_theme_lineColor\", R.color.default_lineColor));\n board.setSectorLineColor(gameSettings.getInt(\"custom_theme_sectorLineColor\", R.color.default_sectorLineColor));\n board.setTextColor(gameSettings.getInt(\"custom_theme_textColor\", R.color.default_textColor));\n board.setTextColorReadOnly(gameSettings.getInt(\"custom_theme_textColorReadOnly\", R.color.default_textColorReadOnly));\n board.setTextColorNote(gameSettings.getInt(\"custom_theme_textColorNote\", R.color.default_textColorNote));\n board.setBackgroundColor(gameSettings.getInt(\"custom_theme_backgroundColor\", R.color.default_backgroundColor));\n board.setBackgroundColorSecondary(gameSettings.getInt(\"custom_theme_backgroundColorSecondary\", R.color.default_backgroundColorSecondary));\n board.setBackgroundColorReadOnly(gameSettings.getInt(\"custom_theme_backgroundColorReadOnly\", R.color.default_backgroundColorReadOnly));\n board.setBackgroundColorTouched(gameSettings.getInt(\"custom_theme_backgroundColorTouched\", R.color.default_backgroundColorTouched));\n board.setBackgroundColorSelected(gameSettings.getInt(\"custom_theme_backgroundColorSelected\", R.color.default_backgroundColorSelected));\n board.setBackgroundColorHighlighted(gameSettings.getInt(\"custom_theme_backgroundColorHighlighted\", R.color.default_backgroundColorHighlighted));\n }\n\n public static void applyThemeToSudokuBoardViewFromContext(String theme, SudokuBoardView board, Context context) {\n if (theme.equals(\"custom\") || theme.equals(\"custom_light\")) {\n applyCustomThemeToSudokuBoardViewFromContext(board, context);\n } else {\n ContextThemeWrapper themeWrapper = new ContextThemeWrapper(context, getThemeResourceIdFromString(theme));\n\n int[] attributes = {\n R.attr.lineColor,\n R.attr.sectorLineColor,\n R.attr.textColor,\n R.attr.textColorReadOnly,\n R.attr.textColorNote,\n R.attr.backgroundColor,\n R.attr.backgroundColorSecondary,\n R.attr.backgroundColorReadOnly,\n R.attr.backgroundColorTouched,\n R.attr.backgroundColorSelected,\n R.attr.backgroundColorHighlighted\n };\n\n TypedArray themeColors = themeWrapper.getTheme().obtainStyledAttributes(attributes);\n board.setLineColor(themeColors.getColor(0, R.color.default_lineColor));\n board.setSectorLineColor(themeColors.getColor(1, R.color.default_sectorLineColor));\n board.setTextColor(themeColors.getColor(2, R.color.default_textColor));\n board.setTextColorReadOnly(themeColors.getColor(3, R.color.default_textColorReadOnly));\n board.setTextColorNote(themeColors.getColor(4, R.color.default_textColorNote));\n board.setBackgroundColor(themeColors.getColor(5, R.color.default_backgroundColor));\n board.setBackgroundColorSecondary(themeColors.getColor(6, R.color.default_backgroundColorSecondary));\n board.setBackgroundColorReadOnly(themeColors.getColor(7, R.color.default_backgroundColorReadOnly));\n board.setBackgroundColorTouched(themeColors.getColor(8, R.color.default_backgroundColorTouched));\n board.setBackgroundColorSelected(themeColors.getColor(9, R.color.default_backgroundColorSelected));\n board.setBackgroundColorHighlighted(themeColors.getColor(10, R.color.default_backgroundColorHighlighted));\n }\n board.invalidate();\n }\n\n public static void prepareSudokuPreviewView(SudokuBoardView board) {\n board.setFocusable(false);\n\n // Create a sample game by starting with the debug game, removing an extra box (sector),\n // adding in notes, and filling in the first 3 clues. This provides a sample of an\n // in-progress game that will demonstrate all of the possible scenarios that have different\n // theme colors applied to them.\n CellCollection cells = CellCollection.createDebugGame();\n cells.getCell(0, 3).setValue(0);\n cells.getCell(0, 4).setValue(0);\n cells.getCell(1, 3).setValue(0);\n cells.getCell(1, 5).setValue(0);\n cells.getCell(2, 4).setValue(0);\n cells.getCell(2, 5).setValue(0);\n cells.markAllCellsAsEditable();\n cells.markFilledCellsAsNotEditable();\n\n cells.getCell(0, 0).setValue(1);\n cells.getCell(0, 1).setValue(2);\n cells.getCell(0, 2).setValue(3);\n\n cells.fillInNotes();\n board.setCells(cells);\n }\n\n public static int findClosestMaterialColor(int color) {\n int minDifference = Integer.MAX_VALUE;\n int selectedIndex = 0;\n int difference = 0;\n int rdiff = 0;\n int gdiff = 0;\n int bdiff = 0;\n\n for (int i = 0; i < MATERIAL_COLORS.length; i++) {\n if (color == MATERIAL_COLORS[i]) {\n return color;\n }\n\n rdiff = Math.abs(Color.red(color) - Color.red(MATERIAL_COLORS[i]));\n gdiff = Math.abs(Color.green(color) - Color.green(MATERIAL_COLORS[i]));\n bdiff = Math.abs(Color.blue(color) - Color.blue(MATERIAL_COLORS[i]));\n difference = rdiff + gdiff + bdiff;\n if (difference < minDifference) {\n minDifference = difference;\n selectedIndex = i;\n }\n }\n\n return MATERIAL_COLORS[selectedIndex];\n }\n\n private static int getColorResourceIdHelper(Context context, String style, int color) {\n String colorAsString = String.format(\"%1$06x\", (color & 0x00FFFFFF));\n return context.getResources().getIdentifier(style + colorAsString, \"style\", context.getPackageName());\n }\n\n public static int getPrimaryColorResourceId(Context context, int color) {\n return getColorResourceIdHelper(context, \"colorPrimary_\", color);\n }\n\n public static int getDarkPrimaryColorResourceId(Context context, int color) {\n return getColorResourceIdHelper(context, \"colorPrimaryDark_\", color);\n }\n\n public static int getAccentColorResourceId(Context context, int color) {\n return getColorResourceIdHelper(context, \"colorAccent_\", color);\n }\n\n public static int getButtonColorResourceId(Context context, int color) {\n return getColorResourceIdHelper(context, \"colorButtonNormal_\", color);\n }\n\n public enum IMButtonStyle {\n DEFAULT, // no background tint, default text color\n ACCENT, // accent background tint, inverse text color\n ACCENT_HIGHCONTRAST // inverse text color background, default text color\n }\n}" ]
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import org.moire.opensudoku.R; import org.moire.opensudoku.game.Cell; import org.moire.opensudoku.game.CellCollection; import org.moire.opensudoku.game.CellCollection.OnChangeListener; import org.moire.opensudoku.game.CellNote; import org.moire.opensudoku.game.SudokuGame; import org.moire.opensudoku.gui.HintsQueue; import org.moire.opensudoku.gui.SudokuBoardView; import org.moire.opensudoku.gui.inputmethod.IMControlPanelStatePersister.StateBundle; import org.moire.opensudoku.utils.ThemeUtils; import java.util.HashMap; import java.util.List; import java.util.Map;
protected View createControlPanelView() { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View controlPanel = inflater.inflate(R.layout.im_numpad, null); mNumberButtons = new HashMap<>(); mNumberButtons.put(1, controlPanel.findViewById(R.id.button_1)); mNumberButtons.put(2, controlPanel.findViewById(R.id.button_2)); mNumberButtons.put(3, controlPanel.findViewById(R.id.button_3)); mNumberButtons.put(4, controlPanel.findViewById(R.id.button_4)); mNumberButtons.put(5, controlPanel.findViewById(R.id.button_5)); mNumberButtons.put(6, controlPanel.findViewById(R.id.button_6)); mNumberButtons.put(7, controlPanel.findViewById(R.id.button_7)); mNumberButtons.put(8, controlPanel.findViewById(R.id.button_8)); mNumberButtons.put(9, controlPanel.findViewById(R.id.button_9)); mNumberButtons.put(0, controlPanel.findViewById(R.id.button_clear)); for (Integer num : mNumberButtons.keySet()) { Button b = mNumberButtons.get(num); b.setTag(num); b.setOnClickListener(mNumberButtonClick); } mSwitchNumNoteButton = controlPanel.findViewById(R.id.switch_num_note); mSwitchNumNoteButton.setOnClickListener(v -> { mEditMode = mEditMode == MODE_EDIT_VALUE ? MODE_EDIT_NOTE : MODE_EDIT_VALUE; update(); }); return controlPanel; } @Override public int getNameResID() { return R.string.numpad; } @Override public int getHelpResID() { return R.string.im_numpad_hint; } @Override public String getAbbrName() { return mContext.getString(R.string.numpad_abbr); } @Override protected void onActivated() { onCellSelected(mBoard.isReadOnly() ? null : mBoard.getSelectedCell()); } @Override protected void onCellSelected(Cell cell) { if (cell != null) { mBoard.setHighlightedValue(cell.getValue()); } else { mBoard.setHighlightedValue(0); } mSelectedCell = cell; update(); } private void update() { switch (mEditMode) { case MODE_EDIT_NOTE: mSwitchNumNoteButton.setImageResource(R.drawable.ic_edit_white); break; case MODE_EDIT_VALUE: mSwitchNumNoteButton.setImageResource(R.drawable.ic_edit_grey); break; } if (mEditMode == MODE_EDIT_VALUE) { int selectedNumber = mSelectedCell == null ? 0 : mSelectedCell.getValue(); for (Button b : mNumberButtons.values()) { if (b.getTag().equals(selectedNumber)) { ThemeUtils.applyIMButtonStateToView(b, ThemeUtils.IMButtonStyle.ACCENT); } else { ThemeUtils.applyIMButtonStateToView(b, ThemeUtils.IMButtonStyle.DEFAULT); } } } else { CellNote note = mSelectedCell == null ? new CellNote() : mSelectedCell.getNote(); List<Integer> notedNumbers = note.getNotedNumbers(); for (Button b : mNumberButtons.values()) { if (notedNumbers.contains(b.getTag())) { ThemeUtils.applyIMButtonStateToView(b, ThemeUtils.IMButtonStyle.ACCENT); } else { ThemeUtils.applyIMButtonStateToView(b, ThemeUtils.IMButtonStyle.DEFAULT); } } } Map<Integer, Integer> valuesUseCount = null; if (mHighlightCompletedValues || mShowNumberTotals) valuesUseCount = mGame.getCells().getValuesUseCount(); if (mHighlightCompletedValues && mEditMode == MODE_EDIT_VALUE) { int selectedNumber = mSelectedCell == null ? 0 : mSelectedCell.getValue(); for (Map.Entry<Integer, Integer> entry : valuesUseCount.entrySet()) { boolean highlightValue = entry.getValue() >= CellCollection.SUDOKU_SIZE; boolean selected = entry.getKey() == selectedNumber; Button b = mNumberButtons.get(entry.getKey()); if (highlightValue && !selected) { ThemeUtils.applyIMButtonStateToView(b, ThemeUtils.IMButtonStyle.ACCENT_HIGHCONTRAST); } } } if (mShowNumberTotals) { for (Map.Entry<Integer, Integer> entry : valuesUseCount.entrySet()) { Button b = mNumberButtons.get(entry.getKey()); b.setText(entry.getKey() + " (" + entry.getValue() + ")"); } } } @Override
protected void onSaveState(StateBundle outState) {
7
devalexx/evilrain
Main/src/com/alex/rain/screens/BasicUIScreen.java
[ "public class RainGame extends Game {\n Stage stage;\n static RainGame instance = new RainGame();\n static float time;\n public static PolygonSpriteBatch polyBatch;\n public static ShapeRenderer shapeRenderer;\n public final static String VERSION = \"0.2.0\";\n\n private RainGame() {\n }\n\n public static RainGame getInstance() {\n return instance;\n }\n\n @Override\n public void create() {\n TextureManager.reload();\n polyBatch = new PolygonSpriteBatch();\n shapeRenderer = new ShapeRenderer();\n\n TextureManager.getAtlas(\"pack.atlas\");\n\n //setLevel(\"level1\", false);\n setScreen(new SplashScreen());\n Gdx.gl.glClearColor(1, 1, 1, 1);\n TextureManager.setLinearFilter(SettingsManager.getSmoothTextureType());\n }\n\n @Override\n public void render() {\n Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);\n if(stage != null) {\n stage.draw();\n stage.act(Gdx.graphics.getDeltaTime());\n }\n\n super.render();\n time += Gdx.graphics.getDeltaTime();\n }\n\n public void setLevel(String name) {\n setLevel(name, false);\n }\n\n public void setLevel(String name, boolean editable) {\n if(stage != null)\n stage.dispose();\n GameWorld gameWorld;\n if(!editable)\n gameWorld = new GameWorld(name);\n else\n gameWorld = new EditableGameWorld(name);\n gameWorld.createWorld();\n stage = gameWorld;\n Gdx.input.setInputProcessor(stage);\n Gdx.input.setCatchBackKey(true);\n\n screen = new GameScreen(gameWorld);\n setScreen(screen);\n }\n\n public void setMenu(Screen screen) {\n setScreen(screen);\n stage.dispose();\n stage = null;\n }\n\n public static float getTime() {\n return time;\n }\n\n @Override\n public void resume() {\n super.resume();\n TextureManager.reload();\n }\n\n @Override\n public void resize(int width, int height) {\n getScreen().resize(width, height);\n }\n}", "public class ResourceManager {\n static ResourceManager instance = new ResourceManager();\n\n static Skin skin;\n\n private ResourceManager() {\n skin = new Skin(Gdx.files.internal(\"data/skins/uiskin.json\"));\n TextureManager.addExistingAtlas(\"uiskin.png\", skin.getAtlas());\n /*for(BitmapFont f : ResourceManager.getAllFonts().values())\n f.setScale(0.5f);*/\n }\n\n public static ResourceManager getInstance() {\n return instance;\n }\n\n public static Skin getSkin() {\n return skin;\n }\n\n public static BitmapFont getFont() {\n return skin.get(\"default-font\", BitmapFont.class);\n }\n\n public static ObjectMap<String, BitmapFont> getAllFonts() {\n return skin.getAll(BitmapFont.class);\n }\n}", "public class TextureManager {\n private static Map<String, Texture> textureMap = new HashMap<String, Texture>();\n private static Map<Texture, TextureData> textureDataMap = new HashMap<Texture, TextureData>();\n\n private static Map<String, TextureAtlas> textureAtlasMap = new HashMap<String, TextureAtlas>();\n private static Map<String, TextureAtlas> textureAtlasNameMap = new HashMap<String, TextureAtlas>();\n private static Map<TextureAtlas, TextureAtlas.TextureAtlasData> textureAtlasDataMap =\n new HashMap<TextureAtlas, TextureAtlas.TextureAtlasData>();\n\n private static TextureManager manager = new TextureManager();\n\n public static Sprite getSpriteFromDefaultAtlas(String textureName) {\n if(!textureAtlasMap.containsKey(\"pack.atlas\"))\n getAtlas(\"images/pack.atlas\");\n return getSpriteFromAtlas(\"pack.atlas\", textureName);\n }\n\n public static Sprite getSpriteFromAtlas(String atlasName, String textureName) {\n if(atlasName == null)\n for(TextureAtlas textureAtlas : textureAtlasMap.values()) {\n Sprite s = textureAtlas.createSprite(textureName);\n if(s != null)\n return s;\n }\n\n if(textureAtlasMap.containsKey(atlasName)) {\n return textureAtlasMap.get(atlasName).createSprite(textureName);\n }\n\n return null;\n }\n\n public static Sprite getRegionFromDefaultAtlas(String textureName) {\n return getSpriteFromAtlas(\"pack.atlas\", textureName);\n }\n\n public static TextureAtlas.AtlasRegion getRegionFromAtlas(String atlasName, String textureName) {\n if(atlasName == null)\n for(TextureAtlas textureAtlas : textureAtlasMap.values()) {\n TextureAtlas.AtlasRegion ar = textureAtlas.findRegion(textureName);\n if(ar != null)\n return ar;\n }\n\n if(textureAtlasMap.containsKey(atlasName)) {\n return textureAtlasMap.get(atlasName).findRegion(textureName);\n }\n\n return null;\n }\n\n public static TextureAtlas getAtlas(String path) {\n if(textureAtlasMap.containsKey(path)) {\n return textureAtlasMap.get(path);\n } else {\n TextureAtlas textureAtlas = new TextureAtlas(Gdx.files.internal(\"data/images/\" + path));\n textureAtlasMap.put(path.substring(path.lastIndexOf(\"/\") + 1, path.length()), textureAtlas);\n for(Texture texture : textureAtlas.getTextures()) {\n String name = \"\" + texture;\n if(texture.getTextureData() instanceof FileTextureData)\n name = ((FileTextureData)texture.getTextureData()).getFileHandle().name();\n\n textureMap.put(name, texture);\n textureDataMap.put(texture, texture.getTextureData());\n }\n\n return textureAtlas;\n }\n }\n\n public static void addExistingAtlas(String path, TextureAtlas textureAtlas) {\n textureAtlasMap.put(path, textureAtlas);\n for(Texture texture : textureAtlas.getTextures()) {\n String name = \"\" + texture;\n if(texture.getTextureData() instanceof FileTextureData)\n name = ((FileTextureData)texture.getTextureData()).getFileHandle().name();\n\n textureMap.put(name, texture);\n textureDataMap.put(texture, texture.getTextureData());\n }\n }\n\n public static Texture getTexture(String path) {\n if(textureMap.containsKey(path)) {\n return textureMap.get(path);\n } else {\n Texture texture = new Texture(Gdx.files.internal(\"data/images/\" + path));\n textureMap.put(path, texture);\n textureDataMap.put(texture, texture.getTextureData());\n return texture;\n }\n }\n\n public static void reload() {\n for(Texture texture : textureMap.values()) {\n texture.load(textureDataMap.get(texture));\n }\n }\n\n public static void setLinearFilter(SettingsManager.SmoothTextureType state) {\n for(Texture t : textureMap.values())\n t.setFilter(state == SettingsManager.SmoothTextureType.ALL_TEXTURES ?\n Texture.TextureFilter.Linear : Texture.TextureFilter.Nearest,\n state == SettingsManager.SmoothTextureType.ALL_TEXTURES ?\n Texture.TextureFilter.Linear : Texture.TextureFilter.Nearest);\n\n for(TextureAtlas ta : textureAtlasMap.values()) {\n for(Texture t : ta.getTextures()) {\n boolean isLinear = false;\n if(state == SettingsManager.SmoothTextureType.ALL_TEXTURES ||\n state == SettingsManager.SmoothTextureType.UI_TEXTURES &&\n t.getTextureData() instanceof FileTextureData &&\n ((FileTextureData)t.getTextureData()).getFileHandle().name().contains(\"uiskin\"))\n isLinear = true;\n\n t.setFilter(isLinear ? Texture.TextureFilter.Linear : Texture.TextureFilter.Nearest,\n isLinear ? Texture.TextureFilter.Linear : Texture.TextureFilter.Nearest);\n }\n }\n }\n}", "public class BasicStage extends Stage {\n public BasicStage(Viewport viewport) {\n super(viewport);\n }\n\n @Override\n public boolean keyDown(int keyCode) {\n if(keyCode == Input.Keys.ESCAPE || keyCode == Input.Keys.Q || keyCode == Input.Keys.BACK) {\n if(RainGame.getInstance().getScreen() instanceof MainMenuScreen)\n Gdx.app.exit();\n else\n RainGame.getInstance().setScreen(new MainMenuScreen());\n }\n\n return super.keyDown(keyCode);\n }\n}", "public class GameViewport extends Viewport {\n public static final int WIDTH = 800, HEIGHT = 480;\n public float offsetX, offsetY;\n public float fullWorldWidth, fullWorldHeight;\n public float scale;\n\n public GameViewport() {\n setCamera(new OrthographicCamera());\n setWorldSize(WIDTH, HEIGHT);\n }\n\n @Override\n public void update(int screenWidth, int screenHeight, boolean centerCamera) {\n Vector2 viewFit = Scaling.fit.apply(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),\n WIDTH, HEIGHT).cpy();\n Vector2 viewFill = Scaling.fill.apply(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),\n WIDTH, HEIGHT);\n\n setScreenBounds(0, 0, screenWidth, screenHeight);\n\n boolean isPortrait = viewFit.x - WIDTH < 0.1;\n boolean isLandscape = viewFit.y - HEIGHT < 0.1;\n offsetX = isLandscape ? viewFill.x / 2 - WIDTH / 2 : 0;\n offsetY = isPortrait ? viewFill.y / 2 - HEIGHT / 2 : 0;\n setWorldSize(isLandscape ? viewFill.x : WIDTH,\n isPortrait ? viewFill.y : HEIGHT);\n fullWorldWidth = 2 * offsetX + getWorldWidth();\n fullWorldHeight = 2 * offsetY + getWorldHeight();\n if(offsetX < 0.01)\n scale = (float)getScreenWidth() / WIDTH;\n else\n scale = (float)getScreenHeight() / HEIGHT;\n apply(centerCamera);\n }\n\n public void apply(boolean centerCamera) {\n Gdx.gl.glViewport(getScreenX(), getScreenY(), getScreenWidth(), getScreenHeight());\n getCamera().viewportWidth = getWorldWidth();\n getCamera().viewportHeight = getWorldHeight();\n if(centerCamera)\n getCamera().position.set(- offsetX + getWorldWidth() / 2, - offsetY + getWorldHeight() / 2, 0);\n getCamera().update();\n }\n}" ]
import com.alex.rain.RainGame; import com.alex.rain.managers.ResourceManager; import com.alex.rain.managers.TextureManager; import com.alex.rain.stages.BasicStage; import com.alex.rain.viewports.GameViewport; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin;
/******************************************************************************* * Copyright 2013 See AUTHORS file. * * Licensed under the GNU GENERAL PUBLIC LICENSE V3 * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.gnu.org/licenses/gpl.html * * 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.alex.rain.screens; public class BasicUIScreen implements Screen { protected Stage stage; protected Texture backgroundTexture = TextureManager.getTexture("background.png"); protected Skin skin = ResourceManager.getSkin(); protected Actor mainUI; protected boolean debugRendererEnabled; public BasicUIScreen() { this(true); } public BasicUIScreen(Stage stage) { this.stage = stage; } public BasicUIScreen(boolean createStage) { backgroundTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat); if(createStage) {
stage = new BasicStage(new GameViewport());
4
fuhoujun/e
demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CustomerServiceImpl.java
[ "public class CustomerQueryParam extends DefaultDataPermissionQueryParam implements QueryParam {\n private String name;\n private String sexId;\n private Boolean vip;\n\t@DateTimeFormat(pattern=\"yyyy-MM-dd\")\n private Date dobStart;\n\t@DateTimeFormat(pattern=\"yyyy-MM-dd\")\n private Date dobEnd;\n private String phone;\n\t\n\tpublic String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\t\n\tpublic String getSexId() {\n return sexId;\n }\n\n public void setSexId(String sexId) {\n this.sexId = sexId;\n }\n\t\n\tpublic Boolean getVip() {\n return vip;\n }\n\n public void setVip(Boolean vip) {\n this.vip = vip;\n }\n\t\n\tpublic Date getDobStart() {\n return dobStart;\n }\n\n public void setDobStart(Date dobStart) {\n this.dobStart = dobStart;\n }\n\t\n\tpublic Date getDobEnd() {\n return dobEnd;\n }\n\n public void setDobEnd(Date dobEnd) {\n this.dobEnd = dobEnd;\n }\n\t\n\tpublic String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n}", "@Entity\n@Table(name = \"demo_company\")\npublic class CompanyEntity extends BaseEntity {\n\tprivate static final long serialVersionUID = 1L;\n\t@Column( nullable=true)\n private String name;\n\t@Column( nullable=true)\n private Integer registeredCapital;\n\t@Column( nullable=true)\n\t@DateTimeFormat(pattern=\"yyyy-MM-dd\")\n private Date registerDate;\n\t@Column( nullable=true)\n private String contactName;\n\t@Column( nullable=true)\n private String phone;\n\t@Column( nullable=true)\n private String address;\n\tpublic String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\tpublic Integer getRegisteredCapital() {\n return registeredCapital;\n }\n\n public void setRegisteredCapital(Integer registeredCapital) {\n this.registeredCapital = registeredCapital;\n }\n\tpublic Date getRegisterDate() {\n return registerDate;\n }\n\n public void setRegisterDate(Date registerDate) {\n this.registerDate = registerDate;\n }\n\tpublic String getContactName() {\n return contactName;\n }\n\n public void setContactName(String contactName) {\n this.contactName = contactName;\n }\n\tpublic String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\tpublic String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n}", "@Entity\n@Table(name = \"demo_customer\")\npublic class CustomerEntity extends BaseEntity {\n\tprivate static final long serialVersionUID = 1L;\n\t@Column( nullable=true)\n private String name;\n\t@ManyToOne()\n private DictionaryEntity sex;\n\t@ManyToOne()\n private CompanyEntity company;\n\t@Column( nullable=true)\n private Boolean vip = false;\n\t@Column( nullable=true)\n\t@DateTimeFormat(pattern=\"yyyy-MM-dd\")\n private Date dob;\n\t@Column( nullable=true)\n private String phone;\n\t@Column( nullable=true)\n private String address;\n\tpublic String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\tpublic DictionaryEntity getSex() {\n return sex;\n }\n\n public void setSex(DictionaryEntity sex) {\n this.sex = sex;\n }\n\tpublic CompanyEntity getCompany() {\n return company;\n }\n\n public void setCompany(CompanyEntity company) {\n this.company = company;\n }\n\tpublic Boolean getVip() {\n return vip;\n }\n\n public void setVip(Boolean vip) {\n this.vip = vip;\n }\n\tpublic Date getDob() {\n return dob;\n }\n\n public void setDob(Date dob) {\n this.dob = dob;\n }\n\tpublic String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\tpublic String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n}", "public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {\n\n @Query(value=\" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate &gt;= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate &lt;= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>\")\n @DynamicQuery\n Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);\n\n}", "public interface CustomerRepository extends GenericRepository<CustomerEntity, String> {\n\n @Query(value=\" from CustomerEntity x where 1=1 <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='sexId'> and x.sex.id = :sexId </notEmpty><notEmpty name='vip'> and x.vip = :vip </notEmpty><notEmpty name='dobStart'> and x.dob &gt;= :dobStart </notEmpty><notEmpty name='dobEnd'> and x.dob &lt;= :dobEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty>\")\n @DynamicQuery\n Page<CustomerEntity> findCustomerPage(CustomerQueryParam customerQueryParam, Pageable pageable);\n\n}" ]
import java.io.IOException; import java.io.OutputStream; import java.util.Date; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.loy.e.basic.data.domain.entity.DictionaryEntity; import com.loy.e.basic.data.repository.DictionaryRepository; import com.loy.e.common.util.DateUtil; import com.loy.e.core.annotation.ControllerLogExeTime; import com.loy.e.core.util.TableToExcelUtil; import com.xx.demo.test.domain.CustomerQueryParam; import com.xx.demo.test.domain.entity.CompanyEntity; import com.xx.demo.test.domain.entity.CustomerEntity; import com.xx.demo.test.repository.CompanyRepository; import com.xx.demo.test.repository.CustomerRepository;
package com.xx.demo.test.service.impl; /** * * @author Loy Fu qq群 540553957 website = http://www.17jee.com */ @RestController @RequestMapping(value={"**/customer"}, method={RequestMethod.POST, RequestMethod.GET}) @Transactional public class CustomerServiceImpl{ @Autowired CustomerRepository customerRepository; @Autowired CompanyRepository companyRepository; @Autowired DictionaryRepository dictionaryRepository; @RequestMapping({ "/page" }) @ControllerLogExeTime(description = "分页查询客户", log = false) public Page<CustomerEntity> queryPage(CustomerQueryParam customerQueryParam, Pageable pageable) { if (customerQueryParam != null) { Date dobEnd = customerQueryParam.getDobEnd(); if (dobEnd != null) { dobEnd = DateUtil.addOneDay(dobEnd); customerQueryParam.setDobEnd(dobEnd); } } Page<CustomerEntity> page = this.customerRepository.findCustomerPage((customerQueryParam), pageable); return page; } @ControllerLogExeTime(description="获取客户", log=false) @RequestMapping({"/get"}) public CustomerEntity get(String id) { CustomerEntity customerEntity = (CustomerEntity)this.customerRepository.get(id); return customerEntity; } @ControllerLogExeTime(description="查看客户", log=false) @RequestMapping({"/detail"}) public CustomerEntity detail(String id) { CustomerEntity customerEntity = (CustomerEntity)this.customerRepository.get(id); return customerEntity; } @ControllerLogExeTime(description="删除客户") @RequestMapping({"/del"}) public void del(String id) { if (StringUtils.isNotEmpty(id)) { String[] idsArr = id.split(","); if (idsArr != null) { for (String idd : idsArr) { CustomerEntity customerEntity = (CustomerEntity)this.customerRepository.get(idd); if (customerEntity != null) { this.customerRepository.delete(customerEntity); } } } } } @RequestMapping({"/save"}) @ControllerLogExeTime(description="保存客户") public CustomerEntity save(CustomerEntity customerEntity) { customerEntity.setId(null); DictionaryEntity sex = customerEntity.getSex(); if (sex != null) { String sexId = (String)sex.getId(); if (StringUtils.isEmpty(sexId)) { sex = null; }else { sex = (DictionaryEntity)this.dictionaryRepository.get(sexId); } } customerEntity.setSex(sex);
CompanyEntity company = customerEntity.getCompany();
1
suguru/mongo-java-async-driver
src/test/java/jp/ameba/mongo/UpdateTest.java
[ "public class Delete extends Request {\n\t\n\tprivate int flags;\n\t\n\tprivate BSONObject selector;\n\t\n\t/**\n\t * Update\n\t * \n\t * @param collectionName\n\t * @param upsert\n\t * @param multiUpdate\n\t * @param selector\n\t * @param update\n\t */\n\tpublic Delete(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tBSONObject selector) {\n\t\tsuper(OperationCode.OP_DELETE, databaseName, collectionName);\n\t\tthis.selector = selector;\n\t\tthis.consistency = Consistency.SAFE;\n\t}\n\t\n\t/**\n\t * selector に合致するオブジェクトを最初の\n\t * 1件だけ削除します。\n\t * このメソッドが呼ばれない場合、該当のオブジェクトすべてが削除されます。\n\t * \n\t * @return\n\t */\n\tpublic Delete singleRemove() {\n\t\tflags = BitWise.addBit(flags, 0);\n\t\treturn this;\n\t}\n\n\t/**\n\t * 更新における {@link Consistency} を設定します。\n\t * \n\t * @param safeLevel\n\t * @return\n\t */\n\tpublic Delete consistency(Consistency consistency) {\n\t\tsetConsistency(consistency);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic void encode(BSONEncoder encoder) {\n\t\t// Body\n\t\tencoder.writeInt(0);\n\t\tencoder.writeCString(fullCollectionName);\n\t\tencoder.writeInt(flags);\n\t\tencoder.putObject(selector);\n\t}\n}", "public class Insert extends Request {\n\t\n\tprivate List<BSONObject> documents;\n\t\n\t/**\n\t * Inserting a single document\n\t * \n\t * @param databaseName\n\t * @param collectionName\n\t * @param document\n\t */\n\tpublic Insert(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tBSONObject document) {\n\t\tsuper(OperationCode.OP_INSERT, databaseName, collectionName);\n\t\tthis.documents = new LinkedList<BSONObject>();\n\t\tthis.documents.add(document);\n\t\tthis.consistency = Consistency.SAFE;\n\t\tif (!document.containsField(\"_id\")) {\n\t\t\tdocument.put(\"_id\", new ObjectId());\n\t\t}\n\t}\n\t\n\t/**\n\t * Inserting multiple documents. (bulk insert)\n\t * \n\t * @param collectionName\n\t * @param upsert\n\t * @param multiUpdate\n\t * @param selector\n\t * @param update\n\t */\n\tpublic Insert(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tList<BSONObject> documents) {\n\t\tsuper(OperationCode.OP_INSERT, databaseName, collectionName);\n\t\tthis.documents = documents;\n\t\tthis.consistency = Consistency.SAFE;\t\t\n\t\tfor (BSONObject document : documents) {\n\t\t\tif (!document.containsField(\"_id\")) {\n\t\t\t\tdocument.put(\"_id\", new ObjectId());\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * 更新における {@link Consistency} を設定します。\n\t * \n\t * @param safeLevel\n\t * @return\n\t */\n\tpublic Insert consistency(Consistency consistency) {\n\t\tsetConsistency(consistency);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic void encode(BSONEncoder encoder) {\n\t\t// Body\n\t\tencoder.writeInt(0);\n\t\tencoder.writeCString(fullCollectionName);\n\t\tfor (int i = 0; i < documents.size(); i++) {\n\t\t\tencoder.putObject(documents.get(i));\n\t\t}\n\t}\n}", "public class Query extends Request {\n\t\n\tprivate int numberToSkip;\n\t\n\tprivate int numberToReturn;\n\t\n\tprivate BSONObject query;\n\t\n\tprivate BSONObject returnFieldSelector;\n\t\n\tprivate int flags;\n\t\n\tpublic Query(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tint numberToSkip,\n\t\t\tint numberToReturn,\n\t\t\tBSONObject query) {\n\t\tthis(databaseName, collectionName, numberToSkip, numberToReturn, query, null);\n\t}\n\t\t\t\n\t\n\tpublic Query(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tint numberToSkip,\n\t\t\tint numberToReturn,\n\t\t\tBSONObject query,\n\t\t\tBSONObject returnFieldSelector) {\n\t\tsuper(OperationCode.OP_QUERY, databaseName, collectionName);\n\t\tthis.numberToSkip = numberToSkip;\n\t\tthis.numberToReturn = numberToReturn;\n\t\tthis.query = query;\n\t\tthis.returnFieldSelector = returnFieldSelector;\n\t\tthis.consistency = Consistency.NONE;\n\t}\n\t\n\tpublic Query tailableCursor(boolean tailable) {\n\t\tthis.flags = BitWise.addBit(flags, 1);\n\t\treturn this;\n\t}\n\t\n\tpublic Query slaveOk(boolean slaveOk) {\n\t\tthis.flags = BitWise.addBit(flags, 2);\n\t\treturn this;\n\t}\n\t\n\tpublic Query oplogReplay(boolean oplogReplay) {\n\t\tthis.flags = BitWise.addBit(flags, 3);\n\t\treturn this;\n\t}\n\t\n\tpublic Query noCursorTimeout(boolean noCursorTimeout) {\n\t\tthis.flags = BitWise.addBit(flags, 4);\n\t\treturn this;\n\t}\n\t\n\tpublic Query awaitData(boolean awaitData) {\n\t\tthis.flags = BitWise.addBit(flags, 5);\n\t\treturn this;\n\t}\n\t\n\tpublic Query exhaust(boolean exhaust) {\n\t\tthis.flags = BitWise.addBit(flags, 6);\n\t\treturn this;\n\t}\n\t\n\tpublic Query numberToReturn(int numberToReturn) {\n\t\tthis.numberToReturn = numberToReturn;\n\t\treturn this;\n\t}\n\t\n\tpublic Query numberToSkip(int numberToSkip) {\n\t\tthis.numberToSkip = numberToSkip;\n\t\treturn this;\n\t}\n\t\n\tpublic Query where(String key, Object value) {\n\t\tthis.query.put(key, value);\n\t\treturn this;\n\t}\n\t\n\tpublic Query field(String key) {\n\t\tif (returnFieldSelector == null) {\n\t\t\treturnFieldSelector = new BasicBSONObject();\n\t\t}\n\t\treturnFieldSelector.put(key, 1);\n\t\treturn this;\n\t}\n\t\n\tpublic int getNumberToReturn() {\n\t\treturn numberToReturn;\n\t}\n\t\n\tpublic int getNumberToSkip() {\n\t\treturn numberToSkip;\n\t}\n\n\t@Override\n\tpublic void encode(BSONEncoder encoder) {\n\t\t// Body\n\t\tencoder.writeInt(flags);\n\t\tencoder.writeCString(fullCollectionName);\n\t\tencoder.writeInt(numberToSkip);\n\t\tencoder.writeInt(numberToReturn);\n\t\tencoder.putObject(query);\n\t\tif (returnFieldSelector != null) {\n\t\t\tencoder.putObject(returnFieldSelector);\n\t\t}\n\t}\n}", "public class Response {\n\t\n\t// ヘッダー情報\n\tprivate MessageHeader header;\n\t// フラグ\n\tprivate int responseFlags;\n\t// カーソルID\n\tprivate long cursorId;\n\t// この返信が開始しているカーソル位置\n\tprivate int startingFrom;\n\t// 返却されているドキュメント数\n\tprivate int numberReturned;\n\t// 返却されたドキュメント内容\n\tprivate List<BSONObject> documents;\n\t\n\tprivate static final BSONDecoder staticDecoder = new BSONDecoder();\n\t\n\tprivate static final List<BSONObject> emptyList = Collections.unmodifiableList(new ArrayList<BSONObject>(0));\n\t\n\t/**\n\t * メッセージヘッダを設定し、レスポンスオブジェクトを作成します。\n\t * @param header\n\t */\n\tpublic Response(MessageHeader header) {\n\t\tthis.header = header;\n\t}\n\t\n\t/**\n\t * メッセージヘッダを取得します。\n\t * @return\n\t */\n\tpublic MessageHeader getHeader() {\n\t\treturn header;\n\t}\n\t\n\t/**\n\t * レスポンスフラグを取得します。\n\t * @return\n\t */\n\tpublic int getResponseFlags() {\n\t\treturn responseFlags;\n\t}\n\t\n\t/**\n\t * このレスポンスの持つカーソルIDを取得します。\n\t * @return\n\t */\n\tpublic long getCursorId() {\n\t\treturn cursorId;\n\t}\n\t\n\t/**\n\t * 返却されたドキュメント数を取得します。\n\t * @return\n\t */\n\tpublic int getNumberReturned() {\n\t\treturn numberReturned;\n\t}\n\t\n\t/**\n\t * 結果の開始位置を取得します。\n\t * @return\n\t */\n\tpublic int getStartingFrom() {\n\t\treturn startingFrom;\n\t}\n\t\n\t/**\n\t * CURSOR NOT FOUND が発生しているか確認します。\n\t * @return\n\t */\n\tpublic boolean isCursorNotFound() {\n\t\treturn BitWise.hasBit(responseFlags, 0);\n\t}\n\t\n\t/**\n\t * このレスポンスが正常に終了した結果であるかを確認します。\n\t * From MongoDB Java driver (CommandResult)\n\t * @return\n\t */\n\tpublic boolean isOk() {\n\t\tif (BitWise.hasBit(responseFlags, 1)) {\n\t\t\treturn false;\n\t\t}\n \tif (documents.size() == 0) {\n \t\treturn true;\n \t}\n \tBSONObject doc = documents.get(0);\n Object o = doc.get(\"ok\");\n if (o == null) {\n return true;\n }\n if (o instanceof Boolean) {\n return (Boolean) o;\n }\n if (o instanceof Number) {\n return ((Number) o).intValue() == 1;\n }\n throw new IllegalArgumentException(\"Illegal class '\" + o.getClass().getName() + \"'\");\n\t}\n\t\n\t/**\n\t * このレスポンスが AWAIT CAPABLE であるか確認します。\n\t * @return\n\t */\n\tpublic boolean isAwaitCapable() {\n\t\treturn BitWise.hasBit(responseFlags, 3);\n\t}\n\t\n /**\n * 失敗している場合のエラーメッセージを取得します。\n * From MongoDB Java driver (CommandResult)\n * @return\n */\n public String getErrorMessage(){\n \tif (documents.size() == 0) {\n \t\treturn null;\n \t}\n \tBSONObject doc = documents.get(0);\n Object errorMessage = doc.get(\"errmsg\");\n return errorMessage == null ? null : errorMessage.toString();\n }\n \n\t/**\n\t * 内包するドキュメント一覧を取得します。\n\t * @return\n\t */\n\tpublic List<BSONObject> getDocuments() {\n\t\treturn documents;\n\t}\n\t\n\t/**\n\t * 内包するドキュメントの最初の1つを取得します。\n\t * @return\n\t */\n\tpublic BSONObject getDocument() {\n\t\tif (documents.size() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn documents.get(0);\n\t}\n\t\n\t/**\n\t * {@link ChannelBuffer} から内容を解析・取得します。\n\t * @param buffer\n\t * @throws IOException\n\t */\n\tpublic void readBuffer(ChannelBuffer buffer) throws IOException {\n\t\t\n\t\tresponseFlags = buffer.readInt();\n\t\tcursorId = buffer.readLong();\n\t\tstartingFrom = buffer.readInt();\n\t\tnumberReturned = buffer.readInt();\n\t\t\n\t\tif (numberReturned == 0) {\n\t\t\tdocuments = emptyList;\n\t\t} else {\n\t\t\t// 残りのバッファからドキュメントを読み出す\n\t\t\tChannelBufferInputStream input = new ChannelBufferInputStream(buffer);\n\t\t\tdocuments = new ArrayList<BSONObject>(numberReturned);\n\t\t\tfor (int i = 0; i < numberReturned; i++) {\n\t\t\t\tdocuments.add(staticDecoder.readObject(input));\n\t\t\t}\n\t\t}\n\t}\n\t\n}", "public class Update extends Request {\n\t\n\tprivate int flags;\n\t\n\tprivate BSONObject selector;\n\t\n\tprivate BSONObject update;\n\t\n\t/**\n\t * UPDATE\n\t * @param databaseName\n\t * @param collectionName\n\t */\n\tpublic Update(\n\t\t\tString databaseName,\n\t\t\tString collectionName) {\n\t\tsuper(OperationCode.OP_UPDATE, databaseName, collectionName);\n\t}\n\t\n\t/**\n\t * UPDATE\n\t * @param collectionName\n\t * @param upsert\n\t * @param multiUpdate\n\t * @param selector\n\t * @param update\n\t */\n\tpublic Update(\n\t\t\tString databaseName,\n\t\t\tString collectionName,\n\t\t\tBSONObject selector,\n\t\t\tBSONObject update) {\n\t\tsuper(OperationCode.OP_UPDATE, databaseName, collectionName);\n\t\tthis.selector = selector;\n\t\tthis.update = update;\n\t\tthis.consistency = Consistency.SAFE;\n\t}\n\n\t/**\n\t * Update対象セレクタを設定します。\n\t * \n\t * @param selector\n\t * @return\n\t */\n\tpublic Update selector(BSONObject selector) {\n\t\tthis.selector = selector;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * 更新対象の内容を設定します。\n\t * @param update\n\t * @return\n\t */\n\tpublic Update update(BSONObject update) {\n\t\tthis.update = update;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * 更新時、該当のオブジェクトが存在しなければ\n\t * 新規に作成し、 insert します。\n\t * \n\t * @return\n\t */\n\tpublic Update upsert() {\n\t\tflags = BitWise.addBit(flags, 0);\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * 複数オブジェクトの更新を設定します\n\t * \n\t * @return\n\t */\n\tpublic Update multiUpdate() {\n\t\tflags = BitWise.addBit(flags, 1);\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * 更新における {@link Consistency} を設定します。\n\t * \n\t * @param safeLevel\n\t * @return\n\t */\n\tpublic Update consistency(Consistency consistency) {\n\t\tsetConsistency(consistency);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic void encode(BSONEncoder encoder) {\n\t\t// Body\n\t\tencoder.writeInt(0);\n\t\tencoder.writeCString(fullCollectionName);\n\t\tencoder.writeInt(flags);\n\t\tencoder.putObject(selector);\n\t\tencoder.putObject(update);\n\t}\n}" ]
import java.io.IOException; import java.net.InetSocketAddress; import jp.ameba.mongo.protocol.Delete; import jp.ameba.mongo.protocol.Insert; import jp.ameba.mongo.protocol.Query; import jp.ameba.mongo.protocol.Response; import jp.ameba.mongo.protocol.Update; import junit.framework.Assert; import org.bson.BSONObject; import org.bson.BasicBSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test;
package jp.ameba.mongo; public class UpdateTest { private MongoConnection client; public UpdateTest() { } @Before public void before() throws IOException { client = new MongoDriver().createConnection(new InetSocketAddress("127.0.0.1", 27017)); client.open(); Assert.assertTrue(client.isOpen()); } @After public void after() throws IOException { client.close(); Assert.assertFalse(client.isOpen()); } @Test public void testUpdate() throws Exception { client.delete(new Delete("test", "update", new BasicBSONObject("_id", "updateId"))); // Test null update client.update(new Update("test", "update", new BasicBSONObject("_id", "updateId"), new BasicBSONObject("name", "abcdefg") ));
Response response = client.query(new Query("test", "update", 0, 1, new BasicBSONObject("_id", "updateId"), null));
2
DavidGoldman/MinecraftScripting
scripting/items/SelectorItem.java
[ "@Mod(modid=ScriptingMod.MOD_ID, name=ScriptingMod.NAME, version=ScriptingMod.VERSION, dependencies = \"after:guilib\")\npublic class ScriptingMod {\n\n\tpublic static final String MOD_ID = \"Scripting\";\n\tpublic static final String NAME = \"In-Game MCEdit Filters & Scripts\";\n\tpublic static final String VERSION = \"1.1.0\";\n\tpublic static final char SECTION = '\\u00A7';\n\tpublic static final PacketPipeline DISPATCHER = new PacketPipeline();\n\n\t@Instance(\"Scripting\")\n\tpublic static ScriptingMod instance;\n\n\t@SidedProxy(clientSide = \"scripting.forge.ClientProxy\", serverSide = \"scripting.forge.Proxy\")\n\tpublic static Proxy proxy;\n\n\tpublic static SelectorItem selector;\n\n\t\n\tprivate Map<String, Selection> selections;\n\tprivate ServerTickHandler serverTicker;\n\n\tprivate Map<String, Object> serverProps;\n\tprivate Map<String, Object> clientProps;\n\tprivate Map<String, Class<?>> abbreviations;\n\t\n\n\tpublic ScriptingMod() {\n\t\tselections = new HashMap<String, Selection>();\n\t\tabbreviations = new HashMap<String, Class<?>>();\n\t\tserverProps = new HashMap<String, Object>();\n\t\tclientProps = new HashMap<String, Object>();\n\t}\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event) {\n\t\tConfig.load(new Configuration(event.getSuggestedConfigurationFile()));\n\n\t\tselector = new SelectorItem();\n\t\tGameRegistry.registerItem(selector, selector.getUnlocalizedName());\n\n\t\tModMetadata modMeta = event.getModMetadata();\n\t\tmodMeta.authorList = Arrays.asList(new String[] { \"Davidee\" });\n\t\tmodMeta.autogenerated = false;\n\t\tmodMeta.credits = \"Thanks to Mojang, Forge, and all your support.\";\n\t\tmodMeta.description = \"Adds Javascript support to Minecraft via Mozilla Rhino.\"\n\t\t\t\t+ \" Users can write their own scripts to run in-game on either the client or server\"\n\t\t\t\t+ \" and also use filters to directly modify their world.\" \n\t\t\t\t+ \"\\nFor more information, visit the URL above.\";\n\t\tmodMeta.url = \"http://www.minecraftforum.net/topic/1951378-/\";\n\t}\n\t\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent event) {\n\t\t/*\n\t\t * Initialize our special context factory\n\t\t */\n\t\tContextFactory.initGlobal(new SandboxContextFactory());\n\t\tReflectionHelper.init();\n\t\tDefaultFilters.init(new File(new File(proxy.getMinecraftDir(), \"scripts\"), \"server\"));\n\t\tFMLCommonHandler.instance().bus().register(this);\n\t\tDISPATCHER.initialize();\n\t\t\n\t\taddAbbreviation(\"Vec3\", ScriptVec3.class);\n\t\taddAbbreviation(\"Vec2\", ScriptVec2.class);\n\t\taddAbbreviation(\"ItemStack\", ScriptItemStack.class);\n\t\taddAbbreviation(\"Rand\", ScriptRandom.class);\n\t\taddAbbreviation(\"Array\", ScriptArray.class);\n\t\taddAbbreviation(\"IO\", ScriptIO.class);\n\t\taddAbbreviation(\"Script\", ScriptHelper.class);\n\t\t\n\t\taddAbbreviation(\"Block\", ScriptBlock.class);\n\t\taddAbbreviation(\"Item\", ScriptItem.class);\n\t\t\n\t\taddAbbreviation(\"Setting\", Setting.class);\n\t\taddAbbreviation(\"SettingBoolean\", SettingBoolean.class);\n\t\taddAbbreviation(\"SettingInt\", SettingInt.class);\n\t\taddAbbreviation(\"SettingFloat\", SettingFloat.class);\n\t\taddAbbreviation(\"SettingString\", SettingString.class);\n\t\taddAbbreviation(\"SettingList\", SettingList.class);\n\t\taddAbbreviation(\"SettingBlock\", SettingBlock.class);\n\t\taddAbbreviation(\"SettingItem\", SettingItem.class);\n\t\t\n\t\taddAbbreviation(\"DataWatcher\", ScriptDataWatcher.class);\n\t\taddAbbreviation(\"Entity\", ScriptEntity.class);\n\t\t\n\t\taddAbbreviation(\"TileEntity\", ScriptTileEntity.class);\n\n\t\taddAbbreviation(\"TAG_Byte\", TAG_Byte.class);\n\t\taddAbbreviation(\"TAG_Byte_Array\", TAG_Byte_Array.class);\n\t\taddAbbreviation(\"TAG_Compound\", TAG_Compound.class);\n\t\taddAbbreviation(\"TAG_Double\", TAG_Double.class);\n\t\taddAbbreviation(\"TAG_Float\", TAG_Float.class);\n\t\taddAbbreviation(\"TAG_Int\", TAG_Int.class);\n\t\taddAbbreviation(\"TAG_Int_Array\", TAG_Int_Array.class);\n\t\taddAbbreviation(\"TAG_List\", TAG_List.class);\n\t\taddAbbreviation(\"TAG_Long\", TAG_Long.class);\n\t\taddAbbreviation(\"TAG_Short\", TAG_Short.class);\n\t\taddAbbreviation(\"TAG_String\", TAG_String.class);\n\t}\n\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event) {\n\t\t/*\n\t\t * Pretend it's the clientProxy.\n\t\t * The ClientProxy will register the ClientTickHandler;\n\t\t * the regular Proxy will do nothing.\n\t\t * \n\t\t * ClientProxy.postInit will only be called from the Minecraft (client) main thread\n\t\t */\n\t\tFile scriptDir = new File(proxy.getMinecraftDir(), \"scripts\");\n\t\tproxy.postInit(scriptDir, clientProps, abbreviations);\n\t\tFMLCommonHandler.instance().bus().register((serverTicker = new ServerTickHandler(scriptDir, serverProps, abbreviations)));\n\t}\n\t\n\t@EventHandler\n\tpublic void serverStarting (FMLServerStartingEvent event) {\n\t\tServerCommandManager manager = (ServerCommandManager) event.getServer().getCommandManager();\n\t\tmanager.registerCommand(new FilterCommand());\n\t}\n\t\n\tpublic ServerCore getServerCore() {\n\t\treturn serverTicker.getServerCore();\n\t}\n\n\tpublic void scriptSleep(int ticks) throws ContinuationPending, IllegalAccessException, IllegalArgumentException {\n\t\tif (isClient()) \n\t\t\tproxy.getClientCore().scriptSleep(ticks);\n\t\telse\n\t\t\tserverTicker.getServerCore().scriptSleep(ticks);\n\t}\n\n\tpublic void addAbbreviation(String abrev, Class<?> clazz) {\n\t\tabbreviations.put(abrev, clazz);\n\t}\n\n\tpublic void setClientProperty(String name, Object obj) {\n\t\tScriptCore core = proxy.getClientCore();\n\t\tif (core == null)\n\t\t\tclientProps.put(name, obj);\n\t\telse\n\t\t\tcore.setProperty(name, obj);\n\t}\n\n\tpublic void setServerProperty(String name, Object obj) {\n\t\tScriptCore core = (serverTicker == null) ? null : serverTicker.getServerCore();\n\t\tif (core == null)\n\t\t\tserverProps.put(name, obj);\n\t\telse\n\t\t\tcore.setProperty(name, obj);\n\t}\n\n\tpublic Selection getSelection(EntityPlayerMP player) {\n\t\tSelection s = selections.get(player.getCommandSenderName());\n\t\tif (s == null) {\n\t\t\ts = new Selection(player.dimension);\n\t\t\tselections.put(player.getCommandSenderName(), s);\n\t\t}\n\t\tif (s.getDimension() != player.dimension) {\n\t\t\ts.reset(player.dimension);\n\t\t\tDISPATCHER.sendTo(ScriptPacket.getPacket(PacketType.SELECTION, s), player);\n\t\t}\n\t\treturn s;\n\t}\n\n\tpublic void updateSelections(List<EntityPlayerMP> allPlayers) {\n\t\tfor (EntityPlayerMP player : allPlayers) {\n\t\t\tSelection s = selections.get(player.getCommandSenderName());\n\t\t\tif (s != null && (s.getDimension() != player.dimension || s.isInvalid())) {\n\t\t\t\ts.reset(player.dimension);\n\t\t\t\tDISPATCHER.sendTo(ScriptPacket.getPacket(PacketType.SELECTION, s), player);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void clearSelections() {\n\t\tselections.clear();\n\t}\n\n\tpublic boolean isClient() {\n\t\treturn FMLCommonHandler.instance().getEffectiveSide().isClient();\n\t}\n\t\n\t@SubscribeEvent\n\tpublic void onPlayerLoggedIn(PlayerLoggedInEvent event) {\n\t\tEntityPlayerMP player = (EntityPlayerMP)event.player;\n\t\tSelection sel = ScriptingMod.instance.getSelection(player);\n\t\tsel.reset(player.dimension);\n\t\tScriptingMod.DISPATCHER.sendTo(ScriptPacket.getPacket(PacketType.SELECTION, sel), player);\n\t}\n\n}", "public class Selection {\n\n\tprivate int dimension;\n\tprivate BlockCoord corner1, corner2;\n\tprivate Entity selectedEntity;\n\tprivate TileEntity selectedTile;\n\n\t//Creates an empty selection\n\tpublic Selection(int dimension) {\n\t\tthis.dimension = dimension;\n\t}\n\n\tpublic Selection(int dimension, Entity selectedEntity) {\n\t\tthis.dimension = dimension;\n\t\tthis.selectedEntity = selectedEntity;\n\t}\n\t\n\tpublic Selection(int dimension, TileEntity selectedTile) {\n\t\tthis.dimension = dimension;\n\t\tthis.selectedTile = selectedTile;\n\t}\n\n\tpublic Selection(int dimension, BlockCoord corner1, BlockCoord corner2) {\n\t\tthis.dimension = dimension;\n\t\tthis.corner1 = corner1;\n\t\tthis.corner2 = corner2;\n\t}\n\n\tpublic void setSelectedEntity(Entity e) {\n\t\tselectedEntity = e;\n\t\tselectedTile = null;\n\t\tcorner1 = null;\n\t\tcorner2 = null;\n\t}\n\t\n\tpublic void setTileEntity(TileEntity t) {\n\t\tselectedTile = t;\n\t\tselectedEntity = null;\n\t\tcorner1 = null;\n\t\tcorner2 = null;\n\t}\n\n\t/**\n\t * Reset selected entity/tile if applicable, else - \n\t * If c is already a corner in this selection, it is removed.\n\t * Otherwise, if the selection has an open spot, it is added.\n\t * In the case 2 corners are already selected, the selection is reset.\n\t * @param c BlockCoord to add\n\t */\n\tpublic void addBlockCoord(BlockCoord c) {\n\t\tif (selectedEntity != null || selectedTile != null) {\n\t\t\tselectedEntity = null;\n\t\t\tselectedTile = null;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (c.equals(corner1)) { //Remove corner1\n\t\t\tcorner1 = corner2;\n\t\t\tcorner2 = null;\n\t\t}\n\t\telse if (c.equals(corner2)) //Remove corner2\n\t\t\tcorner2 = null;\n\t\telse if (corner1 == null)\n\t\t\tcorner1 = c;\n\t\telse if (corner2 == null)\n\t\t\tcorner2 = c;\n\t\telse \n\t\t\tcorner1 = corner2 = null;\n\t}\n\n\tpublic boolean isEntitySelection() {\n\t\treturn selectedEntity != null;\n\t}\n\t\n\tpublic boolean isTileSelection() {\n\t\treturn selectedTile != null;\n\t}\n\t\n\tpublic boolean isRegionSelection() {\n\t\treturn corner1 != null;\n\t}\n\n\tpublic boolean isEmpty() {\n\t\treturn corner1 == null && selectedEntity == null && selectedTile == null;\n\t}\n\t\n\tpublic int getDimension() {\n\t\treturn dimension;\n\t}\n\t\n\tpublic void reset(int dimension) {\n\t\tthis.dimension = dimension;\n\t\tselectedEntity = null;\n\t\tselectedTile = null;\n\t\tcorner1 = corner2 = null;\n\t}\n\n\t/**\n\t * @return A pooled AABB. Do not cache.\n\t */\n\tpublic AxisAlignedBB getAABB() {\n\t\tif (corner2 == null)\n\t\t\treturn AxisAlignedBB.getAABBPool().getAABB(corner1.x, corner1.y, corner1.z, corner1.x + 1, corner1.y + 1, corner1.z + 1);\n\t\tint minX = getMin(corner1.x, corner2.x);\n\t\tint minY = getMin(corner1.y, corner2.y);\n\t\tint minZ = getMin(corner1.z, corner2.z);\n\t\tint maxX = getMax(corner1.x+1, corner2.x+1);\n\t\tint maxY = getMax(corner1.y+1, corner2.y+1);\n\t\tint maxZ = getMax(corner1.z+1, corner2.z+1);\n\t\treturn AxisAlignedBB.getAABBPool().getAABB(minX, minY, minZ, maxX, maxY, maxZ);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Entity> getEntitiesWithinAABB(EntityPlayer player) {\n\t\treturn (List<Entity>) player.worldObj.getEntitiesWithinAABBExcludingEntity(player, getAABB(), Utils.NO_PLAYERS);\n\t}\n\t\n\tpublic List<TileEntity> getTilesWithinAABB(EntityPlayer player) {\n\t\treturn Utils.getTilesInSelectionAABB(player.worldObj, getAABB());\n\t}\n\n\tpublic Entity getSelectedEntity() {\n\t\treturn selectedEntity;\n\t}\n\t\n\tpublic TileEntity getSelectedTile() {\n\t\treturn selectedTile;\n\t}\n\n\tpublic BlockCoord getCorner1() {\n\t\treturn corner1;\n\t}\n\n\tpublic BlockCoord getCorner2() {\n\t\treturn corner2;\n\t}\n\n\tprivate int getMin(int var1, int var2) {\n\t\treturn (var1 < var2) ? var1 : var2;\n\t}\n\n\tprivate int getMax(int var1, int var2) {\n\t\treturn (var1 > var2) ? var1 : var2;\n\t}\n\n\tpublic boolean isInvalid() {\n\t\treturn (selectedTile != null && selectedTile.isInvalid()) || (selectedEntity != null && selectedEntity.isDead);\n\t}\n\t\n}", "public abstract class ScriptPacket extends AbstractPacket {\n\n\tpublic static final String PACKET_ID = \"scripting\";\n\n\tpublic enum PacketType {\n\n\t\tSELECTION(SelectionPacket.class),\n\t\tHAS_SCRIPTS(HasScriptsPacket.class),\n\t\tSTATE(StatePacket.class),\n\t\tSETTINGS(SettingsPacket.class),\n\t\tENTITY_NBT(EntityNBTPacket.class),\n\t\tTILE_NBT(TileNBTPacket.class),\n\t\tCLOSE_GUI(CloseGUIPacket.class),\n\t\tREQUEST(RequestPacket.class);\n\n\t\tprivate Class<? extends ScriptPacket> packetType;\n\n\t\tprivate PacketType(Class<? extends ScriptPacket> cls) {\n\t\t\tthis.packetType = cls;\n\t\t}\n\n\t\tprivate ScriptPacket make() {\n\t\t\ttry {\n\t\t\t\treturn packetType.newInstance();\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\n\t\tpublic static int ordinalForClass(Class<? extends ScriptPacket> cls) throws IllegalArgumentException {\n\t\t\tPacketType[] values = PacketType.values();\n\t\t\tfor (int i = 0; i < values.length; ++i)\n\t\t\t\tif (values[i].packetType == cls)\n\t\t\t\t\treturn i;\n\t\t\tthrow new IllegalArgumentException(\"Unknown class \" + cls);\n\t\t}\n\t}\n\n\tpublic abstract ScriptPacket readData(Object... data);\n\n\t//Packet creation\n\tpublic static ScriptPacket getRequestPacket(PacketType type) {\n\t\treturn getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal()));\n\t}\n\n\tpublic static ScriptPacket getRequestPacket(PacketType type, String data) {\n\t\treturn getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal()), data);\n\t}\n\n\tpublic static ScriptPacket getPacket(PacketType type, Object... data) {\n\t\treturn type.make().readData(data);\n\t}\n\n\t//Helper methods for the PacketPipeline\n\tpublic static ScriptPacket readPacket(ChannelHandlerContext ctx, ByteBuf payload) throws IOException {\n\t\tint type = UnsignedBytes.toInt(payload.readByte());\n\t\tPacketType pType = PacketType.values()[type];\n\t\tScriptPacket packet = pType.make();\n\t\tpacket.decodeFrom(ctx, payload.slice());\n\t\treturn packet;\n\t}\n\n\tpublic static void writePacket(ScriptPacket pkt, ChannelHandlerContext ctx, ByteBuf to) throws IOException {\n\t\tto.writeByte(UnsignedBytes.checkedCast(PacketType.ordinalForClass(pkt.getClass())));\n\t\tpkt.encodeInto(ctx, to);\n\t}\n\n\n\t//String ByteBuf utility methods\n\tpublic static void writeString(String str, ByteBuf buffer) {\n\t\tByteBufUtils.writeUTF8String(buffer, str);\n\t}\n\n\tpublic static String readString(ByteBuf buffer) {\n\t\treturn ByteBufUtils.readUTF8String(buffer);\n\t}\n\n\tpublic static void writeStringArray(String[] arr, ByteBuf to) {\n\t\tto.writeInt(arr.length);\n\t\tfor (String s : arr)\n\t\t\twriteString(s, to);\n\t}\n\t\n\tpublic static String[] readStringArray(ByteBuf from) {\n\t\tString[] arr = new String[from.readInt()];\n\t\tfor (int i = 0; i < arr.length; ++i)\n\t\t\tarr[i] = readString(from);\n\t\treturn arr;\n\t}\n\t\n\t\n\t//Data(In/Out)put utility methods\n\tpublic static void writeNBT(NBTTagCompound compound, DataOutput out) throws IOException {\n\t\tCompressedStreamTools.write(compound, out);\n\t}\n\t\n\tpublic static NBTTagCompound readNBT(DataInput in) throws IOException {\n\t\treturn CompressedStreamTools.read(in);\n\t}\n\t\n\tpublic static void writeItemStack(ItemStack stack, DataOutput out) throws IOException {\n\t\twriteNBT(stack.writeToNBT(new NBTTagCompound()), out);\n\t}\n\t\n\tpublic static ItemStack readItemStack(DataInput in) throws IOException {\n\t\treturn ItemStack.loadItemStackFromNBT(readNBT(in));\n\t}\n\t\n\tpublic static void writeStringArray(String[] arr, DataOutput out) throws IOException {\n\t\tout.writeInt(arr.length);\n\t\tfor (String s : arr)\n\t\t\tout.writeUTF(s);\n\t}\n\t\n\tpublic static String[] readStringArray(DataInput in) throws IOException {\n\t\tString[] arr = new String[in.readInt()];\n\t\tfor (int i = 0; i < arr.length; ++i)\n\t\t\tarr[i] = in.readUTF();\n\t\treturn arr;\n\t}\n}", "public enum PacketType {\n\n\tSELECTION(SelectionPacket.class),\n\tHAS_SCRIPTS(HasScriptsPacket.class),\n\tSTATE(StatePacket.class),\n\tSETTINGS(SettingsPacket.class),\n\tENTITY_NBT(EntityNBTPacket.class),\n\tTILE_NBT(TileNBTPacket.class),\n\tCLOSE_GUI(CloseGUIPacket.class),\n\tREQUEST(RequestPacket.class);\n\n\tprivate Class<? extends ScriptPacket> packetType;\n\n\tprivate PacketType(Class<? extends ScriptPacket> cls) {\n\t\tthis.packetType = cls;\n\t}\n\n\tprivate ScriptPacket make() {\n\t\ttry {\n\t\t\treturn packetType.newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static int ordinalForClass(Class<? extends ScriptPacket> cls) throws IllegalArgumentException {\n\t\tPacketType[] values = PacketType.values();\n\t\tfor (int i = 0; i < values.length; ++i)\n\t\t\tif (values[i].packetType == cls)\n\t\t\t\treturn i;\n\t\tthrow new IllegalArgumentException(\"Unknown class \" + cls);\n\t}\n}", "public final class BlockCoord {\n\t\n\tpublic int x, y, z;\n\t\n\tpublic BlockCoord(int x, int y, int z) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\t\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\t\tif (! (obj instanceof BlockCoord))\n\t\t\treturn false;\n\t\tBlockCoord coord = (BlockCoord)obj;\n\t\treturn this.x == coord.x && this.y == coord.y && this.z == coord.z;\n\t}\n\t\n\tpublic AxisAlignedBB getAABB() {\n\t\treturn AxisAlignedBB.getAABBPool().getAABB(x, y, z, x+1, y+1, z+1);\n\t}\n\t\n\tpublic String toString() {\n\t\treturn \"{\" + x + ',' + y + ',' + z + '}';\n\t}\n}" ]
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import scripting.ScriptingMod; import scripting.Selection; import scripting.packet.ScriptPacket; import scripting.packet.ScriptPacket.PacketType; import scripting.utils.BlockCoord;
package scripting.items; public class SelectorItem extends SItem { public SelectorItem() { super(); bFull3D = true; maxStackSize = 1; setCreativeTab(CreativeTabs.tabMisc); setUnlocalizedName("selector"); } public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10){ if (player instanceof EntityPlayerMP) { Selection sel = ScriptingMod.instance.getSelection((EntityPlayerMP)player); TileEntity te = world.getTileEntity(x, y, z); if (te != null) sel.setTileEntity(te); else sel.addBlockCoord(new BlockCoord(x, y, z));
ScriptingMod.DISPATCHER.sendTo(ScriptPacket.getPacket(PacketType.SELECTION, sel), (EntityPlayerMP)player);
3
arjanfrans/mario-game
core/src/nl/arjanfrans/mario/actions/MarioActions.java
[ "public class Flag extends Actor {\n\tprivate Animation animation;\n\tprivate float stateTime;\n\tprivate float endX;\n\tprivate float endY;\n\tprivate boolean down = false;\n\tprivate float bottomY;\n\tprivate float slideOffset = 2;\n\t\n\tpublic Flag(float x, float y, float width, float height, float endX, float endY) {\n\t\tanimation = Tiles.getAnimation(0.15f, \"evil_flag\");\n\t\tanimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);\n\t\tthis.setOrigin(width / 2, height);\n\t\tthis.setBounds(x + (8 * World.scale), y, 2 * World.scale, height);\n\t\tthis.setTouchable(Touchable.disabled);\n\t\tthis.endX = endX;\n\t\tthis.endY = endY;\n\t\tthis.bottomY = y - (height - slideOffset);\n\t}\n\t\n\t@Override\n\tpublic void act(float delta) {\n\t\tstateTime += delta;\n\t\tsuper.act(delta);\n\t}\n\t\n\tpublic void takeDown() {\n\t\tthis.addAction(Actions.sequence(\n\t\t\t\tActions.delay(0.2f),\n\t\t\t\tActions.moveBy(0, -(this.getHeight() - slideOffset), 2f))\n\t\t\t);\n\t}\n\n\t\n\n\t@Override\n\tpublic void draw(Batch batch, float parentAlpha) {\n\t\tbatch.draw(animation.getKeyFrame(stateTime), this.getX() - (1 * World.scale), this.getY() + (this.getHeight() - slideOffset), \n\t\t\t\tanimation.getKeyFrame(stateTime).getRegionWidth() * World.scale, animation.getKeyFrame(stateTime).getRegionHeight() * World.scale);\n\t}\n\t\n\tpublic Rectangle rect() {\n\t\treturn new Rectangle(this.getX(), this.getY(), this.getWidth(), this.getHeight());\n\t}\n\n\tpublic float getEndX() {\n\t\treturn endX;\n\t}\n\n\tpublic float getEndY() {\n\t\treturn endY;\n\t}\n\n\tpublic boolean isDown() {\n\t\treturn Math.round(this.getY()) == bottomY;\n\t}\n\n\tpublic void setDown(boolean down) {\n\t\tthis.down = down;\n\t}\n\t\n\t\n\n\n}", "public class Mario extends Creature {\n\tprotected MarioAnimation gfx = new MarioAnimation();\n\tprivate float jump_boost = 40f, width, height;\n\tprivate boolean immume;\n\tprotected Rectangle rect = new Rectangle();\n\tprivate boolean controlsEnabled = true;\n\t\n\tpublic Mario(World world, float positionX, float positionY) {\n\t\tsuper(world, positionX, positionY, 8f);\n\t\timmume = false;\n\t\tmoving = true;\n\t\tlevel = 1;\n\t\tupdateSize();\n\t}\n\n\tprotected void updateSize() {\n\t\tthis.setSize(gfx.getDimensions(state, level).x, gfx.getDimensions(state, level).y);\n\t}\n\n\tprivate void hitByEnemy() {\t\n\t\tif(!immume) level--;\n\t\tif(level < 1 && !immume) {\n\t\t\tstate = State.Dying;\n\t\t\tvelocity.set(0, 0);\n\t\t\tthis.setWidth(gfx.getDimensions(state, level).x);\n\t\t\tthis.setHeight(gfx.getDimensions(state, level).y);\n\t\t\tthis.addAction(Actions.sequence(Actions.moveBy(0, 1, 0.2f, Interpolation.linear),\n\t\t\t\t\tActions.delay(0.6f),\n\t\t\t\t\tActions.moveBy(0, -10, 0.6f, Interpolation.linear),\n\t\t\t\t\tActions.delay(1.6f),\n\t\t\t\t\tMoveableActions.DieAction(this)));\n\t\t\tAudio.stopSong();\n\t\t\tAudio.playSong(\"lifelost\", false);\n\t\t}\n\t\telse {\n\t\t\tif(!immume) Audio.powerDown.play();\n\t\t\timmume = true;\n\t\t\tthis.addAction(Actions.sequence(Actions.parallel(Actions.alpha(0f, 2f, Interpolation.linear),\n\t\t\t\t\tActions.fadeIn(0.4f, Interpolation.linear),\n\t\t\t\t\tActions.fadeOut(0.4f, Interpolation.linear),\n\t\t\t\t\tActions.fadeIn(0.4f, Interpolation.linear),\n\t\t\t\t\tActions.fadeOut(0.4f, Interpolation.linear),\n\t\t\t\t\tActions.fadeIn(0.4f, Interpolation.linear)),\n\t\t\t\t\tActions.alpha(1f),\n\t\t\t\t\tMarioActions.stopImmumeAction(this)));\n\t\t}\n\t}\n\t\n\n\t/**\n\t * \n\t * @param flag Flag object.\n\t * @param endX X-position of ending point.\n\t * @param endY Y-position of ending point.\n\t */\n\tpublic void captureFlag(Flag flag, float endX, float endY) {\n\t\tRectangle flagRect = flag.rect();\n\t\tstate = State.FlagSlide;\n\t\t//TODO Flip mario sprite in sliding pose when at bottom\n\t\tthis.addAction(Actions.sequence(\n\t\t\t\tActions.delay(0.2f),\n\t\t\t\tActions.parallel(\n\t\t\t\t\t\tActions.moveTo(this.getX(), flagRect.y, 0.5f, Interpolation.linear), \n\t\t\t\t\t\tMarioActions.flagTakeDownAction(flag)),\n\t\t\t\tMarioActions.setStateAction(this, State.Walking),\n\t\t\t\tMarioActions.walkToAction(this, endX, endY),\n\t\t\t\tMarioActions.setStateAction(this, State.Pose),\n\t\t\t\tMarioActions.finishLevelAction())\n\t\t\t);\n\t\tAudio.stopSong();\n\t\tAudio.flag.play();\n\t}\n\n\tprotected void dieByFalling() {\n\t\tif(this.getY() < -3f) {\n\t\t\t//TODO create some kind of sensor for dying\n\t\t\tstate = State.Dying;\n\t\t\tvelocity.set(0, 0);\n\t\t\tthis.addAction(Actions.sequence(Actions.delay(3f),\n\t\t\t\t\tMoveableActions.DieAction(this)));\n\t\t\tAudio.stopSong();\n\t\t\tAudio.playSong(\"lifelost\", false);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void act(float delta) {\n\t\tsuper.act(delta);\n\t\tif(state != State.Dying) {\n\t\t\tif(state != State.FlagSlide) {\n\t\t\t\tif(controlsEnabled) {\n\t\t\t\t\tif ((Gdx.input.isKeyPressed(Keys.SPACE) || isTouched(0.75f, 1)) && grounded) {\n\t\t\t\t\t\tjump();\n\t\t\t\t\t}\n\t\t\t\t\tif (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A) || isTouched(0, 0.25f)) {\n\t\t\t\t\t\tmove(Direction.LEFT);\n\t\t\t\t\t}\n\t\t\t\t\tif (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D) || isTouched(0.25f, 0.5f)) {\n\t\t\t\t\t\tmove(Direction.RIGHT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\twidth = gfx.getFrameWidth(level, width);\n\t\t\t\theight = gfx.getFrameHeight(level, height);\n\t\t\t\trect.set(this.getX(), this.getY(), width, height);\n\t\t\t\t\n\t\t\t\tcollisionWithEnemy();\n\t\t\t\tcollisionWithMushroom();\n if(state != State.Dying) applyPhysics(rect);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\n\n\t@Override\n\tpublic void draw(Batch batch, float parentAlpha) {\n\t\tTextureRegion frame = gfx.getAnimation(state, level).getKeyFrame(stateTime);\n\t\tupdateSize();\n\t\tColor oldColor = batch.getColor();\n\t\tbatch.setColor(this.getColor());\n\t\tif(state == State.Dying) {\n\t\t\tbatch.draw(frame, getX(), getY(), \n\t\t\t\t\tgetX()+this.getWidth()/2, getY() + this.getHeight()/2,\n\t\t\t\t\tthis.getWidth(), this.getHeight(), getScaleX(), getScaleY(), getRotation());\n\t\t}\n\t\telse {\n\t\t\tif(facesRight) {\n\t\t\t\tbatch.draw(frame, this.getX(), this.getY(), \n\t\t\t\t\t\tthis.getX()+this.getWidth()/2, this.getY() + this.getHeight()/2,\n\t\t\t\t\t\tthis.getWidth(), this.getHeight(), getScaleX(), getScaleY(), getRotation());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbatch.draw(frame, this.getX() + this.getWidth(), this.getY(), \n\t\t\t\t\t\tthis.getX()+this.getWidth()/2, this.getY() + this.getHeight()/2,\n\t\t\t\t\t\t-this.getWidth(), this.getHeight(), getScaleX(), getScaleY(), getRotation());\n\t\t\t}\n\t\t}\n\t\tbatch.setColor(oldColor);\n\t}\n\n\n\n\n\tprivate boolean isTouched(float startX, float endX)\n\t{\n\t\t// check if any finge is touch the area between startX and endX\n\t\t// startX/endX are given between 0 (left edge of the screen) and 1 (right edge of the screen)\n\t\tfor (int i = 0; i < 2; i++)\n\t\t{\n\t\t\tfloat x = Gdx.input.getX() / (float) Gdx.graphics.getWidth();\n\t\t\tif (Gdx.input.isTouched(i) && (x >= startX && x <= endX))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Jump\n\t */\n\tprivate void jump() {\n\t\tif(grounded) {\n\t\t\tvelocity.y += jump_velocity;\n\t\t\tstate = MovingActor.State.Jumping;\n\t\t\tgrounded = false;\n\t\t\tAudio.jump.play();\n\t\t}\t\n\t}\n\n\t@Override\n\tprotected void collisionXAction() {\n\t\tvelocity.x = 0;\n\t}\n\n\n\t/**\n\t * Check for collision with an enemy.\n\t */\n\tprotected void collisionWithEnemy() {\n\t\tArray<Goomba> goombas = world.getEnemies();\n\t\tRectangle marioRect = rectangle();\n\t\tmarioRect.set(this.getX(), this.getY(), this.getWidth(), this.getHeight());\n\t\tfor(Goomba goomba : goombas) {\n\t\t\tRectangle eRect = goomba.rectangle();\n\n\t\t\tif(eRect.overlaps(marioRect) && goomba.state != State.Dying) {\n\t\t\t\tif(velocity.y < 0 && this.getY() > goomba.getY()) {\n\t\t\t\t\tgoomba.deadByTrample(); //enemies dies mario stamped on his head\n\t\t\t\t\tAudio.stomp.play();\n\t\t\t\t\tvelocity.y += jump_boost;\n\t\t\t\t\tgrounded = false;\n\t\t\t\t}\n\t\t\t\telse if(goomba.state != State.Dying){\n\t\t\t\t\thitByEnemy(); //mario dies because he came in from aside or below\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfloat maxheight;\n\t@Override\n\tprotected void applyPhysics(Rectangle rect) {\n\t\tfloat deltaTime = Gdx.graphics.getDeltaTime();\n\t\tif (deltaTime == 0) return;\n\t\tstateTime += deltaTime;\n\t\t\n\t\tvelocity.add(0, World.GRAVITY * deltaTime); // apply gravity if we are falling\n\n\t\tif (Math.abs(velocity.x) < 1) {\t// clamp the velocity to 0 if it's < 1, and set the state to standing\n\t\t\tvelocity.x = 0;\n\t\t\tif (grounded && controlsEnabled) {\n\t\t\t\tstate = State.Standing;\n\t\t\t}\n\t\t}\n\n\t\tvelocity.scl(deltaTime); // multiply by delta time so we know how far we go in this frame\n\n\t\tif(collisionX(rect)) collisionXAction();\n\t\trect.x = this.getX();\n\t\tcollisionY(rect);\n\t\t\n\n\t\tthis.setPosition(this.getX() + velocity.x, this.getY() +velocity.y); \n\t\tvelocity.scl(1 / deltaTime); // unscale the velocity by the inverse delta time and set the latest position\n\t\t\n\t\tvelocity.x *= damping; // Apply damping to the velocity on the x-axis so we don't walk infinitely once a key was pressed\n\t\t\n\t\tdieByFalling();\n\t}\n\n\t/**\n\t * Upgrade mario to level 2.\n\t * @param mushroom\n\t */\n\tprivate void big_mario(Mushroom mushroom) {\n\t\tlevel = 2;\n\t\tWorld.objectsToRemove.add(mushroom);\n\t\tAudio.powerUp.play();\n\t}\n\n\t/**\n\t * Check for collision with a mushroom/powerup\n\t */\n\tprotected void collisionWithMushroom() {\n\t\t//TODO Make it more generic, for all powerups and not just mushrooms\n\t\tArray<Mushroom> mushrooms = world.getMushrooms();\n\t\tRectangle marioRect = rectangle();\n\t\tmarioRect.set(this.getX(), this.getY(), this.getWidth(), this.getHeight());\n\t\tfor(Mushroom mushroom : mushrooms) {\n\t\t\tRectangle eRect = mushroom.rectangle();\n\t\t\tif(mushroom.isVisible() && eRect.overlaps(marioRect) && mushroom.state != State.Dying) {\n\t\t\t\tif(level == 1) big_mario(mushroom);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic Animation getAnimation() {\n\t\treturn gfx.getAnimation(state, level);\n\t}\n\n\n\tpublic void dispose() {\n\t\tgfx.dispose();\n\t}\n\n\tpublic void setImmume(boolean immume) {\n\t\tthis.immume = immume;\n\t}\n\t\n\t@Override\n\tpublic void move(Direction dir) {\n\t\tif(state != State.Dying && moving) {\n\t\t\tif(dir == Direction.LEFT) {\n\t\t\t\tvelocity.x = -max_velocity;\n\t\t\t\tfacesRight = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvelocity.x = max_velocity;\n\t\t\t\tfacesRight = true;\n\t\t\t}\n\t\t\tdirection = dir;\n\t\t\tif (grounded) {\n\t\t\t\tstate = MovingActor.State.Walking;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isControlsEnabled() {\n\t\treturn controlsEnabled;\n\t}\n\n\tpublic void setControlsEnabled(boolean controlsEnabled) {\n\t\tthis.controlsEnabled = controlsEnabled;\n\t}\n\n\n\n\n\n}", "public abstract class MovingActor extends Actor {\n\t//TODO Some states are for Mario only, they don't belong in this class.\n\tpublic static enum State {\n\t\t\n\t\tStanding, Walking, Jumping, Dying, Dead, FlagSlide, NoControl, Pose\n\t}\n\tpublic static enum Direction {\n\t\tLEFT, RIGHT;\n\t}\n\tprotected Pool<Rectangle> rectPool = new Pool<Rectangle>()\n\t{\n\t\t@Override\n\t\tprotected Rectangle newObject()\n\t\t{\n\t\t\treturn new Rectangle();\n\t\t}\n\t};\n\tprotected float max_velocity;\n\tprotected float jump_velocity = 40f;\n\tprotected float damping = 0.87f;\n\tprotected Vector2 position;\n\tprotected Vector2 velocity;\n\tprotected World world;\n\tprotected boolean dead;\n\tprotected boolean moving;\n\tprotected State state = State.Standing;\n\tprotected float stateTime = 0;\n\tprotected int level;\n\tprotected boolean facesRight = true;\n\tprotected Direction direction;\n\t\n\tprotected boolean grounded = false;\n\t\n\tpublic MovingActor(World world, float x, float y, float max_velocity) {\n\t\tthis.world = world;\n\t\tthis.setPosition(x, y);\n\t\tthis.max_velocity = max_velocity;\n\t\tvelocity = new Vector2(0, 0);\n\t\tdead = false;\n\t\tmoving = false;\n\t\tthis.setTouchable(Touchable.disabled);\n\t}\n\n\n\n\tpublic boolean isDead() {\n\t\treturn dead;\n\t}\n\t\n\tpublic void setDead(boolean dead) {\n\t\tthis.dead = dead;\n\t\tworld.removeActor(this);\n\t}\n\t\n\t\n\tprotected Rectangle rectangle() {\n\t\treturn new Rectangle(this.getX(), this.getY(), this.getWidth(), this.getHeight());\n\t}\n\t\n\n\tprotected void applyPhysics(Rectangle rect) {\n\t\tfloat deltaTime = Gdx.graphics.getDeltaTime();\n\t\tif (deltaTime == 0) return;\n\t\tstateTime += deltaTime;\n\t\t\n\t\tvelocity.add(0, World.GRAVITY * deltaTime); // apply gravity if we are falling\n\n\t\tif (Math.abs(velocity.x) < 1) {\t// clamp the velocity to 0 if it's < 1, and set the state to standing\n\t\t\tvelocity.x = 0;\n\t\t\tif (grounded) {\n\t\t\t\tstate = State.Standing;\n\t\t\t}\n\t\t}\n\n\t\tvelocity.scl(deltaTime); // multiply by delta time so we know how far we go in this frame\n\n\t\tif(collisionX(rect)) collisionXAction();\n\t\trect.x = this.getX();\n\t\tcollisionY(rect);\n\n\t\tthis.setPosition(this.getX() + velocity.x, this.getY() + velocity.y); // unscale the velocity by the inverse delta time and set the latest position\n\t\tvelocity.scl(1 / deltaTime);\n\t\tvelocity.x *= damping; // Apply damping to the velocity on the x-axis so we don't walk infinitely once a key was pressed\n\t\t\n\t\tdieByFalling();\n\t}\n\t\n\tprotected abstract void dieByFalling();\n\t\n\tprotected abstract void collisionXAction();\n\t\n\n\tprotected boolean collisionX(Rectangle rect) {\n\t\tint[] bounds = checkTiles(true);\n\t\tArray<Rectangle> tiles = world.getTiles(bounds[0], bounds[1], bounds[2], bounds[3]);\n\t\trect.x += velocity.x;\n\t\tfor (Rectangle tile : tiles) {\n\t\t\tif (rect.overlaps(tile)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfor(StaticActor a : world.getStaticActors()) {\n\t\t\tif(rect.overlaps(a.rectangle()) && !a.isDestroyed()) {\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 * Check from where to where to check. Method is used to help finding tiles\n\t * if the koala is moving right, check the tiles to the right of it's\n\t * right bounding box edge, otherwise check the ones to the left\n\t * if the koala is moving upwards, check the tiles to the top of it's\n\t * top bounding box edge, otherwise check the ones to the bottom\n\t * @param checkx Check x if true or if false check y\n\t * @return startX, startY, endX, enY\n\t */\n\t\n\tprotected int[] checkTiles(boolean checkX) {\n\t\tint startX, startY, endX, endY;\n\t\tif(checkX) {\n\t\t\tif (velocity.x > 0) {\n\t\t\t\tstartX = endX = (int) (this.getX() + this.getWidth() + velocity.x);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstartX = endX = (int) (this.getX() + velocity.x);\n\t\t\t}\n\t\t\tstartY = (int) (this.getY());\n\t\t\tendY = (int) (this.getY() + this.getHeight());\n\t\t}\n\t\telse {\n\t\t\tif (velocity.y > 0) {\n\t\t\t\tstartY = endY = (int) (this.getY() + this.getHeight() + velocity.y); //\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstartY = endY = (int) (this.getY() + velocity.y);\n\t\t\t}\n\t\t\tstartX = (int) (this.getX());\n\t\t\tendX = (int) (this.getX() + this.getWidth());\n\t\t}\n\t\treturn new int[]{startX, startY, endX, endY};\n\t}\n\t\n\tprotected void collisionY(Rectangle rect) {\n\t\tint[] bounds = checkTiles(false);\n\t\tArray<Rectangle> tiles = world.getTiles(bounds[0], bounds[1], bounds[2], bounds[3]);\n\t\trect.y += velocity.y;\n\t\tif(velocity.y < 0 ) {\t//dont allow jumping when falling/walking off an edge\n\t\t\tgrounded = false;\n\t\t}\n\t\tfor (Rectangle tile : tiles) {\n\t\t\tif (rect.overlaps(tile)) {\n\t\t\t\tif (velocity.y > 0) {\n\t\t\t\t\tthis.setY(tile.y - this.getHeight()); //so it is just below/above the tile we collided with\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.setY(tile.y + tile.height);\n\t\t\t\t\thitGround();\n\t\t\t\t}\n\t\t\t\tvelocity.y = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(StaticActor a : world.getStaticActors()) {\n\t\t\tif(rect.overlaps(a.rectangle()) && !a.isDestroyed()) {\n\t\t\t\tif (velocity.y > 0) {\n\t\t\t\t\ta.hit(level);\n\t\t\t\t\tthis.setY(a.getOriginY() - this.getHeight());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.setY(a.getY() + a.getHeight());\n\t\t\t\t\thitGround();\n\t\t\t\t}\n\t\t\t\tvelocity.y = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\trectPool.free(rect);\n\t}\n\n\tpublic void move(Direction dir) {\n\t\tif(state != State.Dying && moving) {\n\t\t\tif(dir == Direction.LEFT) {\n\t\t\t\tvelocity.x = -max_velocity;\n\t\t\t\tfacesRight = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvelocity.x = max_velocity;\n\t\t\t\tfacesRight = true;\n\t\t\t}\n\t\t\tdirection = dir;\n\t\t\tif (grounded) {\n\t\t\t\tstate = MovingActor.State.Walking;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void hitGround() {\n\t\tgrounded = true;\n\t}\n\t\n\tpublic float getMax_velocity() {\n\t\treturn max_velocity;\n\t}\n\t\n\tpublic float getJump_velocity() {\n\t\treturn jump_velocity;\n\t}\n\t\n\tpublic float getDamping() {\n\t\treturn damping;\n\t}\n\n\tpublic float getStateTime() {\n\t\treturn stateTime;\n\t}\n\n\tpublic boolean isFacesRight() {\n\t\treturn facesRight;\n\t}\n\t\n\tpublic Vector2 getVelocity() {\n\t\treturn velocity;\n\t}\n\t\n\tpublic boolean isMoving() {\n\t\treturn moving;\n\t}\n\n\tpublic void setMoving(boolean moving) {\n\t\tthis.moving = moving;\n\t}\n\n\t\n\tpublic State getState() {\n\t\treturn state;\n\t}\n\n\tpublic void setState(State state) {\n\t\tthis.state = state;\n\t}\n\t\n\n}", "public static enum Direction {\n\tLEFT, RIGHT;\n}", "public static enum State {\n\t\t\n\tStanding, Walking, Jumping, Dying, Dead, FlagSlide, NoControl, Pose\n}", "public class World {\n\tprivate Mario player;\n\tprivate TiledMap map;\n\tpublic static final float GRAVITY = -150;\n\tpublic static final float scale = 1/16f;\n\tprivate Array<Goomba> goombas;\n\tprivate Array<Mushroom> mushrooms;\n\tprivate Pool<Rectangle> rectPool = new Pool<Rectangle>()\n\t{\n\t\t@Override\n\t\tprotected Rectangle newObject()\n\t\t{\n\t\t\treturn new Rectangle();\n\t\t}\n\t};\n\tprivate static Tiles tiles = new Tiles();\n\tprivate Stage stage;\n\tprivate WorldRenderer wr;\n\t\n\t// If true the world will reset\n\tpublic static boolean reset_flag = false;\n\t\n\tprivate boolean playing_finish_song = false;\n\t\n\t/**\n\t * The flag at the end of the level.\n\t */\n\tprivate Flag flag;\n\t\n\tpublic static Array<Actor> objectsToRemove = new Array<Actor>();\n\t\n\tpublic World() {\n\t\treset();\n\t}\n\t\n\tprivate boolean level_ended = false;\n\t\n\t\n\tprivate Array<Goomba> generateEnemies() {\n\t\tArray<Goomba> goombas = new Array<Goomba>();\n\t\tMapLayer layer = map.getLayers().get(\"objects\");\n\t\tMapObjects objects = layer.getObjects();\n\t\tIterator<MapObject> objectIt = objects.iterator();\n\t\twhile(objectIt.hasNext()) {\n\t\t\tMapObject obj = objectIt.next();\n\t\t\tString type = (String) obj.getProperties().get(\"type\");\n\t\t\tif(type != null) {\n\t\t\t\tfloat x = (Float) obj.getProperties().get(\"x\");\n\t\t\t\tfloat y = (Float) obj.getProperties().get(\"y\");\n\t\t\t\tif(type.equals(\"goomba\")) {\n\t\t\t\t\tGoomba goomba = new Goomba(this, x * (1/16f), y* (1/16f));\n\t\t\t\t\tgoombas.add(goomba);\n\t\t\t\t\tstage.addActor(goomba);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn goombas;\n\t}\n\t\n\tpublic void removeActor(Actor a) {\n\t\tstage.getActors().removeValue(a, true);\n\t}\n\t\n\tprivate void reset() {\n\t\treset_flag = false;\n\t\tmap = new TmxMapLoader().load(\"data/level1.tmx\");\n\n\t\tanimateTiles((TiledMapTileLayer) map.getLayers().get(\"walls_background\"));\n\t\tinitTileset((TiledMapTileLayer) map.getLayers().get(\"walls_background\"));\n\t\tanimateTiles((TiledMapTileLayer) map.getLayers().get(\"walls\"));\n\t\tinitTileset((TiledMapTileLayer) map.getLayers().get(\"walls\"));\n\t\t\n\t\t\n\t\t//Read the object named 'mario' from the tmx map. Read the starting position.\n\t\tMapObject mario = map.getLayers().get(\"objects\").getObjects().get(\"mario\");\n\t\tint marioX = (int) ((Float) mario.getProperties().get(\"x\") * World.scale);\n\t\tint marioY = (int) ((Float) mario.getProperties().get(\"y\") * World.scale);\n\t\tplayer = new Mario(this, marioX, marioY);\n\t\t\n\t\tstage = new Stage();\n\t\tgoombas = generateEnemies();\n\t\tmushrooms = new Array<Mushroom>();\n\t\tgenerateBricks((TiledMapTileLayer) map.getLayers().get(\"walls\"));\n\t\t\n\t\tgenerateFlag((MapLayer) map.getLayers().get(\"objects\"));\n\t\t\n\t\tstage.addActor(player);\n\t\tString song = (String) map.getLayers().get(\"background\").getObjects().get(\"background_image\").getProperties().get(\"audio\");\n\t\tAudio.stopSong();\n\t\tAudio.playSong(song, true);\n\t\twr = new WorldRenderer(this);\n\t\twr.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\t}\n\t\n\tpublic void update() {\n\t\t//Check if the level has ended\n\t\tendLevel();\n\t\t\n\t\tRectangle screen = rectPool.obtain();\n\t\tscreen.set(wr.getCamera().position.x - wr.getCamera().viewportWidth/2, \n\t\t\t\twr.getCamera().position.y-wr.getCamera().viewportHeight/2,\n\t\t\t\twr.getCamera().viewportWidth, wr.getCamera().viewportHeight);\n\t\tfor(Goomba e : goombas) {\n\t\t\tif(screen.overlaps(e.rectangle())) {\n\t\t\t\te.setMoving(true);\n\t\t\t}\n\t\t\tif(e.isDead()) {\n\t\t\t\tgoombas.removeValue(e, true);\n\t\t\t\tstage.getActors().removeValue(e, true);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(Actor a : objectsToRemove) {\n\t\t\tstage.getActors().removeValue(a, true);\n\t\t\tobjectsToRemove.removeValue(a, true);\n\t\t}\n\t\t\n\t\trectPool.free(screen);\n\t\tstage.act(Gdx.graphics.getDeltaTime());\n\t\tif(player.isDead()) reset();\n\t\t\n\t\twr.render();\n\t}\n\t\n\t/**\n\t * Setup the flag at the end of the level\n\t * @param layer Tmx map layer with the object named 'flag';\n\t */\n\tprivate void generateFlag(MapLayer layer) {\n\t\tMapObject obj = layer.getObjects().get(\"flag\");\n\t\tfloat x = (Float) obj.getProperties().get(\"x\") * World.scale;\n\t\tfloat y = (Float) obj.getProperties().get(\"y\") * World.scale;\n\t\tfloat width = Float.valueOf((String) obj.getProperties().get(\"width\"));\n\t\tfloat height = Float.valueOf((String) obj.getProperties().get(\"height\"));\n\t\t\n\t\t// The object in the map named 'flag_end' determines the position Mario walks to after the flag\n\t\tMapObject flag_end = layer.getObjects().get(\"flag_end\");\n\t\tfloat flag_end_x = (Float) flag_end.getProperties().get(\"x\") * World.scale;\t\n\t\tfloat flag_end_y = (Float) flag_end.getProperties().get(\"y\") * World.scale;\t\n\t\t\n\t\tflag = new Flag(x, y, width, height, flag_end_x, flag_end_y);\n\t\tstage.addActor(flag);\n\t}\n\t\n\t/**\n\t * Turn all bricks into actors.\n\t * @param layer\n\t */\n\tprivate void generateBricks(TiledMapTileLayer layer) {\n\t\tfor (int x = 1; x < layer.getWidth(); x++) {\n\t\t\tfor (int y = 1; y < layer.getHeight(); y++) {\n\t\t\t\tCell cell = layer.getCell(x, y);\n\t\t\t\tif(cell != null) {\n\t\t\t\t\tTiledMapTile oldTile = cell.getTile();\n\t\t\t\t\tif(oldTile.getProperties().containsKey(\"actor\")) {\n\t\t\t\t\t\tString type = (String) oldTile.getProperties().get(\"actor\");\n\t\t\t\t\t\tStaticActor actor = null;\n\t\t\t\t\t\tif(type.equals(\"Brick\") || type.equals(\"Bonus\")) {\n\t\t\t\t\t\t\t//TODO add other colored bricks\n\t\t\t\t\t\t\tString color = (String) oldTile.getProperties().get(\"color\");\n\t\t\t\t\t\t\tboolean destructable = false;\n\t\t\t\t\t\t\tif(oldTile.getProperties().containsKey(\"destructable\")) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tString destr = (String) oldTile.getProperties().get(\"destructable\");\n\t\t\t\t\t\t\t\tdestructable = destr.equals(\"true\") ? true : false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tactor = new Brick(this, x, y, color, type.equals(\"Bonus\"), destructable);\n\t\t\t\t\t\t\titemsInBrick((Brick) actor, x, y);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlayer.setCell(x, y, null);\n\t\t\t\t\t\tstage.addActor(actor);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Check if there are items in a brick, if there are they are added to the brick.\n\t * @param brick\n\t * @param x\n\t * @param y\n\t */\n\tprivate void itemsInBrick(Brick brick, int x, int y) {\n\t\tMapLayer layer = map.getLayers().get(\"hidden_items\");\n\t\tMapObjects objects = layer.getObjects();\n\t\tfor(MapObject obj : objects) {\n\t\t\t\n\t\t\tint obj_x = (int) ((Float) obj.getProperties().get(\"x\") * (1/16f));\n\t\t\tint obj_y = (int) ((Float) obj.getProperties().get(\"y\") * (1/16f));\n\t\t\tif(obj_x == x && obj_y == y) {\n\t\t\t\tString type = (String) obj.getProperties().get(\"type\");\n\t\t\t\tActor item = null;\n\t\t\t\tif(type.equals(\"super_mushroom\")) {\n\t\t\t\t\titem = new Super(this, x, y, 4f);\n\t\t\t\t\tmushrooms.add((Mushroom) item);\n\t\t\t\t}\n\t\t\t\tstage.addActor(item);\t\t\t\t\n\t\t\t\tbrick.addItem(item);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * @return All StaticActor classes. Bricks for example.\n\t */\n\tpublic Array<StaticActor> getStaticActors() {\n\t\tArray<StaticActor> staticActors = new Array<StaticActor>();\n\t\tfor(Actor a : stage.getActors()) {\n\t\t\tif(a instanceof StaticActor) {\n\t\t\t\tstaticActors.add((StaticActor) a);\n\t\t\t}\n\t\t}\n\t\treturn staticActors;\n\t}\n\t\n\t/**\n\t * Make the tiles containing 'animation' key animated.\n\t * @param layer\n\t */\n\tprivate void animateTiles(TiledMapTileLayer layer) {\n\t\tfor (int x = 1; x < layer.getWidth(); x++) {\n\t\t\tfor (int y = 1; y < layer.getHeight(); y++) {\n\t\t\t\tCell cell = layer.getCell(x, y);\n\t\t\t\tif(cell != null) {\n\t\t\t\t\tTiledMapTile oldTile = cell.getTile();\n\t\t\t\t\tif(oldTile.getProperties().containsKey(\"animation\")) {\n\t\t\t\t\t\tString animation = (String) oldTile.getProperties().get(\"animation\");\n\t\t\t\t\t\tfloat speed = 0.15f;\n\t\t\t\t\t\tif(oldTile.getProperties().containsKey(\"speed\")) {\n\t\t\t\t\t\t\tspeed = Float.parseFloat((String) oldTile.getProperties().get(\"speed\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tAnimatedTiledMapTile newTile = new AnimatedTiledMapTile(speed, \n\t\t\t\t\t\t\t\tTiles.getAnimatedTile(animation));\n\t\t\t\t\t\tnewTile.getProperties().putAll(oldTile.getProperties());\n\t\t\t\t\t\tcell.setTile(newTile);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\tprivate void endLevel() {\n\t\tif(!level_ended && player.rect.overlaps(flag.rect())) {\n\t\t\tplayer.captureFlag(flag, flag.getEndX(), flag.getEndY());\n\t\t\tlevel_ended = true;\n\t\t}\n\t\telse if(reset_flag) {\n\t\t\tif(!Audio.currentSong.equals(\"finish\")) Audio.stopSong();\n\t\t\tif(!playing_finish_song && !Audio.getSong().isPlaying()) {\n\t\t\t\tAudio.playSong(\"finish\", false);\n\t\t\t\tplaying_finish_song = true;\n\t\t\t}\n\t\t\t// If song stops playing, reset the level\n\t\t\tif(!Audio.getSong().isPlaying()) this.reset();\n\t\t}\n\t}\n\t\n\tpublic WorldRenderer getRenderer() {\n\t\treturn wr;\n\t}\n\t\n\tpublic Mario getPlayer() {\n\t\treturn player;\n\t}\n\t\n\tpublic TiledMap getMap() {\n\t\treturn map;\n\t}\n\t\n\tpublic Array<Goomba> getEnemies() {\n\t\tArray<Actor> actors = stage.getActors();\n\t\tArray<Goomba> enemies = new Array<Goomba>();\n\t\tfor(Actor a : actors) {\n\t\t\tif(a instanceof Goomba) {\n\t\t\t\tenemies.add((Goomba) a);\n\t\t\t}\n\t\t}\n\t\treturn enemies;\n\t}\n\t\n\tpublic Array<Mushroom> getMushrooms() {\n\t\tArray<Actor> actors = stage.getActors();\n\t\tArray<Mushroom> mushrooms = new Array<Mushroom>();\n\t\tfor(Actor a : actors) {\n\t\t\tif(a instanceof Mushroom) {\n\t\t\t\tmushrooms.add((Mushroom) a);\n\t\t\t}\n\t\t}\n\t\treturn mushrooms;\n\t}\n\t\n\t/**\n\t * Tiles that have a 'texture' property will be using an optimized tileset. This is to avoid screen tearing.\n\t * @param layer\n\t */\n\tprivate void initTileset(TiledMapTileLayer layer) {\n\t\tArrayMap<String, TextureRegion> textureArr = new ArrayMap<String, TextureRegion>();\n\t\tfor(int x = 0; x < layer.getWidth(); x++) {\n\t\t\tfor(int y = 0; y < layer.getHeight(); y++) {\n\t\t\t\tCell cell = layer.getCell(x, y);\n\t\t\t\tif(cell != null) {\n\t\t\t\t\tTiledMapTile oldTile = cell.getTile();\n\t\t\t\t\t\n\t\t\t\t\tif(oldTile.getProperties().containsKey(\"texture\")) {\n\t\t\t\t\t\t//D.o(\"Initializing textures\");\n\t\t\t\t\t\tString texture = (String) oldTile.getProperties().get(\"texture\");\n\t\t\t\t\t\tif(textureArr.containsKey(texture)) {\n\t\t\t\t\t\t\toldTile.getTextureRegion().setRegion(textureArr.get(texture));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tTextureRegion t = Tiles.getTile(texture);\n\t\t\t\t\t\t\ttextureArr.put(texture, t);\n\t\t\t\t\t\t\toldTile.getTextureRegion().setRegion(t);\n\t\t\t\t\t\t}\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}\n\t\n\t\n\t\n\tpublic Array<Rectangle> getTiles(int startX, int startY, int endX, int endY)\n\t{\n\t\tArray<Rectangle> tiles = new Array<Rectangle>();\n\t\tTiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(\"walls\");\n\t\trectPool.freeAll(tiles);\n\t\ttiles.clear();\n\t\tfor (int y = startY; y <= endY; y++)\n\t\t{\n\t\t\tfor (int x = startX; x <= endX; x++)\n\t\t\t{\n\t\t\t\tCell cell = layer.getCell(x, y);\n\t\t\t\tif (cell != null)\n\t\t\t\t{\n\t\t\t\t\tRectangle rect = rectPool.obtain();\n\t\t\t\t\trect.set(x, y, 1, 1);\n\t\t\t\t\ttiles.add(rect);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn tiles;\n\t}\n\t\n\t\n\t\n\tpublic void dispose() {\n\t\tmap.dispose();\n\t\ttiles.dispose();\n\t\tplayer.dispose();\n\t\tfor(Goomba g : getEnemies()) {\n\t\t\tg.dispose();\n\t\t}\n\t\tfor(Mushroom m : getMushrooms()) {\n\t\t\tm.dispose();\n\t\t}\n\t\twr.dispose();\n\t\tAudio.dispose();\n\t\t\n\t}\n\n\n\n\tpublic Stage getStage() {\n\t\treturn stage;\n\t}\n\n}" ]
import nl.arjanfrans.mario.model.Flag; import nl.arjanfrans.mario.model.Mario; import nl.arjanfrans.mario.model.MovingActor; import nl.arjanfrans.mario.model.MovingActor.Direction; import nl.arjanfrans.mario.model.MovingActor.State; import nl.arjanfrans.mario.model.World; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.actions.Actions;
package nl.arjanfrans.mario.actions; public class MarioActions extends Actions { public static Action stopImmumeAction(Mario actor) { return new stopImmume(actor); } static public class stopImmume extends Action { public stopImmume(Mario actor) { this.actor = actor; } public boolean act(float delta) { ((Mario) actor).setImmume(false); return true; } } public static Action bigMarioAction(Mario actor) { return new bigMario(actor); } static public class bigMario extends Action { public bigMario(Mario actor) { this.actor = actor; } public boolean act(float delta) { ((Mario) actor).setImmume(false); return true; } } public static Action flagTakeDownAction(Flag flag) { return new flagTakeDown(flag); } static public class flagTakeDown extends Action { private Flag flag; public flagTakeDown(Flag flag) { this.flag = flag; flag.takeDown(); } public boolean act(float delta) { return flag.isDown(); } } /** * Set the World reset_flag to true * @return */ public static Action finishLevelAction() { return new finishLevel(); } static public class finishLevel extends Action { public boolean act(float delta) { World.reset_flag = true; return true; } }
public static Action setStateAction(Mario actor, State state) {
4
Ahmed-Abdelmeged/ADAS
app/src/main/java/com/example/mego/adas/videos/ui/VideosFragments.java
[ "public final class Constants {\n\n /**\n * Key for get teh video item bundle extra\n */\n public static final String KEY_ITEM_VIDEO = \"item_video\";\n\n /**\n * key for get the accident id key bundle extra\n */\n public static final String ACCIDENT_ID_KEY = \"accident_id\";\n\n /**\n * Google Client API Key\n */\n public static final String API_KEY = \"AIzaSyBKyxvJIHYfhjsvINFgF3fwvCiViQ5Ie7c\";\n\n /**\n * directions Constants that get from the html instructions\n * to determine the photo that will show in the list\n * and send the car direction vay bluetooth\n */\n public static final String DIRECTION_TURN_RIGHT = \"Turn right\";\n public static final String DIRECTION_TURN_LEFT = \"Turn left\";\n public static final String DIRECTION_HEAD = \"Head\";\n public static final String DIRECTION_SLIGHT_RIGHT = \"Slight right\";\n public static final String DIRECTION_SLIGHT_LEFT = \"Slight right\";\n public static final String DIRECTION_KEEP_LEFT = \"Keep left\";\n public static final String DIRECTION_KEEP_RIGHT = \"Keep right\";\n public static final String DIRECTION_MAKE_U_TURN = \"Make a U-turn\";\n public static final String DIRECTION_MERGE = \"Merge\";\n public static final String DIRECTION_ROUNDABOUT = \"roundabout\";\n public static final String DIRECTION_SHARP_RIGHT = \"Sharp right\";\n public static final String DIRECTION_SHARP_LEFT = \"Sharp left\";\n\n /**\n * Firebase database reference Constants for the directions\n */\n public static final String FIREBASE_DIRECTIONS = \"directions\";\n\n public static final String FIREBASE_START_LOCATION = \"startLocation\";\n public static final String FIREBASE_GOING_LOCATION = \"goingLocation\";\n public static final String FIREBASE_CURRENT_LOCATION = \"currentLocation\";\n\n public static final String FIREBASE_LEG_DISTANCE_TEXT = \"legDistance\";\n public static final String FIREBASE_LEG_DURATION_TEXT = \"legDuration\";\n\n public static final String FIREBASE_LEG_OVERVIEW_POLYLINE = \"legOverViewPolyline\";\n\n public static final String FIREBASE_STEPS = \"steps\";\n\n /**\n * Firebase database reference Constants for the videos\n */\n public static final String FIREBASE_LIVE_STREAMING_VIDEO_ID = \"liveStreamingVideoID\";\n\n\n /**\n * Constants to determine if there is a current streaming or not\n */\n public static final String LIVE_STREAMING_NO_LIVE_VIDEO = \"no live video\";\n\n /**\n * Firebase database reference Constants for the car\n */\n public static final String FIREBASE_CAR = \"car\";\n\n public static final String FIREBASE_CONNECTION_STATE = \"connectionState\";\n public static final String FIREBASE_ACCIDENT_STATE = \"accidentState\";\n public static final String FIREBASE_START_STATE = \"startState\";\n public static final String FIREBASE_LOCK_STATE = \"lockState\";\n public static final String FIREBASE_LIGHTS_STATE = \"lightsState\";\n\n public static final String FIREBASE_MAPPING_SERVICES = \"mappingServices\";\n\n public static final String FIREBASE_ACCIDENTS = \"accidents\";\n\n public static final String FIREBASE_SENSORES_VALUES = \"sensorsValues\";\n\n public static final String FIREBASE_USERS = \"users\";\n public static final String FIREBASE_USER_INFO = \"userInfo\";\n\n public static final String FIREBASE_USER_PLAYLIST_ID = \"playlistId\";\n\n\n /**\n * Facebook Uri for the team\n */\n public static final String FACEBOOK_URI_AHMED_ABD_ELMEGED = \"https://www.facebook.com/ven.rto\";\n public static final String FACEBOOK_URI_HUSSAM_MOSTAFA = \"https://www.facebook.com/hussam.mostafa.1994\";\n public static final String FACEBOOK_URI_DOAA_ELSHAZLY = \"https://www.facebook.com/doaa.elshazly.12\";\n\n\n /**\n * Constants for no live video\n */\n public static final String NO_LIVE_VIDEO = \"no live video\";\n\n /**\n * Constants for verify phone number\n */\n public static final String FIREBASE_IS_VERIFIED_PHONE = \"phoneVerified\";\n public static final String FIREBASE_USER_PHONE = \"phoneNumber\";\n\n /**\n * Constants for firebase storage user photo\n */\n public static final String FIREBASE_USER_IMAGE = \"userImage\";\n\n /**\n * Constants for update current user\n */\n public static final String FIREBASE_USER_LOCATION = \"location\";\n public static final String FIREBASE_USER_NAME = \"fullName\";\n\n /**\n * Constants for user device token to use it for FCM\n */\n public static final String FIREBASE_DEVICE_TOKEN = \"devicePushToken\";\n\n /**\n * Key for get the phone number extra when sign up\n */\n public static final String VERIFY_NUMBER_INTENT_EXTRA_KEY = \"verify_number_intent_extra\";\n\n /**\n * Keys for get the JSON objects form FCM\n */\n public static final String FCM_LONGITUDE = \"longitude\";\n public static final String FCM_LATITIDE = \"latitude\";\n public static final String FCM_TITLE = \"title\";\n public static final String FCM_SOUND = \"sound\";\n public static final String FCM_STATE = \"state\";\n\n /**\n * Keys for get the longitude and latitude for the accident fcm notification\n */\n public static final String FCM_LONGITUDE_EXTRA = \"fcm_longitude_extra\";\n public static final String FCM_LATITUDE_EXTRA = \"fcm_latitude_extra\";\n\n}", "public class YouTubeApiClient {\n\n /**\n * Base URl for google youtube api\n */\n private static final String BASE_URL = \"https://www.googleapis.com/youtube/\";\n\n private static Retrofit retrofit = null;\n\n /**\n * Method to get a instance of retrofit\n *\n * @return retrofit instance\n */\n public static Retrofit getYoutubeApiClient() {\n if (retrofit == null) {\n retrofit = new Retrofit.Builder().baseUrl(BASE_URL)\n .addConverterFactory(GsonConverterFactory.create()).build();\n }\n return retrofit;\n }\n}", "public interface YouTubeApiInterface {\n @GET(\"v3/playlistItems?part=snippet&maxResults=10&key=AIzaSyBKyxvJIHYfhjsvINFgF3fwvCiViQ5Ie7c\")\n Call<YouTubeVideo> getVideos(\n @Query(\"playlistId\") String playlistId\n );\n\n @GET(\"v3/playlistItems?part=snippet&maxResults=10&key=AIzaSyBKyxvJIHYfhjsvINFgF3fwvCiViQ5Ie7c\")\n Call<YouTubeVideo> getMoreVideos(\n @Query(\"playlistId\") String playlistId,\n @Query(\"pageToken\") String nextPageToken\n );\n}", "public final class YouTubeApiUtilities {\n\n /**\n * Method used to get the youtube videos from the request\n *\n * @param youTubeVideo the object that returned from the request\n * @return youtube videos items\n */\n public static ArrayList<Item> getVideos(YouTubeVideo youTubeVideo) {\n ArrayList<Item> videos = new ArrayList<>();\n for (int i = 0; i < youTubeVideo.getItems().size(); i++) {\n videos = (ArrayList<Item>) youTubeVideo.getItems();\n }\n return videos;\n }\n\n /**\n * Method to get the video title\n *\n * @param item youtube video item\n * @return video title\n */\n public static String getVideoTitle(Item item) {\n return item.getSnippet().getTitle();\n }\n\n /**\n * Method to get video Publish Time\n *\n * @param item\n * @return\n */\n public static String getVideoPublishTime(Item item) {\n return item.getSnippet().getPublishedAt();\n }\n\n /**\n * Method to get youtube video medium image url\n *\n * @param item\n * @return\n */\n public static String getVideoImageUrl(Item item) {\n return item.getSnippet().getThumbnails().getMedium().getUrl();\n }\n\n /**\n * Method to get youtube video id\n *\n * @param item\n * @return\n */\n public static String getVideoId(Item item) {\n return item.getSnippet().getResourceId().getVideoId();\n }\n\n /**\n * return a DataSend object to parse it to extract the time and date\n */\n public static Date fromISO8601(String publishedDate) {\n Date date = null;\n ISO8601DateFormat dateFormat = new ISO8601DateFormat();\n try {\n date = dateFormat.parse(publishedDate);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return date;\n }\n\n /**\n * Return the formatted date string (i.e. \"Mar 3, 1984\") from a Date object.\n */\n public static String formatDate(Date dateObject) {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"LLL dd, yyyy\", Locale.ENGLISH);\n return dateFormat.format(dateObject);\n }\n\n /**\n * Return the formatted date string (i.e. \"4:30 PM\") from a Date object.\n */\n public static String formatTime(Date dateObject) {\n SimpleDateFormat timeFormat = new SimpleDateFormat(\"h:mm a\", Locale.ENGLISH);\n return timeFormat.format(dateObject);\n }\n}", "public class Item implements Serializable{\n\n @SerializedName(\"kind\")\n @Expose\n private String kind;\n @SerializedName(\"etag\")\n @Expose\n private String etag;\n @SerializedName(\"id\")\n @Expose\n private String id;\n @SerializedName(\"snippet\")\n @Expose\n private Snippet snippet;\n\n public String getKind() {\n return kind;\n }\n\n public void setKind(String kind) {\n this.kind = kind;\n }\n\n public String getEtag() {\n return etag;\n }\n\n public void setEtag(String etag) {\n this.etag = etag;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public Snippet getSnippet() {\n return snippet;\n }\n\n public void setSnippet(Snippet snippet) {\n this.snippet = snippet;\n }\n}", "public class YouTubeVideo {\n\n @SerializedName(\"kind\")\n @Expose\n private String kind;\n @SerializedName(\"etag\")\n @Expose\n private String etag;\n @SerializedName(\"nextPageToken\")\n @Expose\n private String nextPageToken;\n @SerializedName(\"prevPageToken\")\n @Expose\n private String prevPageToken;\n @SerializedName(\"pageInfo\")\n @Expose\n private PageInfo pageInfo;\n @SerializedName(\"items\")\n @Expose\n private List<Item> items = null;\n\n public String getKind() {\n return kind;\n }\n\n public void setKind(String kind) {\n this.kind = kind;\n }\n\n public String getEtag() {\n return etag;\n }\n\n public void setEtag(String etag) {\n this.etag = etag;\n }\n\n public PageInfo getPageInfo() {\n return pageInfo;\n }\n\n public void setPageInfo(PageInfo pageInfo) {\n this.pageInfo = pageInfo;\n }\n\n public List<Item> getItems() {\n return items;\n }\n\n public void setItems(List<Item> items) {\n this.items = items;\n }\n\n public String getNextPageToken() {\n return nextPageToken;\n }\n\n public void setNextPageToken(String nextPageToken) {\n this.nextPageToken = nextPageToken;\n }\n\n public String getPrevPageToken() {\n return prevPageToken;\n }\n\n public void setPrevPageToken(String prevPageToken) {\n this.prevPageToken = prevPageToken;\n }\n}", "public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {\n // The minimum amount of items to have below your current scroll position\n // before loading more.\n private int visibleThreshold = 10;\n // The current offset index of data you have loaded\n private int currentPage = 0;\n // The total number of items in the dataset after the last load\n private int previousTotalItemCount = 0;\n // True if we are still waiting for the last set of data to load.\n private boolean loading = true;\n // Sets the starting page index\n private int startingPageIndex = 0;\n\n RecyclerView.LayoutManager mLayoutManager;\n\n public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {\n this.mLayoutManager = layoutManager;\n }\n\n public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {\n this.mLayoutManager = layoutManager;\n visibleThreshold = visibleThreshold * layoutManager.getSpanCount();\n }\n\n public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {\n this.mLayoutManager = layoutManager;\n visibleThreshold = visibleThreshold * layoutManager.getSpanCount();\n }\n\n public int getLastVisibleItem(int[] lastVisibleItemPositions) {\n int maxSize = 0;\n for (int i = 0; i < lastVisibleItemPositions.length; i++) {\n if (i == 0) {\n maxSize = lastVisibleItemPositions[i];\n }\n else if (lastVisibleItemPositions[i] > maxSize) {\n maxSize = lastVisibleItemPositions[i];\n }\n }\n return maxSize;\n }\n\n // This happens many times a second during a scroll, so be wary of the code you place here.\n // We are given a few useful parameters to help us work out if we need to load some more data,\n // but first we check if we are waiting for the previous load to finish.\n @Override\n public void onScrolled(RecyclerView view, int dx, int dy) {\n int lastVisibleItemPosition = 0;\n int totalItemCount = mLayoutManager.getItemCount();\n\n if (mLayoutManager instanceof StaggeredGridLayoutManager) {\n int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);\n // get maximum element within the list\n lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);\n } else if (mLayoutManager instanceof GridLayoutManager) {\n lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();\n } else if (mLayoutManager instanceof LinearLayoutManager) {\n lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();\n }\n\n // If the total item count is zero and the previous isn't, assume the\n // list is invalidated and should be reset back to initial state\n if (totalItemCount < previousTotalItemCount) {\n this.currentPage = this.startingPageIndex;\n this.previousTotalItemCount = totalItemCount;\n if (totalItemCount == 0) {\n this.loading = true;\n }\n }\n // If it’s still loading, we check to see if the dataset count has\n // changed, if so we conclude it has finished loading and update the current page\n // number and total item count.\n if (loading && (totalItemCount > previousTotalItemCount)) {\n loading = false;\n previousTotalItemCount = totalItemCount;\n }\n\n // If it isn’t currently loading, we check to see if we have breached\n // the visibleThreshold and need to reload more data.\n // If we do need to reload some more data, we execute onLoadMore to fetch the data.\n // threshold should reflect how many total columns there are too\n if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {\n currentPage++;\n onLoadMore(currentPage, totalItemCount, view);\n loading = true;\n }\n }\n\n // Call this method whenever performing new searches\n public void resetState() {\n this.currentPage = this.startingPageIndex;\n this.previousTotalItemCount = 0;\n this.loading = true;\n }\n\n // Defines the process for actually loading more data based on page\n public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);\n}", "public class YouTubeVideosAdapter extends RecyclerView.Adapter<YouTubeVideosAdapter.VideosViewHolder> {\n private ArrayList<Item> mItems;\n\n private final YouTubeVideosAdapterOnClickHandler mClickHandler;\n\n public interface YouTubeVideosAdapterOnClickHandler {\n void onCLick(Item item);\n }\n\n public YouTubeVideosAdapter(YouTubeVideosAdapterOnClickHandler youTubeVideosAdapterOnClickHandler) {\n mClickHandler = youTubeVideosAdapterOnClickHandler;\n }\n\n @Override\n public VideosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n Context context = parent.getContext();\n int layoutIdForListItem = R.layout.youtube_video_list;\n LayoutInflater inflater = LayoutInflater.from(context);\n boolean shouldAttachToParentImmediately = false;\n\n View view = inflater.inflate(layoutIdForListItem, parent, shouldAttachToParentImmediately);\n return new VideosViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(VideosViewHolder holder, int position) {\n //get the current video object to extract DataSend from it\n Item currentVideo = mItems.get(position);\n\n //set the current video title\n String title = YouTubeApiUtilities.getVideoTitle(currentVideo);\n holder.videoTitle.setText(title);\n\n //get the publish date and convert it to date object\n Date dateObject = YouTubeApiUtilities.fromISO8601(YouTubeApiUtilities.getVideoPublishTime(currentVideo));\n\n //set the current video date\n String date = YouTubeApiUtilities.formatDate(dateObject);\n holder.videoDate.setText(date);\n\n //set the video time\n String time = YouTubeApiUtilities.formatTime(dateObject);\n holder.videoTime.setText(time);\n\n //set the video Thumbnail photo\n Glide.with(holder.videoThumbnail.getContext())\n .load(YouTubeApiUtilities.getVideoImageUrl(currentVideo))\n .into(holder.videoThumbnail);\n }\n\n\n @Override\n public int getItemCount() {\n if (mItems == null) return 0;\n return mItems.size();\n }\n\n public class VideosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n TextView videoTitle;\n TextView videoDate;\n TextView videoTime;\n ImageView videoThumbnail;\n\n VideosViewHolder(View view) {\n super(view);\n videoTitle = view.findViewById(R.id.video_title_text_view);\n videoTime = view.findViewById(R.id.video_time_text_view);\n videoThumbnail = view.findViewById(R.id.video_image_view);\n videoDate = view.findViewById(R.id.video_date_text_view);\n\n view.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n if (mItems != null) {\n int adapterPosition = getAdapterPosition();\n mClickHandler.onCLick(mItems.get(adapterPosition));\n }\n }\n }\n\n public void setVideos(ArrayList<Item> items) {\n this.mItems = items;\n notifyDataSetChanged();\n }\n\n public void addVideos(ArrayList<Item> items) {\n this.mItems.addAll(items);\n notifyDataSetChanged();\n }\n\n public void clear() {\n if (mItems != null) {\n this.mItems.clear();\n notifyDataSetChanged();\n }\n }\n}" ]
import android.arch.lifecycle.LifecycleFragment; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; 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.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.abdelmeged.ahmed.networkito.ConnectionType; import com.abdelmeged.ahmed.networkito.ConnectivityChangeListener; import com.abdelmeged.ahmed.networkito.Networkito; import com.example.mego.adas.R; import com.example.mego.adas.utils.Constants; import com.example.mego.adas.videos.api.YouTubeApiClient; import com.example.mego.adas.videos.api.YouTubeApiInterface; import com.example.mego.adas.videos.api.YouTubeApiUtilities; import com.example.mego.adas.videos.api.model.Item; import com.example.mego.adas.videos.api.model.YouTubeVideo; import com.example.mego.adas.utils.EndlessRecyclerViewScrollListener; import com.example.mego.adas.videos.adapter.YouTubeVideosAdapter; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import timber.log.Timber;
/* * Copyright (c) 2017 Ahmed-Abdelmeged * * github: https://github.com/Ahmed-Abdelmeged * email: ahmed.abdelmeged.vm@gamil.com * Facebook: https://www.facebook.com/ven.rto * Twitter: https://twitter.com/A_K_Abd_Elmeged * * 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.example.mego.adas.videos.ui; /** * A simple {@link Fragment} subclass. * <p> * to show list of videos */ public class VideosFragments extends LifecycleFragment implements YouTubeVideosAdapter.YouTubeVideosAdapterOnClickHandler, ConnectivityChangeListener { /** * UI Elements */ private ProgressBar loadingBar; private TextView emptyText; private RecyclerView videosRecycler; /** * adapter for video list view */ private YouTubeVideosAdapter youTubeVideosAdapter; private YouTubeApiInterface youTubeApiInterface; private String playlistId; private String nextPageToken = null; private LinearLayoutManager layoutManager; public VideosFragments() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_videos, container, false); initializeScreen(rootView); //For monitor internet connection states new Networkito(getContext(), this, this); //setup the adapter layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); videosRecycler.setLayoutManager(layoutManager); videosRecycler.setHasFixedSize(true); youTubeVideosAdapter = new YouTubeVideosAdapter(this); videosRecycler.setAdapter(youTubeVideosAdapter); youTubeApiInterface = YouTubeApiClient.getYoutubeApiClient() .create(YouTubeApiInterface.class); //get the current settings for the video settings SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); //extract the playlist value playlistId = sharedPreferences.getString( getString(R.string.settings_playlist_id_key), getString(R.string.settings_playlist_id_default)); // Inflate the layout for this fragment return rootView; } /** * Link the UI Element with XML */ private void initializeScreen(View view) { videosRecycler = view.findViewById(R.id.videos_recycler_view); loadingBar = view.findViewById(R.id.loading_bar); emptyText = view.findViewById(R.id.empty_text_videos); } private void fetchVideosData() { Call<YouTubeVideo> call = youTubeApiInterface.getVideos(playlistId); call.enqueue(new Callback<YouTubeVideo>() { @Override public void onResponse(Call<YouTubeVideo> call, Response<YouTubeVideo> response) { loadingBar.setVisibility(View.INVISIBLE); emptyText.setVisibility(View.INVISIBLE); youTubeVideosAdapter.clear(); emptyText.setText(getString(R.string.no_videos)); if (response.body() != null) { if (YouTubeApiUtilities.getVideos(response.body()).size() == 0) { emptyText.setVisibility(View.VISIBLE); } else { emptyText.setVisibility(View.INVISIBLE); } if (response.body().getNextPageToken() != null) { nextPageToken = response.body().getNextPageToken(); } youTubeVideosAdapter.setVideos(YouTubeApiUtilities.getVideos(response.body())); } } @Override public void onFailure(Call<YouTubeVideo> call, Throwable t) { Timber.e(t.getMessage()); loadingBar.setVisibility(View.INVISIBLE); emptyText.setVisibility(View.VISIBLE); emptyText.setText(getString(R.string.no_videos)); } }); } private void loadNextVideosPage(int page) { if (nextPageToken != null) { Call<YouTubeVideo> call = youTubeApiInterface.getMoreVideos(playlistId, nextPageToken); call.enqueue(new Callback<YouTubeVideo>() { @Override public void onResponse(Call<YouTubeVideo> call, Response<YouTubeVideo> response) { if (response.body() != null) { nextPageToken = response.body().getNextPageToken(); youTubeVideosAdapter.addVideos(YouTubeApiUtilities.getVideos(response.body())); } } @Override public void onFailure(Call<YouTubeVideo> call, Throwable t) { } }); } } private void loadAndDisplayVideos() { loadingBar.setVisibility(View.VISIBLE); emptyText.setVisibility(View.INVISIBLE); fetchVideosData();
EndlessRecyclerViewScrollListener scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
6
hanks-zyh/FlyWoo
app/src/main/java/com/zjk/wifiproject/socket/tcp/TcpClient.java
[ "public class BaseApplication extends Application {\n\n public static boolean isDebugmode = true;\n private boolean isPrintLog = true;\n\n /** 静音、震动默认开关 **/\n private static boolean isSlient = false;\n private static boolean isVIBRATE = true;\n\n /** 新消息提醒 **/\n private static int notiSoundPoolID;\n private static SoundPool notiMediaplayer;\n private static Vibrator notiVibrator;\n\n /** 缓存 **/\n private Map<String, SoftReference<Bitmap>> mAvatarCache;\n\n public static HashMap<String, FileState> sendFileStates;\n public static HashMap<String, FileState> recieveFileStates;\n\n /** 本地图像、缩略图、声音、文件存储路径 **/\n public static String IMAG_PATH;\n public static String THUMBNAIL_PATH;\n public static String VOICE_PATH;\n public static String VEDIO_PATH;\n public static String APK_PATH;\n public static String MUSIC_PATH;\n public static String FILE_PATH;\n public static String SAVE_PATH;\n public static String CAMERA_IMAGE_PATH;\n\n /** mEmoticons 表情 **/\n public static Map<String, Integer> mEmoticonsId;\n public static List<String> mEmoticons;\n public static List<String> mEmoticons_Zem;\n\n\n private static BaseApplication instance;\n\n private Bus bus;\n\n\n\n private static boolean isClient = true;\n\n /**\n * <p>\n * 获取BaseApplication实例\n * <p>\n * 单例模式,返回唯一实例\n * \n * @return instance\n */\n public static BaseApplication getInstance() {\n return instance;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n if (instance == null) {\n instance = this;\n }\n sendFileStates = new HashMap<String, FileState>();\n recieveFileStates = new HashMap<String, FileState>();\n mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();\n // ActivitiesManager.init(getApplicationContext()); // 初始化活动管理器\n // L.setLogStatus(isPrintLog); // 设置是否显示日志\n\n //初始化Fresco库\n Fresco.initialize(this);\n\n initEmoticons();\n initNotification();\n initFolder();\n\n // bus = new Bus();\n }\n\n /* public Bus getBus() {\n return bus;\n }\n\n public void setBus(Bus bus) {\n this.bus = bus;\n }*/\n\n private void initEmoticons() {\n mEmoticonsId = new HashMap<String, Integer>();\n mEmoticons = new ArrayList<String>();\n mEmoticons_Zem = new ArrayList<String>();\n\n // 预载表情\n for (int i = 1; i < 64; i++) {\n String emoticonsName = \"[zem\" + i + \"]\";\n int emoticonsId = getResources().getIdentifier(\"zem\" + i, \"drawable\", getPackageName());\n mEmoticons.add(emoticonsName);\n mEmoticons_Zem.add(emoticonsName);\n mEmoticonsId.put(emoticonsName, emoticonsId);\n }\n }\n\n private void initNotification() {\n notiMediaplayer = new SoundPool(3, AudioManager.STREAM_SYSTEM, 5);\n // notiSoundPoolID = notiMediaplayer.load(this, R.raw.crystalring, 1);\n notiVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);\n }\n\n @Override\n public void onLowMemory() {\n super.onLowMemory();\n L.e(\"BaseApplication\", \"onLowMemory\");\n }\n\n @Override\n public void onTerminate() {\n super.onTerminate();\n L.e(\"BaseApplication\", \"onTerminate\");\n }\n\n // 函数创建文件存储目录\n private void initFolder() {\n if (null == IMAG_PATH) {\n SAVE_PATH = FileUtils.getSDPath();// 获取SD卡的根目录路径,如果不存在就返回Null\n if (null == SAVE_PATH) {\n SAVE_PATH = instance.getFilesDir().toString();// 获取内置存储区目录\n }\n SAVE_PATH += File.separator + \"WifiProject\";\n IMAG_PATH = SAVE_PATH + File.separator + \"image\";\n THUMBNAIL_PATH = SAVE_PATH + File.separator + \"thumbnail\";\n VOICE_PATH = SAVE_PATH + File.separator + \"voice\";\n FILE_PATH = SAVE_PATH + File.separator + \"file\";\n VEDIO_PATH = SAVE_PATH + File.separator + \"vedio\";\n APK_PATH = SAVE_PATH + File.separator + \"apk\";\n MUSIC_PATH = SAVE_PATH + File.separator + \"music\";\n CAMERA_IMAGE_PATH = IMAG_PATH + File.separator;\n if (!FileUtils.isFileExists(IMAG_PATH))\n FileUtils.createDirFile(BaseApplication.IMAG_PATH);\n if (!FileUtils.isFileExists(THUMBNAIL_PATH))\n FileUtils.createDirFile(BaseApplication.THUMBNAIL_PATH);\n if (!FileUtils.isFileExists(VOICE_PATH))\n FileUtils.createDirFile(BaseApplication.VOICE_PATH);\n if (!FileUtils.isFileExists(VEDIO_PATH))\n FileUtils.createDirFile(BaseApplication.VEDIO_PATH);\n if (!FileUtils.isFileExists(APK_PATH))\n FileUtils.createDirFile(BaseApplication.APK_PATH);\n if (!FileUtils.isFileExists(MUSIC_PATH))\n FileUtils.createDirFile(BaseApplication.MUSIC_PATH);\n if (!FileUtils.isFileExists(FILE_PATH))\n FileUtils.createDirFile(BaseApplication.FILE_PATH);\n\n }\n }\n\n\n /* 设置声音提醒 */\n public static boolean getSoundFlag() {\n return !isSlient;\n }\n\n public static void setSoundFlag(boolean pIsSlient) {\n isSlient = pIsSlient;\n }\n\n /* 设置震动提醒 */\n public static boolean getVibrateFlag() {\n return isVIBRATE;\n }\n\n public static void setVibrateFlag(boolean pIsvibrate) {\n isVIBRATE = pIsvibrate;\n }\n\n /**\n * 新消息提醒 - 声音提醒、振动提醒\n */\n public static void playNotification() {\n if (!isSlient) {\n notiMediaplayer.play(notiSoundPoolID, 1, 1, 0, 0, 1);\n }\n if (isVIBRATE) {\n notiVibrator.vibrate(200);\n }\n\n }\n\n public boolean isClient() {\n return isClient;\n }\n public void setIsClient(boolean isClient) {\n this.isClient = isClient;\n }\n}", "public class Constant {\n\n public static final int TCP_SERVER_RECEIVE_PORT = 4447; // 主机接收端口\n public static int READ_BUFFER_SIZE = 1024*4;// 文件流缓冲大小\n}", "public class FileState {\n public long fileSize = 0;\n public long currentSize = 0;\n public int percent = 0;\n public Message.CONTENT_TYPE type = Message.CONTENT_TYPE.TEXT;\n public String filePath;\n\n public FileState() {\n }\n\n public FileState(String fileFullPath) {\n this.filePath = fileFullPath;\n }\n\n public FileState(String fileFullPath, Message.CONTENT_TYPE type) {\n this(fileFullPath);\n this.type = type;\n }\n\n public FileState(long fileSize, long currentSize, String fileName) {\n this.fileSize = fileSize;\n this.currentSize = currentSize;\n this.filePath = fileName;\n }\n\n public FileState(long fileSize, long currentSize, String fileName, Message.CONTENT_TYPE type) {\n this(fileSize, currentSize, fileName);\n this.type = type;\n }\n}", "public class Message extends Entity {\n\n private String senderIMEI;\n private String sendTime;\n private String msgContent;\n private CONTENT_TYPE contentType;\n private int percent;\n\n public int getLength() {\n return length;\n }\n\n public void setLength(int length) {\n this.length = length;\n }\n\n private int length;\n\n\n public Message(String paramSenderIMEI, String paramSendTime, String paramMsgContent,\n CONTENT_TYPE paramContentType) {\n this.senderIMEI = paramSenderIMEI;\n this.sendTime = paramSendTime;\n this.msgContent = paramMsgContent;\n this.contentType = paramContentType;\n }\n public Message(){\n\n }\n\n /** 消息内容类型 **/\n public enum CONTENT_TYPE {\n TEXT, IMAGE, FILE, VOICE, VEDIO, MUSIC,APK, type;\n }\n\n /**\n * 获取消息发送方IMEI\n *\n * @return\n */\n\n public String getSenderIMEI() {\n return senderIMEI;\n }\n\n /**\n * 设置消息发送方IMEI\n *\n * @param paramSenderIMEI\n *\n */\n public void setSenderIMEI(String paramSenderIMEI) {\n this.senderIMEI = paramSenderIMEI;\n }\n\n /**\n * 获取消息内容类型\n *\n * @return\n * @see CONTENT_TYPE\n */\n public CONTENT_TYPE getContentType() {\n return contentType;\n }\n\n /**\n * 设置消息内容类型\n *\n * @param paramContentType\n * @see CONTENT_TYPE\n */\n public void setContentType(CONTENT_TYPE paramContentType) {\n this.contentType = paramContentType;\n }\n\n /**\n * 获取消息发送时间\n *\n * @return\n */\n public String getSendTime() {\n return sendTime;\n }\n\n /**\n * 设置消息发送时间\n *\n * @param paramSendTime\n * 发送时间,格式 xx年xx月xx日 xx:xx:xx\n */\n public void setSendTime(String paramSendTime) {\n this.sendTime = paramSendTime;\n }\n\n /**\n * 获取消息内容\n *\n * @return\n */\n public String getMsgContent() {\n return msgContent;\n }\n\n /**\n * 设置消息内容\n *\n * @param paramMsgContent\n */\n public void setMsgContent(String paramMsgContent) {\n this.msgContent = paramMsgContent;\n }\n\n /**\n * 克隆对象\n *\n * @param\n */\n\n public Message clone() {\n return new Message(senderIMEI, sendTime, msgContent, contentType);\n }\n\n // @JSONField(serialize = false)\n public int getPercent() {\n return percent;\n }\n\n public void setPercent(int percent) {\n this.percent = percent;\n }\n\n}", "public class IPMSGConst {\n\tpublic static final int VERSION = 0x001;\t\t// 版本号\n\tpublic static final int PORT = 0x0979;\t\t\t// 端口号,飞鸽协议默认端口2425\n\t\n\tpublic static final int IPMSG_NOOPERATION\t\t = 0x00000000;\t//不进行任何操作\n\tpublic static final int IPMSG_BR_ENTRY\t\t\t = 0x00000001;\t//用户上线\n\tpublic static final int IPMSG_BR_EXIT\t\t \t = 0x00000002;\t//用户退出\n\tpublic static final int IPMSG_ANSENTRY\t\t\t = 0x00000003;\t//通报在线\n\tpublic static final int IPMSG_BR_ABSENCE\t\t = 0x00000004;\t//改为缺席模式\n\t\n\tpublic static final int IPMSG_BR_ISGETLIST\t\t = 0x00000010;\t//寻找有效的可以发送用户列表的成员\n\tpublic static final int IPMSG_OKGETLIST\t\t\t = 0x00000011;\t//通知用户列表已经获得\n\tpublic static final int IPMSG_GETLIST\t\t\t = 0x00000012;\t//用户列表发送请求\n\tpublic static final int IPMSG_ANSLIST\t\t\t = 0x00000013;\t//应答用户列表发送请求\n\t\n\tpublic static final int IPMSG_SENDMSG \t\t = 0x00000020;\t//发送消息\n\tpublic static final int IPMSG_RECVMSG \t\t\t = 0x00000021;\t//通报收到消息\n\tpublic static final int IPMSG_READMSG \t\t\t = 0x00000030;\t//消息打开通知\n\tpublic static final int IPMSG_DELMSG \t\t\t = 0x00000031;\t//消息丢弃通知\n\tpublic static final int IPMSG_ANSREADMSG\t\t = 0x00000032;\t//消息打开确认通知\n\t\n\tpublic static final int IPMSG_GETINFO\t\t\t = 0x00000040;\t//获得IPMSG版本信息\n\tpublic static final int IPMSG_SENDINFO\t\t\t = 0x00000041;\t//发送IPMSG版本信息\n\t\n\tpublic static final int IPMSG_GETABSENCEINFO\t = 0x00000050;\t//获得缺席信息\n\tpublic static final int IPMSG_SENDABSENCEINFO\t = 0x00000051;\t//发送缺席信息\n\n public static final int IPMSG_UPDATE_FILEPROCESS = 0x00000060; //更新文件传输进度\n public static final int IPMSG_SEND_FILE_SUCCESS = 0x00000061; //文件发送成功 \n public static final int IPMSG_GET_FILE_SUCCESS = 0x00000062; //文件接收成功\n \n\tpublic static final int IPMSG_REQUEST_IMAGE_DATA = 0x00000063; //图片发送请求\n\tpublic static final int IPMSG_CONFIRM_IMAGE_DATA = 0x00000064; //图片接收确认\n\tpublic static final int IPMSG_SEND_IMAGE_SUCCESS = 0x00000065; //图片发送成功\n\tpublic static final int IPMSG_REQUEST_VOICE_DATA = 0x00000066; //录音发送请求\n\tpublic static final int IPMSG_CONFIRM_VOICE_DATA = 0x00000067; //录音接收确认\n\tpublic static final int IPMSG_SEND_VOICE_SUCCESS = 0x00000068; //录音发送成功\n\tpublic static final int IPMSG_REQUEST_FILE_DATA = 0x00000069; //文件发送请求\n\tpublic static final int IPMSG_CONFIRM_FILE_DATA = 0x00000070; //文件接收确认\n\t\n\tpublic static final int IPMSG_GETPUBKEY\t\t\t = 0x00000072;\t//获得RSA公钥\n\tpublic static final int IPMSG_ANSPUBKEY\t\t\t = 0x00000073;\t//应答RSA公钥\n\t\n\t/* option for all command */\n\tpublic static final int IPMSG_ABSENCEOPT \t\t = 0x00000100;\t//缺席模式\n\tpublic static final int IPMSG_SERVEROPT \t\t = 0x00000200;\t//服务器(保留)\n\tpublic static final int IPMSG_DIALUPOPT \t\t = 0x00010000;\t//发送给个人\n\tpublic static final int IPMSG_FILEATTACHOPT \t = 0x00200000;\t//附加文件\n\tpublic static final int IPMSG_ENCRYPTOPT\t\t = 0x00400000;\t//加密\n\n\t//NO_代表请求 AN_代表应答\n\tpublic static final int NO_CONNECT_SUCCESS = 0x00000200;\t//连接服务器成功;\n\tpublic static final int AN_CONNECT_SUCCESS = 0x00000201; //服务器确认连接成功;\n\tpublic static final int NO_SEND_TXT = 0x00000202; //发送文本消息;\n\tpublic static final int AN_SEND_TXT = 0x00000203; //确认接收到了文本消息;\n\tpublic static final int NO_SEND_IMAGE = 0x00000204; //发送图片\n\tpublic static final int AN_SEND_IMAGE = 0x00000205; //确认接收图片\n\tpublic static final int NO_SEND_VOICE = 0x00000206; //发送语音;\n\tpublic static final int AN_SEND_VOICE = 0x00000207; //确认接收语音;\n\tpublic static final int NO_SEND_FILE = 0x00000208; //发送文件\n\tpublic static final int AN_SEND_FILE = 0x00000209; //确认接收文件\n\tpublic static final int NO_SEND_VEDIO = 0x0000020a; //发送视频\n\tpublic static final int AN_SEND_VEDIO = 0x0000020b; //确认接收发送视频\n\tpublic static final int NO_SEND_MUSIC \t\t\t = 0x0000020c; //发送音乐\n\tpublic static final int AN_SEND_MUSIC \t\t\t = 0x0000020d; //确认接受音乐\n\tpublic static final int NO_SEND_APK \t\t\t = 0x0000020e; //发送APK\n\tpublic static final int AN_SEND_APK \t\t\t = 0x0000020f; //确认接APK\n\n\t/**\n\t * Message .what\n\t */\n\tpublic static final int WHAT_FILE_SENDING = 0x00000400; //文件发送中;\n\tpublic static final int WHAT_FILE_RECEIVING = 0x00000401; //文件接收中;\n\n}", "public class L {\n public static boolean isDebug = true; // 是否需要打印bug,可以在application的onCreate函数里面初始化\n private static final String TAG = \"WifiLog\";\n\n public static String fromHere() {\n String ret = \"\";\n if (isDebug) {\n StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];\n StringBuffer toStringBuffer = new StringBuffer(\"[\").append(traceElement.getFileName())\n .append(\" | \").append(traceElement.getMethodName()).append(\" | \")\n .append(traceElement.getLineNumber()).append(\"]\");\n ret = toStringBuffer.toString();\n }\n return ret;\n }\n\n // 下面四个是默认tag的函数\n public static void i(String msg) {\n if (isDebug)\n Log.i(TAG, \"...............\" + msg);\n }\n\n public static void d(String msg) {\n if (isDebug)\n Log.d(TAG, \"...............\" + msg);\n }\n\n public static void e(String msg) {\n if (isDebug)\n Log.e(TAG, \"...............\" + msg);\n }\n\n public static void v(String msg) {\n if (isDebug)\n Log.v(TAG, \"...............\" + msg);\n }\n\n // 下面是传入自定义tag的函数\n public static void i(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void d(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void e(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void v(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n}" ]
import android.content.Context; import android.os.Handler; import com.orhanobut.logger.Logger; import com.zjk.wifiproject.BaseApplication; import com.zjk.wifiproject.entity.Constant; import com.zjk.wifiproject.entity.FileState; import com.zjk.wifiproject.entity.Message; import com.zjk.wifiproject.socket.udp.IPMSGConst; import com.zjk.wifiproject.util.L; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList;
package com.zjk.wifiproject.socket.tcp; public class TcpClient implements Runnable { private static final String TAG = "SZU_TcpClient"; private Thread mThread; private boolean IS_THREAD_STOP = false; // 是否线程开始标志 private boolean SEND_FLAG = false; // 是否发送广播标志 private static Context mContext = null; private static TcpClient instance; // private ArrayList<FileStyle> fileStyles; // private ArrayList<FileState> fileStates; private ArrayList<SendFileThread> sendFileThreads; private SendFileThread sendFileThread; private static Handler mHandler = null; private TcpClient() { sendFileThreads = new ArrayList<SendFileThread>(); mThread = new Thread(this); L.d(TAG, "建立线程成功"); } public static void setHandler(Handler paramHandler) { mHandler = paramHandler; } public Thread getThread() { return mThread; } /** * <p> * 获取TcpService实例 * <p> * 单例模式,返回唯一实例 */ public static TcpClient getInstance(Context context) { mContext = context; if (instance == null) { instance = new TcpClient(); } return instance; } /* public void sendFile(ArrayList<FileStyle> fileStyles, ArrayList<FileState> fileStates, String target_IP) { while (SEND_FLAG == true) ; for (FileStyle fileStyle : fileStyles) { SendFileThread sendFileThread = new SendFileThread(target_IP, fileStyle.fullPath); sendFileThreads.add(sendFileThread); } SEND_FLAG = true; }*/ private TcpClient(Context context) { this(); L.d(TAG, "TCP_Client初始化完毕"); } public void startSend() { L.d(TAG, "发送线程开启"); IS_THREAD_STOP = false; // 使能发送标识 if (!mThread.isAlive()) mThread.start(); } public void sendFile(String filePath, String target_IP) { SendFileThread sendFileThread = new SendFileThread(target_IP, filePath); while (SEND_FLAG == true) ; sendFileThreads.add(sendFileThread); SEND_FLAG = true; }
public void sendFile(String filePath, String target_IP, Message.CONTENT_TYPE type) {
3
lkorth/photo-paper
PhotoPaper/src/main/java/com/lukekorth/photo_paper/SearchActivity.java
[ "public class GridPhotoAdapter extends BaseAdapter {\n\n public static final String TAG = \"GridPhotoAdapter\";\n\n private Context mContext;\n private List<Photo> mPhotos;\n private Picasso mPicasso;\n private int mOneDpInPx;\n\n public GridPhotoAdapter(Context context, ArrayList<Photo> photos) {\n mContext = context;\n mPhotos = photos;\n mPicasso = PicassoHelper.getPicasso(context);\n mOneDpInPx = Utils.dpToPx(mContext, 0.5);\n }\n\n public void setPhotos(List<Photo> photos) {\n mPhotos = photos;\n }\n\n public List<Photo> getPhotos() {\n return mPhotos;\n }\n\n @Override\n public int getCount() {\n return mPhotos.size();\n }\n\n @Override\n public Photo getItem(int position) {\n return mPhotos.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n SquareImageView view = (SquareImageView) convertView;\n if (view == null) {\n view = new SquareImageView(mContext);\n view.setScaleType(CENTER_CROP);\n view.setPadding(mOneDpInPx, mOneDpInPx, mOneDpInPx, mOneDpInPx);\n }\n\n mPicasso.load(getItem(position).imageUrl)\n .placeholder(R.color.grey)\n .fit()\n .tag(TAG)\n .into(view);\n\n return view;\n }\n}", "public class Settings {\n\n private static SharedPreferences getPrefs(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n public static String getFavoriteGallery(Context context) {\n return getPrefs(context).getString(\"favorite_gallery\", null);\n }\n\n public static String getFavoriteGalleryId(Context context) {\n return getPrefs(context).getString(\"favorite_gallery_id\", null);\n }\n\n public static void setFavoriteGallery(Context context, String gallery) {\n getPrefs(context).edit().putString(\"favorite_gallery\", gallery).apply();\n }\n\n public static void setFavoriteGalleryId(Context context, String id) {\n getPrefs(context).edit().putString(\"favorite_gallery_id\", id).apply();\n }\n\n public static String getFeature(Context context) {\n return getPrefs(context).getString(\"feature\", \"popular\");\n }\n\n public static void setFeature(Context context, String feature) {\n getPrefs(context).edit().putString(\"feature\", feature).apply();\n }\n\n public static String getSearchQuery(Context context) {\n return getPrefs(context).getString(\"search_query\", \"\");\n }\n\n public static void setSearchQuery(Context context, String query) {\n getPrefs(context).edit().putString(\"search_query\", query).apply();\n }\n\n public static int[] getCategories(Context context) {\n Set<String> defaultCategory = new HashSet<String>();\n defaultCategory.add(\"8\");\n Set<String> prefCategories = getPrefs(context).getStringSet(\"categories\", defaultCategory);\n\n int[] categories = new int[prefCategories.size()];\n int i = 0;\n for (String category : prefCategories) {\n categories[i] = Integer.parseInt(category);\n i++;\n }\n\n return categories;\n }\n\n public static void setCategories(Context context, Set<String> categories) {\n getPrefs(context).edit().putStringSet(\"categories\", categories).apply();\n }\n\n public static boolean isEnabled(Context context) {\n return getPrefs(context).getBoolean(\"enable\", false);\n }\n\n public static int getUpdateInterval(Context context) {\n return Integer.parseInt(getPrefs(context).getString(\"update_interval\", \"3600\"));\n }\n\n public static void setUpdateInterval(Context context, String interval) {\n getPrefs(context).edit().putString(\"update_interval\", interval).apply();\n }\n\n public static boolean useParallax(Context context) {\n return getPrefs(context).getBoolean(\"use_parallax\", false);\n }\n\n public static boolean useOnlyWifi(Context context) {\n return getPrefs(context).getBoolean(\"use_only_wifi\", true);\n }\n\n public static long getLastUpdated(Context context) {\n return getPrefs(context).getLong(\"last_updated\", 0);\n }\n\n public static void setUpdated(Context context) {\n getPrefs(context).edit().putLong(\"last_updated\", System.currentTimeMillis()).apply();\n }\n\n public static void clearUpdated(Context context) {\n getPrefs(context).edit().putLong(\"last_updated\", 0).apply();\n }\n}", "public class Photo {\n\n @Expose public String id;\n @Expose public String name;\n @Expose public String description;\n @Expose @SerializedName(\"created_at\") public String createdAt;\n @Expose public int category;\n @Expose @SerializedName(\"votes_count\") public int votes;\n @Expose public boolean nsfw;\n @Expose @SerializedName(\"highest_rating\") public double highestRating;\n @Expose @SerializedName(\"times_viewed\") public int views;\n @Expose @SerializedName(\"image_url\") public String imageUrl;\n @Expose public String url;\n @Expose public User user;\n @Expose public boolean voted;\n @Expose public boolean favorited;\n\n}", "public class SearchResult {\n\n @Expose public List<Photo> photos;\n}", "public class PhotoDownloadIntentService extends IntentService {\n\n private Logger mLogger;\n private Realm mRealm;\n private Bus mBus;\n private int mErrorCount;\n private int mPage;\n private int mTotalPages;\n\n public PhotoDownloadIntentService() {\n super(PhotoDownloadIntentService.class.getName());\n }\n\n public static void downloadPhotos(Context context) {\n context.startService(new Intent(context, PhotoDownloadIntentService.class));\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n mLogger = LoggerFactory.getLogger(\"PhotoDownloadIntentService\");\n mBus = WallpaperApplication.getBus();\n mErrorCount = 0;\n mPage = 1;\n mTotalPages = 1;\n mRealm = Realm.getDefaultInstance();\n\n if (Utils.shouldGetPhotos(this, mRealm)) {\n mLogger.debug(\"Attempting to fetch new photos\");\n\n long startTime = System.currentTimeMillis();\n\n while (Photos.unseenPhotoCount(this, mRealm) < 100 && mPage <= mTotalPages &&\n mErrorCount < 5 && Utils.isCurrentNetworkOk(this) &&\n (System.currentTimeMillis() - startTime) < 300000) {\n getPhotos();\n }\n\n mLogger.debug(\"Done fetching photos\");\n\n cachePhotos();\n } else {\n mBus.post(new RemainingPhotosChangedEvent());\n mLogger.debug(\"Not getting photos at this time\");\n }\n\n mRealm.beginTransaction();\n mRealm.where(Photos.class)\n .equalTo(\"seen\", true)\n .lessThan(\"seenAt\", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))\n .findAll()\n .deleteAllFromRealm();\n mRealm.commitTransaction();\n\n mRealm.close();\n }\n\n private void getPhotos() {\n try {\n String feature = Settings.getFeature(this);\n String search = feature.equals(\"search\") ? Settings.getSearchQuery(this) : \"\";\n\n Call<PhotosResponse> call;\n switch (feature) {\n case \"search\":\n call = WallpaperApplication.getNonLoggedInApiClient()\n .getPhotosFromSearch(Settings.getSearchQuery(this), getCategoriesForRequest(), mPage);\n break;\n case \"user_favorites\":\n call = WallpaperApplication.getApiClient().getFavorites(User.getUser(mRealm).getId(),\n Settings.getFavoriteGalleryId(this), getCategoriesForRequest(), mPage);\n break;\n default:\n call = WallpaperApplication.getApiClient().getPhotos(feature, getCategoriesForRequest(), mPage);\n break;\n }\n\n Response<PhotosResponse> response = call.execute();\n int responseCode = response.code();\n mLogger.debug(\"Response code: \" + responseCode);\n if (responseCode != 200) {\n mErrorCount++;\n return;\n }\n\n mPage = response.body().currentPage + 1;\n mTotalPages = response.body().totalPages;\n\n for (int i = 0; i < response.body().photos.length; i++) {\n if (Photos.create(mRealm, response.body().photos[i], feature, search) != null) {\n mLogger.debug(\"Added photo\");\n mBus.post(new RemainingPhotosChangedEvent());\n }\n SystemClock.sleep(25);\n }\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n mErrorCount++;\n }\n\n SystemClock.sleep(5000);\n }\n\n private void cachePhotos() {\n mLogger.debug(\"Caching photos\");\n\n Picasso picasso = PicassoHelper.getPicasso(this);\n List<Photos> photos = Photos.getUnseenPhotos(this, mRealm);\n for (Photos photo : photos) {\n if (Utils.isCurrentNetworkOk(this)) {\n picasso.load(photo.imageUrl)\n .tag(\"PhotoCacheIntentService\")\n .fetch();\n SystemClock.sleep(50);\n } else {\n picasso.cancelTag(\"PhotoCacheIntentService\");\n break;\n }\n }\n\n mLogger.debug(\"Done caching photos\");\n }\n\n private String getCategoriesForRequest() {\n String[] allCategories = getResources().getStringArray(R.array.categories);\n int[] categories = Settings.getCategories(this);\n String filter = \"\";\n for (int category : categories) {\n filter += allCategories[category] + \",\";\n }\n\n try {\n return URLEncoder.encode(filter.substring(0, filter.length() - 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n return null;\n }\n }\n}", "public static Picasso getPicasso(Context context) {\n return new Picasso.Builder(context.getApplicationContext())\n .downloader(new OkHttp3Downloader(context.getApplicationContext(), 512000000)) // 512mb\n .indicatorsEnabled(BuildConfig.DEBUG)\n .build();\n}" ]
import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.GridView; import android.widget.SearchView; import com.lukekorth.photo_paper.adapters.GridPhotoAdapter; import com.lukekorth.photo_paper.helpers.Settings; import com.lukekorth.photo_paper.models.Photo; import com.lukekorth.photo_paper.models.SearchResult; import com.lukekorth.photo_paper.services.PhotoDownloadIntentService; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.lukekorth.photo_paper.helpers.PicassoHelper.getPicasso;
package com.lukekorth.photo_paper; public class SearchActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, AbsListView.OnScrollListener, View.OnClickListener { private static final String QUERY_KEY = "com.lukekorth.photo_paper.SearchActivity.QUERY_KEY"; private SearchView mSearchView; private GridPhotoAdapter mAdapter; private String mCurrentQuery; private Picasso mPicasso; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.grid_view); mPicasso = getPicasso(this); if (savedInstanceState != null) { mCurrentQuery = savedInstanceState.getString(QUERY_KEY); if (!TextUtils.isEmpty(mCurrentQuery)) { setTitle(mCurrentQuery); performSearch(); } } mAdapter = new GridPhotoAdapter(this, new ArrayList<Photo>()); GridView gridView = (GridView) findViewById(R.id.grid_view); gridView.setAdapter(mAdapter); gridView.setEmptyView(findViewById(R.id.no_search_results)); gridView.setOnScrollListener(this); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } WallpaperApplication.getBus().register(this); } @Override protected void onDestroy() { super.onDestroy(); WallpaperApplication.getBus().unregister(this); } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putString(QUERY_KEY, mCurrentQuery); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search, menu); mSearchView = (SearchView) menu.findItem(R.id.search).getActionView(); mSearchView.setQuery(mCurrentQuery, false); if (TextUtils.isEmpty(mCurrentQuery)) { mSearchView.setIconified(false); } mSearchView.setOnQueryTextListener(this); mSearchView.setOnSearchClickListener(this); return true; } @Override public boolean onQueryTextSubmit(String query) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(mSearchView.getWindowToken(), 0); mCurrentQuery = query; setTitle(query); // first call clears the search, second call closes search view mSearchView.setIconified(true); mSearchView.setIconified(true); performSearch(); setProgressBarIndeterminateVisibility(true); return true; } private void performSearch() { if (TextUtils.isEmpty(mCurrentQuery)) { mAdapter.setPhotos(new ArrayList<Photo>()); } WallpaperApplication.getApiClient().search(mCurrentQuery) .enqueue(new Callback<SearchResult>() { @Override public void onResponse(Call<SearchResult> call, Response<SearchResult> response) { onSearchComplete(response.body().photos); } @Override public void onFailure(Call<SearchResult> call, Throwable t) { onSearchComplete(new ArrayList<Photo>()); } }); } public void onSearchComplete(List<Photo> photos) { mAdapter.setPhotos(photos); mAdapter.notifyDataSetChanged(); setProgressBarIndeterminateVisibility(false); } @Override public void onClick(View v) { if (v == mSearchView && !TextUtils.isEmpty(mCurrentQuery)) { mSearchView.setQuery(mCurrentQuery, false); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_TOUCH_SCROLL) { mPicasso.resumeTag(GridPhotoAdapter.TAG); } else { mPicasso.pauseTag(GridPhotoAdapter.TAG); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.save_search: Settings.setFeature(this, "search"); Settings.setSearchQuery(this, mCurrentQuery);
PhotoDownloadIntentService.downloadPhotos(this);
4
MiniPa/cjs_ssms
cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/service/master/UserFrontServiceImpl.java
[ "public class UUIDUtil {\n public static String uuid(){\n UUID uuid=UUID.randomUUID();\n String str = uuid.toString();\n String uuidStr=str.replace(\"-\", \"\");\n return uuidStr;\n }\n}", "public class MD5Util {\n\n public static final String DEFAULT_SALT = \"minipa_chengjs\";\n\n /**\n * 指定加密盐\n * @param str\n * @param salt\n * @return\n */\n public static String md5(String str, String salt){\n if (StringUtil.isNullOrEmpty(salt)) {\n salt = DEFAULT_SALT;\n }\n return new Md5Hash(str,salt).toString() ;\n }\n\n /**\n * 采用默认加密盐\n * @param str\n * @return\n */\n public static String md5(String str){\n return new Md5Hash(str,DEFAULT_SALT).toString() ;\n }\n\n public static void main(String[] args) {\n String md5 = md5(\"123456\", DEFAULT_SALT) ;\n System.out.println(md5); // 119d3a4d2dfbca3d23bd1c52a1d6a6e6\n }\n\n}", "public interface UserRolePermissionDao extends Mapper<Country> {\n\n UUser findByLogin(UUser user);\n\n int findAllCount(UUser user);\n\n List<UUser> findHotUser();\n\n List<UUser> findByParams(UUser user, RowBounds rowBound);\n\n List<UUser> findAllByQuery(UUser user);\n\n List<UUser> list(Map<String, Object> map);\n\n Long getTotal(Map<String, Object> map);\n\n UUser findUserByUsername(String username);\n\n Set<String> findRoleNames(String username);\n\n Set<String> findPermissionNames(Set<String> roleNames);\n\n Set<String> findRoleNamesByUserName(@Param(\"userName\")String userName);\n\n Set<String> findPermissionNamesByRoleNames(@Param(\"set\")Set<String> roleNames);\n\n UUser findUserByUserName(@Param(\"userName\")String userName);\n\n}", "public interface UUserMapper extends Mapper<UUser> {\n\n /**\n * 测试通过POJO参数方式获取page\n * @param uuser\n * @return\n */\n List<UUser> gridUsers(UUser uuser);\n\n /**\n * 测试通过Map参数方式获取page\n * @param params\n * @return\n */\n List<Map<String,String>> users(Map<String,String> params);\n\n}", "@Table(name = \"u_user\")\npublic class UUser {\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY, generator = \"SELECT replace(t.uuid,\\\"-\\\",\\\"\\\") FROM (SELECT uuid() uuid FROM dual) t\")\n private String id;\n\n @Column(name = \"username\")\n private String username;\n\n @Column(name = \"password\")\n private String password;\n\n @Column(name = \"description\")\n private String description;\n\n @Column(name = \"discard\")\n private String discard;\n\n @Column(name = \"createtime\")\n private Date createtime;\n\n @Column(name = \"modifytime\")\n private Date modifytime;\n\n /**\n * @return id\n */\n public String getId() {\n return id;\n }\n\n /**\n * @param id\n */\n public void setId(String id) {\n this.id = id == null ? null : id.trim();\n }\n\n /**\n * @return username\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * @param username\n */\n public void setUsername(String username) {\n this.username = username == null ? null : username.trim();\n }\n\n /**\n * @return password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * @param password\n */\n public void setPassword(String password) {\n this.password = password == null ? null : password.trim();\n }\n\n /**\n * @return description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description\n */\n public void setDescription(String description) {\n this.description = description == null ? null : description.trim();\n }\n\n /**\n * @return discard\n */\n public String getDiscard() {\n return discard;\n }\n\n /**\n * @param discard\n */\n public void setDiscard(String discard) {\n this.discard = discard == null ? null : discard.trim();\n }\n\n /**\n * @return createtime\n */\n public Date getCreatetime() {\n return createtime;\n }\n\n /**\n * @param createtime\n */\n public void setCreatetime(Date createtime) {\n this.createtime = createtime;\n }\n\n /**\n * @return modifytime\n */\n public Date getModifytime() {\n return modifytime;\n }\n\n /**\n * @param modifytime\n */\n public void setModifytime(Date modifytime) {\n this.modifytime = modifytime;\n }\n}", "public class Transactioner {\n\n private static final Logger log = LoggerFactory.getLogger(Transactioner.class);\n\n private TransactionStatus status = null;\n\n private DataSourceTransactionManager transactionManager;\n\n /**\n * 初始化事务对象并开启事务\n * @param transactionManager\n */\n public Transactioner(DataSourceTransactionManager transactionManager) {\n this.transactionManager = transactionManager;\n start(transactionManager);\n }\n\n /**\n * 开启事物\n * @param transactionManager\n */\n public void start(DataSourceTransactionManager transactionManager) {\n DefaultTransactionDefinition def = new DefaultTransactionDefinition();\n /*PROPAGATION_REQUIRES_NEW: 事物隔离级别,开启新事务*/\n def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);\n status = transactionManager.getTransaction(def);\n }\n\n /**\n * 提交事务\n * @param commitOrRollback true-commit, false-rollback\n */\n public void end(boolean commitOrRollback) {\n if (null == status) {\n log.warn(\"事务未开启无法提交\");\n return;\n }\n if (commitOrRollback) {\n transactionManager.commit(status);\n } else {\n transactionManager.rollback(status);\n }\n }\n\n\n}", "public class Page<T> implements Serializable {\n private static final long serialVersionUID = 1L;\n /**\n * 每页显示的数量\n **/\n private int limit;\n /**\n * 总条数\n **/\n private int total;\n /**\n * 当前页数\n **/\n private int pageNo;\n /**\n * 存放集合\n **/\n private List<T> rows = new ArrayList<T>();\n\n public int getOffset() {\n return (pageNo - 1) * limit;\n }\n\n public void setOffset(int offset) {\n }\n\n public void setTotal(int total) {\n this.total = total;\n }\n\n public int getLimit() {\n return limit;\n }\n\n public void setLimit(int limit) {\n this.limit = limit;\n }\n\n\n public List<T> getRows() {\n return rows;\n }\n\n public void setRows(List<T> rows) {\n this.rows = rows;\n }\n\n // 计算总页数\n public int getTotalPages() {\n int totalPages;\n if (total % limit == 0) {\n totalPages = total / limit;\n } else {\n totalPages = (total / limit) + 1;\n }\n return totalPages;\n }\n\n public int getTotal() {\n return total;\n }\n\n public int getOffsets() {\n return (pageNo - 1) * limit;\n }\n\n public int getEndIndex() {\n if (getOffsets() + limit > total) {\n return total;\n } else {\n return getOffsets() + limit;\n }\n }\n\n public int getPageNo() {\n return pageNo;\n }\n\n public void setPageNo(int pageNo) {\n this.pageNo = pageNo;\n }\n}" ]
import com.chengjs.cjsssmsweb.common.util.UUIDUtil; import com.chengjs.cjsssmsweb.common.util.codec.MD5Util; import com.chengjs.cjsssmsweb.mybatis.mapper.dao.UserRolePermissionDao; import com.chengjs.cjsssmsweb.mybatis.mapper.master.UUserMapper; import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser; import com.chengjs.cjsssmsweb.util.Transactioner; import com.chengjs.cjsssmsweb.util.page.Page; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Set;
package com.chengjs.cjsssmsweb.service.master; /** * IUserServiceImpl: * author: <a href="mailto:chengjs_minipa@outlook.com">chengjs_minipa</a>, version:1.0.0, 2017/8/29 */ @Service public class UserFrontServiceImpl implements IUserFrontService{ @Autowired private DataSourceTransactionManager transactionManager; /*========================== userMapper ==========================*/ @Autowired private UUserMapper userMapper; @Override public UUser getUserById(String userid) { return userMapper.selectByPrimaryKey(userid); } @Override public int deleteByPrimaryKey(String userid) { return userMapper.deleteByPrimaryKey(userid); } @Override public int updateByPrimaryKeySelective(UUser user) { return userMapper.updateByPrimaryKeySelective(user); } @Override public int createUser(UUser user) { return userMapper.insertSelective(user); } /*========================== userDao ==========================*/ @Autowired
private UserRolePermissionDao userRolePermissionDao;
2
taichi/siden
siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java
[ "public interface Connection extends AttributeContainer {\n\n\t// endpoint methods\n\n\tCompletableFuture<Void> send(String text);\n\n\tCompletableFuture<Void> send(ByteBuffer payload);\n\n\tCompletableFuture<Void> ping(ByteBuffer payload);\n\n\tCompletableFuture<Void> pong(ByteBuffer payload);\n\n\tCompletableFuture<Void> close();\n\n\tCompletableFuture<Void> close(int code, String reason);\n\n\tvoid sendStream(ExceptionalConsumer<OutputStream, Exception> fn);\n\n\tvoid sendWriter(ExceptionalConsumer<Writer, Exception> fn);\n\n\t// informations\n\n\tString protocolVersion();\n\n\tString subProtocol();\n\n\tboolean secure();\n\n\tboolean open();\n\n\tSet<Connection> peers();\n\n\t// from request\n\n\tOptional<String> params(String key);\n\n\tMap<String, String> params();\n\n\tOptional<String> query(String key);\n\n\tOptional<String> header(String name);\n\n\tList<String> headers(String name);\n\n\tMap<String, List<String>> headers();\n\n\tMap<String, Cookie> cookies();\n\n\tOptional<Cookie> cookie(String name);\n\n\t/**\n\t * get current session\n\t * \n\t * @return session or empty\n\t */\n\tOptional<Session> current();\n\n\tWebSocketChannel raw();\n\n}", "public interface WebSocket {\n\n\tdefault void onConnect(Connection connection) throws Exception {\n\t}\n\n\tdefault void onText(String payload) throws Exception {\n\t}\n\n\tdefault void onBinary(ByteBuffer[] payload) throws Exception {\n\t}\n\n\tdefault void onPong(ByteBuffer[] payload) throws Exception {\n\t}\n\n\tdefault void onPing(ByteBuffer[] payload) throws Exception {\n\t}\n\n\tdefault void onClose(ByteBuffer[] payload) throws Exception {\n\t}\n}", "public interface WebSocketCustomizer {\n\n\tWebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);\n\n\tWebSocketCustomizer onText(\n\t\t\tExceptionalBiConsumer<Connection, String, Exception> fn);\n\n\tWebSocketCustomizer onBinary(\n\t\t\tExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);\n\n\tWebSocketCustomizer onPong(\n\t\t\tExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);\n\n\tWebSocketCustomizer onPing(\n\t\t\tExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);\n\n\tWebSocketCustomizer onClose(\n\t\t\tExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);\n}", "public interface WebSocketFactory {\n\n\tWebSocket create(Connection connection);\n}", "@FunctionalInterface\npublic interface ExceptionalBiConsumer<T, U, EX extends Exception> {\n\n\tvoid accept(T t, U u) throws EX;\n}", "@FunctionalInterface\npublic interface ExceptionalConsumer<T, EX extends Exception> {\n\n\tvoid accept(T t) throws EX;\n}" ]
import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import ninja.siden.Connection; import ninja.siden.WebSocket; import ninja.siden.WebSocketCustomizer; import ninja.siden.WebSocketFactory; import ninja.siden.util.ExceptionalBiConsumer; import ninja.siden.util.ExceptionalConsumer;
/* * Copyright 2014 SATO taichi * * 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 ninja.siden.internal; /** * @author taichi */ public class LambdaWebSocketFactory implements WebSocketFactory, WebSocketCustomizer { List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>(); List<ExceptionalBiConsumer<Connection, String, Exception>> txt = new ArrayList<>(); List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> bin = new ArrayList<>(); List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> pong = new ArrayList<>(); List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> ping = new ArrayList<>(); List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> close = new ArrayList<>(); @Override
public WebSocket create(Connection connection) {
1
Hatzen/EasyPeasyVPN
src/main/java/de/hartz/vpn/main/installation/client/ConfigOpenVPN.java
[ "public class UserData implements Serializable{\n\n private static UserData instance;\n\n private UserList userList = new UserList();\n private ArrayList<Mediator> mediatorList = new ArrayList<>();\n\n //client only.\n public static String serverIp;\n public static Integer serverPort;\n //END OF: client only.\n\n private boolean clientInstallation = true;\n private ConfigState vpnConfigState;\n\n /**\n * Returns the one and only {@link UserData} object. If one is saved it will loaded.\n * @returns the instance.\n */\n public static UserData getInstance() {\n if (instance == null && !loadUserData()) {\n instance = new UserData();\n }\n return instance;\n }\n\n /**\n * @returns a list of all active users in the vpn.\n */\n public UserList getUserList() {\n return userList;\n }\n\n public ArrayList<Mediator> getMediatorList() {\n return mediatorList;\n }\n\n /**\n * Indicates whether this configuration is server or client one.\n * @returns true if its a client installation.\n */\n public boolean isClientInstallation() {\n return clientInstallation;\n }\n\n public void setClientInstallation(boolean clientInstallation) {\n this.clientInstallation = clientInstallation;\n }\n\n /**\n * Sets the current vpn config state and saves it persistent.\n */\n public ConfigState getVpnConfigState() {\n return vpnConfigState;\n }\n\n /**\n * Sets the current vpn config state and saves it persistent.\n */\n public void setVpnConfigState(ConfigState configState) {\n vpnConfigState = configState;\n writeUserData();\n }\n\n private UserData() {\n if (mediatorList.size() == 0) {\n mediatorList.add(new Mediator(\"DEFAULT\",\"http://hartzkai.freehostia.com/thesis/\", -1, -1, true));\n }\n }\n\n /**\n * Loads an old user data object.\n * @returns true if the data was loaded successfully.\n */\n private static boolean loadUserData() {\n try {\n FileInputStream fin = new FileInputStream(USER_DATA_FILE_PATH);\n ObjectInputStream ois = new ObjectInputStream(fin);\n instance = (UserData) ois.readObject();\n return true;\n } catch (Exception e) {\n // TODO: Check for data version.\n System.out.println(\"UserData not loaded. File does not exist (?)\");\n if (new File(USER_DATA_FILE_PATH).exists())\n e.printStackTrace();\n }\n return false;\n }\n\n /**\n * Saves the current user data object persistent.\n * @returns true if the data was saved successfully.\n */\n private boolean writeUserData() {\n try {\n deleteTempData();\n File configFile = new File(USER_DATA_FILE_PATH);\n configFile.getParentFile().mkdirs();\n configFile.createNewFile();\n FileOutputStream fout = new FileOutputStream(configFile);\n ObjectOutputStream oos = new ObjectOutputStream(fout);\n oos.writeObject(instance);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n /**\n * Deletes all data that are cached but should not be persistent.\n */\n private void deleteTempData() {\n userList.clear();\n }\n}", "public class InstallationController {\n\n /**\n * Interface to notify the caller after installation.\n */\n public interface InstallationCallback {\n\n void onInstallationSuccess();\n void onInstallationCanceled();\n\n }\n\n private static InstallationController instance = new InstallationController();\n private InstallationFrame mainFrame;\n private InstallationCallback callback;\n\n private ConfigState tmpConfigState;\n private boolean clientInstallation;\n\n private static boolean hasGUI;\n\n private ArrayList<InstallationPanel> currentPanelOrder;\n private ArrayList<InstallationPanel> clientPanelOrder;\n private ArrayList<InstallationPanel> expressPanelOrder;\n private ArrayList<InstallationPanel> customPanelOrder;\n\n /**\n * Returns the singleton instance of this class\n * @return\n */\n public static InstallationController getInstance() {\n return instance;\n }\n\n /**\n * Getter to see if the user has a graphical UI.\n * @returns true if it is graphical.\n */\n public static boolean hasGUI() {\n return hasGUI;\n }\n\n /**\n * Listener that gets called when the next button was clicked.\n * @param currentPanel The current panel on which the next button was clicked.\n */\n public void onNextClick(InstallationPanel currentPanel) {\n if (currentPanel instanceof StartPanel) {\n currentPanelOrder.clear();\n if (((StartPanel) currentPanel).isExpressInstallation()) {\n currentPanelOrder.addAll(expressPanelOrder);\n } else {\n currentPanelOrder.addAll(customPanelOrder);\n }\n }\n\n showNextPanel(currentPanel);\n }\n\n /**\n * Listener that gets called when the back button was clicked.\n * @param currentPanel\n */\n public void onPreviousClick(JPanel currentPanel) {\n showPreviousPanel(currentPanel);\n }\n\n /**\n * Returns whether a panel is the first panel to show.\n * @param currentPanel The panel to check for.\n * @return\n */\n public boolean isFirst(JPanel currentPanel) {\n return currentPanelOrder.indexOf(currentPanel) == 0;\n }\n\n /**\n * Returns whether a panel is the last panel to show.\n * @param currentPanel The panel to check for.\n * @return\n */\n public boolean isLast(JPanel currentPanel) {\n return currentPanelOrder.indexOf(currentPanel) == currentPanelOrder.size()-1;\n }\n\n /**\n * Starts the installation process.\n * @param showGUI Boolean indicating whether the application is started via console.\n */\n public void startInstallation(boolean showGUI, boolean client, InstallationCallback callback) {\n tmpConfigState = new ConfigState();\n clientInstallation = client;\n hasGUI = showGUI;\n this.callback = callback;\n if (showGUI) {\n // TODO: GUI doesnt react some time. Because of extracting files etc.. Create loading screen. Also might be initalization of all the panels!!\n initGUI();\n\n if(client) {\n System.out.println(\"client installation\");\n currentPanelOrder.clear();\n currentPanelOrder.addAll(clientPanelOrder);\n } else {\n System.out.println(\"server installation\");\n currentPanelOrder.clear();\n currentPanelOrder.addAll(expressPanelOrder);\n }\n\n\n showPanel(0);\n } else {\n drawLogoWithoutGUI();\n if (client)\n new ExpressInstallationPanel().startExternalInstallation();\n }\n }\n\n /**\n * Sets the installation frames visibility. Not possible if it was started without GUI.\n * @param visible Boolean indicating whether the frame should be visible.\n */\n public void setMainFrameVisible(boolean visible) {\n if (!hasGUI)\n return;\n mainFrame.setVisible(visible);\n }\n\n /**\n * Adds a specific panel to the client panel order. After the config file has loaded, so it can decide which adapter to install.\n */\n public void addClientPanel() {\n if (getTmpConfigState().getAdapter() == ConfigState.Adapter.OpenVPN) {\n int i = 0;\n while( i < currentPanelOrder.size()) {\n if (currentPanelOrder.get(i) instanceof ConnectToServerPanel) {\n break;\n }\n i++;\n }\n currentPanelOrder.add(i+1, new ExpressInstallationPanel());\n }\n }\n\n /**\n * Can be called to force going to the next panel.\n * Can produce errors. Should only be called if there is work to be done before going to the next panel.\n */\n public void forceNextPanel(InstallationPanel currentPanel) {\n int nextIndex = currentPanelOrder.indexOf(currentPanel)+1;\n showPanel(nextIndex);\n }\n\n /**\n * Returns the temporarily {@link ConfigState} of the network. After successfull installation it will be moved\n * to {@link UserData}\n * @returns the tmpConfigState.\n */\n public ConfigState getTmpConfigState() {\n return tmpConfigState;\n }\n\n public void setTmpConfigState(ConfigState tmpConfigState) {\n this.tmpConfigState = tmpConfigState;\n }\n\n public boolean isClientInstallation() {\n return clientInstallation;\n }\n\n private void initGUI() {\n hasGUI = true;\n mainFrame = new InstallationFrame(\"installation\");\n mainFrame.setVisible(true);\n\n InstallationPanel startPanel = new StartPanel();\n\n // ClientPanels\n clientPanelOrder.add(new ConnectToServerPanel());\n clientPanelOrder.add(new FinishingPanel());\n\n // ExpressServer Panels\n expressPanelOrder.add(startPanel);\n expressPanelOrder.add(new NetworkNamePanel());\n expressPanelOrder.add(new ExpressInstallationPanel());\n expressPanelOrder.add(new FinishingPanel());\n\n // CustomServer panels\n customPanelOrder.add(startPanel);\n customPanelOrder.add(new ChoosePerformancePanel());\n customPanelOrder.add(new ChooseNetworkType());\n // Anonymisieren?\n // Encryption\n // Authentification Panel (Add user panel)\n // --> Nachirchten, Onlinestatus etc\n // Mediation server\n // How to forward ips / access router\n // \"How secure/ fast is this\" panel\n }\n\n private void showPanel(int index) {\n InstallationPanel panel = currentPanelOrder.get(index);\n panel.onSelect();\n mainFrame.setContent(panel);\n mainFrame.setNextButtonTextToFinish(false);\n mainFrame.setNextEnabled(true);\n mainFrame.setPreviousEnabled(true);\n if (isFirst(panel)) {\n mainFrame.setPreviousEnabled(false);\n }\n if (panel.isFinishingPanel()) {\n mainFrame.setNextButtonTextToFinish(true);\n } else if (isLast(panel)) {\n mainFrame.setNextEnabled(false);\n }\n }\n\n private InstallationController() {\n clientPanelOrder = new ArrayList<>();\n currentPanelOrder = new ArrayList<>();\n expressPanelOrder = new ArrayList<>();\n customPanelOrder = new ArrayList<>();\n }\n\n private void drawLogoWithoutGUI() {\n try {\n BufferedReader in = new BufferedReader(new FileReader(GeneralUtilities.getResourceAsFile(\"icon.txt\")));\n String line = in.readLine();\n while(line != null)\n {\n System.out.println(line);\n line = in.readLine();\n }\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n try {\n Thread.sleep(1500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n private void showNextPanel(InstallationPanel currentPanel) {\n if (currentPanel.isFinishingPanel()) {\n // OnFinish setup config etc.\n UserData.getInstance().setClientInstallation(clientInstallation);\n callback.onInstallationSuccess();\n UserData.getInstance().setVpnConfigState(tmpConfigState);\n mainFrame.dispose();\n }\n\n boolean panelCanBeDeselected = currentPanel.onDeselect();\n if ( !panelCanBeDeselected) {\n return;\n }\n\n if (isLast(currentPanel)) {\n // TODO: Finish installation and start program.\n return;\n }\n int nextIndex = currentPanelOrder.indexOf(currentPanel)+1;\n showPanel(nextIndex);\n }\n\n private void showPreviousPanel(JPanel currentPanel) {\n if (isFirst(currentPanel)) {\n return;\n }\n int nextIndex = currentPanelOrder.indexOf(currentPanel)-1;\n showPanel(nextIndex);\n }\n}", "public final class GeneralUtilities {\n\n private static String OS = System.getProperty(\"os.name\").toLowerCase();\n private static File TEMP_FOLDER;\n\n /**\n * @returns the platform depended file extension for the config files, to start openvpn.\n */\n public static String getOpenVPNConfigExtension() {\n if (isWindows()) {\n return Constants.OpenVpnValues.CONFIG_EXTENSION_WINDOWS.getValue();\n } else if(isLinux()) {\n return Constants.OpenVpnValues.CONFIG_EXTENSION_LINUX.getValue();\n }\n return null;\n }\n\n /**\n * Reads a whole file as a String.\n * @param path System path to the file.\n * @param encoding The encoding of the File. Should be UTF-8 in most cases.\n * @returns the String contents of the file.\n * @throws IOException\n */\n public static String readFile(String path, Charset encoding) throws IOException {\n byte[] encoded = Files.readAllBytes(Paths.get(path));\n return new String(encoded, encoding);\n }\n\n /**\n * Function to load resources like images from the jar file.\n * @param resourcePath The path to the resource starting from package de.hartz.vpn.\n * @returns a file object representing the file.\n */\n public static File getResourceAsFile(String resourcePath) {\n try {\n InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);\n if (in == null) {\n return null;\n }\n Path p = Paths.get(resourcePath);\n String fileName = p.getFileName().toString();\n File tempFile = new File(getTempDirectory(), fileName);\n tempFile.deleteOnExit();\n try (FileOutputStream out = new FileOutputStream(tempFile)) {\n byte[] buffer = new byte[1024];\n int bytesRead;\n while ((bytesRead = in.read(buffer)) != -1) {\n out.write(buffer, 0, bytesRead);\n }\n }\n return tempFile;\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Creates a temporary folder, if not created yet, and returns the path to this folder.\n * https://stackoverflow.com/questions/617414/how-to-create-a-temporary-directory-folder-in-java\n * @return Path to temporary folder.\n * @throws IOException\n */\n public static File getTempDirectory() throws IOException {\n if (GeneralUtilities.TEMP_FOLDER != null) {\n return GeneralUtilities.TEMP_FOLDER;\n }\n final File temp = File.createTempFile(\"easypeasyvpn-\", \"\");\n if(!(temp.delete()))\n {\n throw new IOException(\"Could not delete temp file: \" + temp.getAbsolutePath());\n }\n if(!(temp.mkdir()))\n {\n throw new IOException(\"Could not create temp directory: \" + temp.getAbsolutePath());\n }\n TEMP_FOLDER = temp;\n return temp;\n }\n\n // TODO: Remove if not needed.\n public static String removeExtensionFromFileString(String file) {\n return file.replaceFirst(\"[.][^.]+$\", \"\");\n }\n\n public static boolean deleteTempDirectory() {\n return GeneralUtilities.TEMP_FOLDER.delete();\n }\n\n /**\n * Checks if the program was launched with admin permissions.\n * https://stackoverflow.com/questions/4350356/detect-if-java-application-was-run-as-a-windows-admin\n * @return true if program has admin permissions.\n */\n public static boolean isAdmin(){\n Preferences preferences = Preferences.systemRoot();\n PrintStream systemErr = System.err;\n // Better synchronize to avoid problems with other threads that access System.err.\n synchronized(systemErr){\n System.setErr(null);\n try {\n // SecurityException on Windows.\n preferences.put(\"foo\", \"bar\");\n preferences.remove(\"foo\");\n\n // BackingStoreException on Linux.\n preferences.flush();\n return true;\n } catch(Exception e) {\n return false;\n } finally{\n System.setErr(systemErr);\n }\n }\n }\n\n /**\n * Function that indicates whether the system uses apt as packet manager.\n * @return\n */\n @Linux\n public static boolean hasAPT() {\n ProcessBuilder pb = new ProcessBuilder(\"whereis\", \"apt\");\n pb.redirectErrorStream(true);\n Process process = null;\n try {\n process = pb.start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());\n outputHandler.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n return (outputHandler.getOutput().toString().length() > 0);\n }\n\n /**\n * https://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/\n * @return\n */\n public static boolean isWindows() {\n return (OS.contains(\"win\"));\n }\n\n public static boolean isMac() {\n return (OS.contains(\"mac\"));\n }\n\n public static boolean isLinux() {\n return (OS.contains(\"nix\") || OS.contains(\"nux\") || OS.indexOf(\"aix\") > 0 || isMac());\n }\n}", "public final class OpenVPNUtilities {\n\n //TODO: If possible get rid off..\n // @Windows\n public static String openVPNBinPath;\n\n /**\n * TODO: TIDY UP!!!! MODULARIZE.\n * TODO: Get working under linux?! And maybe same concept to find openssl?\n * Finds the installation path of openvpn through the environment variables.\n * @return The installation path or null if not found.\n */\n public static String getOpenVPNInstallationPath() {\n if (GeneralUtilities.isWindows()) {\n String findValue = \"OpenVPN\";\n\n // After installations getenv() returns old values, missing openvpn...\n // HACK AROUND THIS;\n // https://stackoverflow.com/questions/10434065/how-to-retrieve-the-modified-value-of-an-environment-variable-which-is-modified\n ProcessBuilder pb = new ProcessBuilder( \"cmd.exe\");\n pb.redirectErrorStream(true);\n Process process = null;\n try {\n process = pb.start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());\n PrintWriter commandExecutor = new PrintWriter(process.getOutputStream());\n commandExecutor.println(\"reg query \\\"HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment\\\"\\n\");\n commandExecutor.println(\"exit\");\n commandExecutor.flush();\n commandExecutor.close();\n outputHandler.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n String pathVar = outputHandler.getOutput().toString();\n //TODO: MODULARISE..\n if (pathVar.contains(findValue)) {\n int indexOfFindValue = pathVar.indexOf(findValue);\n // if it should be bin path.. value.indexOf(\";\", indexOfFindValue)\n openVPNBinPath = pathVar.substring( pathVar.lastIndexOf(\";\" ,indexOfFindValue)+1, pathVar.indexOf(\"bin\", indexOfFindValue) + \"bin\".length() );\n String path = pathVar.substring( pathVar.lastIndexOf(\";\" ,indexOfFindValue)+1, indexOfFindValue + findValue.length() );\n if (path.charAt(path.length()-1) != File.separator.charAt(0)) {\n path += File.separator;\n }\n return path;\n }\n //END OF: HACK AROUND THIS;\n\n\n } else {\n // TODO: Files in this folder might be auto started. Wanted?\n String filePath = \"/etc/openvpn/\";\n File installationPath = new File(filePath);\n if(installationPath.exists())\n return filePath;\n else if (installationPath.mkdirs()) {\n return filePath;\n }\n System.err.println(filePath + \" cannot create directories \");\n }\n return null;\n }\n\n /**\n * Checks if OpenSSL/ OpenVPN is avaiale on command line. Needed if openvpn is fresh installed and path is not ready yet.\n * @return true if path needs an extension.\n */\n public static boolean needsPathUpdate() {\n String findValue = \"OpenVPN\";\n Map<String, String> env = System.getenv();\n for (String envName : env.keySet()) {\n String value = env.get(envName);\n if (envName.contains(findValue) || value.contains(findValue) ) {\n return false;\n }\n }\n return true;\n }\n\n}", "public class ConfigOpenVPN {\n //http://www.andysblog.de/openvpn-server-unter-windows-einrichten\n\n private static String INSTALLATION_PATH;\n\n // Default parameters.\n public static final String DEFAULT_PORT = \"1194\";\n public static final String DEFAULT_ADAPTER_NAME = \"tap\";\n\n public static final String DEFAULT_IP = \"10.0.0.0\";\n public static final String DEFAULT_SUBNETMASK = \"255.255.255.0\";\n\n public static final String DEFAULT_CIPHER = \"AES-128-CBC\";\n public static final int DEFAULT_KEY_SIZE = 512;\n\n private ConfigState configState;\n private Logger logger;\n\n public ConfigOpenVPN(ConfigState configState, Logger logger) {\n this.configState = configState;\n this.logger = logger;\n\n INSTALLATION_PATH = OpenVPNUtilities.getOpenVPNInstallationPath();\n if (GeneralUtilities.isWindows()) {\n String replaceSingleBackSlash = \"\\\\\\\\\";\n INSTALLATION_PATH = INSTALLATION_PATH.replaceAll(replaceSingleBackSlash, \"/\");\n } else if (GeneralUtilities.isLinux()) {\n // Create needed folders.\n new File(INSTALLATION_PATH + \"config/\").mkdir();\n new File(INSTALLATION_PATH + \"log/\").mkdir();\n }\n\n createUserFile();\n writeOVPNFile();\n try {\n if (GeneralUtilities.isWindows()) {\n windowsEasyRSA();\n } else if (GeneralUtilities.isLinux()) {\n linuxEasyRSA();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n if ( configState.getNetworkType() == ConfigState.NetworkType.SITE_TO_END) {\n setSiteToEndVPN();\n }\n }\n\n // TODO: Should be (most) OS Independent. replace .bat to java call or something like that.\n private void writeOVPNFile() {\n // More infos about the keys and values: http://wiki.openvpn.eu/index.php/OpenVPN-Syntax\n String content = \"\";\n\n content += \"port \" + DEFAULT_PORT; //TODO: Move to ConfigState.\n content += System.getProperty(\"line.separator\");\n content += \"proto \" + configState.getProtocol();\n content += System.getProperty(\"line.separator\");\n\n content += \"dev \" + DEFAULT_ADAPTER_NAME; // TODO: TAP for broadcasts, TUN for performance.\n content += System.getProperty(\"line.separator\");\n\n // Certificate location.\n String easyRSAPath = \"easy-rsa/keys/\";\n content += \"ca \\\"\" + INSTALLATION_PATH + easyRSAPath + \"ca.crt\\\"\";\n content += System.getProperty(\"line.separator\");\n content += \"cert \\\"\" + INSTALLATION_PATH + easyRSAPath + \"server.crt\\\"\";\n content += System.getProperty(\"line.separator\");\n content += \"key \\\"\" + INSTALLATION_PATH + easyRSAPath + \"server.key\\\"\";\n content += System.getProperty(\"line.separator\");\n\n content += \"dh \\\"\" + INSTALLATION_PATH + easyRSAPath + \"dh\" + DEFAULT_KEY_SIZE + \".pem\\\"\";\n content += System.getProperty(\"line.separator\");\n\n content += \"server \" + DEFAULT_IP + \" \" + DEFAULT_SUBNETMASK; //TODO: Move to ConfigState.\n content += System.getProperty(\"line.separator\");\n\n // Only needed when the clients should keep their ip.\n // ifconfig-pool-persist \"C:\\\\Program Files\\\\OpenVPN\\\\log\\\\ipp.txt\"\n\n // TODO: Use if its site to site network.\n /*String currentRealIp = \"192.168.2.0\"; // TODO: Get Netaddress from currently used lan.\n String currentRealNetmask = \"255.255.255.0\"; // TODO: Get Netaddress from currently used lan.\n // TODO: This might not be needed for site to site network?\n content += \"route \" + currentRealIp + \" \" + currentRealNetmask;\n content += System.getProperty(\"line.separator\");*/\n\n content += \"keepalive \" + 10 + \" \" + 120; // Needed to hold connection.\n content += System.getProperty(\"line.separator\");\n\n content += \"cipher \" + DEFAULT_CIPHER; // TODO: Move to ConfigState. And look for performance increase.\n content += System.getProperty(\"line.separator\");\n\n content += \"persist-key\";\n content += System.getProperty(\"line.separator\");\n content += \"persist-tun\";\n content += System.getProperty(\"line.separator\");\n\n // Log file.\n content += \"status \" + INSTALLATION_PATH + \"log/openvpn-status.log\";\n content += System.getProperty(\"line.separator\");\n\n // Verbose level?\n content += \"verb \" + 3;\n content += System.getProperty(\"line.separator\");\n\n\n /* TODO: Anonymes surfen..\n # If enabled, this directive will configure\n # all clients to redirect their default\n # network gateway through the VPN, causing\n # all IP traffic such as web browsing and\n # and DNS lookups to go through the VPN\n # (The OpenVPN server machine may need to NAT\n # or bridge the TUN/TAP interface to the internet\n # in order for this to work properly).\n */\n //;push \"redirect-gateway def1 bypass-dhcp\"\n\n /* TODO: Active as default. But disable if anonym vpn.\n # Uncomment this directive to allow different\n # clients to be able to \"see\" each other.\n # By default, clients will only see the server.\n # To force clients to only see the server, you\n # will also need to appropriately firewall the\n # server's TUN/TAP interface.\n */\n content += \"client-to-client\";\n content += System.getProperty(\"line.separator\");\n\n /* TODO: Very unsecure. Implemnt.\n # Uncomment this directive if multiple clients\n # might connect with the same certificate/key\n # files or common names. This is recommended\n # only for testing purposes. For production use,\n # each client should have its own certificate/key\n # pair.\n #\n # IF YOU HAVE NOT GENERATED INDIVIDUAL\n # CERTIFICATE/KEY PAIRS FOR EACH CLIENT,\n # EACH HAVING ITS OWN UNIQUE \"COMMON NAME\",\n # UNCOMMENT THIS LINE OUT.\n */\n // TODO: This doesnt work and ends with error: connection refused. Dont know why. Not needed at the moment.\n //content += \"duplicate-cn\";\n //content += System.getProperty(\"line.separator\");\n\n\n /* TODO: #1 FUTURE! Additional Secureity.\n # For extra security beyond that provided\n # by SSL/TLS, create an \"HMAC firewall\"\n # to help block DoS attacks and UDP port flooding.\n #\n # Generate with:\n # openvpn --genkey --secret ta.key\n #\n # The server and each client must have\n # a copy of this key.\n # The second parameter should be '0'\n # on the server and '1' on the clients.\n tls-auth ta.key 0 # This file is secret\n */\n\n /* TODO: #2 FUTURE! Additional performance increase?\n # Enable compression on the VPN link and push the\n # option to the client (2.4+ only, for earlier\n # versions see below)\n ;compress lz4-v2\n ;push \"compress lz4-v2\"\n # For compression compatible with older clients use comp-lzo\n # If you enable it here, you must also\n # enable it in the client config file.\n ;comp-lzo\n */\n\n\n if (configState.isNeedsAuthentication()) {\n //auth-user-pass-verify \"C:\\\\Program Files\\\\OpenVPN\\\\config\\\\auth.bat\" via-env\n //script-security 3\n } else {\n // TODO: Maybe useful for performance increase? Needs authentication parameter.\n //--client-cert-not-required\n }\n\n try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(INSTALLATION_PATH + \"config/server.ovpn\"), \"utf-8\"))) {\n writer.write(content);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void createUserFile() {\n // TODO: Implement.\n // Save password HASH. Not cleartext.\n // INSTALLATION_PATH + \"/config/users.txt\"\n /*\n username1 password1;\n username2 password2;\n */\n }\n\n @Linux\n private void linuxEasyRSA() throws IOException {\n //TODO: Cannot run .vars permission denied.. CHmod -> executable?\n // Easy rsa path was an other than in the tutorial.\n /*String[][] commands = {\n {\"cp\", \"-R\", \"/usr/share/easy-rsa/\", INSTALLATION_PATH + \"/easy-rsa\"}, // TODO: Check maybe mkdir needed.\n {\"./vars\"},\n {\"./clean-all\"},\n {\"./build-ca\", System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\")},\n {\"./build-key-server --batch server\", System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\"),System.getProperty(\"line.separator\")}\n }; //cp -R /usr/share/easy-rsa/* /etc/openvpn/easy-rsa/\n */\n String[][] commands = {\n {\"cp\", \"-R\", \"/usr/share/easy-rsa/\", INSTALLATION_PATH + \"/easy-rsa\"}, // TODO: Check maybe mkdir needed.\n {\"./vars\"},\n {\"./clean-all\"},\n {\"./build-ca\"},\n {\"./build-key-server --batch server\"}\n }; //cp -R /usr/share/easy-rsa/* /etc/openvpn/easy-rsa/\n int exitValue = 0;\n\n // TODO: Get rid off. Just needed because files first have to be copied..\n boolean temp = true;\n for (String[] command : commands) {\n System.out.println(Arrays.toString(command));\n ProcessBuilder pb = new ProcessBuilder(command);\n pb.directory(new File(INSTALLATION_PATH + \"/easy-rsa/\"));\n pb.redirectErrorStream(true);\n Process process = pb.start();\n OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());\n outputHandler.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n logger.addLogLine(outputHandler.getOutput().toString());\n exitValue = process.exitValue();\n System.out.println(\"\" + exitValue);\n System.out.println(\"---\");\n\n if(temp) {\n temp = false;\n\n String content = GeneralUtilities.readFile(INSTALLATION_PATH + \"easy-rsa/vars\", Charset.defaultCharset());\n content = replaceParameter(content, \"HOME=\", \"\\\"${0%/*}\\\"\");\n content = replaceParameter(content, \"KEY_SIZE=\", \"\" + DEFAULT_KEY_SIZE);\n\n content = replaceParameter(content, \"KEY_COUNTRY=\", \"DE\");\n content = replaceParameter(content, \"KEY_PROVINCE=\", \"NRW\");\n content = replaceParameter(content, \"KEY_CITY=\", \"MS\");\n content = replaceParameter(content, \"KEY_ORG=\", \"EasyPeasyVPN\");\n content = replaceParameter(content, \"KEY_EMAIL=\", \"dummy@email.de\");\n try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(INSTALLATION_PATH + \"easy-rsa/vars\"), \"utf-8\"))) {\n writer.write(content);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n @Windows\n private void windowsEasyRSA() throws IOException {\n // TODO: Make OS independent.\n\n // Creates vars.bat.\n try {\n logger.addLogLine(\"Execute \" + \"init-config.bat\");\n ProcessBuilder pb = new ProcessBuilder( INSTALLATION_PATH + \"easy-rsa/\" + \"init-config.bat\");\n pb.directory(new File(INSTALLATION_PATH + \"easy-rsa/\"));\n Process process = pb.start();\n OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());\n outputHandler.start();\n process.waitFor();\n logger.addLogLine(outputHandler.getOutput().toString());\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n String content = GeneralUtilities.readFile(INSTALLATION_PATH + \"easy-rsa/vars.bat\", Charset.defaultCharset());\n content = replaceParameter(content, \"HOME=\", \"%cd%\");\n content = replaceParameter(content, \"KEY_SIZE=\", \"\" + DEFAULT_KEY_SIZE);\n\n content = replaceParameter(content, \"KEY_COUNTRY=\", \"DE\");\n content = replaceParameter(content, \"KEY_PROVINCE=\", \"NRW\");\n content = replaceParameter(content, \"KEY_CITY=\", \"MS\");\n content = replaceParameter(content, \"KEY_ORG=\", \"EasyPeasyVPN\");\n content = replaceParameter(content, \"KEY_EMAIL=\", \"dummy@email.de\");\n try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(INSTALLATION_PATH + \"easy-rsa/vars.bat\"), \"utf-8\"))) {\n writer.write(content);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n runEasyRSACommands(\"clean-all.bat\", 0, 0);\n runEasyRSACommands(\"build-ca.bat\", 8, 0);\n runEasyRSACommands(\"build-dh.bat\", 0, 0);\n runEasyRSACommands(\"build-key-server.bat server\", 10, 2);\n\n // TODO: Build client scripts.\n //TODO: DO THIS ALSO WITH LINUX INSTALLATION!!!!!!!!!!!!!\n ArrayList<String> input = new ArrayList<>();\n for (int i = 0; i < 10; i++) {\n input.add(\"\" + System.getProperty(\"line.separator\"));\n }\n input.set(5, Constants.DEFAULT_CLIENT_NAME + System.getProperty(\"line.separator\"));\n input.set(6, Constants.DEFAULT_CLIENT_NAME + System.getProperty(\"line.separator\"));\n runEasyRSACommands(\"build-key.bat \" + Constants.DEFAULT_CLIENT_NAME, input, 2);\n }\n\n /**\n * Needed, to execute every command with vars.bat and to confirm some values.\n * @param command\n * @param skips Number of how often enter should be entered.\n * @param confirmations number of how often \"y\" should be entered (after the skips).\n * @throws IOException\n */\n private void runEasyRSACommands(String command, int skips, int confirmations) throws IOException {\n ArrayList<String> input = new ArrayList<>();\n for (int i = 0; i < skips; i++) {\n // Skip all settings to use default values.\n input.add(\"\" + System.getProperty(\"line.separator\"));\n }\n runEasyRSACommands(command, input, confirmations);\n }\n\n /**\n * Needed, to execute every command with vars.bat and to confirm some values.\n * @param command\n * @param inputs ArrayList of answers to give.\n * @param confirmations number of how often \"y\" should be entered (after the skips).\n * @throws IOException\n */\n @Windows\n private void runEasyRSACommands(String command, ArrayList<String> inputs, int confirmations) throws IOException {\n ProcessBuilder pb = new ProcessBuilder( \"cmd.exe\");\n pb.redirectErrorStream(true);\n pb.directory(new File(INSTALLATION_PATH + \"easy-rsa/\"));\n Process process = pb.start();\n /*\n TODO: Check if Path environnement contains openssl after installation, otherwise it needs a computer restart..\n Map<String, String> envs = pb.environment();\n System.out.println(envs.get(\"Path\"));\n envs.put(\"openssl\", INSTALLATION_PATH + \"/bin/opensll.exe\");\n */\n OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());\n\n // Write commands.\n PrintWriter commandExecutor = new PrintWriter(process.getOutputStream());\n logger.addLogLine(command);\n if (OpenVPNUtilities.needsPathUpdate()) {\n commandExecutor.println(\"SET PATH=%PATH%;\" + OpenVPNUtilities.openVPNBinPath);\n System.out.println(\"SET PATH=%PATH%;\" + OpenVPNUtilities.openVPNBinPath);\n }\n commandExecutor.println(\"vars.bat\");\n commandExecutor.println(command);\n\n\n for (String input :inputs) {\n commandExecutor.print(input);\n }\n for (int i = 0; i < confirmations; i++) {\n // Confirm all config settings..\n // Very strange behaviour. It needs a delay regarding stackoverflow comment and the exact same command twice.\n // https://stackoverflow.com/questions/39913424/how-to-execute-batch-script-which-takes-multiple-inputs-by-using-java-process-bu\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n commandExecutor.print(\"y\" + \"\\r\\n\");\n commandExecutor.print(\"y\" + \"\\r\\n\");\n commandExecutor.flush();\n }\n\n commandExecutor.println(\"exit\");\n commandExecutor.flush();\n commandExecutor.close();\n outputHandler.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n logger.addLogLine(outputHandler.getOutput().toString());\n }\n\n private String replaceParameter(String source, String key, String value) {\n int startIndex = source.indexOf(key) + key.length();\n int endIndex = source.indexOf(System.getProperty(\"line.separator\") ,startIndex);\n return source.substring(0, startIndex) + value + source.substring(endIndex, source.length());\n }\n\n private void setSiteToEndVPN() {\n // TODO: Implement.\n /* Commands to execute on VPN-server:\n Windows XP and previous registry change is needed:\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\n IPEnableRouter=1\n\n Newer windows versions:\n netsh interface ipv4 set int \"LAN-Verbindung\" forwarding=enabled\n netsh interface ipv4 set int \"LAN-Verbindung 2\" forwarding=enabled\n\n // Also set forwarding in the gateway/router.\n Pseudo: route add 10.0.0.0 mask 255.255.255.0 192.168.0.2 -p\n route add VPN-NETZWERK mask SUBNETZMASKE OPENVPNSERVER -p\n */\n }\n\n}" ]
import de.hartz.vpn.helper.Linux; import de.hartz.vpn.main.UserData; import de.hartz.vpn.main.installation.InstallationController; import de.hartz.vpn.utilities.GeneralUtilities; import de.hartz.vpn.utilities.OpenVPNUtilities; import java.io.*; import static de.hartz.vpn.main.installation.server.ConfigOpenVPN.*;
package de.hartz.vpn.main.installation.client; /** * Class that writes the needed openvpn config file. */ public class ConfigOpenVPN { private static String INSTALLATION_PATH; public ConfigOpenVPN() {
INSTALLATION_PATH = OpenVPNUtilities.getOpenVPNInstallationPath();
3
sct/HexxitGear
src/sct/hexxitgear/HexxitGear.java
[ "public class BlockHexbiscus extends BlockFlower {\n\n public BlockHexbiscus(int id) {\n super(id);\n setCreativeTab(HGCreativeTab.tab);\n setUnlocalizedName(\"hexxitgear.flora.hexbiscus\");\n }\n\n @Override\n public void registerIcons(IconRegister ir) {\n blockIcon = ir.registerIcon(getUnlocalizedName());\n }\n\n @Override\n public int idDropped(int par1, Random par2Random, int par3) {\n return HexxitGear.hexicalEssence.itemID;\n }\n}", "public class HexxitGearRegistry {\n\n public static void init() {\n registerRecipes();\n }\n\n public static void registerRecipes() {\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.hexicalDiamond), new Object[]\n {\n \" I \",\n \"IDI\",\n \" I \",\n 'I', HexxitGear.hexicalEssence,\n 'D', Item.diamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.tribalHelmet), new Object[]\n {\n \"BBB\",\n \"BHB\",\n \" \",\n 'B', Item.bone,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.tribalChest), new Object[]\n {\n \"I I\",\n \"LHL\",\n \"ILI\",\n 'I', \"ingotIron\",\n 'L', Item.leather,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.tribalLeggings), new Object[]\n {\n \"LLL\",\n \"IHI\",\n \"L L\",\n 'I', \"ingotIron\",\n 'L', Item.leather,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.tribalShoes), new Object[]\n {\n \" \",\n \"SHS\",\n \"L L\",\n 'S', Item.silk,\n 'L', Item.leather,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.thiefHelmet), new Object[]\n {\n \"RRR\",\n \"RHR\",\n \" \",\n 'R', new ItemStack(Block.cloth, 1, 14),\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.thiefChest), new Object[]\n {\n \"R R\",\n \"LHL\",\n \"LLL\",\n 'R', new ItemStack(Block.cloth, 1, 14),\n 'L', Item.leather,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.thiefLeggings), new Object[]\n {\n \"LSL\",\n \"LHL\",\n \"L L\",\n 'L', Item.leather,\n 'S', Item.silk,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.thiefBoots), new Object[]\n {\n \" \",\n \"LHL\",\n \"B B\",\n 'L', Item.leather,\n 'H', HexxitGear.hexicalDiamond,\n 'B', new ItemStack(Block.cloth, 1, 7)\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.scaleHelmet), new Object[]\n {\n \"GOG\",\n \"OHO\",\n \" \",\n 'G', \"ingotGold\",\n 'O', Block.obsidian,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.scaleChest), new Object[]\n {\n \"G G\",\n \"OHO\",\n \"GOG\",\n 'G', \"ingotGold\",\n 'O', Block.obsidian,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.scaleLeggings), new Object[]\n {\n \"OOO\",\n \"GHG\",\n \"O O\",\n 'O', Block.obsidian,\n 'G', \"ingotGold\",\n 'H', HexxitGear.hexicalDiamond\n }));\n\n GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(HexxitGear.scaleBoots), new Object[]\n {\n \" \",\n \"OHO\",\n \"O O\",\n 'O', Block.obsidian,\n 'H', HexxitGear.hexicalDiamond\n }));\n\n\n /* Add repair recipes */\n GameRegistry.addShapelessRecipe(new ItemStack(HexxitGear.tribalHelmet, 1, 0), new ItemStack(HexxitGear.tribalHelmet, 1, Short.MAX_VALUE), HexxitGear.hexicalEssence);\n }\n}", "public class PlayerEventHandler {\n\n private int ticks = 0;\n\n @ForgeSubscribe\n public void playerUpdate(LivingEvent.LivingUpdateEvent event) {\n if (ticks > 16) {\n if (event.entityLiving != null && event.entityLiving instanceof EntityPlayer) {\n if (!event.entityLiving.worldObj.isRemote)\n return;\n\n EntityPlayer player = (EntityPlayer) event.entityLiving;\n String capeUrl = CapeHandler.getCapeUrl(player.username);\n if (capeUrl != null && !capeUrl.equals(player.cloakUrl)) {\n player.cloakUrl = capeUrl;\n FMLClientHandler.instance().getClient().renderEngine.obtainImageData(player.cloakUrl, null);\n }\n }\n ticks = 0;\n }\n ticks++;\n }\n}", "public class HGPacketHandler implements IPacketHandler {\n @SuppressWarnings(\"rawtypes\")\n @Override\n public void onPacketData(INetworkManager manager,\n Packet250CustomPayload packet, Player player) {\n DataInputStream data = new DataInputStream(new ByteArrayInputStream(packet.data));\n int packetType = PacketWrapper.readPacketID(data);\n\n if (packetType == Packets.CapeChange) {\n Class[] decodeAs = { String.class, String.class };\n Object[] packetReadout = PacketWrapper.readPacketData(data, decodeAs);\n\n CapeHandler.readCapeUpdate((String)packetReadout[0], (String)packetReadout[1]);\n } else if (packetType == Packets.CapeJoin) {\n CapeHandler.readJoinUpdate(data);\n } else if (packetType == Packets.armorAbility) {\n Class[] decodeAs = { String.class };\n Object[] packetReadout = PacketWrapper.readPacketData(data, decodeAs);\n\n AbilityHandler.readAbilityPacket((String) packetReadout[0]);\n }\n\n }\n}", "public class PlayerTracker implements IPlayerTracker {\n\n public static PlayerTracker instance = new PlayerTracker();\n\n @Override\n public void onPlayerLogin(EntityPlayer player) {\n ArmorSet.getMatchingSet(player);\n CapeHandler.sendJoinUpdate(player);\n }\n\n @Override\n public void onPlayerLogout(EntityPlayer player) {\n ArmorSet.removePlayerArmorSet(player.username);\n }\n\n @Override\n public void onPlayerChangedDimension(EntityPlayer player) {\n }\n\n @Override\n public void onPlayerRespawn(EntityPlayer player) {\n }\n}", "public class HexxitGearConfig {\n\n public static Property hexbiscus;\n\n public static Property tribalHelmetId;\n public static Property tribalChestId;\n public static Property tribalLeggingsId;\n public static Property tribalShoesId;\n public static Property scaleHelmetId;\n public static Property scaleChestId;\n public static Property scaleLeggingsId;\n public static Property scaleBootsId;\n public static Property thiefHelmetId;\n public static Property thiefChestId;\n public static Property thiefLeggingsId;\n public static Property thiefBootsId;\n public static Property hexicalEssence;\n public static Property hexicalDiamond;\n\n public static Property dimensionalBlacklist;\n\n public static File configFolder;\n\n public static void loadCommonConfig(FMLPreInitializationEvent evt)\n {\n Configuration c = new Configuration(evt.getSuggestedConfigurationFile());\n try {\n c.load();\n\n hexbiscus = c.getBlock(\"ID.HexbiscusFlower\", 2400);\n\n tribalHelmetId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.TribalHelmet\", 26200);\n tribalChestId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.TribalChest\", 26201);\n tribalLeggingsId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.TribalLeggings\", 26202);\n tribalShoesId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.TribalShoes\", 26203);\n\n scaleHelmetId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ScaleHelmet\", 26204);\n scaleChestId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ScaleChest\", 26205);\n scaleLeggingsId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ScaleLeggings\", 26206);\n scaleBootsId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ScaleBoots\", 26207);\n\n thiefHelmetId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ThiefHelmet\", 26208);\n thiefChestId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ThiefChest\", 26209);\n thiefLeggingsId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ThiefLeggings\", 26210);\n thiefBootsId = c.getItem(Configuration.CATEGORY_ITEM, \"ID.ThiefBoots\", 26211);\n\n hexicalEssence = c.getItem(Configuration.CATEGORY_ITEM, \"ID.HexicalEssence\", 26212);\n hexicalDiamond = c.getItem(Configuration.CATEGORY_ITEM, \"ID.HexicalDiamond\", 26213);\n\n dimensionalBlacklist = c.get(\"World Generation\", \"Dimensional Blacklist\", \"\");\n dimensionalBlacklist.comment = \"Comma separated list of all blacklisted dimension IDs\";\n\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n c.save();\n }\n }\n\n public static String getConfigBaseFolder()\n {\n return \"sct\";\n }\n\n public static void setConfigFolderBase(File folder)\n {\n configFolder = new File(folder.getAbsolutePath() + \"/\" + getConfigBaseFolder() + \"/\"\n + HexxitGear.modId + \"/\");\n }\n\n public static void extractLang(String[] languages)\n {\n String langResourceBase = \"/sct/\" + HexxitGear.modId + \"/lang/\";\n for (String lang : languages)\n {\n InputStream is = HexxitGear.instance.getClass().getResourceAsStream(langResourceBase + lang + \".lang\");\n try\n {\n File f = new File(configFolder.getAbsolutePath() + \"/lang/\"\n + lang + \".lang\");\n if (!f.exists())\n f.getParentFile().mkdirs();\n OutputStream os = new FileOutputStream(f);\n byte[] buffer = new byte[1024];\n int read = 0;\n while ((read = is.read(buffer)) != -1)\n {\n os.write(buffer, 0, read);\n }\n is.close();\n os.flush();\n os.close();\n }\n catch (IOException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n public static void loadLang()\n {\n File f = new File(configFolder.getAbsolutePath() + \"/lang/\");\n for (File langFile : f.listFiles(new FilenameFilter()\n {\n @Override\n public boolean accept(File dir, String name)\n {\n return name.endsWith(\".lang\");\n }\n }))\n {\n try\n {\n Properties langPack = new Properties();\n langPack.load(new FileInputStream(langFile));\n String lang = langFile.getName().replace(\".lang\", \"\");\n LanguageRegistry.instance().addStringLocalization(langPack,\n lang);\n }\n catch (FileNotFoundException x)\n {\n x.printStackTrace();\n }\n catch (IOException x)\n {\n x.printStackTrace();\n }\n }\n }\n\n public static void registerDimBlacklist() {\n String blacklist = dimensionalBlacklist.getString().trim();\n\n for (String dim : blacklist.split(\",\")) {\n try {\n Integer dimID = Integer.parseInt(dim);\n HexxitGear.addToDimBlacklist(dimID);\n } catch (Exception e) {\n }\n }\n }\n}", "public class HGWorldGen implements IWorldGenerator {\n\n @Override\n public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {\n\n if (HexxitGear.getDimBlacklist().contains(world.provider.dimensionId))\n return;\n\n if (world.getWorldInfo().getTerrainType().getWorldTypeName().equals(\"flat\"))\n return;\n\n int xMin = chunkX << 4;\n int zMin = chunkZ << 4;\n\n int startX = xMin + random.nextInt(16);\n int startZ = zMin + random.nextInt(16);\n\n int tries = random.nextInt(2);\n\n for (int i=0; i < tries; i++) {\n int x = startX + random.nextInt(8) - random.nextInt(8);\n int z = startZ + random.nextInt(8) - random.nextInt(8);\n int y = world.getHeightValue(x, z);\n\n if ((world.isAirBlock(x, y, z) || (world.getBlockId(x,y,z) == Block.snow.blockID)) && HexxitGear.hexbiscus.canBlockStay(world, x, y, z)) {\n if (random.nextInt(50) > 1)\n continue;\n\n world.setBlock(x, y, z, HexxitGear.hexbiscus.blockID, 0, 0);\n }\n }\n }\n}" ]
import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraftforge.common.MinecraftForge; import sct.hexxitgear.block.BlockHexbiscus; import sct.hexxitgear.setup.HexxitGearRegistry; import sct.hexxitgear.event.PlayerEventHandler; import sct.hexxitgear.net.HGPacketHandler; import sct.hexxitgear.tick.PlayerTracker; import sct.hexxitgear.item.*; import sct.hexxitgear.setup.HexxitGearConfig; import sct.hexxitgear.world.HGWorldGen; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger;
/* * HexxitGear * Copyright (C) 2013 Ryan Cohen * * 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 sct.hexxitgear; @Mod(modid = HexxitGear.modId, name = "Hexxit Gear", useMetadata = true, version = HexxitGear.version) @NetworkMod(serverSideRequired = false, clientSideRequired = true,
clientPacketHandlerSpec = @NetworkMod.SidedPacketHandler(channels = { HexxitGear.modNetworkChannel }, packetHandler = HGPacketHandler.class),
3
santoslab/aadl-translator
edu.ksu.cis.projects.mdcf.aadl-translator-test/src/test/java/edu/ksu/cis/projects/mdcf/aadltranslator/test/arch/DeviceModelTests.java
[ "public static boolean initComplete = false;", "public static HashSet<String> usedProperties = new HashSet<>();", "public class DeviceModel extends DevOrProcModel {\n\t\n\tprivate HashBiMap<String, String> inToOutPortNames = HashBiMap.create();\n\t\n\tpublic DeviceModel(){\n\t\tsuper();\n\t\tprocessType = ProcessType.PSEUDODEVICE;\n\t}\n\t\n\tpublic void setComponentType(String componentType){\n\t\tthis.componentType = ComponentType.valueOf(componentType.toUpperCase());\n\t}\n\t\n\tprivate void addOutPortName(String inPortName, String outPortName){\n\t\tinToOutPortNames.put(inPortName, outPortName);\n\t}\n\t\n\tpublic BiMap<String, String> getOutPortNames(){\n\t\treturn inToOutPortNames;\n\t}\n\t\n\tpublic BiMap<String, String> getInPortNames(){\n\t\treturn inToOutPortNames.inverse();\n\t}\n\t\n\t@Override\n\tpublic void addFeature(FeatureModel fm) {\n\t\tif(!(fm instanceof PortModel)){\n\t\t\tports.put(fm.getName(), fm);\n\t\t\treturn;\n\t\t}\n\t\tPortModel pm = (PortModel) fm;\n\t\tPortModel mirror = new PortModel();\n\t\tString pm_suffix = pm.isSubscribe() ? \"In\" : \"Out\";\n\t\tString mirror_suffix = pm.isSubscribe() ? \"Out\" : \"In\";\n\t\t\n\t\t\n\t\tmirror.setCategory(pm.getCategory());\n\t\tmirror.setExchangeName(pm.getExchangeName());\n\t\tmirror.setMaxPeriod(pm.getMaxPeriod());\n\t\tmirror.setMinPeriod(pm.getMinPeriod());\n\t\tmirror.setName(pm.getName() + mirror_suffix);\n\t\tmirror.setSubscribe(!pm.isSubscribe());\n\t\tmirror.setType(pm.getType());\n\t\t\n\t\tpm.setName(pm.getName() + pm_suffix);\n\t\t\n\t\tports.put(mirror.getName(), mirror);\n\t\tports.put(pm.getName(), pm);\n\t\t\n\t\tif(pm.isSubscribe())\n\t\t\taddOutPortName(pm.getName(), mirror.getName());\n\t\telse\n\t\t\taddOutPortName(mirror.getName(), pm.getName());\n\t}\n\t\n//\t@Override\n//\tpublic Map<String, PortModel> getPorts(){\n//\t\treturn ports;\n//\t}\n}", "public static enum ComponentType {\n\tSENSOR, ACTUATOR, CONTROLLER, CONTROLLEDPROCESS, AGGREGATION, TOP\n};", "public class SystemModel extends ComponentModel<DevOrProcModel, SystemConnectionModel>{\n\n\t// Type name -> Child name Model\n\tprivate HashMap<String, DevOrProcModel> typeToComponent;\n\n\tprivate String timestamp;\n\t\n\tprivate List<String> haExplanations = new LinkedList<>();\n\t\n\t// Fault name -> Fault model\n//\tprivate HashMap<String, ErrorTypeModel> faultClasses;\n\n\t/**\n\t * Error type name -> model\n\t */\n\tprivate Map<String, ManifestationTypeModel> errorTypeModels;\n\n\tpublic SystemModel() {\n\t\tsuper();\n\t\ttypeToComponent = new HashMap<>();\n\t}\n\t\n\tpublic ProcessModel getProcessByType(String processTypeName) {\n\t\tif (typeToComponent.get(processTypeName) instanceof ProcessModel)\n\t\t\treturn (ProcessModel) typeToComponent.get(processTypeName);\n\t\telse\n\t\t\treturn null;\n\t}\n\n\tpublic DeviceModel getDeviceByType(String deviceTypeName) {\n\t\tif (typeToComponent.get(deviceTypeName) instanceof DeviceModel)\n\t\t\treturn (DeviceModel) typeToComponent.get(deviceTypeName);\n\t\telse\n\t\t\treturn null;\n\t}\n\t\n\t@Override\n\tpublic void addChild(String childName, DevOrProcModel childModel) throws DuplicateElementException {\n\t\tsuper.addChild(childName, childModel);\n\t\tif(typeToComponent.containsKey(childName))\n\t\t\tthrow new DuplicateElementException(childName + \" already exists\");\n\t\ttypeToComponent.put(childModel.getName(), childModel);\n\t}\n\n\tpublic String getTimestamp() {\n\t\treturn timestamp;\n\t}\n\n\tpublic void setTimestamp(String timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic HashMap<String, ProcessModel> getLogicComponents() {\n\t\tMap<String, DevOrProcModel> preCast = children.entrySet()\n\t\t\t\t.stream()\n\t\t\t\t.filter(p -> p.getValue() instanceof ProcessModel)\n\t\t\t\t.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));\n\t\t\n\t\tHashMap<String, ProcessModel> ret = new HashMap<>();\n\t\tfor(String elemName : preCast.keySet()){\n\t\t\tret.put(elemName, (ProcessModel) preCast.get(elemName));\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\tpublic HashMap<String, DevOrProcModel> getLogicAndDevices() {\n\t\treturn children;\n\t}\n\t\n\tpublic boolean hasProcessType(String typeName) {\n\t\treturn (typeToComponent.containsKey(typeName) && (typeToComponent\n\t\t\t\t.get(typeName) instanceof ProcessModel));\n\t}\n\n\tpublic boolean hasDeviceType(String typeName) {\n\t\treturn (typeToComponent.containsKey(typeName) && (typeToComponent\n\t\t\t\t.get(typeName) instanceof DeviceModel));\n\t}\n\t\n\tpublic HashMap<String, ConnectionModel> getUniqueDevicePublishedChannels(){\n\t\tSet<SystemConnectionModel> chanSet = channels.values()\n\t\t\t\t.stream()\n\t\t\t\t.filter(cs -> cs.publisher instanceof DeviceModel)\n\t\t\t\t.collect(Collectors.toSet());\n\t\t\n\t\t// Get a set that's distinct based on publishing identity \n\t\t// (publisher component name + publisher port name)\n\t\tHashMap<String, ConnectionModel> chanMap = new HashMap<String, ConnectionModel>();\n\t\tfor(ConnectionModel cm : chanSet) {\n\t\t\tchanMap.put(cm.getPubName().concat(cm.getPubPortName()), cm);\n\t\t}\n\t\treturn chanMap;\n\t}\n\t\n\tpublic HashMap<String, ConnectionModel> getUniqueDeviceSubscribedChannels(){\n\t\tSet<SystemConnectionModel> chanSet = channels.values()\n\t\t\t\t.stream()\n\t\t\t\t.filter(cs -> cs.subscriber instanceof DeviceModel)\n\t\t\t\t.collect(Collectors.toSet());\n\t\t\n\t\t// Get a set that's distinct based on subscriber identity \n\t\t// (subscriber component name + subscriber port name)\n\t\tHashMap<String, ConnectionModel> chanMap = new HashMap<String, ConnectionModel>();\n\t\tfor(ConnectionModel cm : chanSet) {\n\t\t\tchanMap.put(cm.getSubName().concat(cm.getSubPortName()), cm);\n\t\t}\n\t\treturn chanMap;\n\t}\n\n\tpublic void setErrorTypes(Map<String, ManifestationTypeModel> errorTypeModels) {\n\t\tthis.errorTypeModels = errorTypeModels;\n\t}\n\t\n\tpublic Set<String> getAllErrorTypes(){\n\t\treturn errorTypeModels.values()\n\t\t\t\t.stream()\n\t\t\t\t.map(v -> v.getManifestationName())\n\t\t\t\t.collect(Collectors.toCollection(LinkedHashSet::new));\n\t}\n\t\n\tpublic ManifestationTypeModel getErrorTypeModelByName(String name){\n\t\tif(errorTypeModels == null){\n\t\t\t// This will happen if there is no error type information at all\n\t\t\t// We don't want to require that, so we just return null\n\t\t\treturn null;\n\t\t}\n\t\treturn errorTypeModels.get(name);\n\t}\n\t\n\tpublic void addExplanation(String exp){\n\t\thaExplanations.add(exp);\n\t}\n\t\n\tpublic List<String> getExplanations(){\n\t\treturn haExplanations;\n\t}\n}", "@RunWith(Suite.class)\n//@InjectWith(typeof(Aadl2UiInjectorProvider)) Look into this, could remove 10s wait time\n@Suite.SuiteClasses({\n\t\t// Architecture Model tests\n\t\tSystemModelTests.class,\n\t\tDeviceModelTests.class,\n\t\tProcessModelTests.class,\n\t\tTaskModelTests.class,\n\t\tPortModelTests.class,\n\t\tSystemConnectionModelTests.class,\n\t\tProcessConnectionModelTests.class,\n\n\t\t// Hazard Analysis Model tests\n//\t\tConnectionModelHazardTests.class,\n\t\tHazardPreliminariesTests.class,\n//\t\tHazardBackgroundTests.class,\n\t\tPropagatableErrorTests.class,\n\t\tExternallyCausedDangerModelTests.class,\n\t\tInternallyCausedDangerModelTests.class,\n\t\tNotDangerousDangerModelTests.class,\n\t\tDetectionAndHandlingTests.class,\n\t\tEliminatedFaultsTests.class,\n\n\t\t// Error-handling tests\n\t\tControllerErrorTests.class,\n\n\t\t// Device EI tests\n\t\t// Disabled by Sam, 11/8/14 -- all tests in this class just assume(true)\n//\t\tDeviceEIGeneratedArtifactsTest.class,\n\t\tDeviceEIAADLSystemErrorTest.class,\n\n\t\t// View tests\n\t\tAppHAReportViewTests.class,\n\t\tAppSuperClassViewTests.class,\n\t\tAppSpecViewTests.class,\n\t\tSTRendererTests.class,\n//\t\tAwasTests.class,\n})\npublic class AllTests {\n\tprivate static final Logger log = Logger\n\t\t\t.getLogger(AllTests.class.getName());\n\n\tpublic static HashMap<String, IFile> targetableFiles = new HashMap<>();\n\tpublic static ResourceSet resourceSet = null;\n\n\tpublic final static String TEST_PLUGIN_BUNDLE_ID = \"edu.ksu.cis.projects.mdcf.aadl-translator-test\";\n\tpublic final static String MAIN_PLUGIN_BUNDLE_ID = \"edu.ksu.cis.projects.mdcf.aadl-translator\";\n\tpublic final static String TEST_DIR = \"src/test/resources/edu/ksu/cis/projects/mdcf/aadltranslator/test/\";\n\tpublic final static String TEMPLATE_DIR = \"src/main/resources/templates/\";\n\n\tpublic static IProject testProject = null;\n\n\tpublic static HashSet<String> usedDevices = new HashSet<>();\n\tpublic static HashSet<String> usedProperties = new HashSet<>();\n\tpublic static ParseErrorReporterFactory parseErrorReporterFactory = TestParseErrorReporterFactory.INSTANCE;\n\tpublic static ParseErrorReporterManager parseErrManager;\n\n\tpublic static boolean initComplete = false;\n\tpublic static StringBuilder errorSB = new StringBuilder();\n\n\t@BeforeClass\n\tpublic static void initialize() {\n\t\ttestProject = ResourcesPlugin.getWorkspace().getRoot()\n\t\t\t\t.getProject(\"TestProject\");\n\t\ttry {\n\n\t\t\tIHandlerService handlerService = (IHandlerService) PlatformUI\n\t\t\t\t\t.getWorkbench().getService(IHandlerService.class);\n\t\t\thandlerService\n\t\t\t\t\t.executeCommand(\n\t\t\t\t\t\t\t\"org.osate.xtext.aadl2.ui.resetpredeclaredproperties\",\n\t\t\t\t\t\t\tnull);\n\n\t\t\tString[] natureIDs = new String[] { \"org.osate.core.aadlnature\",\n\t\t\t\t\t\"org.eclipse.xtext.ui.shared.xtextNature\" };\n\n\t\t\tIProject pluginResources = ResourcesPlugin.getWorkspace().getRoot()\n\t\t\t\t\t.getProject(\"Plugin_Resources\");\n\n\t\t\tIProject[] referencedProjects = new IProject[] { pluginResources };\n\t\t\tif (!testProject.isAccessible()) {\n\t\t\t\ttestProject.create(null);\n\t\t\t\ttestProject.open(null);\n\t\t\t}\n\n\t\t\tIProjectDescription prpd = pluginResources.getDescription();\n\t\t\tprpd.setNatureIds(natureIDs);\n\t\t\tpluginResources.setDescription(prpd, null);\n\n\t\t\tIProjectDescription testpd = testProject.getDescription();\n\t\t\ttestpd.setNatureIds(natureIDs);\n\t\t\ttestpd.setReferencedProjects(referencedProjects);\n\t\t\ttestProject.setDescription(testpd, null);\n\n\t\t\tIFolder packagesFolder = testProject.getFolder(\"packages\");\n\t\t\tif (!packagesFolder.isAccessible()) {\n\t\t\t\tpackagesFolder.create(true, true, null);\n\t\t\t}\n\n\t\t\tIFolder propertySetsFolder = testProject.getFolder(\"propertysets\");\n\t\t\tif (!propertySetsFolder.isAccessible()) {\n\t\t\t\tpropertySetsFolder.create(true, true, null);\n\t\t\t}\n\n\t\t\tresourceSet = OsateResourceUtil.createResourceSet();\n\n\t\t\tinitFiles(packagesFolder, propertySetsFolder);\n\n\t\t\ttestProject\n\t\t\t\t\t.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);\n\t\t} catch (CoreException | ExecutionException | NotDefinedException\n\t\t\t\t| NotEnabledException | NotHandledException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t// This is a total hack because the guice injectors don't finish\n\t\t// running until some time after the build has completed. This 10s wait\n\t\t// allows them to finish, avoiding all sorts of nasty errors\n\t\ttry {\n\t\t\tThread.sleep(10000);\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tinitComplete = true;\n\t}\n\n\tprivate static void initFiles(IFolder packagesFolder,\n\t\t\tIFolder propertySetsFolder) {\n\t\tURL aadlDirUrl = Platform.getBundle(TEST_PLUGIN_BUNDLE_ID).getEntry(\n\t\t\t\tTEST_DIR + \"aadl/\");\n\t\tURL aadlPropertysetsDirUrl = Platform.getBundle(TEST_PLUGIN_BUNDLE_ID)\n\t\t\t\t.getEntry(TEST_DIR + \"aadl/propertyset/\");\n\t\tURL aadlSystemDirUrl = Platform.getBundle(TEST_PLUGIN_BUNDLE_ID)\n\t\t\t\t.getEntry(TEST_DIR + \"aadl/system/\");\n\t\tURL aadlDeviceDirUrl = Platform.getBundle(TEST_PLUGIN_BUNDLE_ID)\n\t\t\t\t.getEntry(TEST_DIR + \"aadl/device/\");\n\t\tFile aadlDir = null;\n\t\tFile aadlPropertysetsDir = null;\n\t\tFile aadlSystemDir = null;\n\t\tFile aadlDeviceDir = null;\n\t\ttry {\n\t\t\taadlDir = new File(FileLocator.toFileURL(aadlDirUrl).toURI());\n\t\t\taadlPropertysetsDir = new File(FileLocator.toFileURL(\n\t\t\t\t\taadlPropertysetsDirUrl).toURI());\n\t\t\taadlSystemDir = new File(FileLocator.toFileURL(aadlSystemDirUrl).toURI());\n\t\t\taadlDeviceDir = new File(FileLocator.toFileURL(aadlDeviceDirUrl).toURI());\n\t\t} catch (IOException | URISyntaxException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tinitFiles(packagesFolder, propertySetsFolder, aadlDir, targetableFiles);\n\t\tinitFiles(packagesFolder, propertySetsFolder, aadlSystemDir,\n\t\t\t\ttargetableFiles);\n\t\tinitFiles(packagesFolder, propertySetsFolder, aadlDeviceDir,\n\t\t\t\ttargetableFiles);\n\t\tinitFiles(packagesFolder, propertySetsFolder, aadlPropertysetsDir,\n\t\t\t\ttargetableFiles);\n\n\t\t/* Device Equipment Interfaces Related Files */\n\t\tURL aadlDeviceEIPackageDirUrl = Platform.getBundle(\n\t\t\t\tTEST_PLUGIN_BUNDLE_ID).getEntry(\n\t\t\t\tTEST_DIR + \"aadl/device_eis/packages/\");\n\t\tURL aadlDeviceEIPropertysetsDirUrl = Platform.getBundle(\n\t\t\t\tTEST_PLUGIN_BUNDLE_ID).getEntry(\n\t\t\t\tTEST_DIR + \"aadl/device_eis/propertysets/\");\n\n\t\tFile aadlDeviceEIPackageDir = null;\n\t\tFile aadlDeviceEIPropertysetsDir = null;\n\n\t\ttry {\n\t\t\taadlDeviceEIPackageDir = new File(FileLocator.toFileURL(\n\t\t\t\t\taadlDeviceEIPackageDirUrl).getPath());\n\t\t\taadlDeviceEIPropertysetsDir = new File(FileLocator.toFileURL(\n\t\t\t\t\taadlDeviceEIPropertysetsDirUrl).getPath());\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tinitFiles(packagesFolder, propertySetsFolder, aadlDeviceEIPackageDir,\n\t\t\t\ttargetableFiles);\n\t\tinitFiles(packagesFolder, propertySetsFolder,\n\t\t\t\taadlDeviceEIPropertysetsDir, targetableFiles);\n\t}\n\n\tprivate static void initFiles(IFolder packagesFolder,\n\t\t\tIFolder propertySetsFolder, File dir,\n\t\t\tHashMap<String, IFile> fileMap) {\n\t\tString fileName = null;\n\t\ttry {\n\t\t\tfor (File f : dir.listFiles()) {\n\t\t\t\tif (f.isHidden() || f.isDirectory())\n\t\t\t\t\tcontinue;\n\t\t\t\tfileName = f.getName().substring(0, f.getName().length() - 5);\n\t\t\t\tfileMap.put(fileName,\n\t\t\t\t\t\tpackagesFolder.getFile(fileName + \".aadl\"));\n\t\t\t\tif (!packagesFolder.getFile(fileName + \".aadl\").exists()) {\n\t\t\t\t\tfileMap.get(fileName).create(new FileInputStream(f), true,\n\t\t\t\t\t\t\tnull);\n\t\t\t\t}\n\t\t\t\tresourceSet.createResource(OsateResourceUtil\n\t\t\t\t\t\t.getResourceURI((IResource) fileMap.get(fileName)));\n\t\t\t}\n\t\t} catch (IOException | CoreException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static SystemModel runArchTransTest(final String testName,\n\t\t\tfinal String systemName) {\n\t\tIFile inputFile = targetableFiles.get(systemName);\t\t\n\t\tHashSet<IFile> supportingFiles = getSupportingFiles(inputFile);\n\t\tTranslator stats = new Translator(new NullProgressMonitor());\n\n\t\tconfigureTranslator(inputFile, stats);\n\t\t\n\t\tparseErrManager = new ParseErrorReporterManager(\n\t\t\t\tparseErrorReporterFactory);\n\n\t\tstats.setErrorManager(parseErrManager);\n\t\tfor (String propSetName : usedProperties) {\n\t\t\tstats.addPropertySetName(propSetName);\n\t\t}\n\t\tResource res = resourceSet.getResource(\n\t\t\t\tOsateResourceUtil.getResourceURI((IResource) inputFile), true);\n\t\tElement target = (Element) res.getContents().get(0);\n\t\t\n\t\tstats.setErrorInfo(getErrorTypes(resourceSet, supportingFiles));\n\t\tstats.process(target);\n\t\tString appName = inputFile.getProject().getName();\n\t\tstats.getSystemModel().setName(appName);\n\t\tfor(DevOrProcModel dopm : stats.getSystemModel().getChildren().values()){\n\t\t\tdopm.setParentName(appName);\n\t\t}\n\t\terrorSB.append(parseErrManager.getReporter((IResource) inputFile)\n\t\t\t\t.toString());\n\t\n\t\tfor (IFile supportingFile : supportingFiles) {\n\t\t\tres = resourceSet.getResource(OsateResourceUtil\n\t\t\t\t\t.getResourceURI((IResource) supportingFile), true);\n\t\t\ttarget = (Element) res.getContents().get(0);\n\t\t\tstats.process(target);\n\t\t\terrorSB.append(parseErrManager.getReporter(\n\t\t\t\t\t(IResource) supportingFile).toString());\n\t\t}\n\n\t\treturn stats.getSystemModel();\n\t}\n\n\tprivate static HashSet<IFile> getSupportingFiles(IFile inputFile) {\n\t\tHashSet<IFile> newSupportingFiles = new HashSet<>();\n\t\tIncludesCalculator ic = new IncludesCalculator(new NullProgressMonitor());\n\t\tElement targetElem = getTargetElement(inputFile);\n\t\tic.process(targetElem);\n\t\tnewSupportingFiles.addAll(ic.getUsedFiles());\n\t\tnewSupportingFiles.remove(inputFile);\n\t\treturn newSupportingFiles;\n\t}\n\n\tpublic static SystemModel runHazardTransTest(final String testName,\n\t\t\tfinal String systemName) {\n\t\tIFile inputFile = targetableFiles.get(systemName);\n\t\tTranslator stats = new Translator(new NullProgressMonitor());\n\t\t\n\t\tconfigureTranslator(inputFile, stats);\n\n\t\tparseErrManager = new ParseErrorReporterManager(\n\t\t\t\tparseErrorReporterFactory);\n\n\t\tstats.setErrorManager(parseErrManager);\n\t\tfor (String propSetName : usedProperties) {\n\t\t\tstats.addPropertySetName(propSetName);\n\t\t}\n\t\tResource res = resourceSet.getResource(\n\t\t\t\tOsateResourceUtil.getResourceURI((IResource) inputFile), true);\n\t\tElement target = (Element) res.getContents().get(0);\n\n\t\tHashSet<IFile> supportingFiles = getSupportingFiles(inputFile);\n\t\t\n\t\tstats.setErrorInfo(getErrorTypes(resourceSet, supportingFiles));\n\t\t\n\t\tstats.process(target);\n\t\tString appName = inputFile.getProject().getName();\n\t\tstats.getSystemModel().setName(appName);\n\t\tfor(DevOrProcModel dopm : stats.getSystemModel().getChildren().values()){\n\t\t\tdopm.setParentName(appName);\n\t\t}\n\t\terrorSB.append(parseErrManager.getReporter((IResource) inputFile)\n\t\t\t\t.toString());\n\n\t\tfor (IFile supportingFile : supportingFiles) {\n\t\t\tres = resourceSet.getResource(OsateResourceUtil\n\t\t\t\t\t.getResourceURI((IResource) supportingFile), true);\n\t\t\ttarget = (Element) res.getContents().get(0);\n\t\t\tstats.process(target);\n\t\t\terrorSB.append(parseErrManager.getReporter(\n\t\t\t\t\t(IResource) supportingFile).toString());\n\t\t}\n\n\t\treturn stats.getSystemModel();\n\t}\n\n\tprivate static void configureTranslator(IFile inputFile, Translator stats) {\n\t\tAadlPackage pack = (AadlPackage) getTargetElement(inputFile);\n\t\tPublicPackageSection sect = pack.getPublicSection();\n\t\tClassifier ownedClassifier = sect.getOwnedClassifiers().get(0);\n\t\tif(ownedClassifier instanceof org.osate.aadl2.System){\n\t\t\t((Translator)stats).setTarget(\"System\");\n\t\t} else if(ownedClassifier instanceof org.osate.aadl2.Device){\n\t\t\t((Translator)stats).setTarget(\"Device\");\n\t\t} else if(ownedClassifier instanceof org.osate.aadl2.Process){\n\t\t\t((Translator)stats).setTarget(\"Process\");\n\t\t}\n\t}\n\n\tpublic static DeviceComponentModel runDeviceTransTest(\n\t\t\tfinal String testName, final String systemName) {\n\n\t\tIFile inputFile = targetableFiles.get(systemName);\n\t\tDeviceTranslator stats = new DeviceTranslator(new NullProgressMonitor());\n\n\t\tlog.setUseParentHandlers(false);\n\n\t\tparseErrManager = new ParseErrorReporterManager(\n\t\t\t\tparseErrorReporterFactory);\n\n\t\tstats.setErrorManager(parseErrManager);\n\t\tfor (String propSetName : usedProperties) {\n\t\t\tstats.addPropertySetName(propSetName);\n\t\t}\n\t\tResource res = resourceSet.getResource(\n\t\t\t\tOsateResourceUtil.getResourceURI((IResource) inputFile), true);\n\t\tElement target = (Element) res.getContents().get(0);\n\n\t\tfor (Diagnostic diag : res.getErrors()) {\n\t\t\tlog.log(Level.SEVERE, \"Error:\" + diag.getMessage());\n\t\t}\n\n\t\tfor (Diagnostic diag : res.getWarnings()) {\n\t\t\tlog.log(Level.SEVERE, \"Warnings:\" + diag.getMessage());\n\t\t}\n\n\t\tstats.process(target);\n\n\t\terrorSB.append(parseErrManager.getReporter((IResource) inputFile)\n\t\t\t\t.toString());\n\n\t\tlog.log(Level.SEVERE, errorSB.toString());\n\t\tif (errorSB.length() == 0) {\n\t\t\tlog.log(Level.FINE, stats.getDeviceComponentModel().toString());\n\t\t}\n\t\treturn stats.getDeviceComponentModel();\n\t}\n\n\tpublic static void runWriterTest(String testName, Object var, String varName,\n\t\t\tSTGroup stg, boolean GENERATE_EXPECTED, String expectedDir) {\n\t\tstg.registerRenderer(String.class, MarkdownLinkRenderer.getInstance());\n\t\tURL expectedOutputUrl = Platform.getBundle(TEST_PLUGIN_BUNDLE_ID)\n\t\t\t\t.getEntry(TEST_DIR + expectedDir + testName + \".txt\");\n\t\tString actualStr = stg.getInstanceOf(testName).add(varName, var)\n\t\t\t\t.render();\n\t\tString expectedStr = null;\n\t\ttry {\n\t\t\tif (GENERATE_EXPECTED) {\n\t\t\t\tFiles.write(Paths.get(FileLocator.toFileURL(expectedOutputUrl).toURI()), actualStr.getBytes());\n\t\t\t\texpectedStr = actualStr;\n\t\t\t\tfail(\"Test was run in generate expected mode!\");\n\t\t\t} else {\n\t\t\t\texpectedStr = new String(\n\t\t\t\t\t\tFiles.readAllBytes(Paths.get(FileLocator.toFileURL(\n\t\t\t\t\t\t\t\texpectedOutputUrl).toURI())));\n\t\t\t}\n\t\t} catch (IOException | URISyntaxException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tactualStr = actualStr.replace(\"\\r\\n\", \"\\n\"); // Fix line endings if we're on windows\n\t\tassertEquals(expectedStr, actualStr);\n\t}\n\n\tprivate static Element getTargetElement(IFile file) {\n\t\tResourceSet rs = OsateResourceUtil.createResourceSet();\n\t\tResource res = rs.getResource(\n\t\t\t\tOsateResourceUtil.getResourceURI((IResource) file), true);\n\t\tElement target = (Element) res.getContents().get(0);\n\t\treturn target;\n\t}\n\t\n\tprivate static HashSet<NamedElement> getErrorTypes(ResourceSet rs, HashSet<IFile> usedFiles) {\n\t\tHashSet<NamedElement> retSet = new HashSet<>();\n\t\tfor (IFile f : usedFiles) {\n\t\t\tResource res = rs.getResource(OsateResourceUtil.getResourceURI((IResource) f), true);\n\t\t\tElement target = (Element) res.getContents().get(0);\n\t\t\tif ((target instanceof PropertySet)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tAadlPackage pack = (AadlPackage) target;\n\t\t\tPublicPackageSection sect = pack.getPublicSection();\n\t\t\tif (sect.getOwnedAnnexLibraries().size() > 0\n\t\t\t\t\t&& sect.getOwnedAnnexLibraries().get(0).getName().equalsIgnoreCase(\"EMV2\")) {\n\t\t\t\tAnnexLibrary annexLibrary = sect.getOwnedAnnexLibraries().get(0);\n\t\t\t\tDefaultAnnexLibrary defaultAnnexLibrary = (DefaultAnnexLibrary) annexLibrary;\n\t\t\t\tErrorModelLibraryImpl emImpl = (ErrorModelLibraryImpl) defaultAnnexLibrary.getParsedAnnexLibrary();\n\t\t\t\tretSet.addAll(emImpl.getTypes());\n\t\t\t\tretSet.addAll(emImpl.getTypesets());\n\t\t\t\tretSet.addAll(emImpl.getBehaviors());\n\t\t\t}\n\t\t}\n\t\treturn retSet;\n\t}\n\n}" ]
import static edu.ksu.cis.projects.mdcf.aadltranslator.test.AllTests.initComplete; import static edu.ksu.cis.projects.mdcf.aadltranslator.test.AllTests.usedProperties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import edu.ksu.cis.projects.mdcf.aadltranslator.model.DeviceModel; import edu.ksu.cis.projects.mdcf.aadltranslator.model.ModelUtil.ComponentType; import edu.ksu.cis.projects.mdcf.aadltranslator.model.SystemModel; import edu.ksu.cis.projects.mdcf.aadltranslator.test.AllTests;
package edu.ksu.cis.projects.mdcf.aadltranslator.test.arch; public class DeviceModelTests { private static DeviceModel deviceModelFromSystem; // private static DeviceModel deviceModelStandalone; @BeforeClass public static void initialize() {
if(!initComplete)
0
emop/EmopAndroid
src/com/emop/client/fragment/RebateListFragment.java
[ "public class WebViewActivity extends BaseActivity {\r\n\tpublic final static int WEB_DONE = 1;\r\n\tpublic final static int WEB_MSG = 2;\r\n\tpublic final static int WEB_LOADING = 3;\r\n\tpublic final static int WEB_LOADED = 4;\t\r\n\t\r\n\tprivate ProgressBar processBar = null;\r\n\tprivate WebView web = null;\r\n\tprivate TextView titleView = null;\r\n\tprivate String curURL = \"\";\r\n \r\n\t@Override\r\n public void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.web_view);\r\n \r\n this.web = (WebView)findViewById(R.id.web);\r\n this.processBar = (ProgressBar)findViewById(R.id.progressbar_loading);\r\n \r\n web.setVerticalScrollBarEnabled(false);\r\n web.setHorizontalScrollBarEnabled(false);\r\n //web.getSettings().s\r\n web.getSettings().setJavaScriptEnabled(true);\r\n web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);\r\n web.setDownloadListener(new DownloadListener(){\r\n\t\t\t@Override\r\n\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition,\r\n\t\t\t\t\tString mimetype, long contentLength) {\r\n\t Uri uri = Uri.parse(url); \r\n\t Intent intent = new Intent(Intent.ACTION_VIEW, uri); \r\n\t startActivity(intent); \r\n\t\t\t}\r\n });\r\n \r\n CookieSyncManager.createInstance(this);\r\n \r\n //web.setWebViewClient(new TaokeWebViewClient());\r\n \r\n titleView = (TextView)findViewById(R.id.title);\r\n \r\n titleView.setLongClickable(true); \r\n titleView.setOnLongClickListener(new OnLongClickListener(){\r\n\t\t\t@Override\r\n\t\t\tpublic boolean onLongClick(View arg0) {\r\n\t\t\t\tif(curURL != null && curURL.length() > 1){\r\n\t\t Uri uri = Uri.parse(curURL); \r\n\t\t Intent intent = new Intent(Intent.ACTION_VIEW, uri); \r\n\t\t startActivity(intent); \r\n\t\t\t\t}\r\n\t\t\t\treturn false;\r\n\t\t\t}\t\t\t\r\n }); \r\n }\r\n\t\r\n protected void onResume (){\r\n \tsuper.onResume();\r\n \t\r\n \tIntent intent = this.getIntent();\r\n \tString title = intent.getStringExtra(\"title\");\r\n \tif(title != null && title.trim().length() > 0 && titleView != null){\r\n \t\ttitleView.setText(title);\r\n \t}\r\n \tif(intent.getBooleanExtra(\"taobaoLogin\", false)){\r\n \t\tweb.setWebViewClient(new TaobaoLoginWebClient(this, processBar));\r\n \t\tif(processBar != null){\r\n \t\t\tprocessBar.setVisibility(View.INVISIBLE);\r\n \t\t}\r\n \t}else {\r\n \t\tweb.setWebViewClient(new TaokeWebViewClient());\r\n \t} \t\r\n \t//Uri dataUri = intent.getData(); \r\n \tString http_url = intent.getStringExtra(\"http_url\");\r\n \tString num_iid = intent.getStringExtra(\"taoke_num_iid\");\r\n\r\n \tboolean autoMobile = autoConvertMobileLink(num_iid);\r\n \tif(!autoMobile && http_url != null && http_url.startsWith(\"http\")){\r\n \t\tLog.d(Constants.TAG_EMOP, \"loading url:\" + http_url);\r\n \t\tweb.loadUrl(http_url);\r\n \t}\r\n \t\r\n \t/**\r\n \t * 如果是淘宝商品,在客户端转换后跳转。\r\n \t */\r\n \tif(autoMobile){\r\n \t\tloadTaoboItem(num_iid, http_url);\r\n \t}\r\n }\r\n \r\n /**\r\n * 判断是否需要自动转换,移动版链接。只有冒泡自己的帐号才需要转换链接。\r\n * @param num_iid\r\n * @return\r\n */\r\n protected boolean autoConvertMobileLink(String num_iid){\r\n \tif(num_iid == null) return false;\r\n \tif(client.trackUserId != null && !client.trackUserId.equals(\"11\")){\r\n \t\treturn false;\r\n \t}\r\n \treturn true;\r\n }\r\n \r\n protected void loadTaoboItem(final String numiid, final String shortUrl){\r\n \tfinal TopAndroidClient client = TopAndroidClient.getAndroidClientByAppKey(Constants.TAOBAO_APPID);\r\n \tTopParameters param = new TopParameters();\r\n \t\r\n \tparam.setMethod(\"taobao.taobaoke.widget.items.convert\");\r\n \tparam.addFields(\"click_url\",\"num_iid\");\r\n \tparam.addParam(\"is_mobile\", \"true\");\r\n \tparam.addParam(\"num_iids\", numiid); \t\r\n\t\t\r\n \tTopApiListener listener = new TopApiListener(){\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onComplete(JSONObject json) {\r\n\t\t\t\t// TODO Auto-generated method stub\r\n\t\t\t\tString click = null;\r\n\t\t\t\t\r\n\t\t\t\ttry{\r\n\t\t\t\t\tJSONArray items = json.getJSONObject(\"taobaoke_widget_items_convert_response\").\r\n\t\t\t\t\t\tgetJSONObject(\"taobaoke_items\").getJSONArray(\"taobaoke_item\");\r\n\t\t\t\t\tJSONObject item = items.getJSONObject(0);\r\n\t\t\t\t\tclick = item.getString(\"click_url\");\r\n\t\t\t\t\tLog.i(\"emop\", \"num iid:\" + numiid + \", convert click url:\" + click);\r\n\t\t\t\t}catch(Exception e){\r\n\t\t\t\t\tLog.w(\"emop\", \"error e:\" + e.toString(), e);\r\n\t\t\t\t}finally{\r\n\t\t\t\t\tif(click != null){\r\n\t\t\t\t\t\tloadMobileUrl(click);\r\n\t\t\t\t\t}else {\t\t\t\t\t\t\r\n\t\t\t\t\t\tloadShortUrl(shortUrl);\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}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onError(ApiError error) {\r\n\t\t\t\tLog.w(\"emop\", \"error e:\" + error.toString());\r\n\t\t\t\tloadShortUrl(shortUrl);\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onException(Exception e) {\r\n\t\t\t\tLog.w(\"emop\", \"error e:\" + e.toString(), e);\r\n\t\t\t\tloadShortUrl(shortUrl);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tprivate void loadMobileUrl(String url){\r\n\t\t\t\tweb.loadUrl(url);\r\n\t\t\t}\r\n\r\n\t\t\tprivate void loadShortUrl(String url){\r\n\t\t\t\tweb.loadUrl(url);\r\n\t\t\t}\r\n\t\t\t\r\n \t};\r\n \tclient.api(param, null, listener, true);\r\n }\r\n \r\n public void onFinish(View v){\r\n \tonBackPressed();\r\n }\r\n \r\n public void onBackPressed() {\r\n \tif(web.canGoBack()){\r\n \t\tweb.goBack();\r\n \t}else {\r\n \t\tfinish();\r\n \t}\r\n }\r\n \r\n public Handler handler = new Handler(){\r\n \t\r\n \tpublic void handleMessage(final Message msg) {\r\n \t\tString message = null;\r\n \t\tif(msg.obj != null){\r\n \t\t\tmessage = msg.obj.toString();\r\n \t\t\tif(message != null){\r\n \t\t\t\tToast.makeText(WebViewActivity.this, message, Toast.LENGTH_LONG).show();\r\n \t\t\t}\r\n \t\t}\r\n \t\tif(msg.what == WEB_DONE){\r\n \t\t\tfinish();\r\n \t\t}else if(msg.what == WEB_LOADING){\r\n \t\t\tprocessBar.setVisibility(View.VISIBLE);\r\n \t\t}else if(msg.what == WEB_LOADED){\r\n \t\t\tprocessBar.setVisibility(View.INVISIBLE);\r\n \t\t}\r\n \t}\r\n\r\n }; \r\n \r\n private class TaokeWebViewClient extends WebViewClient {\r\n \tprivate boolean inTaobao = false;\r\n\r\n @Override\r\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\r\n super.onPageStarted(view, url, favicon);\r\n Log.d(\"xx\", \"url:\" + url);\r\n curURL = url;\r\n //mSpinner.show();\r\n processBar.setVisibility(View.VISIBLE);\r\n }\r\n\r\n @Override\r\n public void onPageFinished(WebView view, String url) {\r\n super.onPageFinished(view, url);\r\n Log.d(\"xx\", \"done url:\" + url);\r\n //curURL = url;\r\n \r\n /**\r\n * 刚进入宝贝详情页时,清空回退记录。这样在点回退的时候才能退出详情页。\r\n * 不然是退回到短网址页面,会再次进入详情页。\r\n */\r\n if((!inTaobao && isProductUrl(url)) || url.endsWith(\"taobao.com/\")){\r\n \tinTaobao = true;\r\n \tweb.clearHistory();\r\n } \r\n processBar.setVisibility(View.INVISIBLE);\r\n }\r\n \r\n @Override\r\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\r\n Log.d(TAG_EMOP, \"Redirect URL: \" + url);\r\n \r\n int i = url.indexOf(\"m.taobao.com\");\r\n \tif(i > 0 && i < 15 && isAvilible(getApplicationContext(), \"com.taobao.taobao\")){\r\n \t\tIntent intent = new Intent();\t\t\t\r\n \t\t//intent.setClass(this, LoginActivity.class);\r\n \t\turl = url.replaceFirst(\"http:\", \"itaobao:\");\r\n \t\tintent.setAction(Intent.ACTION_VIEW);\r\n \t\tintent.setData(Uri.parse(url));\r\n \t//\tintent.setComponent(ComponentName.unflattenFromString(\"com.taobao.taobao/com.taobao.tao.detail.DetailActivity\"))\r\n \t\tstartActivityForResult(intent, OPEN_TAOBAO); \t\r\n \t\tfinish();\r\n \t\treturn true;\r\n \t}else {\r\n \t\treturn false;\r\n \t}\r\n }\r\n \r\n public boolean isProductUrl(String url){\r\n \tif(url.indexOf(\"s.click\") > 0 || url.indexOf(\"view_shop.htm\") > 0){\r\n \t\treturn false;\r\n \t}\r\n \tif(url.indexOf(\"tmall.com\") > 0 || url.indexOf(\"m.taobao.com\") > 0){\r\n \t\treturn true;\r\n \t}\r\n \treturn false;\r\n }\r\n }\r\n \r\n private boolean isAvilible(Context context, String packageName){ \r\n final PackageManager packageManager = context.getPackageManager();//获取packagemanager \r\n List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息 \r\n List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名 \r\n //从pinfo中将包名字逐一取出,压入pName list中 \r\n if(pinfo != null){ \r\n for(int i = 0; i < pinfo.size(); i++){ \r\n String pn = pinfo.get(i).packageName; \r\n if(pn.startsWith(packageName)){\r\n \treturn true;\r\n }\r\n //pName.add(pn); \r\n } \r\n } \r\n return false; //pName.contains(packageName);//判断pName中是否有目标程序的包名,有TRUE,没有FALSE \r\n } \r\n}\r", "public class FmeiClient {\r\n\t//public ImageCache cache = null;\r\n\t//需要长时间保存的图片,例如分类,热门。\r\n\tpublic ImageLoader appImgLoader = null;\r\n\t\r\n\t//临时图片加载,比如瀑布流图片。\r\n\tpublic ImageLoader tmpImgLoader = null;\r\n\t\r\n\tpublic String userId = null;\r\n\t//推荐应用下载的用户ID. 应用里面的链接都是包含这个用的PID\r\n\tpublic String trackUserId = null;\r\n\tpublic String trackPID = null;\r\n\t\r\n\t/**\r\n\t * 收藏夹ID.\r\n\t */\r\n\tpublic String favoriteId = null;\r\n\tpublic boolean isInited = false;\r\n\r\n\tprivate static FmeiClient ins = null;\r\n\tprivate TaodianApi api = null;\r\n\tprivate Context ctx = null;\r\n\tprivate AppConfig config = null;\r\n\t\r\n\t//private stai\r\n\t\r\n\tpublic FmeiClient(){\r\n\t\tthis.api = new TaodianApi();\r\n\t}\r\n\t\r\n\tpublic static FmeiClient getInstance(Context ctx){\r\n\t\treturn getInstance(ctx, false);\r\n\t}\r\n\t\r\n\tpublic static synchronized FmeiClient getInstance(Context ctx, boolean check_conn){\r\n\t\tif(ins == null){\r\n\t\t\tins = new FmeiClient();\r\n\t\t}\r\n\t\tif(ctx != null){\r\n\t\t\tins.ctx = ctx;\r\n\t\t\tins.api.ctx = ctx;\r\n\t\t}\r\n\t\tif(ins.appImgLoader == null && ctx != null){\r\n\t\t\tFile picDir = null;\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tpicDir = ctx.getExternalFilesDir(\"doudougou\");\r\n\t\t\t\t}catch(Throwable e){\r\n\t\t\t\t\tLog.w(TAG_EMOP, \"Error:\" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t\tif(picDir == null){\r\n\t\t\t\t\tpicDir = new File(Environment.getExternalStorageDirectory(), \"doudougou\");\r\n\t\t\t\t}\r\n\t\t\t\tLog.i(TAG_EMOP, \"App cache dir:\" + picDir.getAbsolutePath());\r\n\t\t\t\tif(!picDir.isDirectory()){\r\n\t\t\t\t\tif(!picDir.mkdirs()){\r\n\t\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(!picDir.canWrite()){\r\n\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.i(TAG_EMOP, \"The external storage is disabled.\");\t\t\t\t\r\n\t\t\t\tpicDir = ctx.getCacheDir();\t\t\t\t\r\n\t\t\t}\r\n\t\t\tLog.i(TAG_EMOP, \"App image dir:\" + picDir.getAbsolutePath());\r\n\t\t\tins.appImgLoader = new ImageLoader(ctx, picDir, \r\n\t\t\t\t\t0, 8); \r\n\t\t\tins.tmpImgLoader = ins.appImgLoader;\r\n\t\t}\r\n\t\t\r\n\t\tif(check_conn){\r\n\t\t\tins.check_networking(ctx);\r\n\t\t}\r\n\t\treturn ins;\r\n\t}\r\n\t\r\n\tpublic boolean isLogined(){\r\n\t\treturn this.userId != null && this.userId.length() > 0 && Integer.parseInt(this.userId) > 0;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 链接一下taodian API看看网络是否正常。\r\n\t * @param ctx\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult check_networking(Context ctx){\r\n\t\treturn this.api.connect(ctx);\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getTopicList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.TOPIC_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME,\r\n\t\t\t\tTopic.VIEW_ORDER\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得分类列表.\r\n\t */\r\n\tpublic Cursor getCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得热门分类列表.\r\n\t */\r\n\tpublic Cursor getHotCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.HOT_CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\t\r\n\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getItemList(ContentResolver contentResolver, Uri uri){\r\n\t\tLog.d(com.emop.client.Constants.TAG_EMOP, \"on getItemList:\" + uri.toString());\r\n\t\t\r\n\t\tCursor c = contentResolver.query(uri, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Item.SHORT_KEY, Item.PIC_URL,\r\n\t\t\t\tItem.ITEM_CONTENT_TYPE, \r\n\t\t\t\tItem.UPDATE_TIME, Item.WEIBO_ID,\r\n\t\t\t\tItem.PRICE,\r\n\t\t\t\tItem.MESSAGE,\r\n\t\t\t\tItem.RECT_RATE\r\n\t\t}, null, null, null);\r\n\t\t\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri){\r\n\t\treturn refreshDataByUri(contentResolver, uri, TaodianApi.STATUS_NORMAL);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @param async -- 是否异步返回结果。 如果为true数据在后台线程保存到数据库。网络返回后\r\n\t * @return\r\n\t */\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status){\r\n\t\treturn refreshDataByUri(contentResolver, uri, status, false);\r\n\t}\t\r\n\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status, boolean sync){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh uri:\" + uri.toString());\r\n\t\tApiResult r = null;\r\n switch (Schema.FmeiUriMatcher.match(uri)) {\r\n \tcase Schema.TYPE_CATE_ITEM_LIST:\r\n \tcase Schema.TYPE_HOT_ITEM_LIST:\r\n \tcase Schema.TYPE_TOPIC_ITEM_LIST:\r\n \t\tr = refreshTopicItemList(contentResolver, uri, sync, null);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_TOPICS:\r\n \t\tr = this.refreshTopicList(contentResolver, status, \"\");\r\n \t\tbreak;\r\n \tcase Schema.TYPE_CATES:\r\n \t\tr = this.refreshCateList(contentResolver, status);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_HOTS:\r\n \t\tr = this.refreshHotCatList(contentResolver, status);\r\n \tcase Schema.TYPE_ACT_ITEM_LIST:\r\n \t\tr = this.refreshActivityItemList(contentResolver);\r\n \tcase Schema.TYPE_MYFAV_ITEM_LIST:\r\n \t\tr = this.refreshMyFavoriteItemList(contentResolver);\r\n }\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * \r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t */\r\n\tpublic void refreshUri(ContentResolver contentResolver, Uri uri){\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver){\r\n\t\treturn refreshTopicList(contentResolver, TaodianApi.STATUS_NORMAL, \"\");\r\n\t}\r\n\t/**\r\n\t * 刷新专题列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver, int status, String noCache){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refreshList....\");\r\n\t\tApiResult r = this.api.getTopicList(10, status, noCache);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.TOPIC_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\t//contentResolver.notifyChange(Schema.TOPIC_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshCateList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh cate List....\");\r\n\t\tApiResult r = this.api.getCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshHotCatList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh hot cate List....\");\r\n\t\tApiResult r = this.api.getHotCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.HOT_CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshActList(ContentResolver contentResolver){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh act topic List....\");\r\n\t\tApiResult r = this.api.getActList(1, TaodianApi.STATUS_NORMAL);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新专题图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, int topic_id){\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/topic/\" + topic_id + \"/list\");\r\n\t\t\r\n\t\treturn this.refreshTopicItemList(contentResolver, topicList);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 刷新活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshActivityItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tint topicId = getActivityTopicId(contentResolver);\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/act/\" + topicId + \"/list\");\t\t\r\n\t\tr = this.refreshTopicItemList(contentResolver, topicList);\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新我的收藏活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshMyFavoriteItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tif(this.isLogined()){\r\n\t\t\tString fid = this.getFavoriteId();\r\n\t\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/myfav/\" + fid + \"/list\");\t\r\n\t\t\tLog.e(Constants.TAG_EMOP, \"refresh myfav item list:\" + fid);\r\n\t\t\tr = this.api.getMyFavoriteItemList(fid, this.userId);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\tJSONObject json = null;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t\t}\t\t\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\t\r\n\t\r\n\t/**\r\n\t * 链接活动页,也是一个特殊的专题活动。取到专题的ID.\r\n\t * @return\r\n\t */\r\n\tpublic int getActivityTopicId(ContentResolver contentResolver){\r\n\t\tint topicId = 0;\r\n\t\tCursor c = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\r\n\t\tif(c.getCount() == 0){\r\n\t\t\tthis.refreshActList(contentResolver);\r\n\t\t\tif(c != null)c.close();\r\n\t\t\tc = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\t\t\t\r\n\t\t}\r\n\t\tif(c.getCount() > 0){\r\n\t\t\tc.moveToFirst();\r\n\t\t\tint topic = c.getColumnIndex(BaseColumns._ID);\r\n\t\t\ttopicId = c.getInt(topic);\t\t\t\r\n\t\t}\r\n\t\tif(c != null)c.close();\r\n\t\treturn topicId;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, Uri topicList){\r\n\t\treturn refreshTopicItemList(contentResolver, topicList, false, null);\r\n\t}\r\n\tpublic ApiResult refreshTopicItemList(final ContentResolver contentResolver, final Uri topicList, boolean sync, String force){\r\n\t\tint topic_id = Integer.parseInt(topicList.getPathSegments().get(1)); // (int) ContentUris.parseId(uri);\r\n\t\tString cate = topicList.getPathSegments().get(0);\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh item list:\" + topic_id);\r\n\t\tString pageSize = topicList.getQueryParameter(\"pageSize\");\r\n\t\tString pageNo = topicList.getQueryParameter(\"pageNo\");\r\n\t\tString noCache = topicList.getQueryParameter(\"no_cache\");\r\n\t\tif(force != null && force.equals(\"y\")){\r\n\t\t\tnoCache = \"y\";\r\n\t\t}\r\n\t\t\r\n\t\tint size = 100;\r\n\t\ttry{\r\n\t\t\tsize = Integer.parseInt(pageSize);\r\n\t\t}catch(Throwable e){}\r\n\t\tfinal ApiResult r;\r\n\t\tif(cate.equals(\"act\")){\r\n\t\t\tr = this.api.getTopicItemList(topic_id, size, pageNo);\r\n\t\t}else if(cate.equals(\"shop\")){\r\n\t\t\tr = this.api.getShopItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}else {\r\n\t\t\tr = this.api.getTopicPidItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tRunnable task = new Runnable(){\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tJSONObject json = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcontentResolver.notifyChange(topicList, null);\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t};\r\n\t\t\t\r\n\t\t\tif(sync){\r\n\t\t\t\tnew Thread(task).start();\r\n\t\t\t}else {\r\n\t\t\t\ttask.run();\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过网络查询当前应用的最新版本。\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkUpgradeVersion(){\r\n\t\tApiResult r = this.api.call(\"cms_app_version_check\", null);\t\t\r\n\t\t//PackageManager packageManager = ctx.getPackageManager();\r\n\t\t//PackageInfo packInfo packageManager.getp\t\t\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key){\r\n\t\treturn addFavorite(weiboId, desc, picUrl, numId, shopId, short_url_key, \"taoke\");\r\n\t}\r\n\t\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key, String contentType){\r\n\t\tLog.d(TAG_EMOP, \"add fav, weiboId:\" + weiboId + \", numId:\" + numId + \", shopId:\" + shopId + \", picUrl:\" + picUrl);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\t\tparam.put(\"pic_url\", picUrl);\r\n\t\tparam.put(\"content_type\", contentType);\r\n\t\tparam.put(\"num_iid\", numId);\r\n\t\tparam.put(\"shop_id\", shopId);\r\n\t\tparam.put(\"short_url_key\", short_url_key);\r\n\t\t\r\n\t\tparam.put(\"item_text\", desc);\r\n\t\tr = api.call(\"tuji_topic_add_item\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult removeFavorite(String weiboId){\r\n\t\tLog.d(TAG_EMOP, \"remove fav, weiboId:\" + weiboId);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\r\n\t\tr = api.call(\"tuji_topic_remove_items\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * 加载应用配置信息,例如:sina key,什么的。\r\n\t * @return\r\n\t */\r\n\tpublic AppConfig config(){\r\n\t\tif(config == null){\r\n\t\t\tconfig = new AppConfig();\r\n\t\t\tApiResult r = api.call(\"cms_app_config_info\", null);\r\n\t\t\tif(r != null && r.isOK){\r\n\t\t\t\tconfig.json = r.getJSONObject(\"data\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn config;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 绑定外部登录用户信息,到美觅网系统。\r\n\t * @param source\r\n\t * @param userId\r\n\t * @param token\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult bindUserInfo(String source, String userId, String token){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"source\", source);\r\n\t\tparam.put(\"ref_id\", userId);\r\n\t\tparam.put(\"access_token\", token);\r\n\t\tif(this.userId != null){\r\n\t\t\tparam.put(\"user_id\", this.userId);\r\n\t\t}\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_bind_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult registerUser(Map<String, Object> param){\t\r\n\t\t/**\r\n\t\t * 有user_id是通过,第三方帐号绑定过来。已经生成了user_id.\r\n\t\t * 没有user_id是在应用里面,直接注册的。\r\n\t\t */\r\n\t\tApiResult r = null;\r\n\t\tObject user_id = param.get(\"user_id\");\r\n\t\tif(user_id != null && user_id.toString().length() > 0){\r\n\t\t\tr = api.call(\"user_update_info\", param);\r\n\t\t}else {\r\n\t\t\tr = api.call(\"user_register_new\", param);\r\n\t\t}\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult login(String email, String password){\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"email\", email);\r\n\t\tparam.put(\"password\", password);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void saveLoginUser(Activity ctx, String userId){\r\n\t\tthis.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, userId);\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void saveRefUser(Activity ctx, String source, String userId, String nick){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.putString(Constants.PREFS_SINA_UID, userId);\r\n \teditor.putString(Constants.PREFS_SINA_NICK, nick);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.putString(Constants.PREFS_TAOBAO_UID, userId);\r\n \teditor.putString(Constants.PREFS_TAOBAO_NICK, nick); \t\t\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.putString(Constants.PREFS_QQ_UID, userId);\r\n \teditor.putString(Constants.PREFS_QQ_NICK, nick); \t\t\r\n \t}\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void removeRefUser(Activity ctx, String source){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.remove(Constants.PREFS_SINA_UID);\r\n \t\teditor.remove(Constants.PREFS_SINA_NICK);\r\n \t\teditor.remove(Constants.PREFS_SINA_ACCESS_TOKEN);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_UID);\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_NICK);\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t}\r\n \teditor.commit();\r\n \tString sina = settings.getString(Constants.PREFS_SINA_UID, \"\");\r\n \tString taobao = settings.getString(Constants.PREFS_TAOBAO_UID, \"\");\r\n \tString qq = settings.getString(Constants.PREFS_QQ_UID, \"\");\r\n \t\r\n \tif((sina == null || sina.trim().length() == 0) &&\r\n \t (taobao == null || taobao.trim().length() == 0) &&\r\n \t (qq == null || qq.trim().length() == 0)\r\n \t){\r\n \t\tlogout(ctx);\r\n \t} \t\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\t\r\n\t\r\n\tpublic void logout(Activity ctx){\r\n\t\tthis.userId = null;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, \"0\");\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"logout:\" + userId);\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 我的收藏夹Id.\r\n\t * @return\r\n\t */\r\n\tpublic String getFavoriteId(){\r\n\t\tif((this.favoriteId == null || this.favoriteId.length() == 0) &&\r\n\t\t\t\tthis.isLogined()){\r\n\t\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\t\tparam.put(\"user_id\", userId);\r\n\t\t\tparam.put(\"cate\", 1);\r\n\t\t\tparam.put(\"topic_name\", \"收藏夹\");\r\n\t\t\tparam.put(\"item_head_count\", 0);\r\n\t\t\tparam.put(\"status\", TaodianApi.STATUS_NORMAL);\r\n\t\t\t\r\n\t\t\tApiResult r = api.call(\"tuji_user_topic_list\", param);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\t int count = Integer.parseInt(r.getString(\"data.item_count\").toString());\r\n\t\t\t\t if(count > 0){\r\n\t\t\t\t\t JSONObject obj = r.getJSONObject(\"data\");\r\n\t\t\t\t\t JSONArray items;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\titems = obj.getJSONArray(\"items\");\r\n\t\t\t\t\t\tthis.favoriteId = items.getJSONObject(0).getString(\"id\");\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\tLog.e(TAG_EMOP, \"Get favoriate ID error:\" + e.toString(), e);\r\n\t\t\t\t\t}\r\n\t\t\t\t }\r\n\t\t\t}\r\n\t\t\tif(this.favoriteId == null || this.favoriteId.length() == 0){\r\n\t\t\t\tr = api.call(\"tuji_create_topic\", param);\r\n\t\t\t\tif(r.isOK){\r\n\t\t\t\t\tthis.favoriteId = r.getString(\"data.topic_id\");\r\n\t\t\t\t}\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.favoriteId;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 检查用户PID是否合法。先跳过不检查。\r\n\t * @param id\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkTrackId(String id){\r\n\t\tApiResult r = new ApiResult();\r\n\t\tr.isOK = true;\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void cleanExpiredData(ContentResolver contentResolver){\r\n\t\tLog.d(Constants.TAG_EMOP, \"cleanExpiredData....\");\r\n\t\tcontentResolver.delete(Schema.TOPIC_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.ITME_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 5) + \"\"});\t\r\n\t\t\r\n\t\tcontentResolver.delete(Schema.REBATE_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.SHOP_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 更加ID加载单条内容。主要用在,应用从外部启动后。直接进入详情页面。\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult getWeiboInfo(String uuid){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uuid\", uuid);\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"cms_get_uuid_content\", param);\t\t\r\n\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult getTrackPid(){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uid\", this.trackUserId);\r\n\t\tApiResult r = api.call(\"emop_user_pid\", param);\t\t\r\n\t\tthis.trackPID = r.getString(\"data.pid\");\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult updateTrackId(){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"track_user_id\", trackUserId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_update_track_id\", param);\t\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tString tid = r.getString(\"data.track_user_id\");\r\n\t\t\tif(tid != null && tid.trim().length() > 0){\r\n\t\t\t\ttrackUserId = tid;\r\n\t\t\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\t \tSharedPreferences.Editor editor = settings.edit();\r\n\t\t \teditor.putString(Constants.PREFS_TRACK_ID, tid);\r\n\t\t \teditor.commit();\r\n\t\t\t}\r\n\t\t\tLog.d(\"xx\", \"update task as:\" + tid);\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 1. 读取sd卡\r\n\t * 2. 读取应用meta\r\n\t */\r\n\tpublic void updateLocalTrackId(){\r\n\t\tboolean writeSetting = false;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\ttrackUserId = settings.getString(Constants.PREFS_TRACK_ID, null);\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\twriteSetting = true;\r\n\t\t\ttrackUserId = readTrackIdFromSD();\r\n\t\t}\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\ttrackUserId = getMetaDataValue(\"emop_track_id\");\r\n\t\t\t//测试模式下,track id还没有替换时。默认是EMOP_USER\r\n\t\t\tif(trackUserId != null && trackUserId.equals(\"EMOP_USER\")){\r\n\t\t\t\ttrackUserId = \"11\";\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track from meta:\" + trackUserId);\r\n\t\t}\r\n\t\tif(trackUserId != null && trackUserId.trim().length() > 0){\r\n\t\t\tif(writeSetting){\r\n\t\t\t\tsaveSettings(Constants.PREFS_TRACK_ID, trackUserId);\r\n\t\t\t}\r\n\t\t\tWriteTrackIdToSD(trackUserId);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void WriteTrackIdToSD(String tid){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tOutputStream os = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"write track user pid:'\" + tid + \"' to:\" + track.getAbsolutePath());\r\n\t\t\tos = new FileOutputStream(track);\r\n\t\t\tif(os != null){\r\n\t\t\t\tos.write(tid.getBytes());\r\n\t\t\t}\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.d(TAG_EMOP, \"write error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(os != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tos.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\t\r\n\tprivate String readTrackIdFromSD(){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tBufferedReader input = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track user from:\" + track.getAbsolutePath());\r\n\t\t\tif(track.isFile()){\r\n\t\t\t\tinput = new BufferedReader(new InputStreamReader(new FileInputStream(track)));\r\n\t\t\t\tpid = input.readLine();\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read pid in sdcard:\" + pid);\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.e(TAG_EMOP, \"read pid error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(input != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn pid;\r\n\t}\r\n\t\r\n private String getMetaDataValue(String name) {\r\n Object value = null;\r\n PackageManager packageManager = ctx.getPackageManager();\r\n ApplicationInfo applicationInfo;\r\n try {\r\n applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);\r\n if (applicationInfo != null && applicationInfo.metaData != null) {\r\n value = applicationInfo.metaData.get(name);\r\n }\r\n } catch (NameNotFoundException e) {\r\n throw new RuntimeException(\r\n \"Could not read the name in the manifest file.\", e);\r\n }\r\n if (value == null) {\r\n throw new RuntimeException(\"The name '\" + name\r\n + \"' is not defined in the manifest file's meta data.\");\r\n }\r\n return value.toString();\r\n }\t\r\n\t\t\r\n\tpublic String getSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n\r\n\tpublic String saveSettings(String key, String value){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(key, value);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\t\r\n\tpublic String removeSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.remove(key);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n}\r", "public class QueryParam {\r\n\tpublic final static String PAGE_SIZE = \"pageSize\";\r\n\tpublic final static String PAGE_NO = \"pageNo\";\r\n\t\r\n\tpublic String selection;\r\n\tpublic String[] selectionArgs;\r\n\tpublic String sortOrder;\r\n\tpublic String groupBy;\r\n\tpublic String having;\r\n\tpublic QueryParam(String sel, String[] args, String order){\r\n\t\tthis.selection = sel;\r\n\t\tthis.selectionArgs = args;\r\n\t\tthis.sortOrder = order;\r\n\t}\r\n}\r", "public class Rebate {\r\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/vnd.fmei.rebates\";\r\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.fmei.rebate\";\r\n\t\r\n\tpublic static final String DB_TABLE_NAME = \"rebate\";\r\n\t\r\n\tpublic static final String LOCAL_CATE = \"local_cate\";\r\n\tpublic static final String SHORT_KEY = \"short_url_key\";\r\n\tpublic static final String NUM_IID = \"num_iid\";\r\n\tpublic static final String SHOP_ID = \"shop_id\";\r\n\tpublic static final String TITLE = \"title\";\r\n\tpublic static final String PIC_URL = \"pic_url\";\r\n\r\n\tpublic static final String PRICE = \"price\";\r\n\tpublic static final String COUPON_PRICE = \"coupon_price\";\r\n\tpublic static final String COUPON_RATE = \"coupon_rate\";\r\n\tpublic static final String COUPON_START_TIME = \"coupon_start_time\";\r\n\t\r\n\t\r\n\tpublic static final String COUPON_END_TIME = \"coupon_end_time\";\r\n\tpublic static final String ROOT_CATE = \"root_tag\";\r\n\r\n\tpublic static final String LOCAL_UPDATE_TIME = \"local_update\";\r\n\tpublic static final String WEIGHT = \"weight\";\r\n\t\r\n\tpublic static Uri update(SQLiteDatabase db, Uri uri, ContentValues values){\r\n\t\t\r\n\t\tString taskId = values.getAsString(NUM_IID);\r\n\t\t//values.remove(\"id\");\r\n\t\tList<String> seg = uri.getPathSegments(); //.get(1);\r\n\t\tvalues.put(LOCAL_UPDATE_TIME, System.currentTimeMillis());\r\n int count = db.update(DB_TABLE_NAME, values, BaseColumns._ID + \"=?\", new String[]{taskId});\r\n\t\tif(count == 0){\r\n\t\t\t//Log.d(Constants.TAG_EMOP, String.format(\"insert new item '%s:%s'\", taskId,\r\n\t\t\t//\t\tvalues.getAsString(WEIBO_ID)));\r\n\t\t\tvalues.put(BaseColumns._ID, taskId);\r\n\t\t\tdb.insert(DB_TABLE_NAME, NUM_IID, values);\r\n\t\t}else {\r\n\t\t\t//Log.d(Constants.TAG_EMOP, String.format(\"update rebate info'%s:%s'\", taskId,\r\n\t\t\t//\t\tvalues.getAsString(SHORT_KEY) + \", cate:\" + values.getAsString(ROOT_CATE)));\r\n\t\t}\t\t\r\n\t\t\r\n\t\treturn null;\t\t\t\r\n\t}\r\n\t\r\n\t\r\n\tpublic static void buildRebateListQuery(SQLiteQueryBuilder builder, \r\n\t\t\tString[] fileds, QueryParam param, Uri uri){\r\n\t\tbuilder.setTables(DB_TABLE_NAME);\t\r\n\t\tString cate = uri.getQueryParameter(\"cate\");\r\n\t\t\r\n\t\tif(cate != null){\r\n\t\t\tbuilder.appendWhere(ROOT_CATE + \"='\" + cate + \"'\");\r\n\t\t}\r\n\t\t\r\n\t\tparam.sortOrder = COUPON_START_TIME + \" \" + \"desc, local_update desc\";\r\n\t}\r\n\t\r\n\tpublic static ContentValues convertJson(JSONObject obj){\r\n\t\tContentValues v = new ContentValues();\r\n\t\ttry{\r\n\t\t\tif(obj.has(\"id\")){\r\n\t\t\t\tv.put(\"id\", obj.getInt(\"id\"));\r\n\t\t\t}\r\n\t\t\tif(obj.has(SHORT_KEY)){\r\n\t\t\t\tv.put(SHORT_KEY, obj.getString(SHORT_KEY));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(NUM_IID)){\r\n\t\t\t\tv.put(NUM_IID, obj.getString(NUM_IID));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(SHOP_ID)){\r\n\t\t\t\tv.put(SHOP_ID, obj.getString(SHOP_ID));\r\n\t\t\t}\r\n\t\r\n\t\t\tif(obj.has(TITLE)){\r\n\t\t\t\tv.put(TITLE, obj.getString(TITLE));\r\n\t\t\t}\t\r\n\t\t\t\r\n\t\t\tif(obj.has(PIC_URL)){\r\n\t\t\t\tv.put(PIC_URL, obj.getString(PIC_URL));\r\n\t\t\t}\t\r\n\r\n\t\t\tif(obj.has(PRICE)){\r\n\t\t\t\tv.put(PRICE, obj.getString(PRICE));\r\n\t\t\t}\t\t\t\r\n\t\t\t\r\n\t\t\tif(obj.has(COUPON_PRICE)){\r\n\t\t\t\tv.put(COUPON_PRICE, obj.getString(COUPON_PRICE));\r\n\t\t\t}\t\t\r\n\t\t\tif(obj.has(COUPON_RATE)){\r\n\t\t\t\tv.put(COUPON_RATE, obj.getString(COUPON_RATE));\r\n\t\t\t}\r\n\t\t\tif(obj.has(COUPON_END_TIME) && obj.getString(COUPON_END_TIME) != null){\r\n\t\t\t\tv.put(COUPON_END_TIME, obj.getString(COUPON_END_TIME));\r\n\t\t\t}\r\n\t\t\tif(obj.has(COUPON_START_TIME) && obj.getString(COUPON_START_TIME) != null){\r\n\t\t\t\tv.put(COUPON_START_TIME, obj.getString(COUPON_START_TIME));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(ROOT_CATE)){\r\n\t\t\t\tv.put(ROOT_CATE, obj.getString(ROOT_CATE));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(LOCAL_UPDATE_TIME)){\r\n\t\t\t\tv.put(LOCAL_UPDATE_TIME, obj.getString(LOCAL_UPDATE_TIME));\r\n\t\t\t}\t\r\n\t\t\tif(obj.has(WEIGHT)){\r\n\t\t\t\tv.put(WEIGHT, obj.getString(WEIGHT));\r\n\t\t\t}\t\t\t\r\n\t\t}catch (JSONException e) {\r\n\t\t\tLog.e(Constants.TAG_EMOP, e.toString());\r\n\t\t}\r\n\t\t\r\n\t\treturn v;\t\r\n\t}\r\n\r\n}\r", "public class TimeHelper {\r\n\tpublic static DateFormat timeFormat = new SimpleDateFormat(\"HH:mm:ss\");\r\n\tpublic static DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\r\n\tpublic static DateFormat dateTimeFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\r\n\t\r\n\tpublic static String formatTime(Date time){\r\n\t\treturn timeFormat.format(time);\r\n\t}\r\n\r\n\tpublic static String formatDate(Date time){\r\n\t\treturn dateFormat.format(time);\r\n\t}\r\n\t\r\n\tpublic static String formatDateTime(Date time){\r\n\t\treturn dateTimeFormat.format(time);\r\n\t}\r\n\r\n\tpublic static Date parseDateTime(String time){\r\n\t\ttry {\r\n\t\t\treturn dateTimeFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Date parseDate(String time){\r\n\t\ttry {\r\n\t\t\treturn dateFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Date parseTime(String time){\r\n\t\ttry {\r\n\t\t\treturn timeFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static String formatRemainHour(String end, int maxDate){\r\n\t\tDate date = parseDateTime(end);\r\n\t\tif(date != null && date.getTime() > System.currentTimeMillis()){\r\n\t\t\tlong time = date.getTime() - System.currentTimeMillis();\r\n\t\t\tlong minutes = time / 1000 / 60;\r\n\t\t\t\r\n\t\t\tlong reDay = (minutes / (60 * 24)) % maxDate;\r\n\t\t\t\r\n\t\t\tlong reHour = (minutes % (60 * 24)) / 60;\r\n\t\t\tlong reMin = minutes % 60;\r\n\t\t\treturn String.format(\"%s天%s小时%s分\", reDay, reHour, reMin);\r\n\t\t\t\r\n\t\t}\r\n\t\treturn \"0小时0分\";\r\n\t}\r\n}\r" ]
import java.util.TreeSet; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StrikethroughSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ListView; import android.widget.TextView; import com.baidu.mobstat.StatService; import com.emop.client.R; import com.emop.client.WebViewActivity; import com.emop.client.io.FmeiClient; import com.emop.client.provider.QueryParam; import com.emop.client.provider.model.Rebate; import com.emop.client.utils.TimeHelper;
package com.emop.client.fragment; public class RebateListFragment extends ListFragment{ public final static int MAX_LIST_COUNT = 600; public int cateId = 0; private RebateListAdapter adapter = null; protected Handler handler = new Handler(); protected boolean isRunning = false;
protected FmeiClient client = null;
1
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/ui/DownloadActivity.java
[ "public class YouTubeFragmentedVideo\n{\n public int height;\n public YtFile audioFile;\n public YtFile videoFile;\n}", "public final class Config\n{\n public static final String APP_NAME = \"yib\";\n public static final String LOG_PREFIX = \"[\" + APP_NAME + \"]\";\n\n // YouTube Media Type\n public static final int YOUTUBE_MEDIA_NO_NEW_REQUEST = -1;\n public static final int YOUTUBE_MEDIA_TYPE_VIDEO = 0;\n public static final int YOUTUBE_MEDIA_TYPE_PLAYLIST = 1;\n\n public static final String KEY_YOUTUBE_TYPE = \"YT_MEDIA_TYPE\";\n public static final String KEY_YOUTUBE_TYPE_VIDEO = \"YT_VIDEO\";\n public static final String KEY_YOUTUBE_TYPE_PLAYLIST = \"YT_PLAYLIST\";\n public static final String KEY_YOUTUBE_TYPE_PLAYLIST_VIDEO_POS = \"YT_PLAYLIST_VIDEO_POS\";\n\n public static final String YOUTUBE_LINK = \"YT_DOWNLOAD_LINK\";\n public static final String YOUTUBE_API_KEY = \"AIzaSyAN074XUjainWwyXkhv2hergNIlh2uTWUc\";\n\n // Media Session Token\"\n public static final String INTENT_SESSION_TOKEN = \"com.teocci.ytinbg.SESSION_TOKEN\";\n public static final String KEY_SESSION_TOKEN = \"SESSION_TOKEN\";\n\n // Download properties\n public static final int YT_ITAG_FOR_AUDIO = 140;\n\n public static final String YT_SHORT_LINK = \"://youtu.be/\";\n public static final String YT_WATCH_LINK = \"youtube.com/watch?v=\";\n public static final String YT_PREFIX_LINK = \"https://youtu.be/\";\n\n public static final String YT_REGEX = \"(?:[?&]vi?=|\\\\/embed\\\\/|\\\\/\\\\d\\\\d?\\\\/|\\\\/vi?\\\\/|https?:\\\\/\\\\/(?:www\\\\\" +\n \".)?youtu\\\\.be\\\\/)([A-Za-z0-9_\\\\-]{11})\";\n\n\n public static final String ACCOUNT_NAME = \"GOOGLE_ACCOUNT_NAME\";\n\n public static final long MAX_VIDEOS_RETURNED = 50; //due to YouTube API rules - MAX 50\n\n // Resolution reasonable for carrying around as an icon (generally in\n // MediaDescription.getIconBitmap). This should not be bigger than necessary, because\n // the MediaDescription object should be lightweight. If you set it too high and try to\n // serialize the MediaDescription, you may get FAILED BINDER TRANSACTION errors.\n public static final int MAX_WIDTH_ICON = 128; // pixels\n public static final int MAX_HEIGHT_ICON = 128; // pixels\n\n // The action of the incoming Intent indicating that it contains a command\n // to be executed (see {@link #onStartCommand})\n public static final String ACTION_CMD = \"com.teocci.ytinbg.ACTION_CMD\";\n // The key in the extras of the incoming Intent indicating the command that\n // should be executed (see {@link #onStartCommand})\n public static final String CMD_NAME = \"CMD_NAME\";\n // A value of a CMD_NAME key in the extras of the incoming Intent that\n // indicates that the music playback should be paused (see {@link #onStartCommand})\n public static final String CMD_PAUSE = \"CMD_PAUSE\";\n\n public static final String KEY_LOCK = \"YTinBG_lock\";\n\n // Action to thumbs up a media item\n public static final String CUSTOM_ACTION_THUMBS_UP = \"com.teocci.ytinbg.THUMBS_UP\";\n public static final String EXTRA_START_FULLSCREEN = \"com.teocci.ytinbg.EXTRA_START_FULLSCREEN\";\n\n /**\n * Optionally used with {@link #EXTRA_START_FULLSCREEN} to carry a MediaDescription to\n * the {@link MainActivity}, speeding up the screen rendering\n * while the {@link android.support.v4.media.session.MediaControllerCompat} is connecting.\n */\n public static final String EXTRA_CURRENT_MEDIA_DESCRIPTION = \"com.teocci.ytinbg.CURRENT_MEDIA_DESCRIPTION\";\n \n public static final String CUSTOM_ACTION_PAUSE = \"com.teocci.ytinbg.pause\";\n public static final String CUSTOM_ACTION_PLAY = \"com.teocci.ytinbg.play\";\n public static final String CUSTOM_ACTION_PREV = \"com.teocci.ytinbg.prev\";\n public static final String CUSTOM_ACTION_NEXT = \"com.teocci.ytinbg.next\";\n public static final String CUSTOM_ACTION_STOP = \"com.teocci.ytinbg.stop\";\n\n public static final String MODE_REPEAT_ONE = \"mode_repeat_one\";\n public static final String MODE_REPEAT_ALL = \"mode_repeat_all\";\n public static final String MODE_REPEAT_NONE = \"mode_repeat_none\";\n public static final String MODE_SHUFFLE = \"mode_shuffle\";\n\n\n public static final String YOUTUBE_CHANNEL_LIST = \"snippet\";\n\n // See: https://developers.google.com/youtube/v3/docs/playlistItems/list\n public static final String YOUTUBE_PLAYLIST_PART = \"id,snippet,contentDetails,status\";\n public static final String YOUTUBE_PLAYLIST_FIELDS = \"items(id,snippet/title,snippet/thumbnails/default/url,\" +\n \"contentDetails/itemCount,status)\";\n public static final String YOUTUBE_ACQUIRE_PLAYLIST_PART = \"id,contentDetails,snippet\";\n public static final String YOUTUBE_ACQUIRE_PLAYLIST_FIELDS = \"items(contentDetails/videoId,snippet/title,\" +\n \"snippet/thumbnails/default/url),nextPageToken\";\n\n // See: https://developers.google.com/youtube/v3/docs/videos/list\n public static final String YOUTUBE_SEARCH_LIST_TYPE = \"video\";\n public static final String YOUTUBE_SEARCH_LIST_PART = \"id,snippet\";\n public static final String YOUTUBE_SEARCH_LIST_FIELDS = \"pageInfo,nextPageToken,items(id/videoId,snippet/title,\" +\n \"snippet/thumbnails/default/url)\";\n public static final String YOUTUBE_VIDEO_LIST_PART = \"id,contentDetails,statistics\";\n public static final String YOUTUBE_VIDEO_LIST_FIELDS = \"items(contentDetails/duration,statistics/viewCount)\";\n\n\n public static final String YOUTUBE_VIDEO_PART = \"id,snippet,contentDetails,statistics\";\n public static final String YOUTUBE_VIDEO_FIELDS = \"items(id,snippet/title,\" +\n \"snippet/thumbnails/default/url,contentDetails/duration,statistics/viewCount)\";\n\n public static final String YOUTUBE_PLAYLIST_VIDEO_PART = \"id,contentDetails\";\n public static final String YOUTUBE_PLAYLIST_VIDEO_FIELDS = \"items(contentDetails/duration)\" +\n \"statistics/viewCount)\";\n\n public static final String YOUTUBE_LANGUAGE_KEY = \"hl\";\n // video resource properties that the response will include.\n // selector specifying which fields to include in a partial response.\n\n public static final int YOUTUBE_ITAG_251 = 251; // webm - stereo, 48 KHz 160 Kbps (opus)\n public static final int YOUTUBE_ITAG_250 = 250; // webm - stereo, 48 KHz 64 Kbps (opus)\n public static final int YOUTUBE_ITAG_249 = 249; // webm - stereo, 48 KHz 48 Kbps (opus)\n public static final int YOUTUBE_ITAG_171 = 171; // webm - stereo, 48 KHz 128 Kbps (vortis)\n public static final int YOUTUBE_ITAG_141 = 141; // mp4a - stereo, 44.1 KHz 256 Kbps (aac)\n public static final int YOUTUBE_ITAG_140 = 140; // mp4a - stereo, 44.1 KHz 128 Kbps (aac)\n public static final int YOUTUBE_ITAG_43 = 43; // webm - stereo, 44.1 KHz 128 Kbps (vortis)\n public static final int YOUTUBE_ITAG_22 = 22; // mp4 - stereo, 44.1 KHz 192 Kbps (aac)\n public static final int YOUTUBE_ITAG_18 = 18; // mp4 - stereo, 44.1 KHz 96 Kbps (aac)\n public static final int YOUTUBE_ITAG_36 = 36; // mp4 - stereo, 44.1 KHz 32 Kbps (aac)\n public static final int YOUTUBE_ITAG_17 = 17; // mp4 - stereo, 44.1 KHz 24 Kbps (aac)\n}", "public class VideoMeta {\n\n private static final String IMAGE_BASE_URL = \"http://i.ytimg.com/vi/\";\n\n private String videoId;\n private String title;\n\n private String author;\n private String channelId;\n\n private long videoLength;\n private long viewCount;\n\n private boolean isLiveStream;\n\n protected VideoMeta(String videoId, String title, String author, String channelId, long videoLength, long viewCount, boolean isLiveStream) {\n this.videoId = videoId;\n this.title = title;\n this.author = author;\n this.channelId = channelId;\n this.videoLength = videoLength;\n this.viewCount = viewCount;\n this.isLiveStream = isLiveStream;\n }\n\n\n // 120 x 90\n public String getThumbUrl() {\n return IMAGE_BASE_URL + videoId + \"/default.jpg\";\n }\n\n // 320 x 180\n public String getMqImageUrl() {\n return IMAGE_BASE_URL + videoId + \"/mqdefault.jpg\";\n }\n\n // 480 x 360\n public String getHqImageUrl() {\n return IMAGE_BASE_URL + videoId + \"/hqdefault.jpg\";\n }\n\n // 640 x 480\n public String getSdImageUrl() {\n return IMAGE_BASE_URL + videoId + \"/sddefault.jpg\";\n }\n\n // Max Res\n public String getMaxResImageUrl() {\n return IMAGE_BASE_URL + videoId + \"/maxresdefault.jpg\";\n }\n\n public String getVideoId() {\n return videoId;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public String getChannelId() {\n return channelId;\n }\n\n public boolean isLiveStream() {\n return isLiveStream;\n }\n\n /**\n * The video length in seconds.\n */\n public long getVideoLength() {\n return videoLength;\n }\n\n public long getViewCount() {\n return viewCount;\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 VideoMeta videoMeta = (VideoMeta) o;\n\n if (videoLength != videoMeta.videoLength) return false;\n if (viewCount != videoMeta.viewCount) return false;\n if (isLiveStream != videoMeta.isLiveStream) return false;\n if (videoId != null ? !videoId.equals(videoMeta.videoId) : videoMeta.videoId != null)\n return false;\n if (title != null ? !title.equals(videoMeta.title) : videoMeta.title != null) return false;\n if (author != null ? !author.equals(videoMeta.author) : videoMeta.author != null)\n return false;\n return channelId != null ? channelId.equals(videoMeta.channelId) : videoMeta.channelId == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = videoId != null ? videoId.hashCode() : 0;\n result = 31 * result + (title != null ? title.hashCode() : 0);\n result = 31 * result + (author != null ? author.hashCode() : 0);\n result = 31 * result + (channelId != null ? channelId.hashCode() : 0);\n result = 31 * result + (int) (videoLength ^ (videoLength >>> 32));\n result = 31 * result + (int) (viewCount ^ (viewCount >>> 32));\n result = 31 * result + (isLiveStream ? 1 : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"VideoMeta{\" +\n \"videoId='\" + videoId + '\\'' +\n \", title='\" + title + '\\'' +\n \", author='\" + author + '\\'' +\n \", channelId='\" + channelId + '\\'' +\n \", videoLength=\" + videoLength +\n \", viewCount=\" + viewCount +\n \", isLiveStream=\" + isLiveStream +\n '}';\n }\n}", "public abstract class YouTubeExtractor extends AsyncTask<String, Void, SparseArray<YtFile>>\n{\n\n private final static boolean CACHING = true;\n\n protected static boolean LOGGING = false;\n\n private final static String LOG_TAG = \"YouTubeExtractor\";\n private final static String CACHE_FILE_NAME = \"decipher_js_funct\";\n private final static int DASH_PARSE_RETRIES = 5;\n\n protected WeakReference<Context> weakContext;\n // private Context context;\n private String videoID;\n private VideoMeta videoMeta;\n private boolean includeWebM = true;\n private boolean useHttp = false;\n private boolean parseDashManifest = false;\n private String cacheDirPath;\n\n private volatile String decipheredSignature;\n\n private static String decipherJsFileName;\n private static String decipherFunctions;\n private static String decipherFunctionName;\n\n private final Lock lock = new ReentrantLock();\n private final Condition jsExecuting = lock.newCondition();\n\n private static final String USER_AGENT = \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36\";\n private static final String STREAM_MAP_STRING = \"url_encoded_fmt_stream_map\";\n\n private static final Pattern patYouTubePageLink = Pattern.compile(\"(http|https)://(www\\\\.|m.|)youtube\\\\.com/watch\\\\?v=(.+?)( |\\\\z|&)\");\n private static final Pattern patYouTubeShortLink = Pattern.compile(\"(http|https)://(www\\\\.|)youtu.be/(.+?)( |\\\\z|&)\");\n\n private static final Pattern patDashManifest1 = Pattern.compile(\"dashmpd=(.+?)(&|\\\\z)\");\n private static final Pattern patDashManifest2 = Pattern.compile(\"\\\"dashmpd\\\":\\\"(.+?)\\\"\");\n private static final Pattern patDashManifestEncSig = Pattern.compile(\"/s/([0-9A-F|.]{10,}?)(/|\\\\z)\");\n\n private static final Pattern patTitle = Pattern.compile(\"title%22%3A%22(.*?)(%22|\\\\z)\");\n private static final Pattern patAuthor = Pattern.compile(\"author%22%3A%22(.+?)(%22|\\\\z)\");\n private static final Pattern patChannelId = Pattern.compile(\"channelId%22%3A%22(.+?)(%22|\\\\z)\");\n private static final Pattern patLength = Pattern.compile(\"lengthSeconds%22%3A%22(\\\\d+?)(%22|\\\\z)\");\n private static final Pattern patViewCount = Pattern.compile(\"viewCount%22%3A%22(\\\\d+?)(%22|\\\\z)\");\n private static final Pattern patStatusOk = Pattern.compile(\"status=ok(&|,|\\\\z)\");\n\n private static final Pattern patHlsvp = Pattern.compile(\"hlsvp=(.+?)(&|\\\\z)\");\n private static final Pattern patHlsItag = Pattern.compile(\"/itag/(\\\\d+?)/\");\n\n private static final Pattern patItag = Pattern.compile(\"itag=([0-9]+?)([&,])\");\n\n private static final Pattern patSP = Pattern.compile(\"&sp=([a-z]{2,}?)([&,\\\"])\");\n private static final Pattern patEncSig = Pattern.compile(\"s=([0-9A-F|.]{10,}?)([&,\\\"])\");\n private static final Pattern patIsSigEnc = Pattern.compile(\"s%3D([0-9A-F|.]{10,}?)(%26|%2C|%25)\");\n private static final Pattern patNewEncSig = Pattern.compile(\"(\\\\A|&|\\\")s=([0-9A-Za-z\\\\-_=%]{10,}?)([&,\\\"])\");\n private static final Pattern patIsNewSigEnc = Pattern.compile(\"(%26|%3F|%2C)s%3D([0-9A-Za-z\\\\-_=%]{10,}?)(%26|%2C|\\\\z)\");\n\n private static final Pattern patUrl = Pattern.compile(\"url=(.+?)([&,\\\"\\\\\\\\])\");\n\n private static final Pattern patVariableFunction = Pattern.compile(\"([{; =])([a-zA-Z$][a-zA-Z0-9$]{0,2})\\\\.([a-zA-Z$][a-zA-Z0-9$]{0,2})\\\\(\");\n private static final Pattern patFunction = Pattern.compile(\"([{; =])([a-zA-Z$_][a-zA-Z0-9$]{0,2})\\\\(\");\n\n private static final Pattern patDecryptionJsFile = Pattern.compile(\"jsbin\\\\\\\\/(player(_ias)?-(.+?).js)\");\n// private static final Pattern patSignatureDecFunction = Pattern.compile(\"\\\\(\\\"signature\\\",(.{1,3}?)\\\\(.{1,10}?\\\\)\");\n\n private static final Pattern patSignatureDecFunction = Pattern.compile(\"([\\\\w$]+)\\\\s*=\\\\s*function\\\\(([\\\\w$]+)\\\\).\\\\s*\\\\2=\\\\s*\\\\2\\\\.split\\\\(\\\"\\\"\\\\)\\\\s*;\");\n\n private static final SparseArray<Format> FORMAT_MAP = new SparseArray<>();\n\n static {\n // Video and Audio\n // http://en.wikipedia.org/wiki/YouTube#Quality_and_formats\n\n FORMAT_MAP.put(5, new Format(5, \"flv\", 240, Format.VCodec.H263, Format.ACodec.MP3, 64, false));\n FORMAT_MAP.put(6, new Format(6, \"flv\", 270, Format.VCodec.H263, Format.ACodec.MP3, 64, false));\n FORMAT_MAP.put(17, new Format(17, \"3gp\", 144, Format.VCodec.MPEG4, Format.ACodec.AAC, 24, false));\n FORMAT_MAP.put(18, new Format(18, \"mp4\", 360, Format.VCodec.H264, Format.ACodec.AAC, 96, false));\n FORMAT_MAP.put(22, new Format(22, \"mp4\", 720, Format.VCodec.H264, Format.ACodec.AAC, 192, false));\n FORMAT_MAP.put(34, new Format(36, \"flv\", 360, Format.VCodec.MPEG4, Format.ACodec.AAC, 128, false));\n FORMAT_MAP.put(35, new Format(36, \"flv\", 480, Format.VCodec.MPEG4, Format.ACodec.AAC, 128, false));\n FORMAT_MAP.put(36, new Format(36, \"3gp\", 240, Format.VCodec.MPEG4, Format.ACodec.AAC, 32, false));\n FORMAT_MAP.put(37, new Format(37, \"mp4\", 1080, Format.VCodec.H264, Format.ACodec.AAC, 192, false));\n FORMAT_MAP.put(38, new Format(38, \"mp4\", 3072, Format.VCodec.H264, Format.ACodec.AAC, 192, false));\n FORMAT_MAP.put(43, new Format(43, \"webm\", 360, Format.VCodec.VP8, Format.ACodec.VORBIS, 128, false));\n FORMAT_MAP.put(44, new Format(44, \"webm\", 480, Format.VCodec.VP8, Format.ACodec.VORBIS, 128, false));\n FORMAT_MAP.put(45, new Format(45, \"webm\", 720, Format.VCodec.VP8, Format.ACodec.VORBIS, 192, false));\n FORMAT_MAP.put(46, new Format(46, \"webm\", 1080, Format.VCodec.VP8, Format.ACodec.VORBIS, 192, false));\n FORMAT_MAP.put(59, new Format(59, \"mp4\", 480, Format.VCodec.H264, Format.ACodec.AAC, 128, false));\n FORMAT_MAP.put(78, new Format(78, \"mp4\", 480, Format.VCodec.H264, Format.ACodec.AAC, 128, false));\n\n // Dash Video\n FORMAT_MAP.put(133, new Format(133, \"mp4\", 240, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(134, new Format(134, \"mp4\", 360, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(135, new Format(135, \"mp4\", 480, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(136, new Format(136, \"mp4\", 720, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(137, new Format(137, \"mp4\", 1080, Format.VCodec.H264, Format.ACodec.NONE, true));\n //itag 138 videos are either 3840x2160 or 7680x4320 (sLprVF6d7Ug)\n FORMAT_MAP.put(138, new Format(138, \"mp4\", 4320, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(160, new Format(160, \"mp4\", 144, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(264, new Format(264, \"mp4\", 1440, Format.VCodec.H264, Format.ACodec.NONE, true));\n FORMAT_MAP.put(266, new Format(266, \"mp4\", 2160, Format.VCodec.H264, Format.ACodec.NONE, true));\n\n FORMAT_MAP.put(298, new Format(298, \"mp4\", 720, Format.VCodec.H264, 60, Format.ACodec.NONE, true));\n FORMAT_MAP.put(299, new Format(299, \"mp4\", 1080, Format.VCodec.H264, 60, Format.ACodec.NONE, true));\n\n // Dash Audio\n FORMAT_MAP.put(139, new Format(139, \"m4a\", Format.VCodec.NONE, Format.ACodec.AAC, 48, true));\n FORMAT_MAP.put(140, new Format(140, \"m4a\", Format.VCodec.NONE, Format.ACodec.AAC, 128, true));\n FORMAT_MAP.put(141, new Format(141, \"m4a\", Format.VCodec.NONE, Format.ACodec.AAC, 256, true));\n// FORMAT_MAP.put(256, new Format(256, \"m4a\", Format.VCodec.NONE, Format.ACodec.AAC, XX, true));\n// FORMAT_MAP.put(258, new Format(258, \"m4a\", Format.VCodec.NONE, Format.ACodec.AAC, XX, true));\n\n // WEBM Dash Video\n FORMAT_MAP.put(167, new Format(167, \"webm\", 360, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(168, new Format(168, \"webm\", 480, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(169, new Format(169, \"webm\", 720, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(170, new Format(170, \"webm\", 1080, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(218, new Format(218, \"webm\", 480, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(219, new Format(219, \"webm\", 480, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(278, new Format(278, \"webm\", 144, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(242, new Format(242, \"webm\", 240, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(243, new Format(243, \"webm\", 360, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(244, new Format(244, \"webm\", 480, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(247, new Format(247, \"webm\", 720, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(248, new Format(248, \"webm\", 1080, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(271, new Format(271, \"webm\", 1440, Format.VCodec.VP9, Format.ACodec.NONE, true));\n //itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)\n FORMAT_MAP.put(272, new Format(272, \"webm\", 2160, Format.VCodec.VP9, Format.ACodec.NONE, true));\n FORMAT_MAP.put(313, new Format(313, \"webm\", 2160, Format.VCodec.VP9, Format.ACodec.NONE, true));\n\n FORMAT_MAP.put(302, new Format(302, \"webm\", 720, Format.VCodec.VP9, 60, Format.ACodec.NONE, true));\n FORMAT_MAP.put(303, new Format(303, \"webm\", 1080, Format.VCodec.VP9, 60, Format.ACodec.NONE, true));\n FORMAT_MAP.put(308, new Format(308, \"webm\", 1440, Format.VCodec.VP9, 60, Format.ACodec.NONE, true));\n FORMAT_MAP.put(315, new Format(315, \"webm\", 2160, Format.VCodec.VP9, 60, Format.ACodec.NONE, true));\n\n // WEBM Dash Audio\n FORMAT_MAP.put(171, new Format(171, \"webm\", Format.VCodec.NONE, Format.ACodec.VORBIS, 128, true));\n FORMAT_MAP.put(172, new Format(172, \"webm\", Format.VCodec.NONE, Format.ACodec.VORBIS, 128, true));\n\n // WEBM Dash audio with opus inside\n FORMAT_MAP.put(249, new Format(249, \"webm\", Format.VCodec.NONE, Format.ACodec.OPUS, 50, true));\n FORMAT_MAP.put(250, new Format(250, \"webm\", Format.VCodec.NONE, Format.ACodec.OPUS, 70, true));\n FORMAT_MAP.put(251, new Format(251, \"webm\", Format.VCodec.NONE, Format.ACodec.OPUS, 160, true));\n\n // HLS Live Stream\n FORMAT_MAP.put(91, new Format(91, \"mp4\", 144, Format.VCodec.H264, Format.ACodec.AAC, 48, false, true));\n FORMAT_MAP.put(92, new Format(92, \"mp4\", 240, Format.VCodec.H264, Format.ACodec.AAC, 48, false, true));\n FORMAT_MAP.put(93, new Format(93, \"mp4\", 360, Format.VCodec.H264, Format.ACodec.AAC, 128, false, true));\n FORMAT_MAP.put(94, new Format(94, \"mp4\", 480, Format.VCodec.H264, Format.ACodec.AAC, 128, false, true));\n FORMAT_MAP.put(95, new Format(95, \"mp4\", 720, Format.VCodec.H264, Format.ACodec.AAC, 256, false, true));\n FORMAT_MAP.put(96, new Format(96, \"mp4\", 1080, Format.VCodec.H264, Format.ACodec.AAC, 256, false, true));\n FORMAT_MAP.put(132, new Format(132, \"mp4\", 240, Format.VCodec.H264, Format.ACodec.AAC, 48, false, true));\n FORMAT_MAP.put(151, new Format(151, \"mp4\", 72, Format.VCodec.H264, Format.ACodec.AAC, 24, false, true));\n }\n\n public YouTubeExtractor(@NonNull Context con)\n {\n weakContext = new WeakReference<>(con);\n cacheDirPath = con.getCacheDir().getAbsolutePath();\n }\n\n @Override\n protected void onPostExecute(SparseArray<YtFile> ytFiles)\n {\n onExtractionComplete(ytFiles, videoMeta);\n }\n\n\n /**\n * Start the extraction.\n *\n * @param youtubeLink the youtube page link or video id\n * @param parseDashManifest true if the dash manifest should be downloaded and parsed\n * @param includeWebM true if WebM streams should be extracted\n */\n public void extract(String youtubeLink, boolean parseDashManifest, boolean includeWebM)\n {\n this.parseDashManifest = parseDashManifest;\n this.includeWebM = includeWebM;\n this.execute(youtubeLink);\n }\n\n protected abstract void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta videoMeta);\n\n @Override\n protected SparseArray<YtFile> doInBackground(String... params)\n {\n videoID = null;\n String ytUrl = params[0];\n if (ytUrl == null) {\n return null;\n }\n Matcher mat = patYouTubePageLink.matcher(ytUrl);\n if (mat.find()) {\n videoID = mat.group(3);\n } else {\n mat = patYouTubeShortLink.matcher(ytUrl);\n if (mat.find()) {\n videoID = mat.group(3);\n } else if (ytUrl.matches(\"\\\\p{Graph}+?\")) {\n videoID = ytUrl;\n }\n }\n if (videoID != null) {\n try {\n return getStreamUrls();\n } catch (Exception e) {\n e.printStackTrace();\n }\n } else {\n Log.e(LOG_TAG, \"Wrong YouTube link format\");\n }\n return null;\n }\n\n private SparseArray<YtFile> getStreamUrls() throws IOException, InterruptedException\n {\n String ytInfoUrl = (useHttp) ? \"http://\" : \"https://\";\n ytInfoUrl += \"www.youtube.com/get_video_info?video_id=\" + videoID + \"&eurl=\"\n + URLEncoder.encode(\"https://youtube.googleapis.com/v/\" + videoID, \"UTF-8\");\n\n String dashMpdUrl = null;\n String streamMap = null;\n BufferedReader reader = null;\n URL getUrl = new URL(ytInfoUrl);\n if (LOGGING) Log.d(LOG_TAG, \"infoUrl: \" + ytInfoUrl);\n\n HttpURLConnection urlConnection = (HttpURLConnection) getUrl.openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", USER_AGENT);\n try {\n reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n streamMap = reader.readLine();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (reader != null)\n reader.close();\n urlConnection.disconnect();\n }\n Matcher mat;\n String curJsFileName = null;\n String[] streams;\n SparseArray<String> encSignatures = null;\n SparseArray<String> spKeys = new SparseArray<>();\n\n parseVideoMeta(streamMap);\n\n if (videoMeta.isLiveStream()) {\n mat = patHlsvp.matcher(streamMap);\n if (mat.find()) {\n String hlsvp = URLDecoder.decode(mat.group(1), \"UTF-8\");\n SparseArray<YtFile> ytFiles = new SparseArray<>();\n\n getUrl = new URL(hlsvp);\n urlConnection = (HttpURLConnection) getUrl.openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", USER_AGENT);\n try {\n reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n if (line.startsWith(\"https://\") || line.startsWith(\"http://\")) {\n mat = patHlsItag.matcher(line);\n if (mat.find()) {\n int itag = Integer.parseInt(mat.group(1));\n YtFile newFile = new YtFile(FORMAT_MAP.get(itag), line);\n ytFiles.put(itag, newFile);\n }\n }\n }\n } finally {\n if (reader != null)\n reader.close();\n urlConnection.disconnect();\n }\n\n if (ytFiles.size() == 0) {\n if (LOGGING)\n Log.d(LOG_TAG, streamMap);\n return null;\n }\n return ytFiles;\n }\n return null;\n }\n\n // \"use_cipher_signature\" disappeared, we check whether at least one ciphered signature\n // exists int the stream_map.\n boolean sigEnc = true, statusFail = false;\n if (streamMap != null && streamMap.contains(STREAM_MAP_STRING)) {\n if (!patIsNewSigEnc.matcher(streamMap).find() && !patIsSigEnc.matcher(streamMap).find()) {\n sigEnc = false;\n\n if (!patStatusOk.matcher(streamMap).find())\n statusFail = true;\n }\n }\n\n // Some videos are using a ciphered signature we need to get the\n // deciphering js-file from the youtubepage.\n if (sigEnc || statusFail) {\n // Get the video directly from the youtubepage\n if (CACHING && (decipherJsFileName == null || decipherFunctions == null || decipherFunctionName == null)) {\n readDecipherFunctFromCache();\n }\n if (LOGGING) Log.d(LOG_TAG, \"Get from youtube page\");\n\n getUrl = new URL(\"https://youtube.com/watch?v=\" + videoID);\n urlConnection = (HttpURLConnection) getUrl.openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", USER_AGENT);\n try {\n reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n if (LOGGING) Log.d(\"line\", line);\n if (line.contains(STREAM_MAP_STRING)) {\n streamMap = line.replace(\"\\\\u0026\", \"&\");\n break;\n }\n }\n } finally {\n if (reader != null)\n reader.close();\n urlConnection.disconnect();\n }\n encSignatures = new SparseArray<>();\n\n mat = patDecryptionJsFile.matcher(streamMap);\n if (mat.find()) {\n curJsFileName = mat.group(1).replace(\"\\\\/\", \"/\");\n if (mat.group(2) != null) curJsFileName.replace(mat.group(2), \"\");\n if (decipherJsFileName == null || !decipherJsFileName.equals(curJsFileName)) {\n decipherFunctions = null;\n decipherFunctionName = null;\n }\n decipherJsFileName = curJsFileName;\n }\n\n if (parseDashManifest) {\n mat = patDashManifest2.matcher(streamMap);\n if (mat.find()) {\n dashMpdUrl = mat.group(1).replace(\"\\\\/\", \"/\");\n mat = patDashManifestEncSig.matcher(dashMpdUrl);\n if (mat.find()) {\n encSignatures.append(0, mat.group(1));\n } else {\n dashMpdUrl = null;\n }\n }\n }\n } else {\n if (parseDashManifest) {\n mat = patDashManifest1.matcher(streamMap);\n if (mat.find()) {\n dashMpdUrl = URLDecoder.decode(mat.group(1), \"UTF-8\");\n }\n }\n streamMap = URLDecoder.decode(streamMap, \"UTF-8\");\n }\n\n\n streams = streamMap.split(\",|\" + STREAM_MAP_STRING + \"|&adaptive_fmts=\");\n SparseArray<YtFile> ytFiles = new SparseArray<>();\n for (String encStream : streams) {\n encStream = encStream + \",\";\n if (!encStream.contains(\"itag%3D\")) {\n continue;\n }\n String stream;\n stream = URLDecoder.decode(encStream, \"UTF-8\");\n\n mat = patItag.matcher(stream);\n int itag;\n if (mat.find()) {\n itag = Integer.parseInt(mat.group(1));\n if (LOGGING) Log.d(LOG_TAG, \"Itag found:\" + itag);\n if (FORMAT_MAP.get(itag) == null) {\n if (LOGGING) Log.d(LOG_TAG, \"Itag not in list:\" + itag);\n continue;\n } else if (!includeWebM && FORMAT_MAP.get(itag).getExt().equals(\"webm\")) {\n continue;\n }\n } else {\n continue;\n }\n\n if (curJsFileName != null) {\n mat = patNewEncSig.matcher(stream);\n if (mat.find()) {\n encSignatures.append(itag, URLDecoder.decode(mat.group(2), \"UTF-8\"));\n } else {\n mat = patEncSig.matcher(stream);\n if (mat.find()) {\n encSignatures.append(itag, mat.group(1));\n }\n }\n }\n\n mat = patSP.matcher(streamMap);\n if (mat.find()) {\n spKeys.append(itag, mat.group(1));\n if (LOGGING) Log.d(LOG_TAG, \"patSP found:\" + mat.group(1));\n }\n\n mat = patUrl.matcher(encStream);\n String url = null;\n if (mat.find()) {\n url = mat.group(1);\n }\n\n if (url != null) {\n Format format = FORMAT_MAP.get(itag);\n String finalUrl = URLDecoder.decode(url, \"UTF-8\");\n YtFile newVideo = new YtFile(format, finalUrl);\n ytFiles.put(itag, newVideo);\n }\n }\n\n if (encSignatures != null) {\n if (LOGGING) Log.d(LOG_TAG, \"Decipher signatures: \" + encSignatures.size() + \", videos: \" + ytFiles.size());\n String signature;\n decipheredSignature = null;\n if (decipherSignature(encSignatures)) {\n lock.lock();\n try {\n jsExecuting.await(7, TimeUnit.SECONDS);\n } finally {\n lock.unlock();\n }\n }\n signature = decipheredSignature;\n if (signature == null) {\n return null;\n } else {\n String[] sigs = signature.split(\"\\n\");\n for (int i = 0; i < encSignatures.size() && i < sigs.length; i++) {\n int iTag = encSignatures.keyAt(i);\n if (iTag == 0) {\n dashMpdUrl = dashMpdUrl.replace(\"/s/\" + encSignatures.get(iTag), \"/signature/\" + sigs[i]);\n } else {\n String url = ytFiles.get(iTag).getUrl();\n String sp = '&' + spKeys.get(iTag) + '=';\n url += sp + sigs[i];\n YtFile newFile = new YtFile(FORMAT_MAP.get(iTag), url);\n ytFiles.put(iTag, newFile);\n }\n }\n }\n }\n\n if (parseDashManifest && dashMpdUrl != null) {\n for (int i = 0; i < DASH_PARSE_RETRIES; i++) {\n try {\n // It sometimes fails to connect for no apparent reason. We just retry.\n parseDashManifest(dashMpdUrl, ytFiles);\n break;\n } catch (IOException io) {\n Thread.sleep(5);\n if (LOGGING)\n Log.d(LOG_TAG, \"Failed to parse dash manifest \" + (i + 1));\n }\n }\n }\n\n if (ytFiles.size() == 0) {\n if (LOGGING)\n Log.d(LOG_TAG, streamMap);\n return null;\n }\n return ytFiles;\n }\n\n private boolean decipherSignature(final SparseArray<String> encSignatures) throws IOException\n {\n // Assume the functions don't change that much\n if (decipherFunctionName == null || decipherFunctions == null) {\n String decipherFunctUrl = \"https://s.ytimg.com/yts/jsbin/\" + decipherJsFileName;\n\n BufferedReader reader = null;\n String javascriptFile = null;\n URL url = new URL(decipherFunctUrl);\n HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", USER_AGENT);\n try {\n reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n StringBuilder sb = new StringBuilder(\"\");\n String line;\n while ((line = reader.readLine()) != null) {\n sb.append(line);\n sb.append(\" \");\n }\n javascriptFile = sb.toString();\n } finally {\n if (reader != null)\n reader.close();\n urlConnection.disconnect();\n }\n\n if (LOGGING) Log.d(LOG_TAG, \"Decipher FunctionURL: \" + decipherFunctUrl);\n Matcher mat = patSignatureDecFunction.matcher(javascriptFile);\n if (mat.find()) {\n decipherFunctionName = mat.group(1);\n if (LOGGING) Log.d(LOG_TAG, \"Decipher FunctionName: \" + decipherFunctionName);\n\n Pattern patMainVariable = Pattern.compile(\"(var |\\\\s|,|;)\" + decipherFunctionName.replace(\"$\", \"\\\\$\") +\n \"(=function\\\\((.{1,3})\\\\)\\\\{)\");\n\n String mainDecipherFunct;\n\n mat = patMainVariable.matcher(javascriptFile);\n if (mat.find()) {\n mainDecipherFunct = \"var \" + decipherFunctionName + mat.group(2);\n } else {\n Pattern patMainFunction = Pattern.compile(\"function \" + decipherFunctionName.replace(\"$\", \"\\\\$\") + \"(\\\\((.{1,3})\\\\)\\\\{)\");\n mat = patMainFunction.matcher(javascriptFile);\n if (!mat.find())\n return false;\n mainDecipherFunct = \"function \" + decipherFunctionName + mat.group(2);\n }\n\n int startIndex = mat.end();\n\n for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {\n if (braces == 0 && startIndex + 5 < i) {\n mainDecipherFunct += javascriptFile.substring(startIndex, i) + \";\";\n break;\n }\n if (javascriptFile.charAt(i) == '{')\n braces++;\n else if (javascriptFile.charAt(i) == '}')\n braces--;\n }\n decipherFunctions = mainDecipherFunct;\n // Search the main function for extra functions and variables\n // needed for deciphering\n // Search for variables\n mat = patVariableFunction.matcher(mainDecipherFunct);\n while (mat.find()) {\n String variableDef = \"var \" + mat.group(2) + \"={\";\n if (decipherFunctions.contains(variableDef)) {\n continue;\n }\n startIndex = javascriptFile.indexOf(variableDef) + variableDef.length();\n for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {\n if (braces == 0) {\n decipherFunctions += variableDef + javascriptFile.substring(startIndex, i) + \";\";\n break;\n }\n if (javascriptFile.charAt(i) == '{')\n braces++;\n else if (javascriptFile.charAt(i) == '}')\n braces--;\n }\n }\n // Search for functions\n mat = patFunction.matcher(mainDecipherFunct);\n while (mat.find()) {\n String functionDef = \"function \" + mat.group(2) + \"(\";\n if (decipherFunctions.contains(functionDef)) {\n continue;\n }\n startIndex = javascriptFile.indexOf(functionDef) + functionDef.length();\n for (int braces = 0, i = startIndex; i < javascriptFile.length(); i++) {\n if (braces == 0 && startIndex + 5 < i) {\n decipherFunctions += functionDef + javascriptFile.substring(startIndex, i) + \";\";\n break;\n }\n if (javascriptFile.charAt(i) == '{')\n braces++;\n else if (javascriptFile.charAt(i) == '}')\n braces--;\n }\n }\n\n if (LOGGING) Log.d(LOG_TAG, \"encSignatures: \" + encSignatures);\n if (LOGGING) Log.d(LOG_TAG, \"Decipher Function: \" + decipherFunctions);\n decipherViaWebView(encSignatures);\n if (CACHING) {\n writeDecipherFunctionToCache();\n }\n } else {\n return false;\n }\n } else {\n decipherViaWebView(encSignatures);\n }\n return true;\n }\n\n private void parseDashManifest(String dashMpdUrl, SparseArray<YtFile> ytFiles) throws IOException\n {\n Pattern patBaseUrl = Pattern.compile(\"<\\\\s*BaseURL(.*?)>(.+?)<\\\\s*/BaseURL\\\\s*>\");\n Pattern patDashItag = Pattern.compile(\"itag/([0-9]+?)/\");\n String dashManifest;\n BufferedReader reader = null;\n URL getUrl = new URL(dashMpdUrl);\n HttpURLConnection urlConnection = (HttpURLConnection) getUrl.openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", USER_AGENT);\n try {\n reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n reader.readLine();\n dashManifest = reader.readLine();\n } finally {\n if (reader != null)\n reader.close();\n urlConnection.disconnect();\n }\n if (dashManifest == null)\n return;\n Matcher mat = patBaseUrl.matcher(dashManifest);\n while (mat.find()) {\n int itag;\n String url = mat.group(2);\n Matcher mat2 = patDashItag.matcher(url);\n if (mat2.find()) {\n itag = Integer.parseInt(mat2.group(1));\n if (FORMAT_MAP.get(itag) == null)\n continue;\n if (!includeWebM && FORMAT_MAP.get(itag).getExt().equals(\"webm\"))\n continue;\n } else {\n continue;\n }\n YtFile yf = new YtFile(FORMAT_MAP.get(itag), url);\n ytFiles.append(itag, yf);\n }\n }\n\n private void parseVideoMeta(String getVideoInfo) throws UnsupportedEncodingException\n {\n boolean isLiveStream = false;\n String title = null, author = null, channelId = null;\n long viewCount = 0, length = 0;\n Matcher mat = patTitle.matcher(getVideoInfo);\n if (mat.find()) {\n title = URLDecoder.decode(mat.group(1), \"UTF-8\");\n }\n\n mat = patHlsvp.matcher(getVideoInfo);\n if (mat.find()) {\n isLiveStream = true;\n }\n\n mat = patAuthor.matcher(getVideoInfo);\n if (mat.find()) {\n author = URLDecoder.decode(mat.group(1), \"UTF-8\");\n }\n mat = patChannelId.matcher(getVideoInfo);\n if (mat.find()) {\n channelId = mat.group(1);\n }\n mat = patLength.matcher(getVideoInfo);\n if (mat.find()) {\n length = Long.parseLong(mat.group(1));\n }\n mat = patViewCount.matcher(getVideoInfo);\n if (mat.find()) {\n viewCount = Long.parseLong(mat.group(1));\n }\n videoMeta = new VideoMeta(videoID, title, author, channelId, length, viewCount, isLiveStream);\n }\n\n private void readDecipherFunctFromCache()\n {\n File cacheFile = new File(cacheDirPath + \"/\" + CACHE_FILE_NAME);\n // The cached functions are valid for 2 weeks\n if (cacheFile.exists() && (System.currentTimeMillis() - cacheFile.lastModified()) < 1209600000) {\n BufferedReader reader = null;\n try {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(cacheFile), \"UTF-8\"));\n decipherJsFileName = reader.readLine();\n decipherFunctionName = reader.readLine();\n decipherFunctions = reader.readLine();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n }\n\n /**\n * Parse the dash manifest for different dash streams and high quality audio. Default: false\n */\n public void setParseDashManifest(boolean parseDashManifest)\n {\n this.parseDashManifest = parseDashManifest;\n }\n\n\n /**\n * Include the webm format files into the result. Default: true\n */\n public void setIncludeWebM(boolean includeWebM)\n {\n this.includeWebM = includeWebM;\n }\n\n\n /**\n * Set default protocol of the returned urls to HTTP instead of HTTPS.\n * HTTP may be blocked in some regions so HTTPS is the default value.\n * <p/>\n * Note: Enciphered videos require HTTPS so they are not affected by\n * this.\n */\n public void setDefaultHttpProtocol(boolean useHttp)\n {\n this.useHttp = useHttp;\n }\n\n private void writeDecipherFunctionToCache()\n {\n File cacheFile = new File(cacheDirPath + \"/\" + CACHE_FILE_NAME);\n BufferedWriter writer = null;\n try {\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), \"UTF-8\"));\n writer.write(decipherJsFileName + \"\\n\");\n writer.write(decipherFunctionName + \"\\n\");\n writer.write(decipherFunctions);\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (writer != null) {\n try {\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n private void decipherViaWebView(final SparseArray<String> encSignatures)\n {\n final Context context = weakContext.get();\n if (context == null) {\n return;\n }\n\n final StringBuilder stb = new StringBuilder(decipherFunctions + \" function decipher(\");\n stb.append(\"){return \");\n\n for (int i = 0; i < encSignatures.size(); i++) {\n int key = encSignatures.keyAt(i);\n if (i < encSignatures.size() - 1) {\n stb.append(decipherFunctionName)\n .append(\"('\")\n .append(encSignatures.get(key))\n .append(\"')+\\\"\\\\n\\\"+\");\n } else {\n stb.append(decipherFunctionName)\n .append(\"('\")\n .append(encSignatures.get(key))\n .append(\"')\");\n }\n }\n stb.append(\"};decipher();\");\n\n\n if (LOGGING) Log.e(LOG_TAG, \"FunctionDecipher: \" + stb);\n\n new Handler(Looper.getMainLooper()).post(() -> new JsEvaluator(context).evaluate(stb.toString(), new JsCallback()\n {\n @Override\n public void onResult(String result)\n {\n lock.lock();\n try {\n decipheredSignature = result;\n\n if (LOGGING) Log.e(LOG_TAG, \"JsEvaluator-result: \" + result);\n jsExecuting.signal();\n } finally {\n lock.unlock();\n }\n }\n\n @Override\n public void onError(String errorMessage)\n {\n lock.lock();\n try {\n if (LOGGING)\n Log.e(LOG_TAG, errorMessage);\n jsExecuting.signal();\n } finally {\n lock.unlock();\n }\n }\n }));\n }\n}", "public class YtFile {\n\n private Format format;\n private String url = \"\";\n\n YtFile(Format format, String url) {\n this.format = format;\n this.url = url;\n }\n\n /**\n * The url to download the file.\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Format data for the specific file.\n */\n public Format getFormat() {\n return format;\n }\n\n /**\n * Format data for the specific file.\n */\n @Deprecated\n public Format getMeta() {\n return format;\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 YtFile ytFile = (YtFile) o;\n\n if (format != null ? !format.equals(ytFile.format) : ytFile.format != null) return false;\n return url != null ? url.equals(ytFile.url) : ytFile.url == null;\n }\n\n @Override\n public int hashCode() {\n int result = format != null ? format.hashCode() : 0;\n result = 31 * result + (url != null ? url.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"YtFile{\" +\n \"format=\" + format +\n \", url='\" + url + '\\'' +\n '}';\n }\n}" ]
import android.app.Activity; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.text.method.LinkMovementMethod; import android.util.Log; import android.util.SparseArray; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.teocci.ytinbg.R; import com.teocci.ytinbg.model.YouTubeFragmentedVideo; import com.teocci.ytinbg.utils.Config; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import at.huber.youtubeExtractor.VideoMeta; import at.huber.youtubeExtractor.YouTubeExtractor; import at.huber.youtubeExtractor.YtFile;
package com.teocci.ytinbg.ui; /** * Created by teocci. * * @author teocci@yandex.com on 2017-May-15 */ public class DownloadActivity extends Activity { private static final String TAG = DownloadActivity.class.getSimpleName(); private static String youtubeLink; private LinearLayout mainLayout; private ProgressBar mainProgressBar; private List<YouTubeFragmentedVideo> formatsToShowList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mainLayout = findViewById(R.id.main_layout); mainProgressBar = findViewById(R.id.progress_bar); Intent intent = getIntent(); String ytLink = intent.getStringExtra(Config.YOUTUBE_LINK); //if it's a string you stored. // Check how it was started and if we can get the youtube link if (savedInstanceState == null && ytLink != null && !ytLink.trim().isEmpty()) { if (ytLink != null && (ytLink.contains(Config.YT_SHORT_LINK) || ytLink.contains(Config.YT_WATCH_LINK))) { youtubeLink = ytLink; // We have a valid link getYoutubeDownloadUrl(youtubeLink); } else { Toast.makeText(this, R.string.error_no_yt_link, Toast.LENGTH_LONG).show(); finish(); } } else if (savedInstanceState != null && youtubeLink != null) { getYoutubeDownloadUrl(youtubeLink); } else { finish(); } } private Context getActivityContext() { return DownloadActivity.this; } private void getYoutubeDownloadUrl(String youtubeLink) { new YouTubeExtractor(this) { @Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta)
4
CBSkarmory/AWGW
src/main/java/cbskarmory/units/sea/Carrier.java
[ "public class Player {\n\n public static int numberOfPlayers;\n public final CO CO;\n public final int id;\n private ArrayList<Unit> unitsControlled;\n private int money;\n private ArrayList<Property> propertiesOwned;\n private int commTowers;\n private Color teamColor;\n\n /**\n * Constructs a Player\n *\n * @param startingMoney starting amount of money\n * @param teamColor team color to be assigned to this Player\n */\n public Player(CO commandingOfficer, int startingMoney, Color teamColor) {\n //if error when setting starting funds, set to 0\n if (setMoney(startingMoney) == -1) {\n setMoney(0);\n } else {\n setMoney(startingMoney);\n }\n this.id = ++Player.numberOfPlayers;\n this.CO = commandingOfficer;\n this.teamColor = teamColor;\n this.unitsControlled = new ArrayList<>();\n this.propertiesOwned = new ArrayList<>();\n }\n\n /**\n * @return the player's team color\n */\n public Color getTeamColor() {\n return this.teamColor;\n }\n\n /**\n * @return the amount of money this player has\n */\n public int getMoney() {\n return this.money;\n }\n\n /**\n * @param money a positive integer to set money to\n * @return the amount of money that this player has after execution\n * or -1 if the amount was invalid\n */\n public int setMoney(int money) {\n if (money >= 0) {\n this.money = money;\n return this.money;\n } else {\n return -1;\n }\n }\n\n /**\n * @return a list of all of the units that this player controls\n */\n public ArrayList<Unit> getUnitsControlled() {\n return unitsControlled;\n }\n\n /**\n * @return the number of Units that this player controls\n */\n public int getNumUnitControlled() {\n return getUnitsControlled().size();\n }\n\n /**\n * @return a list of all of the Properties that this player owns\n */\n public ArrayList<Property> getPropertiesOwned() {\n return this.propertiesOwned;\n }\n\n /**\n * @return the number of Properties that this player controls\n */\n public int getNumPropertiesOwned() {\n return getPropertiesOwned().size();\n }\n\n public int getCommTowers() {\n return commTowers;\n }\n\n public void setCommTowers(int commTowers) {\n this.commTowers = commTowers;\n }\n\n public boolean hasHQ() {\n for (Property prop : getPropertiesOwned()) {\n if (prop instanceof HQ) {\n return true;\n }\n }\n return false;\n }\n}", "public enum MoveType {\n FOOT,\n TIRES,\n TREADS,\n SEA,\n AIR,\n LANDER\n}", "public abstract class Terrain extends Location {\n\n protected TerrainGrid hostGrid;\n\n /**\n * Constructs a Terrain with given row and column coordinates.\n *\n * @param r the row\n * @param c the column\n */\n public Terrain(int r, int c, TerrainGrid<Actor> hostGrid) {\n super(r, c);\n this.hostGrid = hostGrid;\n }\n\n /**\n * @return the defense points of this Terrain\n * non-air units occupying the terrain gain a 10% defense bonus per defense point\n */\n public abstract int getDefense();\n\n /**\n * @return the cost of mobility points that a unit of movementType would take\n * to traverse this terrain\n */\n public double getMoveCost(MoveType movementType) {\n switch (movementType) {\n case AIR:\n return getMoveCostAir();\n case SEA:\n return getMoveCostBoat();\n case FOOT:\n return getMoveCostFoot();\n case TIRES:\n return getMoveCostTires();\n case TREADS:\n return getMoveCostTreads();\n case LANDER:\n return getMoveCostLander();\n default:\n throw new IllegalArgumentException();\n }\n }\n\n /**\n * @return the cost of mobility points that a unit of movementType.FOOT would take\n * to traverse this terrain -- override to set\n */\n protected abstract double getMoveCostFoot();\n\n /**\n * @return the cost of mobility points that a unit of movementType.TIRES would take\n * to traverse this terrain -- override to set\n */\n protected abstract double getMoveCostTires();\n\n /**\n * @return the cost of mobility points that a unit of movementType.TREADS would take\n * to traverse this terrain -- override to set\n */\n protected abstract double getMoveCostTreads();\n\n /**\n * @return the cost of mobility points that a unit of movementType.AIR would take\n * to traverse this terrain -- override to set\n */\n protected double getMoveCostAir() {\n return 1;\n }\n\n /**\n * @return the cost of mobility points that a unit of movementType.SEA would take\n * to traverse this terrain -- override to set\n */\n protected double getMoveCostBoat() {\n return 999;\n }\n\n /**\n * @return the cost of mobility points that a unit of movementType.LANDER would take\n * to traverse this terrain -- override to set\n */\n protected double getMoveCostLander() {\n return 999;\n }\n\n /**\n * @return Manhattan distance to other terrain t\n */\n public int getDistanceTo(Terrain t) {\n return Math.abs(this.getRow() - t.getRow()) + Math.abs(this.getCol() - t.getCol());\n }\n\n @Override\n public Location getAdjacentLocation(int direction) {\n int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE;\n if (adjustedDirection < 0)\n adjustedDirection += FULL_CIRCLE;\n\n adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT;\n int dc = 0;\n int dr = 0;\n if (adjustedDirection == EAST)\n dc = 1;\n else if (adjustedDirection == SOUTHEAST) {\n dc = 1;\n dr = 1;\n } else if (adjustedDirection == SOUTH)\n dr = 1;\n else if (adjustedDirection == SOUTHWEST) {\n dc = -1;\n dr = 1;\n } else if (adjustedDirection == WEST)\n dc = -1;\n else if (adjustedDirection == NORTHWEST) {\n dc = -1;\n dr = -1;\n } else if (adjustedDirection == NORTH)\n dr = -1;\n else if (adjustedDirection == NORTHEAST) {\n dc = 1;\n dr = -1;\n }\n try {\n return hostGrid.getLocationArray()[getRow() + dr][getCol() + dc];\n } catch (ArrayIndexOutOfBoundsException e) {\n return null;\n }\n }\n\n /**\n * @return list of Manhattan adjacent Terrains\n */\n public ArrayList<Terrain> getAllAdjacentTerrains() {\n ArrayList<Terrain> adjacent = new ArrayList<Terrain>();\n //45 deg for all, 90 for Manhattan\n for (int dir = 0; dir < 360; dir += 90) {\n Terrain t = (Terrain) getAdjacentLocation(dir);\n if (t != null) {\n adjacent.add(t);\n }\n }\n return adjacent;\n }\n\n public String getUIName() {\n switch (this.getClass().getSimpleName()) {\n case \"Property\":\n return \"City\";\n default:\n return this.getClass().getSimpleName();\n }\n }\n\n public String getDefenseStarsAsString() {\n Object a;\n if ((a = hostGrid.get(this)) != null && (a instanceof Air)) {\n return \"☆☆☆☆☆\";\n }\n int def = getDefense();\n return \"★★★★★\".substring(0, def) + \"☆☆☆☆☆\".substring(def, 5);\n }\n\n public TerrainGrid getHostGrid() {\n return hostGrid;\n }\n}", "public abstract class Air extends Unit {\n\n /**\n * calls super(Player) from child classes\n * don't invoke this\n *\n * @param owner owner of unit\n */\n public Air(Player owner) {\n super(owner);\n }\n\n @Override\n public void outOfFuel() {\n //TODO crash animation\n this.selfDestruct(true);\n }\n\n @Override\n public MoveType getMovementType() {\n return MoveType.AIR;\n }\n\n}", "public interface Carry {\n /**\n * @return whether or not this Carry can carry any more Units\n */\n default boolean isFull() {\n return getMaxCapacity() == getUnits().size();\n }\n\n /**\n * @return maximum number of Units this can carry\n */\n default public int getMaxCapacity() {\n return 1;\n }\n\n /**\n * @return a List of the units carried (can be empty)\n */\n public ArrayList<Unit> getUnits();\n\n /**\n * Refills {@link fuel} and {@link ammo} for adjacent allied {@link Unit}s\n */\n public void resupply();\n\n /**\n * @return whether or not this Carry has resupplying capabilities\n */\n public boolean canResupply();\n\n /**\n * Precondition: Carry is not full and Carry can carry the Unit\n * precondition is checked with canCarry() and isFull()\n * PostCondition: getUnits() returns ArrayList containing Unit u\n */\n public default void addUnit(Unit u) {\n this.getUnits().add(u);\n }\n\n /**\n * Drops off one carried Unit in valid Manhattan adjacent tile\n * can still move after this action; this can drop off multiple Units given space\n * Precondition: This Carry is carrying at least one Unit for which\n * it can be dropped in a Manhattan adjacent tile\n */\n public default void drop() {\n //TODO Implement me\n }\n\n /**\n * @return whether or not this Carry can carry the Unit\n */\n boolean canCarry(Unit u);\n\n}", "public abstract class Sea extends Unit {\n\n /**\n * calls super(Player) from child classes\n * don't invoke this\n *\n * @param owner owner of unit\n */\n public Sea(Player owner) {\n super(owner);\n }\n\n @Override\n public MoveType getMovementType() {\n return MoveType.SEA;\n }\n\n @Override\n public void outOfFuel() {\n //TODO sinking animation\n this.selfDestruct();\n }\n\n\n}", "public abstract class Unit extends Actor {\n public boolean hasMoved;\n\n //constructor\n /**\n * Not a lazy boolean flag, as ability to move involves a myriad of\n * factors including {@link fuel}, participation in\n * combat, transport, and other special circumstances like {@link CO} powers and electronic\n * warfare (EW)\n */\n protected boolean canMove;\n //ownership\n private Player owner;\n //combat defense\n private Suit suit;\n private int health = 100;\n private Weapon[] weapons = new Weapon[2];\n private int ammo;\n private double fuel;\n private int dailyCost;\n private double mobility;\n private double maxMobility;\n\n /**\n * Constructs a Unit owned by owner\n * also loads the values for daily fuel cost and max mobility\n */\n public Unit(Player owner) {\n if (null != owner) {\n setOwner(owner);\n this.setDailyCost(loadDailyCost());\n this.setMaxMobility(loadMaxMobility());\n //this.canMove = true;\n this.setFuel(99);\n this.resetMovement();\n } else {\n //FOR FACTORY MENU, FIXME in Factory class NOT VERY EFFICIENT\n //don't worry, it will get deleted soon\n }\n }\n\n /**\n * @deprecated debug purposes only\n */\n public Unit() {\n }\n\n private static Queue<Terrain> genPath(Terrain t, Map<Terrain, Terrain> parentMap) throws IllegalArgumentException {\n if (!parentMap.containsKey(t)) {\n throw new IllegalArgumentException();\n }\n Queue<Terrain> ans = new LinkedList<>();\n Terrain parent = parentMap.get(t);\n if (parent == null) {\n //we started here, no need to move\n return ans;\n } else {\n ans = genPath(parent, parentMap);\n ans.add(t);\n return ans;\n }\n }\n\n /**\n * @deprecated never call this\n */\n @Override\n public void act() {\n }\n\n public Player getOwner() {\n return this.owner;\n }\n\n public void setOwner(Player newOwner) {\n if (null != newOwner) {\n this.owner = newOwner;\n this.owner.getUnitsControlled().add(this);\n this.setColor(owner.getTeamColor());\n } else {\n throw new IllegalArgumentException(\"owner is null\");\n }\n }\n\n //money\n public abstract int getBuildCost();\n\n public Suit getSuit() {\n return suit;\n }\n\n public void setSuit(Suit s) {\n this.suit = s;\n }\n\n /**\n * @return percent of damage taken generally as decimal\n */\n public abstract double getBaseArmorResistance();\n\n public int getHealth() {\n return health;\n }\n\n /**\n * only use this for true dmg aka ICBM or internally\n *\n * @param hp to set to\n */\n public void setHealth(int hp) {\n health = hp;\n if (health <= 0) {\n this.selfDestruct();\n }\n }\n\n public UnitType getUnitType() {\n ResourceBundle b = ResourceBundle.getBundle(\"unit_to_unit_type\");\n return UnitType.valueOf(b.getString(getType()));\n }\n\n public String getType() {\n return this.getClass().getSimpleName();\n }\n\n //TODO override this to set resistances\n public double resist(double damage, String source) {\n return damage;\n }\n\n //taking damage and dying\n public void takeDamage(double damage, String source) {\n if (suit != null) {\n damage = suit.resist(damage, source);\n damage = this.resist(damage, source);\n }\n this.health -= Math.round(damage);\n if (this.health <= 0) {\n this.health = 0;\n this.selfDestruct();\n }\n }\n\n protected void selfDestruct(boolean... showNoFuelIcon) {\n //TODO animation\n\n URL fireIconLocation = this.getClass().getClassLoader().getResource(\"32x/fire.png\");\n URL noFuelIconLocation = this.getClass().getClassLoader().getResource(\"32x/noFuel.png\");\n Set<Terrain> where = new HashSet<Terrain>();\n where.add((Terrain) getLocation());\n try {\n TerrainGrid tg = (TerrainGrid) getGrid();\n GridPanel display = tg.hostWorld.getWorldFrame().control.display;\n AVWorld avw = tg.hostWorld;\n final Unit _this = this;\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n try {\n if (showNoFuelIcon.length != 0 && showNoFuelIcon[0]) {\n for (int x = 0; x < 3; x++) {\n display.showIconsOnSetOfLocations(new ImageIcon(noFuelIconLocation).getImage(), where);\n Thread.sleep(250);\n }\n }\n display.repaint();\n for (int x = 0; x < 3; x++) {\n display.showIconsOnSetOfLocations(new ImageIcon(fireIconLocation).getImage(), where);\n Thread.sleep(250);\n\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n } finally {\n _this.removeSelfFromGrid();\n _this.getOwner().getUnitsControlled().remove(_this);\n display.repaint();\n }\n\n }\n\n }).start();\n\n } catch (ClassCastException cce) {\n System.err.println(\"?? Host grid is not TerrainGrid. wat. PROBABLY FATAL ERROR Moving on...\");\n this.removeSelfFromGrid();\n this.getOwner().getUnitsControlled().remove(this);\n return;\n }\n }\n\n //combat offense\n protected void setWeapon(int index, String weaponType) {\n this.weapons[index] = new Weapon(weaponType, this);\n if (index == 0) {\n this.setAmmo(weapons[0].getMaxAmmo());\n }\n }\n\n //movement\n\n public Weapon[] getWeapons() {\n return weapons;\n }\n\n public int getAmmo() {\n return ammo;\n }\n\n public void setAmmo(int x) {\n if (x >= 0) {\n ammo = x;\n } else {\n throw new IllegalArgumentException(\"bad attempt to set ammo to negative\");\n }\n }\n\n /**\n * @return whether or not this unit can attack Unit u\n * Gets overridden for ranged units, indirect fire, etc\n */\n public boolean canTarget(Unit u) {\n if ((WeaponType.NONE.equals(getWeapons()[0].getWeaponType()) && null == getWeapons()[1]) || (getAmmo() == 0)) {\n return false;\n }\n return couldTarget(u, (Terrain) getLocation());\n }\n\n /**\n * @return whether or not this unit can attack Unit toCheck from Terrain hypothetical\n * Gets overridden for ranged units, indirect fire, etc\n */\n public boolean couldTarget(Unit toCheck, Terrain hypothetical) {\n if (null == toCheck || toCheck instanceof HiddenUnit) {\n return false; //can't target nothing or hidden things\n }\n return hypothetical.getDistanceTo((Terrain) toCheck.getLocation()) == 1;\n }\n\n /**\n * @return whether or not this unit can counterattack Unit u\n * Gets overridden for ranged units, indirect fire, etc\n */\n public boolean canCounter(Unit u) {\n return canTarget(u);\n }\n\n /**\n * * This Unit attacks the targeted Unit. If the target is still alive and\n * can counter this unit, as determined by canCounter(Unit), it counterattacks afterwards\n * Precondition: ammo > 0 or has secondary weapon, target is in range\n * as determined by canTarget(Unit)\n */\n public void fire(Unit target) {\n immobilize();\n //fire first\n //stronger weapon\n double wep1, wep2, damage;\n wep1 = this.weapons[0].damageCalc(target);\n if (null != this.weapons[1]) {\n wep2 = this.weapons[1].damageCalc(target);\n } else {\n wep2 = 0;\n }\n boolean usedPrimary = (wep1 >= wep2);\n if (usedPrimary) {\n this.setAmmo(getAmmo() - 1);\n damage = wep1;\n } else {\n damage = wep2;\n }\n //luck\n double luck = (double) Weapon.luck();\n luck = this.owner.CO.passive(luck, COFlag.LUCK, getUnitType());\n damage += luck;\n String source;\n if (usedPrimary) {\n source = this.weapons[0].getWeaponType();\n } else {\n source = this.weapons[1].getWeaponType();\n }\n damage = this.owner.CO.passive(damage, COFlag.ATTACK, this.getUnitType());\n target.takeDamage(damage, source);\n //attacking uncloaks\n if (this instanceof Stealth) {\n Stealth me = (Stealth) (this);\n if (me.isHidden()) {\n me.unHide();\n }\n } else if (this instanceof Stealth2) {\n Stealth2 me = (Stealth2) (this);\n if (me.isHidden()) {\n me.unHide();\n }\n }\n //counter attack if target is alive and direct fire\n if (target.getHealth() > 0 && target.canCounter(this)) {\n wep1 = target.weapons[0].damageCalc(this);\n if (null != target.weapons[1]) {\n wep2 = target.weapons[1].damageCalc(this);\n } else {\n wep2 = 0;\n }\n usedPrimary = wep1 >= wep2;\n if (usedPrimary) {\n target.ammo--;\n damage = wep1;\n } else {\n damage = wep2;\n }\n //luck\n luck = Math.random() * 10 + 0.1;\n //CO power affects luck\n luck = target.owner.CO.passive(luck, COFlag.LUCK, target.getUnitType());\n damage += luck;\n if (usedPrimary) {\n source = target.weapons[0].getWeaponType();\n } else {\n source = target.weapons[1].getWeaponType();\n }\n damage = target.owner.CO.passive(damage, COFlag.COUNTER, this.getUnitType());\n this.takeDamage(damage, source);\n }\n }\n\n public void deductDailyCost() {\n this.setFuel(getFuel() - getDailyCost());\n }\n\n /**\n * As you may have noticed, this has void return type.\n * This method is usually invoked upon fuel reaching or dropping below 0,\n * by the <i>{@link setFuel()}</i> method\n * This is public because it can also be invoked by other special\n * circumstances like {@link CO} powers and electronic warfare (EW)\n */\n public abstract void outOfFuel();\n\n public void setMobility(double x) {\n if (x >= 0) {\n this.mobility = x;\n } else {\n throw new IllegalArgumentException(\"bad attempt to set negative mobility\");\n }\n }\n\n /**\n * @return Current {@link mobility} of the {@link Unit}\n */\n public double getCurrentMobility() {\n return this.mobility;\n }\n\n /**\n * @return Maximum {@link mobility} of the {@link Unit}\n * {@link mobility} is set to this value at the start of each turn\n * by <i>{@link resetMovement()}</i> or by special circumstances like {@link CO} powers\n */\n public double getMaxMobility() {\n return this.maxMobility;\n }\n\n /**\n * sets the maximum mobility of the unit to maxMobility\n * should invoked from the constructor\n * Precondition: maxMobility is a positive integer\n * Postcondition: this.maxMobility is set to maxMobility\n */\n private void setMaxMobility(double maxMobility) {\n if (maxMobility >= 0) {\n this.maxMobility = maxMobility;\n } else {\n throw new IllegalArgumentException(\"bad attempt to max mobility (0 or negative)\");\n }\n }\n\n /**\n * loads the maximum mobility for this unit from a resourcebundle\n * for use in constructor for setMaxMobility()\n *\n * @return maximum mobility value for the unit\n */\n private double loadMaxMobility() {\n ResourceBundle b = ResourceBundle.getBundle(\"unit_move\");\n return (double) ((int) (Double.parseDouble(b.getString(getType())) + 0.5));\n }\n\n /**\n * loads the daily fuel cost for this unit from a resourcebundle\n * for use in constructor for setDailyCost()\n *\n * @return maximum mobility value for the unit\n */\n private int loadDailyCost() {\n if (this instanceof HiddenUnit) {\n HiddenUnit me = (HiddenUnit) this;\n Unit cont = (me).getContainedUnit();\n return (cont.loadDailyCost());\n }\n ResourceBundle b = ResourceBundle.getBundle(\"unit_daily_fuel\");\n try {\n double ans = Double.parseDouble(b.getString(getType()));\n return (int) (this.owner.CO.passive(ans, COFlag.DAILY_COST, getUnitType()));\n } catch (NumberFormatException e) {\n\t System.err.println(Arrays.toString(e.getStackTrace()));\n\t System.err.println(\"Corrupt File?\");\n System.err.println(\"Method: Unit.loadDailyCost()\");\n throw e;\n }\n }\n\n /**\n * @return the daily fuel cost of the unit\n * override this method to \"set\" a different daily fuel cost of the unit\n * should be 0 for land units, different for air and sea units\n */\n public int getDailyCost() {\n return dailyCost;\n }\n\n /**\n * sets the daily fuel cost of the unit to cost\n * should invoked from the constructor\n * Precondition: fuelCost is a positive integer\n * Postcondition: this.dailyCost is set to fuelCost\n */\n private void setDailyCost(int x) {\n this.dailyCost = x;\n }\n\n /**\n * @return The {@link MoveType} of this {@link Unit}\n */\n public abstract MoveType getMovementType();\n\n /**\n * @return Amount of fuel remaining. Fuel is required to move,\n * and is consumed when moving. {@link fuel} is truncated to integer at the start of each turn by\n * the resetMovement() method.\n */\n public double getFuel() {\n return this.fuel;\n }\n\n /**\n * @return Amount of fuel remaining. Mobility is required to move, and is consumed when moving.\n * maxMobility fuel is converted into mobility at the start of each turn by resetMovement().\n * fuel is truncated to integer at the start of each turn by the resetMovement() method.\n */\n public void setFuel(double d) {\n this.fuel = d;\n if (fuel < 0) {\n outOfFuel();\n }\n }\n\n /**\n * @return Whether or not this unit can still move. A {@link Unit} can move\n * until they runs out of {@link mobility}, participates in combat,\n * or is dropped off from a carrying unit. A {@link Unit} currently carried cannot move,\n * but will move with the carrying unit.\n */\n public boolean canMove() {\n if (this.getCurrentMobility() == 0) {\n immobilize();\n return false;\n }\n return this.canMove;\n }\n\n /**\n * sets canMove to false, changes colors\n *\n * @return whether or not the unit was already UNABLE to move\n */\n public boolean immobilize() {\n if (!canMove) {\n return true;\n } else {\n canMove = false;\n if (getColor() != null) {\n setColor(getColor().darker());\n }\n return false;\n }\n }\n\n /**\n * Resets movement-related variables for new day or {@link CO} power, namely:\n * <p>{@link canMove}<p>{@link fuel}\n * Postcondition: The daily fuel cost of the unit is deducted from fuel.\n * up to maxMobility is deducted from fuel and the same amount is\n * added to mobility.\n */\n public void resetMovement() {\n //this.hasMoved = false;\n if (!canMove && getColor() != null) {\n setColor(getColor().brighter());\n }\n this.canMove = true;\n this.fuel = (int) (getFuel());\n if (null != getLocation()) {//If not carried\n this.setFuel(this.getFuel() - (this.maxMobility - mobility));\n this.deductDailyCost();\n }\n if (getFuel() > 0) {\n this.mobility = this.maxMobility;\n }\n }\n\n /**\n * Precondition: the unit has enough mobility to make it to the Terrain toMoveto\n * Postcondition: the unit moves to the Terrain toMoveTo, traversing each terrain in a good path\n *\n * @throws Exception\n */\n public void move(Terrain toMoveTo, boolean... realMove) throws Exception {\n Terrain t = (Terrain) getLocation();\n boolean moveSuccess = realMove.length == 0 ?\n move(findPathTo(toMoveTo)) : move(findPathTo(toMoveTo), realMove[0]);\n if (moveSuccess) {\n immobilize();\n t = (Terrain) getLocation();\n for (Terrain checkingForHidden : t.getAllAdjacentTerrains()) {\n Actor occ = getGrid().get(checkingForHidden);\n if (occ instanceof HiddenUnit && ((HiddenUnit) occ).getContainedUnit().getOwner() != this.getOwner()) {\n HiddenUnit hu = (HiddenUnit) occ;\n Unit aha = hu.unBox();\n aha.immobilize();\n if (aha instanceof Stealth) {\n ((Stealth) aha).unHide();\n } else if (aha instanceof Stealth2) {\n ((Stealth2) aha).unHide();\n }\n }\n }\n } else {\n System.out.println(\"move failed, see line 441 of Unit\");\n }\n }\n\n /**\n * uses DFS\n *\n * @return a set of Terrains that the unit can move to, given constraints of the surrounding\n * terrain, units, and current mobility level\n */\n public Set<Terrain> getValidMoveSpaces() {\n Set<Terrain> ans = new HashSet<>();\n ans.add((Terrain) this.getLocation());\n if (!this.canMove()) {\n return ans;\n }\n Stack<Terrain> toCheck = new Stack<>();\n toCheck.push((Terrain) this.getLocation());\n Map<Terrain, Double> distances = new HashMap<>();\n distances.put((Terrain) this.getLocation(), 0.0);\n while (0 != toCheck.size()) {\n double distTo;\n Terrain current = toCheck.pop();\n ArrayList<Terrain> adjacent = current.getAllAdjacentTerrains();\n for (Terrain t : adjacent) {\n if ((distTo = distances.get(current) + t.getMoveCost(this.getMovementType())) <= mobility) {\n if (null == getGrid().get(t)) {\n if (!distances.containsKey(t) || distTo < distances.get(t)) {\n distances.put(t, distTo);\n toCheck.push(t);\n }\n ans.add(t);\n } else {\n Unit u = (Unit) getGrid().get(t);\n if (u.getOwner() == this.getOwner()) {\n if (distances.containsKey(t)) {\n if (distTo < distances.get(t)) {\n distances.put(t, distTo);\n toCheck.push(t);\n }\n } else {\n distances.put(t, distTo);\n toCheck.push(t);\n }\n if (u instanceof Carry) {\n Carry c = (Carry) u;\n if (c.canCarry(this)) {\n ans.add(t);\n }\n }\n }\n }\n }\n }\n }\n return ans;\n\n }\n\n //\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n//\tprivate Queue<Terrain> findpathTo_2(Terrain target) throws IllegalArgumentException{\n//\t\tif(null==target){\n//\t\t\tthrow new IllegalArgumentException(\"target is null\");\n//\t\t}\n//\t\tMap<Terrain, Integer> shortDistances = new HashMap<>();\n//\t\tMap<Terrain, Terrain> previousLink = new HashMap<>();\n//\t\tTerrain current = (Terrain) getLocation();\n//\t\tComparator<Terrain> comp = new Comparator<Terrain>() {\n//\t\t\t/**\n//\t\t\t * Approximates which has shorter path to get to\n//\t\t\t */\n//\t\t\t@Override\n//\t\t\tpublic int compare(Terrain arg0, Terrain arg1) {\n//\t\t\t\tint x;\n//\t\t\t\t//heuristic will never overestimate total cost\n//\t\t\t\tInteger c0 = ((-1==(x = calculatePathCost(arg0))?Integer.MAX_VALUE:x))+arg0.getDistanceTo(target);\n//\t\t\t\tInteger c1 = ((-1==(x = calculatePathCost(arg1))?Integer.MAX_VALUE:x))+arg1.getDistanceTo(target);\n//\t\t\t\treturn c0.compareTo(c1);\n//\t\t\t}\n//\t\t\tprivate int calculatePathCost(Terrain t){\n//\t\t\t\tif(!previousLink.containsKey(t)){\n//\t\t\t\t\treturn -1;\n//\t\t\t\t}\n//\t\t\t\tTerrain parent = previousLink.get(t);\n//\t\t\t\tif(null==parent){\n//\t\t\t\t\treturn 0;\n//\t\t\t\t}else{\n//\t\t\t\t\treturn (int) (calculatePathCost(previousLink.get(parent))+parent.getMoveCost(getMovementType()));\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\t\n//\t\t};\n//\t\tPriorityQueue<Terrain> toCheck = new PriorityQueue<>(comp);\n//\t\t//add all tiles in range\n//\t\ttoCheck.addAll(getValidMoveSpaces());\n//\t\t\n//\t\t\n//\t\t\n//\t\t\n//\t}\n\n private int totalCost(Queue<Terrain> path) {\n if (null == path || path.isEmpty()) {\n return 0;\n } else {\n int ans = 0;\n for (Terrain t : path) {\n ans += t.getMoveCost(getMovementType());\n }\n return ans;\n }\n }\n\n private int totalCost(Terrain t, Map<Terrain, Terrain> previousLink) {\n if (!previousLink.containsKey(t)) {\n throw new IllegalStateException(\"terrain not mapped to parent — how did we get here?\");\n }\n Terrain parent = previousLink.get(t);\n if (null == parent) {\n//\t\t\treturn (int) t.getMoveCost(getMovementType());\n //we started here, 0\n return 0;\n } else {\n return (int) (t.getMoveCost(getMovementType()) + totalCost(parent, previousLink));\n }\n }\n\n /**\n * Precondition: the unit has enough mobility to reach the Terrain that the path is being found to.\n * The returned path will be optimal, uses A*\n *\n * @return a queue of Terrains that could be traversed to reach the destination\n * @throws Exception\n */\n private Queue<Terrain> findPathTo(Terrain target) throws Exception {\n Queue<Terrain> ans = new LinkedList<>();\n\n if (null == target) {\n return new LinkedList<>();\n }\n\n if (target == getLocation()) {\n //you are already here\n return ans;\n }\n Map<Terrain, Terrain> previousLink = new HashMap<>();\n previousLink.put((Terrain) getLocation(), null);\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n Comparator<Terrain> comp = new Comparator() {\n @Override\n /**\n * Approximates which path is better\n */\n public int compare(Object o1, Object o2) {\n Terrain t1 = (Terrain) o1;\n Terrain t2 = (Terrain) o2;\n//\t\t\t\tInteger c1 = totalCost(savedPaths.get(t1))+t1.getDistanceTo(target);\n//\t\t\t\tInteger c2 = totalCost(savedPaths.get(t2))+t2.getDistanceTo(target);\n Integer c1 = totalCost(t1, previousLink) + t1.getDistanceTo(target);\n Integer c2 = totalCost(t2, previousLink) + t2.getDistanceTo(target);\n return c1.compareTo(c2);\n }\n\n };\n PriorityQueue<Terrain> toCheck = new PriorityQueue<>(comp);\n toCheck.add((Terrain) getLocation());\n while (!toCheck.isEmpty()) {\n Terrain current = toCheck.poll();\n for (Terrain t : current.getAllAdjacentTerrains()) {\n if (999 != t.getMoveCost(getMovementType()) &&\n (null == getGrid().get(t) || ((Unit) (getGrid().get(t))).getOwner() == this.getOwner())) {\n\n boolean updated = false;\n if (!previousLink.containsKey(t)) {\n previousLink.put(t, current);\n updated = true;\n }\n\n if (t == target) {\n return genPath(t, previousLink);\n }\n\n if (t.getMoveCost(getMovementType()) + totalCost(current, previousLink) < totalCost(t, previousLink)) {\n previousLink.put(t, current);\n updated = true;\n }\n if (totalCost(t, previousLink) <= getCurrentMobility() && updated) {\n if (!toCheck.contains(t)) {\n toCheck.add(t);\n }\n\n }\n }\n }\n }\n //if you got here, then there is no path\n //See Precondition: there is a path, checked by getValidMoveSpaces\n throw new Exception(\"no path, precondition not met\");\n\n }\n\n /**\n * Should only be invoked by {@code move(Queue<Terrain> path)} method\n * Postcondition: this.getLocation returns t\n */\n private void traverse(Grid<Actor> gr, Terrain t) {\n double moveCost = t.getMoveCost(this.getMovementType());\n setMobility(getCurrentMobility() - moveCost);\n }\n\n /**\n * Moves the {@link Unit} along a path of {@link Terrain}s.\n *\n * @param path A {@link Queue} of adjacent {@link Terrain}s\n * @return Whether or not {@link Unit} was successful in moving all the way along the path.\n * For now, it should always be successful because fog of war/land mines etc are not implemented yet\n */\n public boolean move(Queue<Terrain> path, boolean... realMove) {\n if (0 == path.size()) {\n //already done\n return true;\n }\n Terrain t = path.poll();\n Grid<Actor> gr = this.getGrid();\n //reached end of path, success\n if (t == null) {\n return true;\n }\n //invalid Terrain, fail -- should never happen\n if (!(gr.isValid(t))) {\n System.err.println(\"invalid terrain, not sure what happened here\");\n return false;\n }\n //not enough mobility -- should never happen\n if (t.getMoveCost((this.getMovementType())) > this.getCurrentMobility()) {\n System.err.println(\"not enough mobi -- check BFS algorithm???\");\n return false;\n }\n //Terrain is occupied by something other than allied Unit, fail\n try {\n Unit u = (Unit) (gr.get(t));\n if (null != u && u.getOwner() != this.getOwner()) {\n System.err.println(\"Terrain is occupied by something other than allied Unit, fail\");\n return false;\n }\n } catch (ClassCastException actorIsNotAUnit) {\n System.err.println(Arrays.toString(actorIsNotAUnit.getStackTrace()));\n System.err.println(\"why do you have non-units in the grid\");\n return false;\n }\n //move on\n traverse(getGrid(), t);\n if (path.peek() == null && realMove.length != 0) {\n teleport(t);\n }\n return realMove.length == 0 ? move(path) : move(path, true);\n }\n\n private void teleport(Terrain t) {\n Grid gr = getGrid();\n this.removeSelfFromGrid();\n this.putSelfInGrid(gr, t);\n }\n\n\n /**\n * Precondition: Carry c canCarry(this) is true\n *\n * @param c the Carry that this Unit will be loaded into\n * @throws Exception if unit cannot be carried\n */\n public void load(Carry c) throws Exception {\n if (c.canCarry(this)) {\n c.addUnit(this);\n } else {\n throw new Exception(\"cannot be carried, precondition not met\");\n }\n immobilize();\n }\n\n public String getWeaponInfo() {\n if (this instanceof HiddenUnit) {\n return null;\n }\n if (WeaponType.NONE.equals(getWeapons()[0].getWeaponType())) {\n if (getWeapons()[1] == null) {\n return \"Unarmed\";\n } else {\n return \"∞ ammo: \" + getWeapons()[1].getWeaponType();\n }\n } else {\n return getAmmo() + \" ammo: \" + getWeapons()[0].getWeaponType() +\n ((null != getWeapons()[1]) ? \", ∞ ammo: \" + getWeapons()[1].getWeaponType() : \"\");\n }\n }\n\n public String getInfo() {\n return getType() + ((null != getLocation() && getLocation() instanceof Terrain) ? \" at \" + ((Terrain) getLocation()).getUIName() + getLocation() : \"\")\n + \" [\" + getHealth() + \" HP, \" + ((int) getFuel()) + \" fuel, \" + getWeaponInfo() + \" ]\" +\n (((this instanceof Stealth && ((Stealth) this).isHidden()) || (this instanceof Stealth2 && ((Stealth2) this).isHidden())) ?\n \"[hidden]\" : \"\");\n }\n\n public String getConciseInfo() {\n return getType() + \" [\" + getHealth() + \" HP]\";\n }\n\n /**\n * @return whether or not this unit is a jet aircraft\n */\n public boolean isJet() {\n return (this instanceof Fighter || this instanceof Bomber || this instanceof StealthBomber ||\n this instanceof AdvFighter || this instanceof JSF || this instanceof CAS || this instanceof DropShip);\n }\n}", "public final class WeaponType {\n\n\t//direct fire\n\tpublic static final String NONE = \"NONE\";\n\tpublic static final String RIFLE = \"RIFLE\";\n\tpublic static final String ROCKET_LAUNCHER = \"ROCKET_LAUNCHER\";\n\tpublic static final String MG = \"MG\";\n\tpublic static final String HMG = \"HMG\";\n\tpublic static final String AP = \"AP\";\n\tpublic static final String HE = \"HE\";\n\tpublic static final String HEAT = \"HEAT\";\n\tpublic static final String ROCKET_POD = \"ROCKET_POD\";\n\tpublic static final String MISSILE = \"MISSILE\";\n\tpublic static final String FLAK = \"FLAK\";\n\tpublic static final String TORPEDO = \"TORPEDO\";\n\tpublic static final String DEPTH_CHARGE = \"DEPTH_CHARGE\";\n\t\n\t//indirect fire\n\tpublic static final String SHELL = \"SHELL\";\n\tpublic static final String MISSILES = \"MISSILES\";\n\tpublic static final String ROCKET = \"ROCKET\";\n\tpublic static final String ROTARY = \"ROTARY\";\n\t\n\t//special\n\tpublic static final String ICBM = \"ICBM\";\n}" ]
import java.util.ArrayList; import cbskarmory.Player; import cbskarmory.PassiveFlag.MoveType; import cbskarmory.terrain.Terrain; import cbskarmory.units.Air; import cbskarmory.units.Carry; import cbskarmory.units.Sea; import cbskarmory.units.Unit; import cbskarmory.weapons.WeaponType;
/* * Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory) * * This code 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. * * This code 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. * * @author CBSkarmory */ package cbskarmory.units.sea; /** * The aircraft carrier is a sea unit * Gets ROTARY (midrange anti-air) * Can target aircraft in Manhattan radius of 1-4 * Costs 3000 * Can carry 3 air units * Costs 1 fuel/turn to stay afloat */ public class Carrier extends Sea implements Carry { /** * Constructs am aircraft carrier * sets primary weapon to ROTARY * * @param owner owner of the unit */ public Carrier(Player owner) { super(owner); setWeapon(0, WeaponType.ROTARY); carried = new ArrayList<Unit>(); } ArrayList<Unit> carried; @Override public ArrayList<Unit> getUnits() { return carried; } @Override public int getMaxCapacity() { return 3; } @Override public void resupply() { //nope } @Override public boolean canResupply() { return false; } @Override public boolean canCarry(Unit u) { //can carry 3 air units
if (u instanceof Air) {
3
AndyGu/ShanBay
src/com/shanbay/words/handler/WordsUserHandler.java
[ "public class UserHandler<T extends APIClient> extends ModelResponseHandler<User>\n{\n private ShanbayActivity<T> mActivity;\n\n public UserHandler(ShanbayActivity<T> paramShanbayActivity)\n {\n super(User.class);\n this.mActivity = paramShanbayActivity;\n }\n\n protected void onAuthenticationFailure()\n {\n\t Log.e(\"UserHandler\", \"onAuthenticationFailure()\");\n this.mActivity.finish();\n this.mActivity.onRequestLogin();\n }\n\n public void onFailure(ModelResponseException mrException, JsonElement jsonElement)\n {\n\n\t Log.e(\"UserHandler\", \"onFailure()\");\n this.mActivity.handleCommonException(mrException);\n }\n \n public void onSuccess(int paramInt, User user)\n {\n\t Log.e(\"UserHandler\", \"onSuccess()\");\n UserCache.update(this.mActivity, user);\n onUserLoaded();\n }\n\n protected void onUserLoaded()\n {\n\t Log.e(\"UserHandler\", \"onUserLoaded()\");\n }\n\n\tpublic void user() {\n\t\tLog.e(\"UserHandler\", \"user()\");\n\t\tthis.mActivity.getClient().user(this.mActivity, this);\n\t}\n}", "public abstract class ShanbayActivity<T extends APIClient> extends BaseActivity<T>\n{\n public void home()\n {\n home(null);\n }\n\n public abstract void home(String paramString);\n\n protected void installApp(App paramApp)\n {\n if (!isFinishing());\n try\n {\n Intent localIntent = new Intent(\"android.intent.action.VIEW\");\n localIntent.setData(Uri.parse(HttpClient.getAbsoluteUrl(paramApp.rateUrl, APIClient.HOST)));\n startActivity(localIntent);\n return;\n }\n catch (Exception localException)\n {\n localException.printStackTrace();\n }\n }\n\n public void logout()\n {\n this.mClient.logout(this, new DataResponseHandler()\n {\n @Override\n public void onFailure(ModelResponseException paramAnonymousModelResponseException, JsonElement paramAnonymousJsonElement)\n {\n if (!ShanbayActivity.this.handleCommonException(paramAnonymousModelResponseException))\n ShanbayActivity.this.showToast(paramAnonymousModelResponseException.getMessage());\n }\n\n @Override\n public void onSuccess(int paramAnonymousInt, JsonElement paramAnonymousJsonElement)\n {\n ShanbayActivity.this.dismissProgressDialog();\n ShanbayActivity.this.onLogout();\n }\n });\n }\n\n public void logoutDialog()\n {\n new AlertDialog.Builder(this).setMessage(R.string.msg_logout).setTitle(R.string.logout).setPositiveButton(R.string.logout, new DialogInterface.OnClickListener()\n {\n public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)\n {\n ShanbayActivity.this.logout();\n }\n }).setNegativeButton(getString(R.string.cancel), null).show();\n }\n\n protected void onDestroy()\n {\n this.mClient.cancelRequest(this, true);\n super.onDestroy();\n }\n\n public abstract void onLogout();\n\n public abstract void onRequestLogin();\n\n @SuppressLint(\"NewApi\")\n public void startApp(App paramApp)\n {\n Intent localIntent = getPackageManager().getLaunchIntentForPackage(paramApp.identifier);\n if (localIntent == null)\n {\n installApp(paramApp);\n return;\n }\n startActivity(localIntent);\n }\n}", "public class CheckinDate extends Model\n{\n public String localTime;\n public String sessionDate;\n public String timezone;\n}", "public class WordsClient extends APIClient\n{\n static final String API_APPLET_ROOTS = \"api/v1/roots/applet/\";\n static final String API_BUY_APPLET_TEMPLATE = \"/api/v1/market/%s/buy/\";\n static final String API_CHECKIN = \"api/v1/checkin/\";\n static final String API_CHECKIN_LIST = \"api/v1/checkin/user/\";\n static final String API_CHECKIN_MAKEUP = \"/api/v1/checkin/makeup/\";\n static final String API_CHECKIN_SESSION_DATE = \"api/v1/checkin/date/\";\n static final String API_COINS_USER_ACCOUNT = \"/api/v1/coins/useraccount/\";\n static final String API_DEFINITIONS = \"api/v1/bdc/vocabulary/definitions/\";\n static final String API_EXAMPLE = \"api/v1/bdc/example/\";\n static final String API_GET_APPLET_PRICE = \"/api/v1/market/applet/price/\";\n static final String API_INIT_CONTENT_VERSION = \"/api/v1/bdc/contentversion/?type=\";\n static final String API_NOTE = \"api/v1/bdc/note/\";\n static final String API_NOTE_COLLECT = \"api/v1/bdc/note/collect/\";\n static final String API_RECOMMEND = \"api/v1/mobile/promotion/\";\n static final String API_REVIEW = \"api/v1/bdc/review/\";\n static final String API_REVIEW_INDEX = \"/api/v1/bdc/review/index/\";\n static final String API_STATS = \"api/v1/bdc/stats/today/\";\n static final String API_SYNC_REVIEW = \"/api/v1/bdc/review/sync/\";\n static final String API_TODAY_REVIEW = \"/api/v1/bdc/review/sync/\";\n static final String API_USER_APPLET = \"api/v1/market/userapplet/\";\n static final String API_USER_SETTING = \"api/v1/bdc/setting/\";\n static final String API_VACABULARY_TEST = \"/api/v1/vocabtest/wechat/\";\n static final String API_VOCABULARY = \"api/v1/bdc/vocabulary/\";\n static final String API_WORDBOOK_CATEGORIES = \"api/v1/wordbook/categories/\";\n static final String API_WORDBOOK_CATEGORY = \"api/v1/wordbook/category/{id}/\";\n static final String API_WORDBOOK_USER = \"api/v1/wordbook/userwordbook/\";\n static final String API_WORDS_CHECKIN_AWARD = \"/api/v1/badger/award/checkin/\";\n static final String API_WORDS_EXPERIENCE = \"/api/v1/bdc/experience/?roots={root}&collins={collin}&category={category}\";\n static final String API_WORDS_EXPERIENCE_CATEGORY = \"/api/v1/bdc/experience/category/\";\n static final String API_WORDS_FAQ = \"/api/v1/help/faq/\";\n static final String API_WORDS_QUOTE = \"/api/v1/quote/\";\n private static WordsClient singleton;\n\n public static String getAbsoluteUrl(String paramString)\n {\n if ((paramString.startsWith(\"http://\")) || (paramString.startsWith(\"https://\")))\n return paramString;\n if (paramString.startsWith(\"/\"))\n return HOST + paramString.substring(1);\n return HOST + paramString;\n }\n\n public static WordsClient getInstance()\n {\n if (singleton == null)\n singleton = new WordsClient();\n return singleton;\n }\n\n public void activateWordbook(Context paramContext, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"wordbook_id\", Long.toString(paramInt));\n localRequestParams.put(\"action\", \"activate\");\n put(paramContext, \"api/v1/wordbook/userwordbook/update/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void buyApplet(Context paramContext, String paramString, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n String str = String.format(\"/api/v1/market/%s/buy/\", new Object[] { paramString });\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"price_id\", Long.toString(paramLong));\n post(paramContext, str, localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void cacheSound(String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n if (StringUtils.isNotBlank(paramString))\n cacheSound(paramString, Env.getAudioCacheFile(AudioUtil.getFilenameByUrl(paramString)), paramAsyncHttpResponseHandler);\n }\n\n public void checkin(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/checkin/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void checkin(Context paramContext, String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"user_note\", paramString);\n post(paramContext, \"api/v1/checkin/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void checkinDiary(Context paramContext, long paramLong, String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"checkin_id\", Long.toString(paramLong));\n localRequestParams.put(\"user_note\", paramString);\n put(paramContext, \"api/v1/checkin/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void checkinList(Context paramContext, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n long l = UserCache.userId(paramContext);\n get(paramContext, \"api/v1/checkin/user/\" + l + \"/?page=\" + paramInt, null, paramAsyncHttpResponseHandler);\n }\n\n public void checkinMakeup(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/checkin/makeup/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void checkinMakeup(Context paramContext, String paramString1, String paramString2, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"date\", paramString1);\n localRequestParams.put(\"note\", paramString2);\n post(paramContext, \"/api/v1/checkin/makeup/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void collectNote(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"note_id\", Long.toString(paramLong));\n post(paramContext, \"api/v1/bdc/note/collect/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void collinsDefinition(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/vocabulary/definitions/\" + paramLong, null, paramAsyncHttpResponseHandler);\n }\n\n public void deleteNote(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n delete(paramContext, \"api/v1/bdc/note/\" + Long.toString(paramLong), paramAsyncHttpResponseHandler);\n }\n\n public void exampleInWords(Context paramContext, ArrayList<Long> paramArrayList, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/example/?ids=\" + Misc.idsToQueryString(paramArrayList), null, paramAsyncHttpResponseHandler);\n }\n\n public void experienceCategory(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/bdc/experience/category/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void experienceData(Context mContext, int root, int collin, long category, AsyncHttpResponseHandler ahrh)\n {\n\t Log.e(\"WordsClient.experienceData()\", \"WordsClient.experienceData()\");\n\t get(mContext, \"/api/v1/bdc/experience/?roots={root}&collins={collin}&category={category}\".replace(\"{root}\", Integer.toString(root)).replace(\"{collin}\", Integer.toString(collin)).replace(\"{category}\", Long.toString(category)), null, ahrh);\n }\n\n public void getAppletPrices(Context paramContext, String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"iap\", \"0\");\n localRequestParams.put(\"code\", paramString);\n get(paramContext, \"/api/v1/market/applet/price/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void getCheckinAward(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/badger/award/checkin/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void getCoinsAccount(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/coins/useraccount/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void getFAQ(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/help/faq/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void getQuote(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/quote/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void getRoots(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/roots/applet/?ids=\" + paramLong, null, paramAsyncHttpResponseHandler);\n }\n\n public void getVocabularyTestList(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/vocabtest/wechat/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void initContentVersion(Context paramContext, String paramString, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/bdc/contentversion/?type=\" + paramString + \"&version=\" + String.valueOf(paramLong), null, paramAsyncHttpResponseHandler);\n }\n\n public void note(Context paramContext, Collection<Long> paramCollection, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n if (paramCollection.size() == 0);\n for (String str = \"0\"; ; str = Misc.idsToQueryString((List)paramCollection))\n {\n get(paramContext, \"api/v1/bdc/note/?ids=\" + str, null, paramAsyncHttpResponseHandler);\n return;\n }\n }\n\n public void noteByVocabulary(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/note/?vocabulary_id=\" + paramLong, null, paramAsyncHttpResponseHandler);\n }\n\n public void postVocabularyTestResult(Context paramContext, List<Long> paramList1, List<Long> paramList2, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"correct_words\", Misc.idsToQueryString(paramList1));\n localRequestParams.put(\"words\", Misc.idsToQueryString(paramList2));\n post(paramContext, \"/api/v1/vocabtest/wechat/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void putPlayMode(Context paramContext, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"auto_play_mode\", String.valueOf(paramInt));\n put(paramContext, \"api/v1/bdc/setting/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void putUserSetting(Context paramContext, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"target_level\", String.valueOf(paramInt));\n put(paramContext, \"api/v1/bdc/setting/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void reviewIndex(Context paramContext, String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"/api/v1/bdc/review/index/?update_type=\" + paramString, null, paramAsyncHttpResponseHandler);\n }\n\n public void sessionDate(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/checkin/date/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void stats(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/stats/today/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void subscribeWordbook(Context paramContext, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"wordbook_id\", Long.toString(paramInt));\n localRequestParams.put(\"action\", \"subscribe\");\n put(paramContext, \"api/v1/wordbook/userwordbook/update/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void syncData(Context paramContext, List<ReviewSyncData> paramList, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n// RequestParams localRequestParams = new RequestParams();\n// localRequestParams.put(\"ids\", SyncDataDao.buildIdStr(paramList));\n// localRequestParams.put(\"review_statuses\", SyncDataDao.buildStatusStr(paramList));\n// localRequestParams.put(\"retentions\", SyncDataDao.buildRetentionStr(paramList));\n// localRequestParams.put(\"seconds\", SyncDataDao.buildDeltaSecondsStr(paramList));\n// put(paramContext, \"/api/v1/bdc/review/sync/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void testDownloadMedia(Context paramContext, String paramString, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, paramString, null, paramAsyncHttpResponseHandler);\n }\n\n public void updateCollinsDefinition(Context paramContext, long paramLong1, long paramLong2, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n String str = \"api/v1/bdc/learning/\" + paramLong1;\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"sense\", String.valueOf(paramLong2));\n put(paramContext, str, localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void updateReviewIndex(Context paramContext, String paramString, int paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n RequestParams localRequestParams = new RequestParams();\n localRequestParams.put(\"update_type\", paramString);\n localRequestParams.put(\"index\", String.valueOf(paramInt));\n put(paramContext, \"/api/v1/bdc/review/index/\", localRequestParams, paramAsyncHttpResponseHandler);\n }\n\n public void userApplet(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n long l = UserCache.userId(paramContext);\n get(paramContext, \"api/v1/market/userapplet/\" + l + \"/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void userSetting(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/setting/\" + paramLong, null, paramAsyncHttpResponseHandler);\n }\n\n public void userWordbook(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n long l = UserCache.userId(paramContext);\n get(paramContext, \"api/v1/wordbook/userwordbook/\" + l + \"/\", null, paramAsyncHttpResponseHandler);\n }\n\n public void vocabularyInWords(Context paramContext, ArrayList<Long> paramArrayList, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/bdc/vocabulary/?ids=\" + Misc.idsToQueryString(paramArrayList), null, paramAsyncHttpResponseHandler);\n }\n\n public void wordbookByCategory(Context paramContext, long paramLong, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/wordbook/category/{id}/\".replace(\"{id}\", paramLong + \"\"), null, paramAsyncHttpResponseHandler);\n }\n\n public void wordbookCategories(Context paramContext, AsyncHttpResponseHandler paramAsyncHttpResponseHandler)\n {\n get(paramContext, \"api/v1/wordbook/categories/\", null, paramAsyncHttpResponseHandler);\n }\n}", "public class WordsActivity extends ShanbayActivity<WordsClient>\n{\n\tprotected final String ACTION_HOME_INIT = \"home_init\";\n\tprotected final String ACTION_HOME_INIT_KEY = \"session_date\";\n\tprotected final String ACTION_HOME_NORMAL = \"home_normal\";\n\tprotected final String ACTION_HOME_LOGOUT = \"home_logout\";\n\tprivate AudioManager mAudioManger;\n\tprivate WordsSoundPlayer mSoundPlayer;\n\tprivate Toast mToastNetworkFailure;\n\n public WordsClient getClient()\n {\n return WordsClient.getInstance();\n }\n\n public WordsSoundPlayer getSoundPlayer()\n {\n if (this.mSoundPlayer == null)\n this.mSoundPlayer = new WordsSoundPlayer(getClient());\n return this.mSoundPlayer;\n }\n\n public void goHome()\n {\n\t Log.e(\"WordsActivity.goHome()\", \"WordsActivity.goHome()\");\n// Intent localIntent = new Intent(this, HomeActivity.class);\n// localIntent.setFlags(67108864);\n// localIntent.setAction(\"home_normal\");\n// startActivity(localIntent);\n }\n\n public void goHomeInit(String paramString)\n {\n\t Log.e(\"WordsActivity.goHomeInit(String)\", \"WordsActivity.goHomeInit(String)\");\n// Intent localIntent = new Intent(this, HomeActivity.class);\n// localIntent.setAction(\"home_init\");\n// localIntent.setFlags(67108864);\n// localIntent.putExtra(\"session_date\", paramString);\n// startActivity(localIntent);\n }\n\n public void home(String paramString)\n {\n\t Log.e(\"WordsActivity.home(String)\", \"WordsActivity.home(String)\");\n// if (!(this instanceof HomeActivity))\n// {\n// Intent localIntent = new Intent(this, HomeActivity.class);\n// localIntent.setFlags(67108864);\n// if (paramString != null)\n// localIntent.setAction(paramString);\n// startActivity(localIntent);\n// }\n }\n\n public void networkFailure()\n {\n showNetworkFailureToast();\n }\n\n protected void onCreate(Bundle paramBundle)\n {\n super.onCreate(paramBundle);\n this.mAudioManger = ((AudioManager)getSystemService(\"audio\"));\n d(\"onCreate:\");\n }\n\n protected void onDestroy()\n {\n super.onDestroy();\n d(\"onDestroy\");\n if (this.mSoundPlayer != null)\n this.mSoundPlayer.stopSound();\n dismissProgressDialog();\n }\n\n public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)\n {\n switch (paramInt)\n {\n default:\n return super.onKeyDown(paramInt, paramKeyEvent);\n case 24:\n this.mAudioManger.adjustStreamVolume(3, 1, 5);\n return true;\n case 25:\n }\n this.mAudioManger.adjustStreamVolume(3, -1, 5);\n return true;\n }\n\n public void onLogout()\n {\n home(\"home_logout\");\n finish();\n }\n\n protected void onPause()\n {\n super.onPause();\n d(\"onPause\");\n if (this.mSoundPlayer != null)\n this.mSoundPlayer.stopSound();\n }\n\n public void onRequestLogin()\n {\n startActivity(new Intent(this, WelcomeActivity.class));\n }\n\n protected void onRestoreInstanceState(Bundle paramBundle)\n {\n d(\"onRestoreInstanceState:\" + paramBundle);\n super.onRestoreInstanceState(paramBundle);\n }\n\n protected void onResume()\n {\n super.onResume();\n d(\"onResume\");\n }\n\n protected void onSaveInstanceState(Bundle paramBundle)\n {\n d(\"onSaveInstanceState:\" + paramBundle);\n super.onSaveInstanceState(paramBundle);\n }\n\n protected void onStart()\n {\n super.onStart();\n d(\"onStart\");\n }\n\n protected void onStop()\n {\n super.onStop();\n d(\"onStop\");\n if (this.mSoundPlayer != null)\n this.mSoundPlayer.stopSound();\n }\n\n public void serverFailure()\n {\n// startActivity(new Intent(this, ServerFailureActivity.class));\n// finish();\n }\n\n public void showNetworkFailureToast()\n {\n if (isFinishing())\n return;\n if (this.mToastNetworkFailure == null)\n {\n this.mToastNetworkFailure = new Toast(this);\n View localView = LayoutInflater.from(this).inflate(2130903276, null);\n this.mToastNetworkFailure.setView(localView);\n this.mToastNetworkFailure.setGravity(0, 0, 0);\n this.mToastNetworkFailure.setDuration(0);\n this.mToastNetworkFailure.show();\n return;\n }\n this.mToastNetworkFailure.show();\n }\n}" ]
import android.util.Log; import com.shanbay.account.UserHandler; import com.shanbay.app.ShanbayActivity; import com.shanbay.community.model.CheckinDate; import com.shanbay.words.WordsClient; import com.shanbay.words.activity.WordsActivity;
package com.shanbay.words.handler; public class WordsUserHandler extends UserHandler<WordsClient> { private WordsActivity mActivity; private WordSessionDateHandler mSessionDateHandler; public WordsUserHandler(ShanbayActivity<WordsClient> mActivity) { super(mActivity); this.mActivity = ((WordsActivity)mActivity); } protected void onUserLoaded() { Log.e("WordsUserHandler", "onUserLoaded()"); this.mSessionDateHandler = new WordSessionDateHandler(this.mActivity) {
protected void onCheckinSessisonFinish(boolean paramAnonymousBoolean, CheckinDate paramAnonymousCheckinDate)
2
Qualtagh/JBroTable
test/io/github/qualtagh/swing/table/tutorial/CustomRenderer.java
[ "public interface IModelFieldGroup extends Cloneable {\n String getCaption();\n void setCaption( String caption );\n \n String getIdentifier();\n void setIdentifier( String identifier );\n \n ModelFieldGroup getParent();\n \n int getColspan();\n \n int getRowspan();\n void setRowspan( int rowspan );\n \n boolean isManageable();\n void setManageable( boolean manageable );\n \n boolean isFixed();\n void setFixed( boolean fixed );\n \n IModelFieldGroup clone();\n boolean equals( Object obj, boolean withParent );\n}", "public class ModelData implements Serializable {\n private static final long serialVersionUID = 1L;\n /** This constant is returned if the requested field and its coordinates are not found. */\n public static final int NO_FIELD_COORDINATES[] = { -1, -1 };\n\n private ModelRow rows[];\n private ModelField fields[];\n private transient Map< String, Integer > fieldsIndex = new HashMap< String, Integer >();\n private transient Map< String, int[] > fieldGroupsIndex = new HashMap< String, int[] >();\n private transient List< IModelFieldGroup[] > fieldGroups = new ArrayList< IModelFieldGroup[] >();\n\n public ModelData() {\n this( null );\n }\n\n public ModelData( ModelField fields[] ) {\n setFields( fields );\n }\n\n public ModelData( IModelFieldGroup fieldGroups[] ) {\n this( ModelFieldGroup.getBottomFields( fieldGroups ) );\n }\n \n private void readObject( ObjectInputStream ois ) throws IOException, ClassNotFoundException {\n ois.defaultReadObject();\n indexateFields();\n }\n\n public void setFields( ModelField fields[] ) {\n if ( ModelField.equals( this.fields, fields ) ) {\n // Fields are equal but object references may differ, so this set of a new reference is required.\n this.fields = fields;\n } else {\n if ( this.fields != null )\n rows = null;\n this.fields = fields;\n indexateFields();\n }\n }\n\n public ModelField[] getFields() {\n return fields;\n }\n\n public int getFieldsCount() {\n return getFieldsCount( false );\n }\n \n public int getFieldsCount( boolean visibleOnly ) {\n if ( fields == null ) {\n return 0;\n }\n return visibleOnly ? ModelField.getVisibleFieldsCount( fields ) : fields.length;\n }\n\n public List< IModelFieldGroup[] > getFieldGroups() {\n return fieldGroups;\n }\n \n public void setRows( ModelRow rows[] ) {\n this.rows = rows;\n }\n\n public ModelRow[] getRows() {\n return rows;\n }\n\n public int getRowsCount() {\n return rows == null ? 0 : rows.length;\n }\n \n /**\n * Get index of a field in a table data model by a given field identifier.\n * @param identifier field identifier\n * @return index of a field, or -1 if such field doesn't exist\n */\n public int getIndexOfModelField( String identifier ) {\n Integer ret = fieldsIndex.get( identifier );\n return ret == null ? -1 : ret;\n }\n \n /**\n * Get coordinates of a field (or a field group) by a given field identifier.\n * A pair ( column, row ) is returned.\n * @param identifier field group identifier\n * @return a pair ( x, y ), or ( -1, -1 ) if such field does not exist. Non null.\n */\n public int[] getIndexOfModelFieldGroup( String identifier ) {\n int ret[] = fieldGroupsIndex.get( identifier );\n return ret == null ? NO_FIELD_COORDINATES : ret;\n }\n \n public Object getValue( int row, String fieldName ) {\n if ( row < 0 || row >= getRowsCount() ) {\n return null;\n }\n int fIdx = getIndexOfModelField( fieldName );\n if ( fIdx == -1 ) {\n return null;\n }\n return rows[ row ] == null ? null : rows[ row ].getValue( fIdx );\n }\n\n public Object getValue( int row, int field ) {\n if ( row < 0 || row >= getRowsCount() ) {\n return null;\n }\n if ( field < 0 || field >= getFieldsCount() ) {\n return null;\n }\n return rows[ row ] == null ? null : rows[ row ].getValue( field );\n }\n \n public void setValue( int row, String fieldName, Object value ) {\n if ( row < 0 || row >= getRowsCount() ) {\n return;\n }\n int fIdx = getIndexOfModelField( fieldName );\n if ( fIdx == -1 ) {\n return;\n }\n rows[ row ].getValues()[ fIdx ] = value;\n }\n\n public void setValue( int row, int field, Object value ) {\n if ( row < 0 || row >= getRowsCount() ) {\n return;\n }\n if ( field < 0 || field >= getFieldsCount() ) {\n return;\n }\n rows[ row ].getValues()[ field ] = value;\n }\n\n private void indexateFields() {\n if ( fields == null )\n fields = new ModelField[ 0 ];\n Map<String, Integer> newFieldsIndex = new HashMap<String, Integer>( fields.length );\n for ( int i = 0; i < fields.length; i++ )\n if ( newFieldsIndex.put( fields[ i ].getIdentifier(), i ) != null )\n throw new IllegalArgumentException( \"Duplicated identifier: \" + fields[ i ].getIdentifier() );\n fieldsIndex = newFieldsIndex;\n fieldGroupsIndex = new HashMap<String, int[]>();\n IModelFieldGroup upper[] = ModelFieldGroup.getUpperFieldGroups( fields );\n ModelField bottom[] = ModelFieldGroup.getBottomFields( upper );\n if ( !Arrays.equals( bottom, fields ) )\n throw new IllegalArgumentException( \"Field groups contain more children than specified in fields array.\\nActual: \" + Arrays.toString( fields ) + \"\\nExpected: \" + Arrays.toString( bottom ) );\n calculateRowspan( fields );\n for ( IModelFieldGroup group : upper )\n group.setRowspan( 0 );\n calculateRowspanForUpper( upper );\n fieldGroups = new ArrayList< IModelFieldGroup[] >();\n addFieldGroupsRecursively( upper, 0, new HashMap< String, Integer >() );\n }\n\n private void calculateRowspan( IModelFieldGroup fieldGroups[] ) {\n List< IModelFieldGroup > parents = new ArrayList< IModelFieldGroup >();\n FieldGroupsLoop:\n for ( IModelFieldGroup fieldGroup : fieldGroups ) {\n ModelFieldGroup parent = fieldGroup.getParent();\n if ( parent != null && parent.getChildrenRowspan() == -1 ) {\n int childrenRowspan = 0;\n for ( IModelFieldGroup child : parent.getChildren() ) {\n int rowspan = child.getRowspan();\n if ( rowspan < 1 )\n rowspan = 1;\n if ( child instanceof ModelFieldGroup ) {\n int childChildrenRowspan = ( ( ModelFieldGroup )child ).getChildrenRowspan();\n if ( childChildrenRowspan >= 0 )\n rowspan += childChildrenRowspan;\n else\n continue FieldGroupsLoop;\n }\n if ( rowspan > childrenRowspan )\n childrenRowspan = rowspan;\n }\n parent.setChildrenRowspan( childrenRowspan );\n for ( IModelFieldGroup child : parent.getChildren() ) {\n int rowspan = childrenRowspan;\n if ( child instanceof ModelFieldGroup ) {\n rowspan -= ( ( ModelFieldGroup )child ).getChildrenRowspan();\n }\n child.setRowspan( rowspan );\n }\n parents.add( parent );\n }\n }\n if ( !parents.isEmpty() )\n calculateRowspan( parents.toArray( new IModelFieldGroup[ parents.size() ] ) );\n }\n \n private void calculateRowspanForUpper( IModelFieldGroup upper[] ) {\n int childrenRowspan = 0;\n for ( IModelFieldGroup fieldGroup : upper ) {\n int rowspan = fieldGroup.getRowspan();\n if ( rowspan < 1 )\n rowspan = 1;\n if ( fieldGroup instanceof ModelFieldGroup ) {\n rowspan += ( ( ModelFieldGroup )fieldGroup ).getChildrenRowspan();\n }\n if ( rowspan > childrenRowspan )\n childrenRowspan = rowspan;\n }\n for ( IModelFieldGroup fieldGroup : upper ) {\n int rowspan = childrenRowspan;\n if ( fieldGroup instanceof ModelFieldGroup ) {\n rowspan -= ( ( ModelFieldGroup )fieldGroup ).getChildrenRowspan();\n }\n fieldGroup.setRowspan( rowspan );\n }\n }\n\n private void addFieldGroupsRecursively( IModelFieldGroup upper[], int level, Map< String, Integer > fieldPosIndex ) {\n fieldGroups.add( upper );\n int x = 0;\n int posX = 0;\n List< IModelFieldGroup > current = new ArrayList< IModelFieldGroup >();\n for ( IModelFieldGroup fieldGroup : upper ) {\n int rowspan = fieldGroup.getRowspan();\n String identifier = fieldGroup.getIdentifier();\n int prev[] = fieldGroupsIndex.get( identifier );\n boolean groupFinished = rowspan == 1;\n if ( prev == null ) {\n fieldGroupsIndex.put( identifier, new int[]{ x, level } );\n fieldPosIndex.put( identifier, posX );\n } else {\n int prevX = fieldPosIndex.get( identifier );\n if ( prevX != posX )\n throw new IllegalArgumentException( \"Field group should be unbroken: \" + fieldGroup );\n if ( !groupFinished )\n groupFinished = rowspan == 1 + level - prev[ 1 ];\n }\n if ( groupFinished ) {\n if ( fieldGroup instanceof ModelFieldGroup ) {\n ModelFieldGroup group = ( ModelFieldGroup )fieldGroup;\n current.addAll( group.getChildren() );\n }\n } else\n current.add( fieldGroup );\n x++;\n posX += fieldGroup.getColspan();\n }\n if ( !current.isEmpty() )\n addFieldGroupsRecursively( current.toArray( new IModelFieldGroup[ current.size() ] ), level + 1, fieldPosIndex );\n }\n\n /**\n * A method for testing purposes.\n * @return a string representation of this array's header (fields and their groups)\n * @deprecated should not be used in production code\n */\n public String getHeaderString() {\n int maxIdentifierLength = 0;\n for ( String identifier : fieldGroupsIndex.keySet() )\n if ( identifier.length() > maxIdentifierLength )\n maxIdentifierLength = identifier.length();\n if ( maxIdentifierLength == 0 )\n maxIdentifierLength = 1;\n maxIdentifierLength++;\n int maxX = fields.length;\n StringBuilder sb = new StringBuilder();\n for ( IModelFieldGroup groups[] : fieldGroups ) {\n if ( sb.length() > 0 )\n sb.append( '\\n' );\n else\n sb.append( Utils.rpad( \"\", '+', maxX * ( maxIdentifierLength + 3 ) ) ).append( '\\n' );\n for ( IModelFieldGroup group : groups ) {\n sb.append( \"+ \" ).append( Utils.rpad( group.getIdentifier(), ( maxIdentifierLength + 3 ) * group.getColspan() - 3 ) ).append( '+' );\n }\n sb.append( '\\n' ).append( Utils.rpad( \"\", '+', maxX * ( maxIdentifierLength + 3 ) ) );\n }\n return sb.toString();\n }\n\n /**\n * Scan field groups starting from bottom.\n * <b>For testing purposes only.</b>\n * @param depthFirst scan field groups in depth-first manner if true, otherwise scan in breadth-first manner\n * @return field groups sequence\n * @deprecated use {@link #getFieldGroups} instead\n */\n public Iterable< IModelFieldGroup > getAllFieldGroupsFromBottom( final boolean depthFirst ) {\n return new Iterable< IModelFieldGroup >() {\n private final Deque< IModelFieldGroup > list = new ArrayDeque< IModelFieldGroup >( Arrays.asList( fields ) );\n private final Set< String > visited = new HashSet< String >();\n \n @Override\n public Iterator< IModelFieldGroup > iterator() {\n return new Iterator< IModelFieldGroup >() {\n @Override\n public boolean hasNext() {\n return !list.isEmpty();\n }\n\n @Override\n public IModelFieldGroup next() {\n IModelFieldGroup ret = list.pollFirst();\n IModelFieldGroup parent = ret.getParent();\n if ( parent != null && visited.add( parent.getIdentifier() ) ) {\n if ( depthFirst )\n list.addFirst( parent );\n else\n list.addLast( parent );\n }\n return ret;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n };\n }\n \n /**\n * Scan field groups starting from top.\n * @param depthFirst scan field groups in depth-first manner if true, otherwise scan in breadth-first manner\n * @return field groups sequence\n */\n public Iterable< IModelFieldGroup > getAllFieldGroupsFromTop( final boolean depthFirst ) {\n return new Iterable< IModelFieldGroup >() {\n private final Deque< IModelFieldGroup > list = new ArrayDeque< IModelFieldGroup >( fieldGroups.isEmpty() ? Collections.EMPTY_LIST : Arrays.asList( fieldGroups.get( 0 ) ) );\n \n @Override\n public Iterator< IModelFieldGroup > iterator() {\n return new Iterator< IModelFieldGroup >() {\n @Override\n public boolean hasNext() {\n return !list.isEmpty();\n }\n\n @Override\n public IModelFieldGroup next() {\n IModelFieldGroup ret = list.pollFirst();\n if ( ret instanceof ModelFieldGroup ) {\n if ( depthFirst ) {\n List< IModelFieldGroup > children = ( ( ModelFieldGroup )ret ).getChildren();\n for ( int i = children.size() - 1; i >= 0; i-- )\n list.addFirst( children.get( i ) );\n } else\n for ( IModelFieldGroup child : ( ( ModelFieldGroup )ret ).getChildren() )\n list.addLast( child );\n }\n return ret;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n };\n }\n \n /**\n * Return a copy of this data object with a new field (or field group) added\n * @param addTo id of parent group (null for root) to which the new field should be inserted\n * @param field the new column (or group) to be inserted\n * @return a copy of this with a given field added\n * @throws IllegalArgumentException if addTo points to a non-existing group\n * @throws ClassCastException if addTo points to a regular field (not a group)\n */\n public ModelData withField( String addTo, IModelFieldGroup field ) throws IllegalArgumentException, ClassCastException {\n if ( field == null )\n throw new IllegalArgumentException( \"Field cannot be null\" );\n int idx[] = addTo == null ? null : getIndexOfModelFieldGroup( addTo );\n if ( idx != null && idx[ 0 ] == -1 )\n throw new IllegalArgumentException( \"Parent group \\\"\" + addTo + \"\\\" not found\" );\n IModelFieldGroup newGroups[];\n if ( idx == null )\n {\n IModelFieldGroup groups[] = ModelFieldGroup.getUpperFieldGroups( getFields() );\n newGroups = new IModelFieldGroup[ groups.length + 1 ];\n System.arraycopy( groups, 0, newGroups, 0, groups.length );\n newGroups[ groups.length ] = field;\n }\n else\n {\n ModelField newFields[] = ModelField.copyOfModelFields( getFields() );\n ModelData idxData = new ModelData( newFields );\n ModelFieldGroup group = ( ModelFieldGroup )idxData.getFieldGroups().get( idx[ 1 ] )[ idx[ 0 ] ];\n group.withChild( field );\n newGroups = ModelFieldGroup.getUpperFieldGroups( newFields );\n }\n ModelField newFields[] = ModelFieldGroup.getBottomFields( newGroups );\n ModelData newData = new ModelData( newFields );\n if ( rows != null )\n {\n newFields = ModelFieldGroup.getBottomFields( new IModelFieldGroup[]{ field } );\n if ( newFields.length == 0 )\n throw new IllegalArgumentException( \"No columns found in column group \\\"\" + field.getIdentifier() + '\"' );\n int colFromIncl = newData.getIndexOfModelField( newFields[ 0 ].getIdentifier() );\n int colToExcl = colFromIncl + field.getColspan();\n int newLength = newData.getFieldsCount();\n ModelRow newRows[] = new ModelRow[ rows.length ];\n for ( int i = 0; i < rows.length; i++ )\n {\n ModelRow newRow = new ModelRow( newLength );\n newRows[ i ] = newRow;\n Object values[] = rows[ i ].getValues();\n if ( values == null || values.length == 0 )\n continue;\n Object newValues[] = newRow.getValues();\n if ( colFromIncl > 0 )\n System.arraycopy( values, 0, newValues, 0, colFromIncl );\n if ( colFromIncl < values.length )\n System.arraycopy( values, colFromIncl, newValues, colToExcl, values.length - colFromIncl );\n }\n newData.setRows( newRows );\n }\n return newData;\n }\n \n /**\n * Returns a copy of this data object without a given field (or field group)\n * @param id identifier of a field (group) to be removed\n * @return a copy of this with a given field removed\n * @throws IllegalArgumentException when there are no fields with a given id\n */\n public ModelData withoutField( String id ) throws IllegalArgumentException {\n int idx[] = getIndexOfModelFieldGroup( id );\n if ( idx[ 0 ] == -1 )\n throw new IllegalArgumentException( \"Group \\\"\" + id + \"\\\" not found\" );\n IModelFieldGroup group = getFieldGroups().get( idx[ 1 ] )[ idx[ 0 ] ];\n while ( true ) {\n ModelFieldGroup parent = group.getParent();\n if ( parent == null || parent.getChildren().size() != 1 )\n break;\n group = parent;\n }\n id = group.getIdentifier();\n idx = getIndexOfModelFieldGroup( id );\n ModelRow newRows[] = null;\n if ( rows != null )\n {\n ModelField groupFields[] = ModelFieldGroup.getBottomFields( new IModelFieldGroup[]{ group } );\n if ( groupFields.length > 0 ) {\n int colToExcl = getIndexOfModelField( groupFields[ 0 ].getIdentifier() );\n int colFromIncl = colToExcl + group.getColspan();\n int newLength = getFieldsCount() - group.getColspan();\n newRows = new ModelRow[ rows.length ];\n for ( int i = 0; i < rows.length; i++ )\n {\n ModelRow newRow = new ModelRow( newLength );\n newRows[ i ] = newRow;\n Object values[] = rows[ i ].getValues();\n if ( values == null || values.length == 0 )\n continue;\n Object newValues[] = newRow.getValues();\n if ( colToExcl > 0 )\n System.arraycopy( values, 0, newValues, 0, colToExcl );\n if ( colFromIncl < values.length )\n System.arraycopy( values, colFromIncl, newValues, colToExcl, values.length - colFromIncl );\n }\n }\n }\n IModelFieldGroup newGroups[];\n if ( idx[ 1 ] == 0 )\n {\n IModelFieldGroup groups[] = ModelFieldGroup.getUpperFieldGroups( getFields() );\n newGroups = new IModelFieldGroup[ groups.length - 1 ];\n if ( idx[ 0 ] > 0 )\n System.arraycopy( groups, 0, newGroups, 0, idx[ 0 ] );\n if ( idx[ 0 ] < newGroups.length )\n System.arraycopy( groups, idx[ 0 ] + 1, newGroups, idx[ 0 ], newGroups.length - idx[ 0 ] );\n }\n else\n {\n ModelField newFields[] = ModelField.copyOfModelFields( getFields() );\n ModelData idxData = new ModelData( newFields );\n group = idxData.getFieldGroups().get( idx[ 1 ] )[ idx[ 0 ] ];\n ModelFieldGroup parent = group.getParent();\n parent.removeChild( group );\n newGroups = ModelFieldGroup.getUpperFieldGroups( newFields );\n }\n ModelField newFields[] = ModelFieldGroup.getBottomFields( newGroups );\n ModelData newData = new ModelData( newFields );\n if ( newRows != null )\n newData.setRows( newRows );\n return newData;\n }\n \n public void removeRow( int row ) throws IndexOutOfBoundsException {\n ModelRow newRows[] = new ModelRow[ getRowsCount() - 1 ];\n if ( row > 0 )\n System.arraycopy( rows, 0, newRows, 0, row );\n if ( row < newRows.length )\n System.arraycopy( rows, row + 1, newRows, row, newRows.length - row );\n setRows( newRows );\n }\n\n public void addRow( Object rowData[] ) {\n int row = getRowsCount();\n ModelRow newRows[] = new ModelRow[ row + 1 ];\n if ( row > 0 )\n System.arraycopy( rows, 0, newRows, 0, row );\n newRows[ row ] = new ModelRow( getFieldsCount() );\n newRows[ row ].setValues( rowData );\n newRows[ row ].setLength( getFieldsCount() );\n setRows( newRows );\n }\n}", "public class ModelField implements Serializable, Comparable< ModelField >, IModelFieldGroup {\n private static final long serialVersionUID = 3L;\n \n private String identifier;\n private String caption;\n private ModelFieldGroup parent;\n private int rowspan;\n private boolean fixed;\n private boolean manageable;\n private boolean visible;\n private Integer defaultWidth;\n\n public ModelField() {\n this( null, null );\n }\n\n public ModelField( String identifier, String caption ) {\n this.caption = caption;\n this.identifier = identifier;\n visible = true;\n manageable = true;\n }\n\n @Override\n public void setIdentifier( String identifier ) {\n if ( identifier == null )\n throw new IllegalArgumentException( \"Trying to set a null identifier for the field \" + this.identifier + \" (\" + caption + \")\" );\n this.identifier = identifier;\n }\n\n @Override\n public String getIdentifier() {\n return identifier;\n }\n\n /**\n * Field ID. Should be unique in the whole array.\n * @param identifier field ID, usually a database field name\n * @return this\n */\n public ModelField withIdentifier( String identifier ) {\n setIdentifier( identifier );\n return this;\n }\n \n public void setVisible( boolean visible ) {\n this.visible = visible;\n }\n\n public boolean isVisible() {\n return visible;\n }\n \n /**\n * Field visibility property.\n * @param visible true - this field should be visible in table, false - this column should be hidden\n * @return this\n */\n public ModelField withVisible( boolean visible ) {\n setVisible( visible );\n return this;\n }\n\n public Integer getDefaultWidth() {\n return defaultWidth;\n }\n\n public void setDefaultWidth( Integer defaultWidth ) {\n this.defaultWidth = defaultWidth;\n }\n \n /**\n * Initial column width.\n * <p>{@code null} value means that initial width is not set. A default one would be used (determined by Swing).</p>\n * @param defaultWidth initial column width\n * @return this\n */\n public ModelField withDefaultWidth( Integer defaultWidth ) {\n setDefaultWidth( defaultWidth );\n return this;\n }\n\n @Override\n public String getCaption() {\n return caption;\n }\n\n @Override\n public void setCaption( String caption ) {\n this.caption = caption;\n }\n\n /**\n * Visible column title. Can start with &lt;html&gt; and contain hypertext markup.\n * @param caption column title\n * @return this\n */\n public ModelField withCaption( String caption ) {\n setCaption( caption );\n return this;\n }\n \n @Override\n public void setFixed( boolean fixed ) {\n this.fixed = fixed;\n if ( fixed && parent != null )\n parent.setFixed( fixed );\n }\n\n @Override\n public boolean isFixed() {\n return fixed;\n }\n\n /**\n * Fix (dock, freeze) this column at the left side of the table. Scrolling won't move it.\n * @param fixed {@code false} - this column can be scrolled, {@code true} - this column is fixed at the left side of the table<br>\n * {@code true} value would also fix parent columns group at the left side\n * @return this\n */\n public ModelField withFixed( boolean fixed ) {\n setFixed( fixed );\n return this;\n }\n \n @Override\n public void setManageable( boolean manageable ) {\n this.manageable = manageable;\n if ( !manageable && parent != null )\n parent.setManageable( manageable );\n }\n\n @Override\n public boolean isManageable() {\n return manageable;\n }\n\n /**\n * Determines user ability to move or hide this column.\n * @param manageable {@code true} - this column can be hidden, shown and moved, {@code false} - this column is fixed<br>\n * {@code false} value would also make parent unmanageable\n * @return this\n */\n public ModelField withManageable( boolean manageable ) {\n setManageable( manageable );\n return this;\n }\n\n @Override\n public ModelFieldGroup getParent() {\n return parent;\n }\n\n void setParent( ModelFieldGroup parent ) {\n this.parent = parent;\n }\n \n private ModelField withParent( ModelFieldGroup parent ) {\n setParent( parent );\n return this;\n }\n \n @Override\n public ModelField clone() {\n ModelField ret;\n try {\n ret = ( ModelField )super.clone();\n } catch ( CloneNotSupportedException e ) {\n ret = new ModelField();\n }\n return ret.withIdentifier( identifier )\n .withCaption( caption )\n .withVisible( visible )\n .withFixed( fixed )\n .withManageable( manageable )\n .withParent( parent )\n .withRowspan( rowspan )\n .withDefaultWidth( defaultWidth );\n }\n\n @Override\n public boolean equals( Object obj ) {\n return equals( obj, true );\n }\n \n @Override\n public boolean equals( Object obj, boolean withParent ) {\n if ( !( obj instanceof ModelField ) ) {\n return false;\n }\n if ( this == obj ) {\n return true;\n }\n ModelField field = ( ModelField )obj;\n return Utils.equals( identifier, field.identifier ) &&\n Utils.equals( caption, field.caption ) &&\n ( !withParent || Utils.equals( parent, field.parent ) );\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 19 * hash + ( this.identifier == null ? 0 : this.identifier.hashCode() );\n hash = 19 * hash + ( this.caption == null ? 0 : this.caption.hashCode() );\n return hash;\n }\n \n @Override\n public int getColspan() {\n return 1;\n }\n \n @Override\n public int getRowspan() {\n return rowspan;\n }\n \n @Override\n public void setRowspan( int rowspan ) {\n this.rowspan = rowspan;\n }\n \n /**\n * Explicitly sets rowspan for this column.\n * @param rowspan a quantity of header rows that should be combined together in one header cell\n * @return this\n */\n public ModelField withRowspan( int rowspan ) {\n setRowspan( rowspan );\n return this;\n }\n\n @Override\n public String toString() {\n return getIdentifier();\n }\n\n @Override\n public int compareTo( ModelField modelField ) {\n return modelField == null || modelField.identifier == null ? -1 : identifier == null ? 1 : identifier.compareTo( modelField.identifier );\n }\n\n public static boolean equals( ModelField fields1[], ModelField fields2[] ) {\n if ( fields1 == null && fields2 == null ) {\n return true;\n }\n if ( fields1 == null && fields2 != null ||\n fields1 != null && fields2 == null ||\n fields1.length != fields2.length ) {\n return false;\n }\n for ( int a = 0; a < fields1.length; a ++ ) {\n if ( !fields1[ a ].equals( fields2[ a ] ) ) {\n return false;\n }\n }\n return true;\n }\n \n public static int getVisibleFieldsCount( ModelField fields[] ) {\n if ( fields == null || fields.length == 0 ) {\n return 0;\n }\n int result = 0;\n for ( ModelField field : fields ) {\n if ( field.isVisible() ) {\n result ++;\n }\n }\n return result;\n }\n\n public static int getIndexOfModelField( ModelField fields[], String identifier ) {\n if ( fields == null || fields.length == 0 || identifier == null ) {\n return -1;\n }\n for ( int a = 0; a < fields.length; a ++ ) {\n if ( fields[ a ] != null && fields[ a ].identifier.equals( identifier ) ) {\n return a;\n }\n }\n return -1;\n }\n\n public static LinkedHashMap< String, Integer > getIndexes( ModelField fields[] ) {\n LinkedHashMap< String, Integer > ret = new LinkedHashMap< String, Integer >( fields.length );\n for ( int i = 0; i < fields.length; i++ )\n ret.put( fields[ i ].getIdentifier(), i );\n return ret;\n }\n \n public static ModelField[] copyOfModelFields( ModelField fields[] ) {\n if ( fields == null || fields.length == 0 )\n return fields;\n IModelFieldGroup upperFields[] = ModelFieldGroup.getUpperFieldGroups( fields );\n IModelFieldGroup ret[] = new IModelFieldGroup[ upperFields.length ];\n for ( int i = 0; i < upperFields.length; i++ )\n ret[ i ] = upperFields[ i ].clone();\n return ModelFieldGroup.getBottomFields( ret );\n }\n\n /**\n * Checks if {@code this} is a descendant of {@code ancestorCandidate}.\n * @param ancestorCandidate a probable ancestor of {@code this}\n * @param checkAncestorCandidateItself also return {@code true} if {@code this} == {@code ancestorCandidate}\n * @return true iff ancestorCandidate is an ancestor of {@code this}\n */\n public boolean isDescendantOf( IModelFieldGroup ancestorCandidate, boolean checkAncestorCandidateItself ) {\n if ( ancestorCandidate == null )\n return false;\n if ( !checkAncestorCandidateItself )\n ancestorCandidate = ancestorCandidate.getParent();\n while ( ancestorCandidate != null )\n if ( ancestorCandidate == this )\n return true;\n else\n ancestorCandidate = ancestorCandidate.getParent();\n return false;\n }\n}", "public class ModelFieldGroup implements IModelFieldGroup, Serializable {\n private static final long serialVersionUID = 4L;\n \n private String identifier;\n private String caption;\n private ModelFieldGroup parent;\n private int rowspan;\n private boolean fixed;\n private boolean manageable;\n private transient int colspan;\n private transient int childrenRowspan;\n private List< IModelFieldGroup > children = new ArrayList< IModelFieldGroup >();\n \n public ModelFieldGroup() {\n this( null, null );\n }\n \n public ModelFieldGroup( String identifier, String caption ) {\n this.identifier = identifier;\n this.caption = caption;\n manageable = true;\n childrenRowspan = -1;\n }\n \n private void readObject( ObjectInputStream ois ) throws IOException, ClassNotFoundException {\n ois.defaultReadObject();\n childrenRowspan = -1;\n }\n\n @Override\n public String getCaption() {\n return caption;\n }\n\n @Override\n public void setCaption( String caption ) {\n this.caption = caption;\n }\n \n public ModelFieldGroup withCaption( String caption ) {\n setCaption( caption );\n return this;\n }\n\n @Override\n public String getIdentifier() {\n return identifier;\n }\n\n @Override\n public void setIdentifier( String identifier ) {\n this.identifier = identifier;\n }\n \n public ModelFieldGroup withIdentifier( String identifier ) {\n setIdentifier( identifier );\n return this;\n }\n\n @Override\n public ModelFieldGroup getParent() {\n return parent;\n }\n\n private void setParent( ModelFieldGroup parent ) {\n this.parent = parent;\n }\n \n private ModelFieldGroup withParent( ModelFieldGroup parent ) {\n setParent( parent );\n return this;\n }\n \n public IModelFieldGroup getChild( String identifier ) {\n if ( identifier == null ) {\n for ( IModelFieldGroup child : children )\n if ( child.getIdentifier() == null )\n return child;\n } else {\n for ( IModelFieldGroup child : children )\n if ( identifier.equals( child.getIdentifier() ) )\n return child;\n }\n return null;\n }\n\n public List< IModelFieldGroup > getChildren() {\n return Collections.unmodifiableList( children );\n }\n \n void removeChild( IModelFieldGroup child ) {\n children.remove( child );\n int childColspan = child.getColspan();\n ModelFieldGroup ancestor = this;\n while ( ancestor != null ) {\n ancestor.colspan -= childColspan;\n ancestor.childrenRowspan = -1;\n ancestor = ancestor.getParent();\n }\n }\n \n public ModelFieldGroup withChild( IModelFieldGroup child ) {\n if ( child != null ) {\n children.add( child );\n int childColspan = child.getColspan();\n ModelFieldGroup ancestor = this;\n while ( ancestor != null ) {\n ancestor.colspan += childColspan;\n ancestor.childrenRowspan = -1;\n ancestor = ancestor.getParent();\n }\n if ( child instanceof ModelField )\n ( ( ModelField )child ).setParent( this );\n else\n ( ( ModelFieldGroup )child ).setParent( this );\n if ( !child.isManageable() )\n setManageable( false );\n else if ( !isManageable() )\n child.setManageable( false );\n if ( child.isFixed() )\n setFixed( true );\n else if ( isFixed() )\n child.setFixed( true );\n }\n return this;\n }\n \n @Override\n public int getColspan() {\n if ( colspan == 0 )\n for ( IModelFieldGroup child : children )\n colspan += child.getColspan();\n return colspan;\n }\n \n @Override\n public int getRowspan() {\n return rowspan;\n }\n \n @Override\n public void setRowspan( int rowspan ) {\n this.rowspan = rowspan;\n }\n \n public ModelFieldGroup withRowspan( int rowspan ) {\n setRowspan( rowspan );\n return this;\n }\n\n public int getChildrenRowspan() {\n return childrenRowspan;\n }\n\n void setChildrenRowspan( int childrenRowspan ) {\n this.childrenRowspan = childrenRowspan;\n }\n\n @Override\n public ModelFieldGroup clone() {\n ModelFieldGroup ret;\n try {\n ret = ( ModelFieldGroup )super.clone();\n ret.childrenRowspan = -1;\n ret.colspan = 0;\n ret.children = new ArrayList< IModelFieldGroup >();\n } catch ( CloneNotSupportedException e ) {\n ret = new ModelFieldGroup();\n }\n ret.withIdentifier( identifier )\n .withCaption( caption )\n .withRowspan( rowspan )\n .withFixed( fixed )\n .withManageable( manageable )\n .withParent( parent );\n for ( IModelFieldGroup child : getChildren() )\n ret = ret.withChild( child.clone() );\n return ret;\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 59 * hash + ( this.caption == null ? 0 : this.caption.hashCode() );\n hash = 59 * hash + ( this.identifier == null ? 0 : this.identifier.hashCode() );\n return hash;\n }\n\n @Override\n public boolean equals( Object obj ) {\n return equals( obj, true );\n }\n\n @Override\n public boolean equals( Object obj, boolean withParent ) {\n if ( !( obj instanceof ModelFieldGroup ) ) {\n return false;\n }\n if ( this == obj ) {\n return true;\n }\n final ModelFieldGroup other = ( ModelFieldGroup )obj;\n if ( !Utils.equals( caption, other.caption ) ||\n !Utils.equals( identifier, other.identifier ) ||\n withParent && !Utils.equals( parent, other.parent ) ||\n children.size() != other.children.size() )\n return false;\n for ( int i = 0; i < children.size(); i++ )\n if ( !children.get( i ).equals( other.children.get( i ), false ) )\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return getIdentifier();\n }\n \n public static ModelField[] getBottomFields( IModelFieldGroup fieldGroups[] ) {\n if ( fieldGroups == null )\n return null;\n Map< String, ModelField > ret = new LinkedHashMap< String, ModelField >();\n getBottomFields( Arrays.asList( fieldGroups ), ret );\n return ret.values().toArray( new ModelField[ ret.size() ] );\n }\n \n private static void getBottomFields( List< IModelFieldGroup > fieldGroups, Map< String, ModelField > ret ) {\n for ( IModelFieldGroup fieldGroup : fieldGroups ) {\n if ( fieldGroup instanceof ModelFieldGroup ) {\n ModelFieldGroup group = ( ModelFieldGroup )fieldGroup;\n getBottomFields( group.getChildren(), ret );\n } else if ( fieldGroup instanceof ModelField ) {\n ModelField field = ( ModelField )fieldGroup;\n ModelField prevField;\n if ( ( prevField = ret.put( field.getIdentifier(), field ) ) != null )\n throw new IllegalArgumentException( \"Non-unique DB field name: \" + field + \" VS \" + prevField );\n }\n }\n }\n \n public static IModelFieldGroup[] getUpperFieldGroups( IModelFieldGroup fields[] ) {\n if ( fields == null )\n return null;\n Map< String, Integer > uniqueGroups = new LinkedHashMap< String, Integer >();\n List< IModelFieldGroup > ret = new ArrayList< IModelFieldGroup >();\n for ( IModelFieldGroup field : fields ) {\n IModelFieldGroup parent = field.getParent();\n while ( parent != null ) {\n field = parent;\n parent = field.getParent();\n }\n Integer prev = uniqueGroups.put( field.getIdentifier(), uniqueGroups.size() );\n if ( prev == null ) {\n uniqueGroups.put( field.getIdentifier(), uniqueGroups.size() );\n ret.add( field );\n } else if ( !prev.equals( uniqueGroups.size() ) )\n throw new IllegalArgumentException( \"Field groups should be unbroken and should have unique DB field names. Repeated: \" + field.getIdentifier() );\n }\n return ret.toArray( new IModelFieldGroup[ ret.size() ] );\n }\n\n @Override\n public boolean isFixed() {\n return fixed;\n }\n\n @Override\n public void setFixed( boolean fixed ) {\n this.fixed = fixed;\n if ( !fixed ) {\n for ( IModelFieldGroup child : children )\n child.setFixed( fixed );\n } else if ( parent != null )\n parent.setFixed( fixed );\n }\n\n /**\n * Fix (dock, freeze) this column at the left side of the table. Scrolling won't move it.\n * @param fixed {@code false} - this column can be scrolled, {@code true} - this column is fixed at the left side of the table<br>\n * {@code true} would make all ancestor fields fixed at the left side, {@code false} would make all descendants scrollable (thus free from fixation)\n * @return this\n */\n public ModelFieldGroup withFixed( boolean fixed ) {\n setFixed( fixed );\n return this;\n }\n\n @Override\n public boolean isManageable() {\n return manageable;\n }\n\n @Override\n public void setManageable( boolean manageable ) {\n this.manageable = manageable;\n if ( manageable ) {\n for ( IModelFieldGroup child : children )\n child.setManageable( manageable );\n } else if ( parent != null )\n parent.setManageable( manageable );\n }\n\n /**\n * The ability of this field group to be moved by a user.\n * @param manageable {@code true} would make all descendant fields manageable, {@code false} would make all ancestors fixed\n * @return this\n */\n public ModelFieldGroup withManageable( boolean manageable ) {\n setManageable( manageable );\n return this;\n }\n}", "public class ModelRow implements java.io.Serializable {\n\n private static final long serialVersionUID = 4L;\n\n private Object values[];\n\n public ModelRow() {\n this( 0 );\n }\n\n public ModelRow( int length ) {\n values = null;\n setLength( length );\n }\n \n public ModelRow( Object... values ) {\n this.values = values;\n }\n\n @Override\n public int hashCode() {\n return Arrays.deepHashCode( values );\n }\n\n @Override\n public boolean equals( Object obj ) {\n return obj instanceof ModelRow && Arrays.deepEquals( values, ( ( ModelRow )obj ).values );\n }\n\n @Override\n public ModelRow clone() {\n return values == null ? new ModelRow() : new ModelRow( values.clone() );\n }\n\n public Object getValue( int index ) {\n if ( values == null || index < 0 || index >= values.length ) {\n return null;\n }\n return values[ index ];\n }\n\n public boolean setValue( int index, Object value ) {\n if ( values == null || index < 0 || index >= values.length ) {\n return false;\n }\n values[ index ] = value;\n return true;\n }\n\n public void setLength( int length ) {\n if ( values != null && values.length == length ) {\n return;\n }\n Object newValues[] = new Object[ length ];\n if ( values != null && values.length != 0 ) {\n System.arraycopy( values, 0, newValues, 0, Math.min( values.length, length ) );\n }\n values = newValues;\n }\n\n public int getLength() {\n return values == null ? 0 : values.length;\n }\n\n public Object[] getValues() {\n return values;\n }\n \n public void setValues( Object[] values ) {\n this.values = values;\n }\n\n}", "public class Utils {\n private static final Logger LOGGER = Logger.getLogger( Utils.class );\n \n public static boolean equals( Object o1, Object o2 ) {\n return o1 == null ? o2 == null : o2 != null && o1.equals( o2 );\n }\n \n public static String rpad( String s, int n ) {\n if ( null == s )\n return null;\n if ( n <= 0 )\n return \"\";\n if ( n < s.length() )\n return s.substring( 0, n );\n return String.format( \"%1$-\" + n + \"s\", s );\n }\n \n public static String rpad( String text, char padChar, int length ) {\n if ( text == null )\n return null;\n if ( length <= 0 || length < text.length() )\n return text;\n StringBuilder result = new StringBuilder( text );\n while ( result.length() < length )\n result.append( padChar );\n return result.toString();\n }\n \n public static void initSimpleConsoleLogger() {\n String logProps = \"log4j.rootLogger=DEBUG, Console\\n\" +\n \"log4j.appender.Console=org.apache.log4j.ConsoleAppender\\n\" +\n \"log4j.appender.Console.layout=org.apache.log4j.PatternLayout\\n\" +\n \"log4j.appender.Console.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss,SSS} [%p] - %m%n\\n\";\n Properties props = new Properties();\n try {\n props.load( new ByteArrayInputStream( logProps.getBytes() ) );\n } catch ( IOException e ) {\n }\n PropertyConfigurator.configure( props );\n }\n \n public static void setSystemLookAndFeel() {\n try {\n UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );\n } catch ( InstantiationException e ) {\n LOGGER.error( null, e );\n } catch ( ClassNotFoundException e ) {\n LOGGER.error( null, e );\n } catch ( IllegalAccessException e ) {\n LOGGER.error( null, e );\n } catch ( UnsupportedLookAndFeelException e ) {\n LOGGER.error( null, e );\n }\n }\n\n public static void updateComponentTreeUI() {\n for ( Window window : Window.getWindows() )\n updateComponentTreeUI( window );\n }\n\n private static void updateComponentTreeUI( Window window ) {\n SwingUtilities.updateComponentTreeUI( window );\n for ( Window w : window.getOwnedWindows() )\n updateComponentTreeUI( w );\n }\n}", "public interface CustomTableHeaderRenderer {\n /**\n * <b>Warning:</b> originalComponent may be shared within a level by different cells.\n * If rendering of one cell changes originalComponent's properties\n * then rendering of other cells should restore original properties (or set them to appropriate values).\n * @param originalComponent a component returned by an underlying (L&amp;F) renderer\n * @param table a corresponding table\n * @param value table header cell value\n * @param isSelected is mouse over this cell\n * @param hasFocus was a focus gained by this cell (e. g., by pressing tab)\n * @param isDragged is mouse dragging this cell (column or column group)\n * @param row a row (level) in this table header\n * @param viewColumn cell horizontal position in the current row as it is viewed at the moment\n * @param modelColumn cell horizontal position in the current row as it was defined by the model at initialization\n * @param dataField model column (or column group) that corresponds to this cell\n * @return a component that defines rendering of the current table header cell\n */\n Component getTableCellRendererComponent( Component originalComponent, JBroTable table, Object value, boolean isSelected, boolean hasFocus, boolean isDragged, int row, int viewColumn, int modelColumn, IModelFieldGroup dataField );\n}", "public class JBroTable extends JTable {\n private static final Logger LOGGER = Logger.getLogger( JBroTable.class );\n private Integer currentLevel;\n private JScrollPane scrollPane;\n private boolean scrollPaneFixed;\n /**\n * This field points to a main table for a fixed table\n * (fixed table is just a non-scrollable part of the main table).\n * This field is null for a regular table.\n */\n private JBroTable masterTable;\n\n public JBroTable() {\n this( null );\n }\n \n public JBroTable( ModelData data ) {\n super( new JBroTableModel( data ) );\n super.setUI( new JBroTableUI() );\n checkFieldWidths();\n refresh();\n }\n\n @Override\n public void setUI( TableUI ui ) {\n JBroTableUI oldUI = getUI();\n if ( oldUI != null || ui instanceof JBroTableUI ) {\n super.setUI( ui );\n if ( !( ui instanceof JBroTableUI ) ) {\n if ( ui != null )\n ui.uninstallUI( this );\n this.ui = oldUI;\n oldUI.setNoDefaults( true );\n oldUI.installUI( this );\n oldUI.setNoDefaults( false );\n firePropertyChange( \"UI\", ui, oldUI );\n refresh();\n }\n }\n }\n\n @Override\n public JBroTableUI getUI() {\n return ( JBroTableUI )super.getUI();\n }\n\n private void refresh() {\n if ( getUI() != null )\n getUI().clearCellImagesCache();\n revalidate();\n repaint( getVisibleRect() );\n }\n\n @Override\n public JBroTableModel getModel() {\n return ( JBroTableModel )super.getModel();\n }\n\n public ModelData getData() {\n return getModel().getData();\n }\n \n private void checkFieldWidths() {\n ModelData data = getData();\n if ( data == null )\n return;\n ModelField fields[] = data.getFields();\n if ( fields == null )\n return;\n boolean changed = false;\n boolean tableIsJustAFixedPart = getMasterTable() != null;\n for ( int i = columnModel.getColumnCount() - 1; i >= 0; i-- ) {\n TableColumn column = columnModel.getColumn( i );\n int modelIndex = column.getModelIndex();\n ModelField field = fields[ modelIndex ];\n if ( field.isVisible() && field.isFixed() == tableIsJustAFixedPart ) {\n String headerValue = field.getCaption();\n if ( !Utils.equals( headerValue, column.getHeaderValue() ) ) {\n column.setHeaderValue( headerValue );\n changed = true;\n }\n Integer defaultWidth = field.getDefaultWidth();\n if ( defaultWidth != null && defaultWidth >= 0 ) {\n defaultWidth = Math.min( Math.max( defaultWidth, column.getMinWidth() ), column.getMaxWidth() );\n if ( defaultWidth != column.getPreferredWidth() ) {\n column.setPreferredWidth( defaultWidth );\n changed = true;\n }\n }\n } else {\n changed = true;\n removeColumn( column );\n }\n }\n if ( changed )\n tableStructureChanged();\n }\n \n /**\n * Set new data.\n * @param data new array of data\n */\n public void setData( ModelData data ) {\n getModel().setData( data );\n checkFieldWidths();\n refresh();\n }\n\n @Override\n public void setModel( TableModel dataModel ) {\n super.setModel( dataModel );\n checkFieldWidths();\n refresh();\n }\n\n /**\n * Set new order of columns (including visibility). Does not affect table model.\n * @param newFields a list of new fields identifiers\n */\n public void reorderFields( String newFields[] ) {\n ModelData data = getData();\n ModelField modelFields[] = data.getFields();\n // Column indexes in model\n LinkedHashMap< String, Integer > modelPositions = ModelField.getIndexes( modelFields );\n // Current order of visible columns\n LinkedHashSet< Integer > iold = new LinkedHashSet< Integer >( modelFields.length );\n for ( int i = 0; i < columnModel.getColumnCount(); i++ ) {\n TableColumn column = columnModel.getColumn( i );\n iold.add( column.getModelIndex() );\n }\n // New order of visible columns\n LinkedHashSet< Integer > inew = new LinkedHashSet< Integer >( modelFields.length );\n for ( String fieldName : newFields ) {\n if ( fieldName == null )\n continue;\n Integer pos = modelPositions.get( fieldName );\n // Fields list doesn't correspond to current data array\n if ( pos == null ) {\n LOGGER.warn( \"reorderFields called on obsolete data model. Call setData first.\" );\n return;\n }\n inew.add( pos );\n }\n ArrayList< ModelField > manageable = null;\n // Delete absent columns\n for ( Iterator< Integer > it = iold.iterator(); it.hasNext(); ) {\n Integer pos = it.next();\n if ( !inew.contains( pos ) ) {\n ModelField field = modelFields[ pos ];\n if ( field.isManageable() ) {\n it.remove();\n field.setVisible( false );\n removeColumn( columnModel.getColumn( convertColumnIndexToView( pos ) ) );\n } else {\n field.setManageable( true );\n if ( manageable == null )\n manageable = new ArrayList< ModelField >();\n manageable.add( field );\n // Exceptional event: unmanageable column was hidden. It should become visible again.\n // This situation is really rare (API doesn't allow this to happen), so performance is not an issue.\n // Traversing the whole list to find initial column position.\n ArrayList< Integer > swap = new ArrayList< Integer >( inew.size() + 1 );\n swap.addAll( inew );\n for ( int i = 0; i < swap.size(); i++ ) {\n Integer p = swap.get( i );\n if ( p.compareTo( pos ) > 0 ) {\n swap.add( i, pos );\n break;\n }\n }\n if ( swap.size() <= inew.size() )\n swap.add( pos );\n inew.clear();\n inew.addAll( swap );\n }\n }\n }\n // Add new columns\n for ( Iterator< Integer > it = inew.iterator(); it.hasNext(); ) {\n Integer pos = it.next();\n if ( !iold.contains( pos ) ) {\n ModelField field = modelFields[ pos ];\n if ( field.isManageable() ) {\n iold.add( pos );\n field.setVisible( true );\n int coords[] = data.getIndexOfModelFieldGroup( field.getIdentifier() );\n addColumn( new JBroTableColumn( coords[ 0 ], coords[ 1 ], pos, field.getRowspan() ) );\n } else\n it.remove();\n }\n }\n int newVisibleIndexes[] = new int[ inew.size() ];\n int n = 0;\n for ( Integer pos : inew ) {\n newVisibleIndexes[ n++ ] = convertColumnIndexToView( pos );\n }\n // Permutations\n for ( int i = 0; i < newVisibleIndexes.length; i++ ) {\n int pos = newVisibleIndexes[ i ];\n while ( pos != i ) {\n int posPos = newVisibleIndexes[ pos ];\n swapColumns( posPos, pos );\n newVisibleIndexes[ pos ] = pos;\n newVisibleIndexes[ i ] = posPos;\n pos = posPos;\n }\n }\n if ( manageable != null )\n for ( ModelField field : manageable )\n field.setManageable( false );\n checkFieldWidths();\n }\n \n /**\n * Swap two columns positions (does not affect model).\n * @param first swapping column\n * @param second swapping column\n */\n public void swapColumns( int first, int second ) {\n if ( first > second ) {\n int t = first;\n first = second;\n second = t;\n } else if ( first == second ) {\n return;\n }\n moveColumn( first, second );\n moveColumn( second - 1, first );\n }\n\n /**\n * A list of visible columns in the view order separated by \";\". One extra \";\" is added at the end.\n * @return a list of visible columns\n */\n public String getFieldsOrder() {\n ModelData data = getData();\n if ( data == null ) {\n return \"\";\n }\n ModelField fields[] = data.getFields();\n if ( fields == null ) {\n return \"\";\n }\n StringBuilder result = new StringBuilder();\n for ( int i = 0; i < columnModel.getColumnCount(); i++ ) {\n result.append( fields[ columnModel.getColumn( i ).getModelIndex() ].getIdentifier() ).append( ';' );\n }\n return result.toString();\n }\n \n /**\n * Set a list of columns.\n * @param fieldsOrder a list of visible columns in the view order separated by \";\", must end with \";\"\n */\n public void setFieldsOrder( String fieldsOrder ) {\n if ( fieldsOrder == null ) {\n fieldsOrder = \"\";\n }\n reorderFields( fieldsOrder.split( \";\" ) );\n }\n\n /**\n * A list of pairs ( Identifier, column width in pixels ).\n * <p>A separator inside a pair is \":\".<br>\n * Pairs separator is \";\".<br>\n * No extra \";\" at the end.<br>\n * Columns have the view order. Only visible columns are printed.<br>\n * The model order fields can be obtained using method {@link #getColumnsWidths()}.</p>\n * @return a list of fields and their widths\n */\n public String getFieldsOrderAndWidths() {\n ModelData data = getData();\n if ( data == null ) {\n return \"\";\n }\n ModelField fields[] = data.getFields();\n if ( fields == null ) {\n return \"\";\n }\n StringBuilder result = new StringBuilder();\n for ( int i = 0; i < columnModel.getColumnCount(); i++ ) {\n TableColumn column = columnModel.getColumn( i );\n if ( result.length() != 0 ) {\n result.append( ';' );\n }\n result.append( fields[ column.getModelIndex() ].getIdentifier() )\n .append( ':' )\n .append( column.getPreferredWidth() );\n }\n return result.toString();\n }\n\n /**\n * Set a list of fields and the width of each of them.\n * @param colWidths a list of pairs ( Identifier, column width ) in format of method {@link #getFieldsOrderAndWidths()}\n */\n public void setFieldsOrderAndWidths( String colWidths ) {\n reorderFields( setColumnsWidths( colWidths, true ) );\n }\n\n /**\n * A list of pairs ( Identifier, field width in pixels ).\n * <p>The output format is described at method {@link #getFieldsOrderAndWidths()}.<br>\n * Fields are printed in the model order. Only visible fields are included.<br>\n * The view order list can be obtained by method {@link #getFieldsOrderAndWidths()}.</p>\n * @return a list of fields and their widths\n */\n public String getColumnsWidths() {\n StringBuilder result = new StringBuilder();\n TableColumnModel colModel = getColumnModel();\n ModelField[] fields = getData().getFields();\n for ( int a = 0; a < fields.length; a++ ) {\n int idx = convertColumnIndexToView( a );\n if ( idx >= 0 ) {\n if ( result.length() != 0 ) {\n result.append( ';' );\n }\n result.append( fields[ a ].getIdentifier() )\n .append( ':' )\n .append( colModel.getColumn( idx ).getPreferredWidth() );\n }\n }\n return result.toString();\n }\n\n /**\n * Set widths of columns. The order and visibility of columns wouldn't be touched.\n * @param colWidths a list of pairs ( Identifier, column width ) in format of method {@link #getFieldsOrderAndWidths()}\n */\n public void setColumnsWidths( String colWidths ) {\n setColumnsWidths( colWidths, false );\n }\n\n private String[] setColumnsWidths( String colWidths, boolean addIfAbsent ) {\n if ( colWidths == null || colWidths.isEmpty() ) {\n return new String[ 0 ];\n }\n String[] widths = colWidths.split( \";\" );\n if ( widths == null || widths.length == 0 ) {\n return new String[ 0 ];\n }\n Pattern pattern = Pattern.compile( \"(\\\\S+):(\\\\d+)\" );\n ModelField[] fields = getData().getFields();\n LinkedHashMap< String, Integer > fieldIndexes = ModelField.getIndexes( fields );\n ArrayList< String > ret = new ArrayList< String >();\n for ( String width : widths ) {\n Matcher matcher = pattern.matcher( width );\n if ( matcher.matches() ) {\n String colName = matcher.group( 1 );\n int colWidth = Integer.parseInt( matcher.group( 2 ) );\n Integer origIdx = fieldIndexes.get( colName );\n if ( origIdx == null ) {\n continue;\n }\n ret.add( colName );\n int fIdx = convertColumnIndexToView( origIdx );\n if ( fIdx < 0 ) {\n if ( addIfAbsent ) {\n addColumn( new TableColumn( origIdx ) );\n ModelField field = fields[ origIdx ];\n if ( field.isManageable() )\n field.setVisible( true );\n fIdx = convertColumnIndexToView( origIdx );\n } else\n continue;\n }\n TableColumn column = columnModel.getColumn( fIdx );\n column.setPreferredWidth( colWidth );\n }\n }\n return ret.toArray( new String[ ret.size() ] );\n }\n \n /**\n * Get index of column in table header by field identifier.\n * @param identifier field identifier.\n * @return index of column in the view order\n */\n public int convertColumnIndexToView( String identifier ) {\n return convertColumnIndexToView( getData().getIndexOfModelField( identifier ) );\n }\n\n @Override\n public void columnMoved( TableColumnModelEvent e ) {\n }\n\n /**\n * Value in a cell located at the given row and a column identified by name.\n * @param row row number\n * @param identifier column identifier\n * @return cell value\n */\n public Object getValueAt( int row, String identifier ) {\n return getData().getValue( row, identifier );\n }\n\n @Override\n protected JBroTableColumnModel createDefaultColumnModel() {\n return new JBroTableColumnModel( this );\n }\n\n @Override\n public void createDefaultColumnsFromModel() {\n TableColumnModel m = getColumnModel();\n if ( !( m instanceof JBroTableColumnModel ) ) {\n super.createDefaultColumnsFromModel();\n return;\n }\n JBroTableColumnModel gcm = ( JBroTableColumnModel )m;\n gcm.clear();\n ModelData data = getData();\n if ( data == null )\n return;\n Iterable< IModelFieldGroup > groups = data.getAllFieldGroupsFromTop( true );\n for ( IModelFieldGroup fieldGroup : groups ) {\n int groupCoords[] = data.getIndexOfModelFieldGroup( fieldGroup.getIdentifier() );\n int groupLevel = groupCoords[ 1 ];\n int groupX = groupCoords[ 0 ];\n gcm.addColumn( fieldGroup, groupX, groupLevel );\n }\n }\n\n @Override\n protected JTableHeader createDefaultTableHeader() {\n TableColumnModel m = getColumnModel();\n if ( !( m instanceof JBroTableColumnModel ) )\n return super.createDefaultTableHeader();\n JBroTableColumnModel gcm = ( JBroTableColumnModel )m;\n return new JBroTableHeader( gcm );\n }\n\n @Override\n public void columnSelectionChanged( ListSelectionEvent e ) {\n if ( getRowSelectionAllowed() ) {\n int leadRow = selectionModel.getLeadSelectionIndex();\n if ( leadRow >= 0 && leadRow < getRowCount() ) {\n Rectangle first = getUI().getSpanCoordinates( e.getFirstIndex(), leadRow );\n Rectangle last = getUI().getSpanCoordinates( e.getLastIndex(), leadRow );\n first = first.x < 0 || first.y < 0 ? last : last.x < 0 || last.y < 0 ? first : first.union( last );\n if ( first.x >= 0 && first.width > 1 ) {\n e = new ListSelectionEvent( e.getSource(), first.x, first.x + first.width - 1, e.getValueIsAdjusting() );\n }\n }\n }\n super.columnSelectionChanged( e );\n }\n\n void setCurrentLevel( Integer currentLevel ) {\n this.currentLevel = currentLevel;\n }\n\n @Override\n public TableColumnModel getColumnModel() {\n return currentLevel == null ? super.getColumnModel() : getTableHeader().getColumnModel( currentLevel );\n }\n\n @Override\n public JBroTableHeader getTableHeader() {\n return ( JBroTableHeader )super.getTableHeader();\n }\n\n @Override\n public void valueChanged( ListSelectionEvent e ) {\n super.valueChanged( e );\n getUI().onRowsSelected( e.getFirstIndex(), e.getLastIndex() );\n }\n \n /**\n * This method creates (if it doesn't exist yet) and returns a scroll pane that contains a viewport\n * with fixed columns. This scroll pane may have a null viewport if a model contains no visible\n * fixed columns.\n * <p>To obtain a left fixed table, call {@link #getSlaveTable}.</p>\n * @return a scroll pane with a fixed left part (if required), or null if this table is just a fixed part\n */\n public JScrollPane getScrollPane() {\n if ( scrollPane != null || getMasterTable() != null )\n return scrollPane;\n scrollPane = new JScrollPane( this );\n updateScrollPane();\n addPropertyChangeListener( new PropertyChangeListener() {\n @Override\n public void propertyChange( PropertyChangeEvent e ) {\n JViewport viewport = scrollPane.getRowHeader();\n if ( viewport == null )\n return;\n Component comp = viewport.getView();\n if ( !( comp instanceof JBroTable ) )\n return;\n JBroTable fixed = ( JBroTable )comp;\n String property = e.getPropertyName();\n if ( \"selectionModel\".equals( property ) )\n fixed.setSelectionModel( getSelectionModel() );\n else if ( \"rowSorter\".equals( property ) )\n fixed.setRowSorter( getRowSorter() );\n else if ( \"model\".equals( property ) )\n fixed.setModel( getModel() );\n else if ( \"showVerticalLines\".equals( property ) )\n fixed.setShowVerticalLines( getShowVerticalLines() );\n else if ( \"rowMargin\".equals( property ) )\n fixed.setRowMargin( getRowMargin() );\n else if ( \"rowHeight\".equals( property ) )\n fixed.setRowHeight( getRowHeight() );\n else if ( \"fillsViewportHeight\".equals( property ) )\n fixed.setFillsViewportHeight( getFillsViewportHeight() );\n }\n } );\n JScrollBar scrollBar = scrollPane.getVerticalScrollBar();\n if ( scrollBar != null ) {\n scrollBar.addAdjustmentListener( new AdjustmentListener() {\n @Override\n public void adjustmentValueChanged( AdjustmentEvent e ) {\n if ( e.getAdjustmentType() == AdjustmentEvent.TRACK )\n getUI().setRowsScrolling( e.getValueIsAdjusting() );\n }\n } );\n }\n return scrollPane;\n }\n\n @Override\n public void tableChanged( TableModelEvent e ) {\n if ( getUI() != null )\n getUI().clearCellImagesCache();\n super.tableChanged( e );\n if ( e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW )\n tableStructureChanged();\n }\n \n private void tableStructureChanged() {\n if ( getTableHeader() != null && getTableHeader().getUI() != null )\n getTableHeader().getUI().clearCellImagesCache();\n updateScrollPane();\n JBroTableHeader header = getTableHeader();\n if ( header != null ) {\n header.updateUI();\n header.repaint();\n }\n }\n\n @Override\n public void sorterChanged( RowSorterEvent e ) {\n if ( getTableHeader() != null && getTableHeader().getUI() != null )\n getTableHeader().getUI().clearCellImagesCache();\n super.sorterChanged( e );\n }\n\n @Override\n public void columnMarginChanged( ChangeEvent e ) {\n if ( !( e instanceof JBroTableColumnModel.WidthChangeEvent ) ) {\n super.columnMarginChanged( e );\n return;\n }\n JBroTableColumnModel.WidthChangeEvent we = ( JBroTableColumnModel.WidthChangeEvent )e;\n JBroTableColumn column = we.getColumn();\n JBroTableHeader header = getTableHeader();\n TableColumnModel columnModel = header == null ? getColumnModel() : header.getColumnModel();\n Enumeration< TableColumn > cols = columnModel.getColumns();\n int x = 0;\n int idx = 0;\n while ( cols.hasMoreElements() ) {\n TableColumn col = cols.nextElement();\n if ( col == column )\n break;\n x += col.getWidth();\n idx++;\n }\n if ( getUI() != null ) {\n Set< String > spannedColumns = getUI().getSpannedColumns();\n if ( spannedColumns.contains( column.getIdentifier() ) ) {\n for ( ; idx >= 0; idx-- ) {\n TableColumn col = columnModel.getColumn( idx );\n if ( spannedColumns.contains( ( String )col.getIdentifier() ) )\n x -= col.getWidth();\n else\n break;\n }\n }\n }\n if ( isEditing() && !getCellEditor().stopCellEditing() )\n getCellEditor().cancelCellEditing();\n Container parent = getParent() == null ? null : getParent().getParent();\n if ( getAutoResizeMode() == JTable.AUTO_RESIZE_OFF && header != null && header.getResizingColumn() == column && ( parent == null || parent instanceof JScrollPane ) ) {\n if ( column.getPreferredWidth() != column.getWidth() ) {\n Dimension size = getPreferredSize();\n int oldW = column.getPreferredWidth();\n column.setPreferredWidth( column.getWidth() );\n int newW = column.getPreferredWidth();\n size.width += newW - oldW;\n setPreferredSize( size );\n if ( getParent() instanceof JViewport )\n ( ( JViewport )getParent() ).setViewSize( size );\n if ( parent != null ) {\n JScrollPane scrollPane = ( JScrollPane )parent;\n scrollPane.getHorizontalScrollBar().getModel().setMaximum( size.width );\n }\n }\n } else\n revalidate();\n if ( header == null )\n repaint( x, 0, getWidth() - x, getHeight() );\n else if ( columnModel instanceof JBroTableColumnModel ) {\n header.repaintHeaderAndTable( x, 0, header.getWidth() - x );\n JBroTableHeaderUI ui = header.getUI();\n JBroTableColumnModel gcm = ( JBroTableColumnModel )columnModel;\n while ( ( column = gcm.getColumnParent( column ) ) != null )\n header.repaint( ui.getGroupHeaderBoundsFor( column ) );\n } else {\n repaint( x, 0, getWidth() - x, getHeight() );\n header.repaint();\n }\n }\n\n /**\n * If this table is just a fixed (non-scrollable) part then this method would return main part.\n * @return main table for a fixed one, otherwise null\n */\n public JBroTable getMasterTable() {\n return masterTable;\n }\n \n /**\n * If this table has fixed columns then this method would return a fixed (non-scrollable) part.\n * @return fixed part for a main table, otherwise null\n */\n public JBroTable getSlaveTable() {\n if ( getScrollPane() == null )\n return null;\n JViewport viewport = getScrollPane().getRowHeader();\n if ( viewport == null )\n return null;\n Component ret = viewport.getView();\n if ( !( ret instanceof JBroTable ) )\n return null;\n return ( JBroTable )ret;\n }\n\n @Override\n public boolean hasFocus() {\n return masterTable == null ? super.hasFocus() : masterTable.hasFocus();\n }\n\n @Override\n public void setRowHeight( int row, int rowHeight ) {\n super.setRowHeight( row, rowHeight );\n JBroTable fixed = getSlaveTable();\n if ( fixed != null )\n fixed.setRowHeight( row, rowHeight );\n }\n \n private void updateScrollPane() {\n if ( scrollPane == null || getMasterTable() != null )\n return;\n ModelData data = getData();\n boolean hasFixed = false;\n if ( data != null ) {\n for ( ModelField field : data.getFields() ) {\n if ( field.isFixed() && field.isVisible() ) {\n hasFixed = true;\n break;\n }\n }\n }\n if ( !hasFixed ) {\n if ( scrollPaneFixed && scrollPane.getRowHeader() != null ) {\n scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, null );\n scrollPane.setRowHeader( null );\n scrollPaneFixed = false;\n }\n return;\n }\n if ( scrollPane.getRowHeader() == null ) {\n scrollPaneFixed = true;\n JBroTable fixed = newInstance();\n fixed.masterTable = this;\n fixed.setModel( getModel() );\n fixed.setSelectionModel( getSelectionModel() );\n fixed.setRowSorter( getRowSorter() );\n fixed.setAutoResizeMode( getAutoResizeMode() );\n fixed.setFocusable( false );\n fixed.setUpdateSelectionOnSort( false );\n fixed.setFillsViewportHeight( getFillsViewportHeight() );\n fixed.setRowHeight( getRowHeight() );\n fixed.setRowMargin( getRowMargin() );\n fixed.setShowVerticalLines( getShowVerticalLines() );\n fixed.setPreferredScrollableViewportSize( fixed.getPreferredSize() );\n \n MouseAdapter ma = new MouseAdapter() {\n private TableColumn column;\n private int columnWidth;\n private int pressedX;\n\n @Override\n public void mousePressed( MouseEvent e ) {\n JTableHeader header = ( JTableHeader )e.getComponent();\n TableColumnModel tcm = header.getColumnModel();\n int columnIndex = tcm.getColumnIndexAtX( e.getX() - 3 );\n if ( columnIndex == tcm.getColumnCount() - 1 &&\n header.getCursor() == JBroTableHeaderUI.RESIZE_CURSOR &&\n header.getTable().getAutoResizeMode() != JTable.AUTO_RESIZE_OFF ) {\n column = tcm.getColumn( columnIndex );\n columnWidth = column.getWidth();\n pressedX = e.getX();\n }\n }\n\n @Override\n public void mouseReleased( MouseEvent e ) {\n column = null;\n columnWidth = 0;\n pressedX = 0;\n }\n\n @Override\n public void mouseDragged( MouseEvent e ) {\n JTableHeader header = ( JTableHeader )e.getComponent();\n JTable table = header.getTable();\n if ( column != null ) {\n int width = columnWidth - pressedX + e.getX();\n column.setPreferredWidth( width );\n }\n table.setPreferredScrollableViewportSize( table.getPreferredSize() );\n }\n };\n JBroTableHeader header = fixed.getTableHeader();\n header.addMouseListener( ma );\n header.addMouseMotionListener( ma );\n \n scrollPane.setRowHeaderView( fixed );\n scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, fixed.getTableHeader() );\n scrollPane.getRowHeader().addChangeListener( new ChangeListener() {\n @Override\n public void stateChanged( ChangeEvent e ) {\n JViewport viewport = ( JViewport )e.getSource();\n scrollPane.getVerticalScrollBar().setValue( viewport.getViewPosition().y );\n }\n } );\n }\n }\n \n /**\n * This method should be overridden for proper creation of fixed non-scrollable part of the table.\n * @return new instance of an inherited class\n */\n protected JBroTable newInstance() {\n return new JBroTable();\n }\n}" ]
import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.UIManager; import io.github.qualtagh.swing.table.model.IModelFieldGroup; import io.github.qualtagh.swing.table.model.ModelData; import io.github.qualtagh.swing.table.model.ModelField; import io.github.qualtagh.swing.table.model.ModelFieldGroup; import io.github.qualtagh.swing.table.model.ModelRow; import io.github.qualtagh.swing.table.model.Utils; import io.github.qualtagh.swing.table.view.CustomTableHeaderRenderer; import io.github.qualtagh.swing.table.view.JBroTable;
package io.github.qualtagh.swing.table.tutorial; public class CustomRenderer { public static void main( String args[] ) throws Exception { Utils.initSimpleConsoleLogger(); UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); IModelFieldGroup groups[] = new IModelFieldGroup[] {
new ModelField( "USER_ID", "User identifier" ),
2
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/loot/functions/LootFunctionSetRandomAbility.java
[ "@SuppressWarnings(\"javadoc\")\npublic class Reference {\n\t\n // Mod info\n public static final String MOD_ID = \"everlastingabilities\";\n public static final String GA_TRACKING_ID = \"UA-65307010-9\";\n public static final String VERSION_URL = \"https://raw.githubusercontent.com/CyclopsMC/Versions/master/\" + MinecraftHelpers.getMinecraftVersionMajorMinor() + \"/EverlastingAbilities.txt\";\n \n // Paths\n public static final String TEXTURE_PATH_GUI = \"textures/gui/\";\n public static final String TEXTURE_PATH_SKINS = \"textures/skins/\";\n public static final String TEXTURE_PATH_MODELS = \"textures/models/\";\n public static final String TEXTURE_PATH_ENTITIES = \"textures/entities/\";\n public static final String TEXTURE_PATH_GUIBACKGROUNDS = \"textures/gui/title/background/\";\n public static final String TEXTURE_PATH_ITEMS = \"textures/items/\";\n public static final String TEXTURE_PATH_PARTICLES = \"textures/particles/\";\n public static final String MODEL_PATH = \"models/\";\n\n}", "public class AbilityHelpers {\n\n /**\n * This value is synced with {@link GeneralConfig#maxPlayerAbilities} from the server.\n * This is to ensure that clients can not hack around the ability limit.\n */\n public static int maxPlayerAbilitiesClient = -1;\n\n public static final int[] RARITY_COLORS = new int[] {\n Helpers.RGBToInt(255, 255, 255),\n Helpers.RGBToInt(255, 255, 0),\n Helpers.RGBToInt(0, 255, 255),\n Helpers.RGBToInt(255, 0, 255),\n };\n\n public static int getExperienceForLevel(int level) {\n if (level == 0) {\n return 0;\n } else if (level < 16) {\n return (int) (Math.pow(level, 2) + 6 * level);\n } else if (level < 31) {\n return (int) (2.5 * Math.pow(level, 2) - 40.5 * level + 360);\n } else {\n return (int) (4.5 * Math.pow(level, 2) - 162.5 * level + 2220);\n }\n }\n\n public static int getLevelForExperience(int experience) {\n int i = 0;\n int newXp, lastXp = -1;\n while ((newXp = getExperienceForLevel(i)) <= experience) {\n if (newXp <= lastXp) break; // Avoid infinite loops when the MC level is too high, resulting in an xp overflow. See https://github.com/CyclopsMC/EverlastingAbilities/issues/27\n i++;\n lastXp = newXp;\n }\n return i - 1;\n }\n\n public static Predicate<IAbilityType> createRarityPredicate(Rarity rarity) {\n return abilityType -> abilityType.getRarity() == rarity;\n }\n\n public static List<IAbilityType> getAbilityTypes(Predicate<IAbilityType> abilityFilter) {\n return AbilityTypes.REGISTRY.getValues()\n .stream()\n .filter(abilityFilter)\n .collect(Collectors.toList());\n }\n\n public static List<IAbilityType> getAbilityTypesPlayerSpawn() {\n return getAbilityTypes(IAbilityType::isObtainableOnPlayerSpawn);\n }\n\n public static List<IAbilityType> getAbilityTypesMobSpawn() {\n return getAbilityTypes(IAbilityType::isObtainableOnMobSpawn);\n }\n\n public static List<IAbilityType> getAbilityTypesCrafting() {\n return getAbilityTypes(IAbilityType::isObtainableOnCraft);\n }\n\n public static List<IAbilityType> getAbilityTypesLoot() {\n return getAbilityTypes(IAbilityType::isObtainableOnLoot);\n }\n\n public static void onPlayerAbilityChanged(PlayerEntity player, IAbilityType abilityType, int oldLevel, int newLevel) {\n abilityType.onChangedLevel(player, oldLevel, newLevel);\n }\n\n public static int getMaxPlayerAbilities(World world) {\n return world.isRemote() ? maxPlayerAbilitiesClient : GeneralConfig.maxPlayerAbilities;\n }\n\n /**\n * Add the given ability.\n * @param player The player.\n * @param ability The ability.\n * @param doAdd If the addition should actually be done.\n * @param modifyXp Whether to require player to have enough XP before adding\n * @return The ability part that was added.\n */\n @NonNull\n public static Ability addPlayerAbility(PlayerEntity player, Ability ability, boolean doAdd, boolean modifyXp) {\n return player.getCapability(MutableAbilityStoreConfig.CAPABILITY)\n .map(abilityStore -> {\n int oldLevel = abilityStore.hasAbilityType(ability.getAbilityType())\n ? abilityStore.getAbility(ability.getAbilityType()).getLevel() : 0;\n\n // Check max ability count\n if (getMaxPlayerAbilities(player.getEntityWorld()) >= 0 && oldLevel == 0\n && getMaxPlayerAbilities(player.getEntityWorld()) <= abilityStore.getAbilities().size()) {\n return Ability.EMPTY;\n }\n\n Ability result = abilityStore.addAbility(ability, doAdd);\n int currentXp = player.experienceTotal;\n if (result != null && modifyXp && getExperience(result) > currentXp) {\n int maxLevels = player.experienceTotal / result.getAbilityType().getBaseXpPerLevel();\n if (maxLevels == 0) {\n result = Ability.EMPTY;\n } else {\n result = new Ability(result.getAbilityType(), maxLevels);\n }\n }\n if (doAdd && !result.isEmpty()) {\n player.experienceTotal -= getExperience(result);\n // Fix xp bar\n player.experienceLevel = getLevelForExperience(player.experienceTotal);\n int xpForLevel = getExperienceForLevel(player.experienceLevel);\n player.experience = (float)(player.experienceTotal - xpForLevel) / (float)player.xpBarCap();\n\n int newLevel = abilityStore.getAbility(result.getAbilityType()).getLevel();\n onPlayerAbilityChanged(player, result.getAbilityType(), oldLevel, newLevel);\n }\n return result;\n })\n .orElse(Ability.EMPTY);\n }\n\n /**\n * Remove the given ability.\n * @param player The player.\n * @param ability The ability.\n * @param doRemove If the removal should actually be done.\n * @param modifyXp Whether to refund XP cost of ability\n * @return The ability part that was removed.\n */\n @NonNull\n public static Ability removePlayerAbility(PlayerEntity player, Ability ability, boolean doRemove, boolean modifyXp) {\n return player.getCapability(MutableAbilityStoreConfig.CAPABILITY, null)\n .map(abilityStore -> {\n int oldLevel = abilityStore.hasAbilityType(ability.getAbilityType())\n ? abilityStore.getAbility(ability.getAbilityType()).getLevel() : 0;\n Ability result = abilityStore.removeAbility(ability, doRemove);\n if (modifyXp && !result.isEmpty()) {\n player.giveExperiencePoints(getExperience(result));\n int newLevel = abilityStore.hasAbilityType(result.getAbilityType())\n ? abilityStore.getAbility(result.getAbilityType()).getLevel() : 0;\n onPlayerAbilityChanged(player, result.getAbilityType(), oldLevel, newLevel);\n }\n return result;\n })\n .orElse(Ability.EMPTY);\n }\n\n public static int getExperience(@NonNull Ability ability) {\n if (ability.isEmpty()) {\n return 0;\n }\n return ability.getAbilityType().getBaseXpPerLevel() * ability.getLevel();\n }\n\n public static void setPlayerAbilities(ServerPlayerEntity player, Map<IAbilityType, Integer> abilityTypes) {\n player.getCapability(MutableAbilityStoreConfig.CAPABILITY)\n .ifPresent(abilityStore -> abilityStore.setAbilities(abilityTypes));\n }\n\n public static boolean canInsert(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n Ability added = mutableAbilityStore.addAbility(ability, false);\n return added.getLevel() == ability.getLevel();\n }\n\n public static boolean canExtract(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n Ability added = mutableAbilityStore.removeAbility(ability, false);\n return added.getLevel() == ability.getLevel();\n }\n\n public static boolean canInsertToPlayer(Ability ability, PlayerEntity player) {\n Ability added = addPlayerAbility(player, ability, false, true);\n return added.getLevel() == ability.getLevel();\n }\n\n public static Ability insert(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n return mutableAbilityStore.addAbility(ability, true);\n }\n\n public static Ability extract(Ability ability, IMutableAbilityStore mutableAbilityStore) {\n return mutableAbilityStore.removeAbility(ability, true);\n }\n\n public static Optional<IAbilityType> getRandomAbility(List<IAbilityType> abilityTypes, Random random, Rarity rarity) {\n List<IAbilityType> filtered = abilityTypes.stream().filter(createRarityPredicate(rarity)).collect(Collectors.toList());\n if (filtered.size() > 0) {\n return Optional.of(filtered.get(random.nextInt(filtered.size())));\n }\n return Optional.empty();\n }\n\n public static Optional<IAbilityType> getRandomAbilityUntilRarity(List<IAbilityType> abilityTypes, Random random, Rarity rarity, boolean inclusive) {\n NavigableSet<Rarity> validRarities = AbilityHelpers.getValidAbilityRarities(abilityTypes).headSet(rarity, inclusive);\n Iterator<Rarity> it = validRarities.descendingIterator();\n while (it.hasNext()) {\n Optional<IAbilityType> optional = getRandomAbility(abilityTypes, random, it.next());\n if (optional.isPresent()) {\n return optional;\n }\n }\n return Optional.empty();\n }\n\n public static Optional<ItemStack> getRandomTotem(List<IAbilityType> abilityTypes, Rarity rarity, Random rand) {\n return getRandomAbility(abilityTypes, rand, rarity).flatMap(\n abilityType -> Optional.of(ItemAbilityTotem.getTotem(new Ability(abilityType, 1))));\n }\n \n\n public static Rarity getRandomRarity(List<IAbilityType> abilityTypes, Random rand) {\n int chance = rand.nextInt(50);\n Rarity rarity;\n if (chance >= 49) {\n rarity = Rarity.EPIC;\n } else if (chance >= 40) {\n rarity = Rarity.RARE;\n } else if (chance >= 25) {\n rarity = Rarity.UNCOMMON;\n } else {\n rarity = Rarity.COMMON;\n }\n\n // Fallback to a random selection of a rarity that is guaranteed to exist in the registered abilities\n if (!hasRarityAbilities(abilityTypes, rarity)) {\n int size = abilityTypes.size();\n if (size == 0) {\n throw new IllegalStateException(\"No abilities were registered, at least one ability must be enabled for this mod to function correctly.\");\n }\n rarity = Iterables.get(abilityTypes, rand.nextInt(size)).getRarity();\n }\n\n return rarity;\n }\n\n public static boolean hasRarityAbilities(List<IAbilityType> abilityTypes, Rarity rarity) {\n return abilityTypes.stream().anyMatch(createRarityPredicate(rarity));\n }\n\n public static NavigableSet<Rarity> getValidAbilityRarities(List<IAbilityType> abilityTypes) {\n NavigableSet<Rarity> rarities = Sets.newTreeSet();\n for (Rarity rarity : Rarity.values()) {\n if (hasRarityAbilities(abilityTypes, rarity)) {\n rarities.add(rarity);\n }\n }\n return rarities;\n }\n\n public static Triple<Integer, Integer, Integer> getAverageRarityColor(IAbilityStore abilityStore) {\n int r = 0;\n int g = 0;\n int b = 0;\n int count = 1;\n for (IAbilityType abilityType : abilityStore.getAbilityTypes()) {\n Triple<Float, Float, Float> color = Helpers.intToRGB(AbilityHelpers.RARITY_COLORS\n [Math.min(AbilityHelpers.RARITY_COLORS.length - 1, abilityType.getRarity().ordinal())]);\n r += color.getLeft() * 255;\n g += color.getMiddle() * 255;\n b += color.getRight() * 255;\n count++;\n }\n return Triple.of(r / count, g / count, b / count);\n }\n\n public static Supplier<Rarity> getSafeRarity(Supplier<Integer> rarityGetter) {\n return () -> {\n Integer rarity = rarityGetter.get();\n return rarity < 0 ? Rarity.COMMON : (rarity >= Rarity.values().length ? Rarity.EPIC : Rarity.values()[rarity]);\n };\n }\n\n}", "public class Ability implements Comparable<Ability> {\n\n public static final Ability EMPTY = new Ability(new AbilityType(\"\", \"\", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0);\n\n private final IAbilityType abilityType;\n private final int level;\n\n public Ability(@Nonnull IAbilityType abilityType, int level) {\n this.abilityType = Objects.requireNonNull(abilityType);\n this.level = level;\n }\n\n public IAbilityType getAbilityType() {\n return abilityType;\n }\n\n public int getLevel() {\n return level;\n }\n\n @Override\n public String toString() {\n return String.format(\"[%s @ %s]\", abilityType.getTranslationKey(), level);\n }\n\n @Override\n public int compareTo(Ability other) {\n return this.toString().compareTo(other.toString());\n }\n\n public ITextComponent getTextComponent() {\n return new StringTextComponent(\"[\")\n .append(new TranslationTextComponent(abilityType.getTranslationKey()))\n .appendString(\" @ \" + level + \"]\");\n }\n\n public boolean isEmpty() {\n return getLevel() <= 0;\n }\n\n}", "public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> {\n\n public String getTranslationKey();\n public String getUnlocalizedDescription();\n public Rarity getRarity();\n public int getMaxLevel();\n public default int getMaxLevelInfinitySafe() {\n return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel();\n }\n public int getBaseXpPerLevel();\n public boolean isObtainableOnPlayerSpawn();\n public boolean isObtainableOnMobSpawn();\n public boolean isObtainableOnCraft();\n public boolean isObtainableOnLoot();\n\n public void onTick(PlayerEntity player, int level);\n public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel);\n\n}", "public class MutableAbilityStoreConfig extends CapabilityConfig {\n\n /**\n * The unique instance.\n */\n public static MutableAbilityStoreConfig _instance;\n\n @CapabilityInject(IMutableAbilityStore.class)\n public static Capability<IMutableAbilityStore> CAPABILITY = null;\n\n /**\n * Make a new instance.\n */\n public MutableAbilityStoreConfig() {\n super(EverlastingAbilities._instance,\n \"mutableAbilityStore\",\n IMutableAbilityStore.class,\n new AbilityStoreStorage(),\n DefaultMutableAbilityStore::new);\n }\n}" ]
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.loot.LootFunctionType; import net.minecraft.util.ResourceLocation; import net.minecraft.loot.LootContext; import net.minecraft.loot.LootFunction; import net.minecraft.loot.conditions.ILootCondition; import org.cyclops.cyclopscore.helper.LootHelpers; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.ability.AbilityHelpers; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.List;
package org.cyclops.everlastingabilities.loot.functions; /** * A loot function that sets a random into an item. * @author rubensworks */ public class LootFunctionSetRandomAbility extends LootFunction { public static final LootFunctionType TYPE = LootHelpers.registerFunction(new ResourceLocation(Reference.MOD_ID, "set_random_ability"), new LootFunctionSetRandomAbility.Serializer()); public LootFunctionSetRandomAbility(ILootCondition[] conditionsIn) { super(conditionsIn); } @Override public ItemStack doApply(ItemStack stack, LootContext context) {
List<IAbilityType> abilityTypes = AbilityHelpers.getAbilityTypesLoot();
1
GoogleCloudPlatform/endpoints-codelab-android
todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoTxtTouch.java
[ "public class FilterFactory {\n public static Filter<Task> generateAndFilter(List<Priority> priorities,\n List<String> contexts, List<String> projects, String text,\n boolean caseSensitive) {\n AndFilter filter = new AndFilter();\n\n if (priorities.size() > 0) {\n filter.addFilter(new ByPriorityFilter(priorities));\n }\n\n if (contexts.size() > 0) {\n filter.addFilter(new ByContextFilter(contexts));\n }\n\n if (projects.size() > 0) {\n filter.addFilter(new ByProjectFilter(projects));\n }\n\n if (!Strings.isEmptyOrNull(text)) {\n filter.addFilter(new ByTextFilter(text, caseSensitive));\n }\n\n return filter;\n }\n}", "public enum Priority {\n NONE(\"-\", \" \", \"\", \"\"), A(\"A\", \"A\", \"A\", \"(A)\"), B(\"B\", \"B\", \"B\", \"(B)\"), C(\n \"C\", \"C\", \"C\", \"(C)\"), D(\"D\", \"D\", \"D\", \"(D)\"), E(\"E\", \"E\", \"E\",\n \"(E)\"), F(\"F\", \"F\", \"F\", \"(F)\"), G(\"G\", \"G\", \"G\", \"(G)\"), H(\"H\",\n \"H\", \"H\", \"(H)\"), I(\"I\", \"I\", \"I\", \"(I)\"), J(\"J\", \"J\", \"J\", \"(J)\"), K(\n \"K\", \"K\", \"K\", \"(K)\"), L(\"L\", \"L\", \"L\", \"(L)\"), M(\"M\", \"M\", \"M\",\n \"(M)\"), N(\"N\", \"N\", \"N\", \"(N)\"), O(\"O\", \"O\", \"O\", \"(O)\"), P(\"P\",\n \"P\", \"P\", \"(P)\"), Q(\"Q\", \"Q\", \"Q\", \"(Q)\"), R(\"R\", \"R\", \"R\", \"(R)\"), S(\n \"S\", \"S\", \"S\", \"(S)\"), T(\"T\", \"T\", \"T\", \"(T)\"), U(\"U\", \"U\", \"U\",\n \"(U)\"), V(\"V\", \"V\", \"V\", \"(V)\"), W(\"W\", \"W\", \"W\", \"(W)\"), X(\"X\",\n \"X\", \"X\", \"(X)\"), Y(\"Y\", \"Y\", \"Y\", \"(Y)\"), Z(\"Z\", \"Z\", \"Z\", \"(Z)\");\n\n private final String code;\n private final String listFormat;\n private final String detailFormat;\n private final String fileFormat;\n\n private Priority(String code, String listFormat, String detailFormat, String fileFormat) {\n this.code = code;\n this.listFormat = listFormat;\n this.detailFormat = detailFormat;\n this.fileFormat = fileFormat;\n }\n\n public String getCode() {\n return code;\n }\n\n public String inListFormat() {\n return listFormat;\n }\n\n public String inDetailFormat() {\n return detailFormat;\n }\n\n public String inFileFormat() {\n return fileFormat;\n }\n\n private static Priority[] reverseValues() {\n Priority[] values = Priority.values();\n Priority[] reversed = new Priority[values.length];\n\n for (int i = 0; i < values.length; i++) {\n int index = values.length - 1 - i;\n reversed[index] = values[i];\n }\n\n return reversed;\n }\n\n public static List<Priority> range(Priority p1, Priority p2) {\n ArrayList<Priority> priorities = new ArrayList<Priority>();\n boolean add = false;\n\n for (Priority p : (p1.ordinal() < p2.ordinal() ? Priority.values()\n : Priority.reverseValues())) {\n if (p == p1) {\n add = true;\n }\n\n if (add) {\n priorities.add(p);\n }\n\n if (p == p2) {\n break;\n }\n }\n\n return priorities;\n }\n\n public static List<String> rangeInCode(Priority p1, Priority p2) {\n List<Priority> priorities = Priority.range(p1, p2);\n List<String> result = new ArrayList<String>(priorities.size());\n\n for (Priority p : priorities) {\n result.add(p.getCode());\n }\n\n return result;\n }\n\n public static ArrayList<String> inCode(Collection<Priority> priorities) {\n ArrayList<String> strings = new ArrayList<String>();\n\n for (Priority p : priorities) {\n strings.add(p.getCode());\n }\n\n return strings;\n }\n\n public static ArrayList<Priority> toPriority(List<String> codes) {\n ArrayList<Priority> priorities = new ArrayList<Priority>();\n\n for (String code : codes) {\n priorities.add(Priority.toPriority(code));\n }\n\n return priorities;\n }\n\n public static Priority toPriority(String s) {\n if (s == null) {\n return NONE;\n }\n\n for (Priority p : Priority.values()) {\n if (p.code.equals(s.toUpperCase(Locale.US))) {\n return p;\n }\n }\n\n return NONE;\n }\n}", "public enum Sort {\n /**\n * Priority descending sort should result in Tasks in the following order\n * <p>\n * (A), (B), (C), ..., (Z), (NO PRIORITY), (COMPLETED)\n * </p>\n * <p>\n * If tasks are of the same priority level, they are sorted by task id\n * ascending\n * </p>\n */\n PRIORITY_DESC(0, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n int result = t1.getSortPriority().compareTo(t2.getSortPriority());\n\n if (result != 0) {\n return result;\n }\n\n return Sort.ID_ASC.getComparator().compare(t1, t2);\n }\n }),\n\n /**\n * Id ascending sort should result in Tasks in the following order\n * <p>\n * 1, 2, 3, 4, ..., n\n * </p>\n */\n ID_ASC(1, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n return ((Long) t1.getId()).compareTo((Long) t2.getId());\n }\n }),\n\n /**\n * Id descending sort should result in Tasks in the following order\n * <p>\n * n, ..., 4, 3, 2, 1\n * </p>\n */\n ID_DESC(2, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n return ((Long) t2.getId()).compareTo((Long) t1.getId());\n }\n }),\n\n /**\n * Text ascending sort should result in Tasks sorting in the following order\n * <p>\n * (incomplete) a, b, c, d, e, ..., z, (completed) a, b, c, d, e, ..., z\n * </p>\n * <p>\n * If tasks are of the same text (and completion) value, they are sorted by\n * task id ascending\n * </p>\n */\n TEXT_ASC(3, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n int result = ((Boolean) t1.isCompleted()).compareTo((Boolean) t2.isCompleted());\n\n if (result != 0) {\n return result;\n }\n\n result = t1.getText().compareToIgnoreCase(t2.getText());\n\n if (result != 0) {\n return result;\n }\n\n return Sort.ID_ASC.getComparator().compare(t1, t2);\n }\n }),\n\n /**\n * Date ascending sort should result in Tasks ordered by creation date,\n * earliest first. Tasks with no creation date will be sorted by line number\n * in ascending order after those with a date. Followed finally by completed\n * tasks.\n * <p>\n * If tasks are of the same date sort level, they are sorted by task id\n * ascending\n * </p>\n */\n DATE_ASC(4, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n int result = t1.getAscSortDate().compareTo(t2.getAscSortDate());\n\n if (result != 0) {\n return result;\n }\n\n return Sort.ID_ASC.getComparator().compare(t1, t2);\n }\n }),\n\n /**\n * Date descending sort should result in Tasks ordered by creation date,\n * most recent first. Tasks with no creation date will be sorted by line\n * number in descending order before all tasks with dates.\n * <p>\n * If tasks are of the same date level, they are sorted by task id\n * descending\n * </p>\n */\n DATE_DESC(5, new Comparator<Task>() {\n @Override\n public int compare(Task t1, Task t2) {\n if ((t1 == null) || (t2 == null)) {\n throw new NullPointerException(\"Null task passed into comparator\");\n }\n\n int result = t2.getDescSortDate().compareTo(t1.getDescSortDate());\n\n if (result != 0) {\n return result;\n }\n\n return Sort.ID_DESC.getComparator().compare(t1, t2);\n }\n });\n\n private final int id;\n private final Comparator<Task> comparator;\n\n private Sort(int id, Comparator<Task> comparator) {\n this.id = id;\n this.comparator = comparator;\n }\n\n public int getId() {\n return id;\n }\n\n public Comparator<Task> getComparator() {\n return comparator;\n }\n\n /**\n * Retrieves the sort selection by its id, default to PRIORITY_DESC if no\n * matching sort is found\n * \n * @param id the sort id to lookup\n * @return the matching sort or PRIORITY_DESC if no match is found\n */\n public static Sort getById(int id) {\n for (Sort sort : Sort.values()) {\n if (sort.id == id) {\n return sort;\n }\n }\n\n return Sort.PRIORITY_DESC;\n }\n}", "@SuppressWarnings(\"serial\")\npublic class Task implements Serializable {\n private static final String COMPLETED = \"x \";\n private static final String DATE_FORMAT = \"yyyy-MM-dd\";\n private final String originalText;\n private final Priority originalPriority;\n\n private long id;\n private Priority priority;\n private boolean deleted = false;\n private boolean completed = false;\n private String text;\n private String completionDate;\n private String prependedDate;\n private String relativeAge = \"\";\n private List<String> contexts;\n private List<String> projects;\n private List<String> mailAddresses;\n private List<URL> links;\n private List<String> phoneNumbers;\n\n public Task(long id, String rawText, Date defaultPrependedDate) {\n this.id = id;\n this.init(rawText, defaultPrependedDate);\n this.originalPriority = priority;\n this.originalText = text;\n }\n\n public Task(long id, String rawText) {\n this(id, rawText, null);\n }\n\n public void update(String rawText) {\n this.init(rawText, null);\n }\n\n private void init(String rawText, Date defaultPrependedDate) {\n TextSplitter splitter = TextSplitter.getInstance();\n TextSplitter.SplitResult splitResult = splitter.split(rawText);\n this.priority = splitResult.priority;\n this.text = splitResult.text;\n this.prependedDate = splitResult.prependedDate;\n this.completed = splitResult.completed;\n this.completionDate = splitResult.completedDate;\n\n this.contexts = ContextParser.getInstance().parse(text);\n this.projects = ProjectParser.getInstance().parse(text);\n this.mailAddresses = MailAddressParser.getInstance().parse(text);\n this.links = LinkParser.getInstance().parse(text);\n this.phoneNumbers = PhoneNumberParser.getInstance().parse(text);\n this.deleted = Strings.isEmptyOrNull(text);\n\n if (defaultPrependedDate != null\n && Strings.isEmptyOrNull(this.prependedDate)) {\n SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);\n this.prependedDate = formatter.format(defaultPrependedDate);\n }\n\n if (!Strings.isEmptyOrNull(this.prependedDate)) {\n SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);\n\n try {\n Date d = sdf.parse(this.prependedDate);\n this.relativeAge = RelativeDate.getRelativeDate(d);\n } catch (ParseException e) {\n // e.printStackTrace();\n }\n }\n }\n\n public Priority getOriginalPriority() {\n return originalPriority;\n }\n\n public String getOriginalText() {\n return originalText;\n }\n\n public String getText() {\n return text;\n }\n\n public long getId() {\n return id;\n }\n\n public void setPriority(Priority priority) {\n this.priority = priority;\n }\n\n public Priority getPriority() {\n return priority;\n }\n\n public List<String> getContexts() {\n return contexts;\n }\n\n public List<URL> getLinks() {\n return links;\n }\n\n public List<String> getPhoneNumbers() {\n return phoneNumbers;\n }\n\n public List<String> getProjects() {\n return projects;\n }\n\n public List<String> getMailAddresses() {\n return mailAddresses;\n }\n\n public String getPrependedDate() {\n return prependedDate;\n }\n\n public String getRelativeAge() {\n return relativeAge;\n }\n\n public boolean isDeleted() {\n return deleted;\n }\n\n public boolean isCompleted() {\n return completed;\n }\n\n public String getCompletionDate() {\n return completionDate;\n }\n\n public void markComplete(Date date) {\n if (!this.completed) {\n this.priority = Priority.NONE;\n this.completionDate = new SimpleDateFormat(Task.DATE_FORMAT).format(date);\n this.deleted = false;\n this.completed = true;\n }\n }\n\n public void markIncomplete() {\n if (this.completed) {\n this.completionDate = \"\";\n this.completed = false;\n }\n }\n\n public void delete() {\n this.update(\"\");\n }\n\n // TODO need a better solution (TaskFormatter?) here\n public String inScreenFormat() {\n StringBuilder sb = new StringBuilder();\n\n if (this.completed) {\n sb.append(COMPLETED).append(this.completionDate).append(\" \");\n\n if (!Strings.isEmptyOrNull(this.prependedDate)) {\n sb.append(this.prependedDate).append(\" \");\n }\n }\n\n sb.append(this.text);\n\n return sb.toString();\n }\n\n public String inFileFormat() {\n StringBuilder sb = new StringBuilder();\n\n if (this.completed) {\n sb.append(COMPLETED).append(this.completionDate).append(\" \");\n\n if (!Strings.isEmptyOrNull(this.prependedDate)) {\n sb.append(this.prependedDate).append(\" \");\n }\n } else {\n if (priority != Priority.NONE) {\n sb.append(priority.inFileFormat()).append(\" \");\n }\n\n if (!Strings.isEmptyOrNull(this.prependedDate)) {\n sb.append(this.prependedDate).append(\" \");\n }\n }\n\n sb.append(this.text);\n\n return sb.toString();\n }\n\n public void copyInto(Task destination) {\n destination.id = this.id;\n destination.init(this.inFileFormat(), null);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (obj == null) {\n return false;\n }\n\n if (((Object) this).getClass() != obj.getClass()) {\n return false;\n }\n\n Task other = (Task) obj;\n\n if (completed != other.completed) {\n return false;\n }\n\n if (completionDate == null) {\n if (other.completionDate != null) {\n return false;\n }\n } else if (!completionDate.equals(other.completionDate)) {\n return false;\n }\n\n if (contexts == null) {\n if (other.contexts != null) {\n return false;\n }\n } else if (!contexts.equals(other.contexts)) {\n return false;\n }\n\n if (deleted != other.deleted) {\n return false;\n }\n\n if (id != other.id) {\n return false;\n }\n\n if (links == null) {\n if (other.links != null) {\n return false;\n }\n } else if (!links.equals(other.links)) {\n return false;\n }\n\n if (mailAddresses == null) {\n if (other.mailAddresses != null) {\n return false;\n }\n } else if (!mailAddresses.equals(other.mailAddresses)) {\n if (phoneNumbers == null) {\n if (other.phoneNumbers != null) {\n return false;\n }\n } else if (!phoneNumbers.equals(other.phoneNumbers)) {\n return false;\n }\n }\n\n if (prependedDate == null) {\n if (other.prependedDate != null) {\n return false;\n }\n } else if (!prependedDate.equals(other.prependedDate)) {\n return false;\n }\n\n if (priority != other.priority) {\n return false;\n }\n\n if (projects == null) {\n if (other.projects != null) {\n return false;\n }\n } else if (!projects.equals(other.projects)) {\n return false;\n }\n\n if (relativeAge == null) {\n if (other.relativeAge != null) {\n return false;\n }\n } else if (!relativeAge.equals(other.relativeAge)) {\n return false;\n }\n\n if (text == null) {\n if (other.text != null) {\n return false;\n }\n } else if (!text.equals(other.text)) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n\n int result = 1;\n\n result = prime * result + (completed ? 1231 : 1237);\n result = prime * result\n + ((completionDate == null) ? 0 : completionDate.hashCode());\n result = prime * result\n + ((contexts == null) ? 0 : contexts.hashCode());\n result = prime * result + (deleted ? 1231 : 1237);\n result = prime * result + (int) (id ^ (id >>> 32));\n result = prime * result + ((links == null) ? 0 : links.hashCode());\n result = prime * result\n + ((mailAddresses == null) ? 0 : mailAddresses.hashCode())\n + ((phoneNumbers == null) ? 0 : phoneNumbers.hashCode());\n result = prime * result\n + ((prependedDate == null) ? 0 : prependedDate.hashCode());\n result = prime * result\n + ((priority == null) ? 0 : priority.hashCode());\n result = prime * result\n + ((projects == null) ? 0 : projects.hashCode());\n result = prime * result\n + ((relativeAge == null) ? 0 : relativeAge.hashCode());\n result = prime * result + ((text == null) ? 0 : text.hashCode());\n\n return result;\n }\n\n /**\n * Returns the fully extended priority order: A - Z, None, Completed\n * \n * @return fullyExtendedPriority\n */\n public Integer getSortPriority() {\n if (completed) {\n return Priority.values().length;\n }\n\n return (priority.ordinal() > 0 ? priority.ordinal() - 1 : Priority.values().length - 1);\n }\n\n public String getAscSortDate() {\n if (completed) {\n return \"9999-99-99\";\n }\n\n if (Strings.isEmptyOrNull(prependedDate)) {\n return \"9999-99-98\";\n }\n\n return prependedDate;\n }\n\n public String getDescSortDate() {\n if (completed) {\n return \"0000-00-00\";\n }\n\n if (Strings.isEmptyOrNull(prependedDate)) {\n return \"9999-99-99\";\n }\n\n return prependedDate;\n }\n\n public void initWithFilters(ArrayList<Priority> prios, ArrayList<String> ctxts,\n ArrayList<String> pjs) {\n if ((prios != null) && (prios.size() == 1)) {\n setPriority(prios.get(0));\n }\n\n if ((ctxts != null) && (ctxts.size() == 1)) {\n contexts.clear();\n contexts.add(ctxts.get(0));\n }\n\n if ((pjs != null) && (pjs.size() == 1)) {\n projects.clear();\n projects.add(pjs.get(0));\n }\n }\n}", "public interface TaskBag {\n void reload();\n\n void clear();\n\n void addAsTask(String input);\n\n void update(Task task);\n\n void delete(Task task);\n\n List<Task> getTasks();\n\n List<Task> getTasks(Filter<Task> filter, Comparator<Task> comparator);\n\n int size();\n\n ArrayList<String> getProjects(boolean includeNone);\n\n ArrayList<String> getContexts(boolean includeNone);\n\n ArrayList<Priority> getPriorities();\n\n /* REMOTE APIs */\n // FUTURE make this syncWithRemote()\n /**\n * Push tasks in localRepository into remoteRepository if you're not working\n * offline\n */\n void pushToRemote(boolean overwrite);\n\n /**\n * Force-push tasks in localRepository into remoteRepository disregarding\n * Work Offline status\n */\n void pushToRemote(boolean overridePreference, boolean overwrite);\n\n /**\n * Pulls tasks from remoteRepository, stores in localRepository\n */\n void pullFromRemote();\n\n /**\n * Force-pull tasks from remoteRepository into localRepository disregarding\n * Work Offline status\n */\n void pullFromRemote(boolean overridePreference);\n\n /* END REMOTE APIs */\n}", "@SuppressWarnings(\"serial\")\npublic class TaskPersistException extends RuntimeException {\n public TaskPersistException(String message) {\n super(message);\n }\n\n public TaskPersistException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public final class Strings {\n public static final String SINGLE_SPACE = \" \";\n\n /**\n * Inserts a given string into another padding it with spaces. Is aware if\n * the insertion point has a space on either end and does not add extra\n * spaces.\n * \n * @param s the string to insert into\n * @param insertAt the position to insert the string\n * @param stringToInsert the string to insert\n * @return the result of inserting the stringToInsert into the passed in\n * string\n * @throws IndexOutOfBoundsException if the insertAt is negative, or\n * insertAt is larger than the length of s String object\n */\n public static String insertPadded(String s, int insertAt, String stringToInsert) {\n if (Strings.isEmptyOrNull(stringToInsert)) {\n return s;\n }\n\n if (insertAt < 0) {\n throw new IndexOutOfBoundsException(\"Invalid insertAt of [\"\n + insertAt + \"] for string [\" + s + \"]\");\n }\n\n StringBuilder newText = new StringBuilder();\n\n if (insertAt > 0) {\n newText.append(s.substring(0, insertAt));\n\n if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {\n newText.append(SINGLE_SPACE);\n }\n\n newText.append(stringToInsert);\n String postItem = s.substring(insertAt);\n\n if (postItem.indexOf(SINGLE_SPACE) != 0) {\n newText.append(SINGLE_SPACE);\n }\n\n newText.append(postItem);\n } else {\n newText.append(stringToInsert);\n\n if (s.indexOf(SINGLE_SPACE) != 0) {\n newText.append(SINGLE_SPACE);\n }\n\n newText.append(s);\n }\n\n return newText.toString();\n }\n\n /**\n * Inserts a given string into another padding it with spaces. Is aware if\n * the insertion point has a space on either end and does not add extra\n * spaces. If the string-to-insert is already present (and not part of\n * another word) we return the original string unchanged.\n * \n * @param s the string to insert into\n * @param insertAt the position to insert the string\n * @param stringToInsert the string to insert\n * @return the result of inserting the stringToInsert into the passed in\n * string\n * @throws IndexOutOfBoundsException if the insertAt is negative, or\n * insertAt is larger than the length of s String object\n */\n public static String insertPaddedIfNeeded(String s, int insertAt, String stringToInsert) {\n if (Strings.isEmptyOrNull(stringToInsert)) {\n return s;\n }\n\n boolean found = false;\n int startPos = 0;\n\n while ((startPos < s.length()) && (!found)) {\n int pos = s.indexOf(stringToInsert, startPos);\n\n if (pos < 0)\n break;\n\n startPos = pos + 1;\n int before = pos - 1;\n int after = pos + stringToInsert.length();\n\n if (((pos == 0) || (Character.isWhitespace(s.charAt(before)))) &&\n ((after >= s.length()) || (Character.isWhitespace(s.charAt(after)))))\n found = true;\n }\n\n if (found) {\n StringBuilder newText = new StringBuilder(s);\n\n if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {\n newText.append(SINGLE_SPACE);\n }\n\n return (newText.toString());\n } else\n return (Strings.insertPadded(s, insertAt, stringToInsert));\n }\n\n /**\n * Checks the passed in string to see if it is null or an empty string\n * \n * @param s the string to check\n * @return true if null or \"\"\n */\n public static boolean isEmptyOrNull(String s) {\n return s == null || s.length() == 0;\n }\n\n /**\n * Checks the passed in string to see if it is null, empty, or blank; where\n * 'blank' is defined as consisting entirely of whitespace.\n * \n * @param s the string to check\n * @return true if null or \"\" or all whitespace\n */\n public static boolean isBlank(String s) {\n return isEmptyOrNull(s) || s.trim().length() == 0;\n }\n}", "public class Util {\n private static String TAG = Util.class.getSimpleName();\n\n private static final int CONNECTION_TIMEOUT = 120000;\n\n private static final int SOCKET_TIMEOUT = 120000;\n\n private Util() {\n }\n\n public static HttpParams getTimeoutHttpParams() {\n HttpParams params = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);\n HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);\n\n return params;\n }\n\n public static void closeStream(Closeable stream) {\n if (stream != null) {\n try {\n stream.close();\n stream = null;\n } catch (IOException e) {\n Log.w(TAG, \"Close stream exception\", e);\n }\n }\n }\n\n public static InputStream getInputStreamFromUrl(String url)\n throws ClientProtocolException, IOException {\n HttpGet request = new HttpGet(url);\n DefaultHttpClient client = new DefaultHttpClient(getTimeoutHttpParams());\n HttpResponse response = client.execute(request);\n int statusCode = response.getStatusLine().getStatusCode();\n\n if (statusCode != 200) {\n Log.e(TAG, \"Failed to get stream for: \" + url);\n throw new IOException(\"Failed to get stream for: \" + url);\n }\n\n return response.getEntity().getContent();\n }\n\n public static String fetchContent(String url)\n throws ClientProtocolException, IOException {\n InputStream input = getInputStreamFromUrl(url);\n\n try {\n int c;\n byte[] buffer = new byte[8192];\n StringBuilder sb = new StringBuilder();\n\n while ((c = input.read(buffer)) != -1) {\n sb.append(new String(buffer, 0, c));\n }\n\n return sb.toString();\n } finally {\n closeStream(input);\n }\n }\n\n public static String readStream(InputStream is) {\n if (is == null) {\n return null;\n }\n\n try {\n int c;\n byte[] buffer = new byte[8192];\n StringBuilder sb = new StringBuilder();\n\n while ((c = is.read(buffer)) != -1) {\n sb.append(new String(buffer, 0, c));\n }\n\n return sb.toString();\n } catch (Throwable e) {\n e.printStackTrace();\n } finally {\n closeStream(is);\n }\n\n return null;\n }\n\n public static void writeFile(InputStream is, File file)\n throws ClientProtocolException, IOException {\n FileOutputStream os = new FileOutputStream(file);\n\n try {\n int c;\n byte[] buffer = new byte[8192];\n\n while ((c = is.read(buffer)) != -1) {\n os.write(buffer, 0, c);\n }\n } finally {\n closeStream(is);\n closeStream(os);\n }\n }\n\n public static void showToastLong(Context cxt, int resid) {\n Toast.makeText(cxt, resid, Toast.LENGTH_LONG).show();\n }\n\n public static void showToastShort(Context cxt, int resid) {\n Toast.makeText(cxt, resid, Toast.LENGTH_SHORT).show();\n }\n\n public static void showToastLong(Context cxt, String msg) {\n Toast.makeText(cxt, msg, Toast.LENGTH_LONG).show();\n }\n\n public static void showToastShort(Context cxt, String msg) {\n Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();\n }\n\n public interface OnMultiChoiceDialogListener {\n void onClick(boolean[] selected);\n }\n\n public static Dialog createMultiChoiceDialog(Context cxt,\n CharSequence[] keys, boolean[] values, Integer titleId,\n Integer iconId, final OnMultiChoiceDialogListener listener) {\n final boolean[] res;\n\n if (values == null) {\n res = new boolean[keys.length];\n } else {\n res = values;\n }\n\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n\n if (iconId != null) {\n builder.setIcon(iconId);\n }\n\n if (titleId != null) {\n builder.setTitle(titleId);\n }\n\n builder.setMultiChoiceItems(keys, values,\n new DialogInterface.OnMultiChoiceClickListener() {\n public void onClick(DialogInterface dialog,\n int whichButton, boolean isChecked) {\n res[whichButton] = isChecked;\n }\n });\n\n builder.setPositiveButton(R.string.ok,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n listener.onClick(res);\n }\n });\n\n builder.setNegativeButton(R.string.cancel, null);\n\n return builder.create();\n }\n\n public static void showDialog(Context cxt, int titleid, int msgid) {\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n builder.setTitle(titleid);\n builder.setMessage(msgid);\n builder.setPositiveButton(android.R.string.ok, null);\n builder.setCancelable(true);\n builder.show();\n }\n\n public static void showDialog(Context cxt, int titleid, String msg) {\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n builder.setTitle(titleid);\n builder.setMessage(msg);\n builder.setPositiveButton(android.R.string.ok, null);\n builder.setCancelable(true);\n builder.show();\n }\n\n public static void showConfirmationDialog(Context cxt, int msgid, OnClickListener oklistener) {\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n // builder.setTitle(cxt.getPackageName());\n builder.setMessage(msgid);\n builder.setPositiveButton(android.R.string.ok, oklistener);\n builder.setNegativeButton(android.R.string.cancel, null);\n builder.setCancelable(true);\n builder.show();\n }\n\n public static void showConfirmationDialog(Context cxt, int msgid, OnClickListener oklistener,\n int titleid) {\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n // builder.setTitle(cxt.getPackageName());\n builder.setTitle(titleid);\n builder.setMessage(msgid);\n builder.setPositiveButton(android.R.string.ok, oklistener);\n builder.setNegativeButton(android.R.string.cancel, null);\n builder.setCancelable(true);\n builder.show();\n }\n\n public static void showDeleteConfirmationDialog(Context cxt, OnClickListener oklistener) {\n AlertDialog.Builder builder = new AlertDialog.Builder(cxt);\n builder.setTitle(R.string.delete_task_title);\n builder.setMessage(R.string.delete_task_message);\n builder.setPositiveButton(R.string.delete_task_confirm, oklistener);\n builder.setNegativeButton(R.string.cancel, null);\n builder.show();\n }\n\n public static boolean isDeviceWritable() {\n String sdState = Environment.getExternalStorageState();\n\n if (Environment.MEDIA_MOUNTED.equals(sdState)) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isDeviceReadable() {\n String sdState = Environment.getExternalStorageState();\n\n if (Environment.MEDIA_MOUNTED.equals(sdState)\n || Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdState)) {\n return true;\n } else {\n return false;\n }\n }\n\n public interface InputDialogListener {\n void onClick(String input);\n }\n\n public interface LoginDialogListener {\n void onClick(String username, String password);\n }\n\n public static void createParentDirectory(File dest) throws TodoException {\n if (dest == null) {\n throw new TodoException(\"createParentDirectory: dest is null\");\n }\n\n File dir = dest.getParentFile();\n\n if (dir != null && !dir.exists()) {\n createParentDirectory(dir);\n }\n\n if (!dir.exists()) {\n if (!dir.mkdirs()) {\n Log.e(TAG, \"Could not create dirs: \" + dir.getAbsolutePath());\n\n throw new TodoException(\"Could not create dirs: \" + dir.getAbsolutePath());\n }\n }\n }\n\n public static void renameFile(File origFile, File newFile, boolean overwrite) {\n if (!origFile.exists()) {\n Log.e(TAG, \"Error renaming file: \" + origFile + \" does not exist\");\n\n throw new TodoException(\"Error renaming file: \" + origFile + \" does not exist\");\n }\n\n createParentDirectory(newFile);\n\n if (overwrite && newFile.exists()) {\n if (!newFile.delete()) {\n Log.e(TAG, \"Error renaming file: failed to delete \" + newFile);\n\n throw new TodoException(\"Error renaming file: failed to delete \" + newFile);\n }\n }\n\n if (!origFile.renameTo(newFile)) {\n Log.e(TAG, \"Error renaming \" + origFile + \" to \" + newFile);\n\n throw new TodoException(\"Error renaming \" + origFile + \" to \" + newFile);\n }\n }\n\n public static void copyFile(File origFile, File newFile, boolean overwrite) {\n if (!origFile.exists()) {\n Log.e(TAG, \"Error renaming file: \" + origFile + \" does not exist\");\n\n throw new TodoException(\"Error copying file: \" + origFile + \" does not exist\");\n }\n\n createParentDirectory(newFile);\n\n if (!overwrite && newFile.exists()) {\n Log.e(TAG, \"Error copying file: destination exists: \" + newFile);\n\n throw new TodoException(\"Error copying file: destination exists: \" + newFile);\n }\n\n try {\n FileInputStream fis = new FileInputStream(origFile);\n FileOutputStream fos = new FileOutputStream(newFile);\n FileChannel in = fis.getChannel();\n fos.getChannel().transferFrom(in, 0, in.size());\n fis.close();\n fos.close();\n } catch (Exception e) {\n Log.e(TAG, \"Error copying \" + origFile + \" to \" + newFile);\n\n throw new TodoException(\"Error copying \" + origFile + \" to \" + newFile, e);\n }\n }\n\n public static ArrayAdapter<String> newSpinnerAdapter(Context cxt, List<String> items) {\n ArrayAdapter<String> adapter = new ArrayAdapter<String>(cxt,\n android.R.layout.simple_spinner_item, items);\n adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n\n return adapter;\n }\n\n public static void setGray(SpannableString ss, List<String> items) {\n String data = ss.toString();\n\n for (String item : items) {\n int i = data.indexOf(\"@\" + item);\n\n if (i != -1) {\n ss.setSpan(new ForegroundColorSpan(Color.GRAY), i,\n i + 1 + item.length(),\n Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n }\n\n int j = data.indexOf(\"+\" + item);\n\n if (j != -1) {\n ss.setSpan(new ForegroundColorSpan(Color.GRAY), j,\n j + 1 + item.length(),\n Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n }\n }\n }\n\n public static boolean isOnline(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n\n return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();\n }\n\n public static String join(Collection<?> s, String delimiter) {\n StringBuilder builder = new StringBuilder();\n\n if (s == null) {\n return \"\";\n }\n\n Iterator<?> iter = s.iterator();\n\n while (iter.hasNext()) {\n builder.append(iter.next());\n\n if (!iter.hasNext()) {\n break;\n }\n\n builder.append(delimiter);\n }\n\n return builder.toString();\n }\n\n public static ArrayList<String> split(String s, String delimeter) {\n if (Strings.isBlank(s)) {\n return new ArrayList<String>();\n }\n\n return new ArrayList<String>(Arrays.asList(s.split(delimeter)));\n }\n}" ]
import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshAttacher; import uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Paint; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.CalendarContract.Events; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.text.SpannableString; import android.util.Log; import android.util.SparseBooleanArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListActivity; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.ActionMode.Callback; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.todotxt.todotxttouch.task.FilterFactory; import com.todotxt.todotxttouch.task.Priority; import com.todotxt.todotxttouch.task.Sort; import com.todotxt.todotxttouch.task.Task; import com.todotxt.todotxttouch.task.TaskBag; import com.todotxt.todotxttouch.task.TaskPersistException; import com.todotxt.todotxttouch.util.Strings; import com.todotxt.todotxttouch.util.Util; import de.timroes.swipetodismiss.SwipeDismissList;
case R.id.uncomplete: undoCompleteTasks(checkedTasks, true); break; case R.id.delete: deleteTasks(checkedTasks); break; case R.id.url: Log.v(TAG, "url: " + item.getTitle().toString()); intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item .getTitle().toString())); startActivity(intent); break; case R.id.mail: Log.v(TAG, "mail: " + item.getTitle().toString()); intent = new Intent(Intent.ACTION_SEND, Uri.parse(item .getTitle().toString())); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { item.getTitle().toString() }); intent.setType("text/plain"); startActivity(intent); break; case R.id.phone_number: Log.v(TAG, "phone_number"); intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + item.getTitle().toString())); startActivity(intent); break; default: Log.w(TAG, "unrecognized menuItem: " + menuid); } mMode.finish(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { getListView().clearChoices(); m_adapter.notifyDataSetChanged(); m_swipeList.setEnabled(true); mMode = null; } }); } mMode.setTitle(checkedCount + " " + getString(R.string.selected)); Menu menu = mMode.getMenu(); MenuItem updateAction = menu.findItem(R.id.update); MenuItem completeAction = menu.findItem(R.id.done); MenuItem uncompleteAction = menu.findItem(R.id.uncomplete); // Only show update action with a single task selected if (checkedCount == 1) { updateAction.setVisible(true); Task task = checkedTasks.get(0); if (task.isCompleted()) { completeAction.setVisible(false); } else { uncompleteAction.setVisible(false); } for (URL url : task.getLinks()) { menu.add(Menu.CATEGORY_SECONDARY, R.id.url, Menu.NONE, url.toString()); } for (String s1 : task.getMailAddresses()) { menu.add(Menu.CATEGORY_SECONDARY, R.id.mail, Menu.NONE, s1); } for (String s : task.getPhoneNumbers()) { menu.add(Menu.CATEGORY_SECONDARY, R.id.phone_number, Menu.NONE, s); } } else { updateAction.setVisible(false); completeAction.setVisible(true); uncompleteAction.setVisible(true); menu.removeGroup(Menu.CATEGORY_SECONDARY); } } void clearFilter() { // Filter cleared, exit CAB if active if (inActionMode()) { mMode.finish(); } m_app.m_prios = new ArrayList<Priority>(); // Collections.emptyList(); m_app.m_contexts = new ArrayList<String>(); // Collections.emptyList(); m_app.m_projects = new ArrayList<String>(); // Collections.emptyList(); m_app.m_filters = new ArrayList<String>(); m_app.m_search = ""; m_app.storeFilters(); setDrawerChoices(); } void setFilteredTasks(boolean reload) { if (reload) { try { taskBag.reload(); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } if (mScrollPosition < 0) { calculateScrollPosition(); } m_adapter.clear();
for (Task task : taskBag.getTasks(FilterFactory.generateAndFilter(
0
ppicas/android-clean-architecture-mvp
app/src/main/java/cat/ppicas/cleanarch/ui/activity/CityDetailsActivity.java
[ "public class CityDetailFragment extends Fragment implements CityDetailVista,\n PresenterFactory<CityDetailPresenter> {\n\n private static final String ARG_CITY_ID = \"cityId\";\n\n private String mCityId;\n\n private CityDetailPresenter mPresenter;\n\n public static CityDetailFragment newInstance(String cityId) {\n Bundle args = new Bundle();\n args.putString(ARG_CITY_ID, cityId);\n CityDetailFragment fragment = new CityDetailFragment();\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n Bundle args = getArguments();\n if (args == null || !args.containsKey(ARG_CITY_ID)) {\n throw new IllegalArgumentException(\"Invalid Fragment arguments\");\n }\n\n mCityId = args.getString(ARG_CITY_ID);\n\n mPresenter = ((PresenterHolder) getActivity()).getOrCreatePresenter(this);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_city_detail, container, false);\n\n ViewPager viewPager = (ViewPager) view.findViewById(R.id.city_detail__view_pager);\n viewPager.setAdapter(new LocalPageAdapter(getFragmentManager()));\n\n return view;\n }\n\n @Override\n public void onStart() {\n super.onStart();\n mPresenter.start(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n mPresenter.stop();\n }\n\n @Override\n public void setTitle(int stringResId, Object... args) {\n getActivity().setTitle(getString(stringResId, args));\n }\n\n @Override\n public void displayLoading(boolean display) {\n getActivity().setProgressBarIndeterminate(true);\n getActivity().setProgressBarIndeterminateVisibility(display);\n }\n\n @Override\n public void displayError(int stringResId, Object... args) {\n Toast.makeText(getActivity().getApplicationContext(), stringResId, Toast.LENGTH_LONG).show();\n }\n\n @Override\n public CityDetailPresenter createPresenter() {\n ServiceContainer sc = ServiceContainers.getFromApp(getActivity());\n return new CityDetailPresenter(sc.getTaskExecutor(), sc.getCityRepository(),\n getResources(), mCityId);\n }\n\n @Override\n public String getPresenterTag() {\n return CityDetailFragment.class.getName();\n }\n\n private class LocalPageAdapter extends FragmentStatePagerAdapter {\n\n public LocalPageAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public Fragment getItem(int position) {\n if (position == 0) {\n return CityCurrentWeatherFragment.newInstance(mCityId);\n } else {\n return CityDailyForecastFragment.newInstance(mCityId, position - 1);\n }\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n if (position == 0) {\n return getString(R.string.city_details__tab_current);\n } else {\n return mPresenter.getForecastPageTitle(position - 1);\n }\n }\n\n @Override\n public int getCount() {\n return 1 + 3;\n }\n }\n}", "public class PresenterHolderFragment extends Fragment implements PresenterHolder {\n\n private static final String STATE_PRESENTERS = \"presenters\";\n\n private final Map<String, Presenter<?>> mPresenterMap = new HashMap<String, Presenter<?>>();\n\n private Bundle mPresentersStates;\n\n @Override\n public void onCreate(Bundle state) {\n super.onCreate(state);\n setRetainInstance(true);\n\n if (state != null) {\n mPresentersStates = state.getBundle(STATE_PRESENTERS);\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle state) {\n super.onSaveInstanceState(state);\n Bundle presentersStates = new Bundle();\n for (Map.Entry<String, Presenter<?>> entry : mPresenterMap.entrySet()) {\n Bundle presenterState = new Bundle();\n entry.getValue().saveState(presenterState);\n presentersStates.putBundle(entry.getKey(), presenterState);\n }\n state.putBundle(STATE_PRESENTERS, presentersStates);\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n for (Presenter<?> presenter : mPresenterMap.values()) {\n presenter.onDestroy();\n }\n }\n\n @Override\n public <T extends Presenter<?>> T getOrCreatePresenter(PresenterFactory<T> presenterFactory) {\n String tag = presenterFactory.getPresenterTag();\n\n @SuppressWarnings(\"unchecked\")\n T presenter = (T) mPresenterMap.get(tag);\n\n if (presenter == null) {\n presenter = presenterFactory.createPresenter();\n if (mPresentersStates != null && mPresentersStates.containsKey(tag)) {\n presenter.restoreState(mPresentersStates.getBundle(tag));\n }\n mPresenterMap.put(tag, presenter);\n }\n\n return presenter;\n }\n\n @Override\n public void destroyPresenter(PresenterFactory<?> presenterFactory) {\n String tag = presenterFactory.getPresenterTag();\n Presenter<?> presenter = mPresenterMap.get(tag);\n if (presenter != null) {\n presenter.onDestroy();\n }\n mPresenterMap.remove(tag);\n }\n}", "public abstract class Presenter<T extends Vista> {\n\n private T mVista;\n\n /**\n * Returns the current bound {@link Vista} if any.\n *\n * @return The bound {@code Vista} or {@code null}.\n */\n @Nullable\n public T getVista() {\n return mVista;\n }\n\n /**\n * Must be called to bind the {@link Vista} and let the {@link Presenter} know that can start\n * {@code Vista} updates. Normally this method will be called from {@link Activity#onStart()}\n * or from {@link Fragment#onStart()}.\n *\n * @param vista A {@code Vista} instance to bind.\n */\n public final void start(T vista) {\n mVista = vista;\n onStart(vista);\n }\n\n /**\n * Must be called un unbind the {@link Vista} and let the {@link Presenter} know that must\n * stop updating the {@code Vista}. Normally this method will be called from\n * {@link Activity#onStop()} or from {@link Fragment#onStop()}.\n */\n public final void stop() {\n mVista = null;\n onStop();\n }\n\n /**\n * Called when the {@link Presenter} can start {@link Vista} updates.\n *\n * @param vista The bound {@code Vista}.\n */\n public abstract void onStart(T vista);\n\n /**\n * Called when the {@link Presenter} must stop {@link Vista} updates. The extending\n * {@code Presenter} can override this method to provide some custom logic.\n */\n public void onStop() {\n }\n\n /**\n * Called to ask the {@link Presenter} to save its current dynamic state, so it\n * can later be reconstructed in a new instance of its process is\n * restarted.\n *\n * @param state Bundle in which to place your saved state.\n * @see Activity#onSaveInstanceState(Bundle)\n */\n public void saveState(Bundle state) {\n }\n\n /**\n * Called to ask the {@link Presenter} to restore the previous saved state.\n *\n * @param state The data most recently supplied in {@link #saveState}.\n * @see Activity#onRestoreInstanceState(Bundle)\n */\n public void restoreState(Bundle state) {\n }\n\n /**\n * Called when this {@link Presenter} is going to be destroyed, so it has a chance to\n * release resources. The extending {@code Presenter} can override this method to provide some\n * custom logic.\n */\n public void onDestroy() {\n }\n}", "public interface PresenterFactory<T extends Presenter<?>> {\n\n T createPresenter();\n\n String getPresenterTag();\n\n}", "public interface PresenterHolder {\n\n <T extends Presenter<?>> T getOrCreatePresenter(PresenterFactory<T> presenterFactory);\n\n void destroyPresenter(PresenterFactory<?> presenterFactory);\n\n}" ]
import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.view.Window; import cat.ppicas.cleanarch.ui.fragment.CityDetailFragment; import cat.ppicas.cleanarch.ui.fragment.PresenterHolderFragment; import cat.ppicas.framework.ui.Presenter; import cat.ppicas.framework.ui.PresenterFactory; import cat.ppicas.framework.ui.PresenterHolder;
/* * Copyright (C) 2015 Pau Picas Sans <pau.picas@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package cat.ppicas.cleanarch.ui.activity; public class CityDetailsActivity extends Activity implements PresenterHolder { private PresenterHolder mPresenterHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (savedInstanceState == null) { Intent intent = new Intent(getIntent()); getFragmentManager().beginTransaction() .add(new PresenterHolderFragment(), null)
.add(android.R.id.content, CityDetailFragment.newInstance(intent.getCityId()))
0
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
[ "public class OpenFeed extends Application {\n\n private static OpenFeed application;\n\n public OpenFeed() {\n application = this;\n }\n\n public static OpenFeed getApplication() {\n return application;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n TwitterService.getInstance().init();\n }\n}", "public class NotificationEvent extends Event<String> {\n\n public NotificationEvent(String result) {\n super(result);\n }\n}", "public class TwitterEvents {\n\n public static class OAuthRequestTokenEvent extends Event<RequestToken> {\n public OAuthRequestTokenEvent(RequestToken result) {\n super(result);\n }\n }\n\n public static class OAuthAccessTokenEvent extends Event<AccessToken> {\n public OAuthAccessTokenEvent(AccessToken result) {\n super(result);\n }\n }\n\n public static class HomeTimelineEvent extends Event<List<Status>> {\n public HomeTimelineEvent(List<Status> result) {\n super(result);\n }\n }\n\n public static class SearchEvent extends Event<QueryResult> {\n public SearchEvent(QueryResult result) {\n super(result);\n }\n }\n\n public static class UserEvent extends Event<User> {\n public UserEvent(User result) {\n super(result);\n }\n }\n\n public static class RetweetedStatusEvent extends Event<Status> {\n public RetweetedStatusEvent(Status result) {\n super(result);\n }\n }\n\n public static class CreatedFavoriteEvent extends Event<Status> {\n public CreatedFavoriteEvent(Status result) {\n super(result);\n }\n }\n\n public static class DestroyedFavoriteEvent extends Event<Status> {\n public DestroyedFavoriteEvent(Status result) {\n super(result);\n }\n }\n\n public static class DestroyedStatusEvent extends Event<Status> {\n public DestroyedStatusEvent(Status result) {\n super(result);\n }\n }\n\n}", "public final class BusProvider {\n private static OpenFeedBus BUS = new OpenFeedBus();\n\n public static OpenFeedBus getInstance() {\n return BUS;\n }\n\n private BusProvider() {\n }\n}", "public class Preferences {\n\n public static final String PREFERENCES_NAME = \"openfeed_preferences\";\n public static final String TWITTER_ACCESS_TOKEN_KEY = \"twitter_access_token_key\";\n public static final String TWITTER_ACCESS_TOKEN_SECRET = \"twitter_access_token_secret\";\n\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
package com.williammora.openfeed.services; public class TwitterService { private static final String TAG = TwitterService.class.getSimpleName(); private static TwitterService ourInstance = new TwitterService(); private RequestToken requestToken; private Context context; private AsyncTwitter twitter; private boolean loaded; public static TwitterService getInstance() { return ourInstance; } private TwitterService() { } public void init() { if (loaded) { return; }
context = OpenFeed.getApplication().getApplicationContext();
0
goodow/realtime-channel
src/main/java/com/goodow/realtime/channel/impl/BusProxy.java
[ "@JsType\npublic interface Bus {\n String ON_OPEN = \"@realtime/bus/onOpen\";\n String ON_CLOSE = \"@realtime/bus/onClose\";\n String ON_ERROR = \"@realtime/bus/onError\";\n\n /**\n * Close the Bus and release all resources.\n */\n void close();\n\n /* The state of the Bus. */\n State getReadyState();\n\n /* Returns the session ID used by this bus. */\n String getSessionId();\n\n /**\n * Publish a message\n *\n * @param topic The topic to publish it to\n * @param msg The message\n */\n Bus publish(String topic, Object msg);\n\n /**\n * Publish a local message\n *\n * @param topic The topic to publish it to\n * @param msg The message\n */\n Bus publishLocal(String topic, Object msg);\n\n /**\n * Send a message\n *\n * @param topic The topic to send it to\n * @param msg The message\n * @param replyHandler Reply handler will be called when any reply from the recipient is received\n */\n <T> Bus send(String topic, Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * Send a local message\n *\n * @param topic The topic to send it to\n * @param msg The message\n * @param replyHandler Reply handler will be called when any reply from the recipient is received\n */\n <T> Bus sendLocal(String topic, Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * Set a BusHook on the Bus\n *\n * @param hook The hook\n */\n Bus setHook(BusHook hook);\n\n /**\n * Registers a handler against the specified topic\n *\n * @param topic The topic to register it at\n * @param handler The handler\n * @return the handler registration, can be stored in order to unregister the handler later\n */\n @SuppressWarnings(\"rawtypes\")\n Registration subscribe(String topic, Handler<? extends Message> handler);\n\n /**\n * Registers a local handler against the specified topic. The handler info won't be propagated\n * across the cluster\n *\n * @param topic The topic to register it at\n * @param handler The handler\n */\n @SuppressWarnings(\"rawtypes\")\n Registration subscribeLocal(String topic, Handler<? extends Message> handler);\n}", "public interface BusHook {\n /**\n * Called when the bus is opened\n */\n void handleOpened();\n\n /**\n * Called when the bus is closed\n */\n void handlePostClose();\n\n /**\n * Called before close the bus\n * \n * @return true to close the bus, false to reject it\n */\n boolean handlePreClose();\n\n /**\n * Called before register a handler\n * \n * @param topic The topic\n * @param handler The handler\n * @return true to let the registration occur, false otherwise\n */\n @SuppressWarnings(\"rawtypes\")\n boolean handlePreSubscribe(String topic, Handler<? extends Message> handler);\n\n /**\n * Called when a message is received\n * \n * @param message The message\n * @return true To allow the message to deliver, false otherwise\n */\n boolean handleReceiveMessage(Message<?> message);\n\n /**\n * Called when sending or publishing on the bus\n * \n * @param send if true it's a send else it's a publish\n * @param topic The topic the message is being sent/published to\n * @param msg The message\n * @param replyHandler Reply handler will be called when any reply from the recipient is received\n * @return true To allow the send/publish to occur, false otherwise\n */\n <T> boolean handleSendOrPub(boolean send, String topic, Object msg,\n Handler<Message<T>> replyHandler);\n\n /**\n * Called when unregistering a handler\n * \n * @param topic The topic\n * @return true to let the unregistration occur, false otherwise\n */\n boolean handleUnsubscribe(String topic);\n}", "@JsType\npublic interface Message<T> {\n /**\n * The body of the message\n */\n T body();\n\n /**\n * Signal that processing of this message failed. If the message was sent specifying a result\n * handler the handler will be called with a failure corresponding to the failure code and message\n * specified here\n *\n * @param failureCode A failure code to pass back to the sender\n * @param msg A message to pass back to the sender\n */\n void fail(int failureCode, String msg);\n\n /**\n * @return Whether this message originated in the local session.\n */\n boolean isLocal();\n\n /**\n * Reply to this message. If the message was sent specifying a reply handler, that handler will be\n * called when it has received a reply. If the message wasn't sent specifying a receipt handler\n * this method does nothing.\n */\n @JsNoExport\n void reply(Object msg);\n\n /**\n * The same as {@code reply(Object msg)} but you can specify handler for the reply - i.e. to\n * receive the reply to the reply.\n */\n @SuppressWarnings(\"hiding\")\n <T> void reply(Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * The reply topic (if any)\n */\n String replyTopic();\n\n /**\n * The topic the message was sent to\n */\n String topic();\n}", "@JsExport\n@JsType\npublic enum State {\n CONNECTING, OPEN, CLOSING, CLOSED;\n public static final State values[] = values();\n}", "public interface Handler<E> {\n\n /**\n * Something has happened, so handle it.\n */\n void handle(E event);\n}", "@JsType\npublic interface Registration {\n\n Registration EMPTY = new Registration() {\n @Override\n public void unregister() {\n }\n };\n\n /**\n * Deregisters the handler associated with this registration object if the handler is still\n * attached to the event bus. If the handler is no longer attached to the event bus, this is a\n * no-op.\n */\n void unregister();\n}" ]
import com.goodow.realtime.channel.Bus; import com.goodow.realtime.channel.BusHook; import com.goodow.realtime.channel.Message; import com.goodow.realtime.channel.State; import com.goodow.realtime.core.Handler; import com.goodow.realtime.core.Registration;
/* * Copyright 2014 Goodow.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.goodow.realtime.channel.impl; public abstract class BusProxy implements Bus { protected final Bus delegate; protected BusHook hook; public BusProxy(Bus delegate) { this.delegate = delegate; } @Override public void close() { delegate.close(); } public Bus getDelegate() { return delegate; } @Override public State getReadyState() { return delegate.getReadyState(); } @Override public String getSessionId() { return delegate.getSessionId(); } @Override public Bus publish(String topic, Object msg) { return delegate.publish(topic, msg); } @Override public Bus publishLocal(String topic, Object msg) { return delegate.publishLocal(topic, msg); } @SuppressWarnings("rawtypes") @Override
public Registration subscribe(String topic, Handler<? extends Message> handler) {
2
rhritz/kyberia-haiku
app/models/feeds/BookmarkUpdates.java
[ "@Entity(\"Activity\")\npublic class Activity extends MongoEntity {\n\n public static DBCollection dbcol = null;\n private static final String key = \"activity_\";\n \n private ObjectId oid; // o ktorom objekte je tato notifikacia\n private Integer type; // enum? new, delete...? zatial neviem\n private Long date;\n private String name; // nazov prispevku, meno usera atd\n // pripadne popis aktivity?\n private List<ObjectId> vector;\n // vecna otazka: String alebo oids?\n private List<ObjectId> ids; // idcka nodov ktore notifikujeme\n private List<ObjectId> uids; // userov ktorych notifikujeme, skrze friend/follow\n private ObjectId parid; // user submission children - len ak parowner != owner\n private ObjectId owner;\n \n public Activity () {}\n\n public Activity (ObjectId oid,\n Long date,\n List<ObjectId> ids,\n List<ObjectId> uids,\n List<ObjectId> vector,\n ObjectId parid,\n ObjectId owner)\n {\n this.oid = oid;\n this.date = date;\n this.ids = ids;\n this.uids = uids;\n this.vector = vector;\n this.parid = parid;\n this.owner = owner;\n }\n \n public static void newNodeActivity(\n ObjectId id,\n NodeContent node,\n List<ObjectId> parents,\n ObjectId ownerid,\n ObjectId parOwnerId\n )\n {\n try {\n Logger.info(\"@newNodeActivity\");\n List<ObjectId> friends = User.load(ownerid).getFriends();\n User parent = User.load(parOwnerId);\n if (parent != null) {\n parOwnerId = parent.getId();\n }\n // parents==vektor sucasne aj (ak mame vsetkych)\n Activity notif = new Activity(id, System.currentTimeMillis(),\n parents, friends, parents, parOwnerId,node.getOwner());\n notif.save();\n\n // lame - prerobit!\n SortedSet<UserLocation> uso = UserLocation.getAll();\n if (uso == null)\n return;\n HashMap<String,Integer> usersOnline = new HashMap<String,Integer>();\n for (UserLocation u : uso)\n usersOnline.put(u.getUid().toString(), 1);\n // update bookmarks for users online\n for (ObjectId par : parents)\n for (Bookmark b : Bookmark.getByDest(par)) \n if (usersOnline.containsKey(b.getUid().toString())) \n Bookmark.updateVisit(b.getUid(),par.toString());\n } catch (Exception ex) {\n Logger.info(\"newNodeActivity failed:\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n }\n\n /**\n * @return the oid\n */\n public ObjectId getOid() {\n return oid;\n }\n\n @Override\n public Activity enhance() {\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n\n}", "@Entity(\"Bookmark\")\npublic class Bookmark extends MongoEntity {\n\n public static DBCollection dbcol = null;\n private static final String key = \"bookmark_\";\n\n private ObjectId dest;\n private String alt; // alt link to diplay next to dest url\n private String name; // dest name\n private String typ;\n private Long lastVisit;\n // private List notifications; // list of activities since last visit(?)\n private ObjectId uid;\n\n @Transient\n private Integer numNew;\n\n private List<String> tags;\n\n private static final String USERID = \"uid\";\n private static final String NAME = \"name\";\n private static final String DEST = \"dest\";\n\n private static final BasicDBObject sort = new BasicDBObject(NAME, 1);\n\n public Bookmark() {}\n\n public Bookmark(ObjectId dest, User user, String type)\n {\n\n this.dest = checkNotNull(dest);\n uid = checkNotNull(user).getId();\n name = checkNotNull(NodeContent.load(dest, user)).getName();\n lastVisit = System.currentTimeMillis();\n typ = checkNotNull(type);\n }\n\n public static List<Bookmark> getUserBookmarks(String uid)\n {\n List<Bookmark> b = new LinkedList<Bookmark>();\n List<String> bkeys = Cache.get(\"bookmark_\" + uid, LinkedList.class);\n if (bkeys != null) {\n Logger.info(\"user bookmarks cached\");\n for (String bkey : bkeys) {\n Bookmark boo = Cache.get(key(uid,bkey), Bookmark.class);\n // invalidated or expired\n if (boo == null )\n boo = loadAndStore(uid, bkey);\n b.add(boo);\n }\n return b;\n }\n try {\n BasicDBObject query = new BasicDBObject(USERID, toId(uid));\n DBCursor iobj = dbcol.find(query).sort(sort);\n if (iobj != null) {\n Logger.info(\"user bookmarks found\");\n int i = 0;\n bkeys = new LinkedList<String>();\n while(iobj.hasNext())\n {\n Bookmark boo = MongoDB.fromDBObject(Bookmark.class, iobj.next());\n boo.numNew = boo.loadNotifsForBookmark();\n // TODO toto by malo byt nutne len docasne\n b.add(boo);\n Cache.add(key(uid, boo.dest.toString()), boo);\n bkeys.add(boo.dest.toString());\n }\n Cache.add(\"bookmark_\" + uid, bkeys);\n }\n } catch (Exception ex) {\n Logger.info(\"getUserBookmarks\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return b;\n }\n\n // load one bookmark\n private static Bookmark loadAndStore(String uid, String dest) {\n Bookmark b = null;\n Logger.info(\"Bookmark.loadAndStore :: \" + key(uid,dest));\n try {\n BasicDBObject query = new BasicDBObject(USERID, toId(uid)).\n append(DEST, toId(dest));\n DBObject iobj = dbcol.findOne(query);\n if (iobj != null) {\n b = MongoDB.fromDBObject(Bookmark.class,iobj);\n b.numNew = b.loadNotifsForBookmark();\n Cache.add(key(uid,dest), b);\n }\n } catch (Exception ex) {\n Logger.info(\"Bookmark.loadAndStore\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return b;\n }\n\n public static Bookmark getByUserAndDest(ObjectId uid, String dest) {\n Bookmark b = Cache.get(key(uid.toString(), dest), Bookmark.class);\n if (b != null)\n return b;\n else\n return loadAndStore(uid.toString(), dest);\n }\n\n // TODO\n public static Bookmark getByUserAndDest(ObjectId uid, ObjectId dest) {\n Bookmark b = Cache.get(key(uid.toString(), dest.toString()), Bookmark.class);\n if (b != null)\n return b;\n else\n return loadAndStore(uid.toString(), dest.toString());\n }\n\n public int loadNotifsForBookmark()\n {\n int len = 0;\n // Integer clen = Cache.get(ID + username, String.class);\n try {\n BasicDBObject query = new BasicDBObject(typ == null ? \"ids\" : typ, dest).\n append(\"date\", new BasicDBObject(\"$gt\",\n lastVisit == null ? 0 : lastVisit ));\n // Logger.info(\"loadNotifsForBookmark::\" + query.toString());\n len = Activity.dbcol.find(query).count();\n } catch (Exception ex) {\n Logger.info(\"loadNotifsForBookmark\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return len;\n }\n\n // List of Bookmarks by destination id\n public static List<Bookmark> getByDest(ObjectId dest)\n {\n List<Bookmark> b = null;\n try {\n DBCursor iobj = dbcol.find(new BasicDBObject(DEST, dest));\n // Logger.info(\"getByDest::\" + iobj);\n b = MongoDB.transform(iobj, MongoDB.getSelf().toBookmark());\n } catch (Exception ex) {\n Logger.info(\"getByDest::\" + dest);\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return b;\n }\n\n public static void add(ObjectId dest, User user, String type)\n {\n ObjectId uid = user.getId();\n Bookmark b = Cache.get(key(uid.toString(),dest.toString()), Bookmark.class);\n if (b != null)\n return;\n b = new Bookmark(dest, user, type);\n b.save();\n Cache.delete(key + uid);\n }\n\n public static void delete(String dest, String uid) // -> ObjectId\n {\n Cache.delete(key + uid);\n Cache.delete(key(uid,dest));\n try {\n dbcol.remove(new BasicDBObject(USERID, uid).append(DEST, dest));\n } catch (Exception ex) {\n Logger.info(\"Bookmark.delete\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n }\n\n public static void updateVisit(ObjectId uid, String location) {\n String key = key(uid.toString(),location);\n Logger.info(\"Updating visit::\" + key);\n Bookmark b = Cache.get(key, Bookmark.class);\n if (b != null) {\n // Logger.info(\"Updating visit - really\");\n b.lastVisit = System.currentTimeMillis();\n b.numNew = 0;\n Cache.replace(key, b);\n b.update();\n }\n }\n\n static void invalidate(ObjectId uid, String dest) {\n Cache.delete(key(uid.toString(),dest));\n }\n\n /**\n * @return the uid\n */\n public ObjectId getUid() {\n return uid;\n }\n\n private static String key(String uid, String dest) {\n return key + uid + \"_\" + dest;\n }\n\n /**\n * @return the lastVisit\n */\n public Long getLastVisit() {\n return lastVisit;\n }\n\n /**\n * @param lastVisit the lastVisit to set\n */\n public void setLastVisit(Long lastVisit) {\n this.lastVisit = lastVisit;\n }\n\n /**\n * @return the typ\n */\n public String getTyp() {\n return typ;\n }\n\n /**\n * @param typ the typ to set\n */\n public void setTyp(String typ) {\n this.typ = typ;\n }\n\n @Override\n public Bookmark enhance() {\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n}", "@Entity(\"Feed\")\npublic class Feed extends MongoEntity{\n\n public static DBCollection dbcol = null;\n private static final String key = \"feed_\";\n\n protected String name;\n protected ObjectId owner;\n protected List<ObjectId> nodes;\n protected Integer maxNodes;\n protected String subClass;\n protected String dataName;\n\n // + pripadne neskor permisions atd\n @Transient\n private List<NodeContent> content;\n\n public Feed () { name = getClass().getCanonicalName(); }\n \n // pridaj 'clanok' do feedu\n public static void addToFeed(String feedName, ObjectId contentId)\n {\n // test na pocet\n }\n\n public static Feed loadContent(ObjectId feedId)\n {\n Feed toLoad = load(feedId);\n if (toLoad != null) \n toLoad.loadContent();\n return toLoad;\n }\n\n public void loadContent()\n {\n // content = NodeContent.load(nodes);\n }\n\n public static Feed load(ObjectId id)\n {\n Feed n = Cache.get(key + id, Feed.class);\n if (n != null )\n return n;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"_id\",id));\n if (iobj != null) {\n n = MongoDB.fromDBObject(Feed.class, iobj);\n Cache.add(key + id, n);\n }\n } catch (Exception ex) {\n Logger.info(\"load feed\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return n;\n }\n\n String getName() {\n return name;\n }\n \n public void getData( Map<String, String> params,\n Request request,\n Session session,\n User user,\n RenderArgs renderArgs) {\n }\n\n public void init(Page page) {}\n\n static <T extends Feed> T getByName(String name, Page page) {\n T le = null;\n try {\n Class<T> fu = (Class<T>) Class.forName(name);\n le = fu.newInstance();\n le.init(page);\n } catch (Exception ex) {\n Logger.info(\"Feed.getByName::\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return le;\n }\n\n static Feed loadSubclass(ObjectId feedId, Page page) {\n Feed feed = null;\n try {\n feed = load(feedId);\n Class c = Class.forName(\"models.\" + feed.subClass);\n feed = sc(c,feed,page);\n } catch (ClassNotFoundException ex) {\n Logger.info(\"Feed.loadSubclass::\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return feed;\n }\n\n private static <T extends Feed> T sc(Class<T> c, Feed fu, Page page) {\n T le = null;\n try {\n le = c.newInstance();\n le.id = fu.id;\n le.name = fu.name;\n le.maxNodes = fu.maxNodes;\n le.owner = fu.owner;\n le.init(page);\n } catch (Exception ex) {\n Logger.info(\"Feed.sc::\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return le;\n }\n\n @Override\n public Feed enhance() {\n // .loadContent();\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n\n}", "public abstract class MongoEntity implements Serializable {\n @Id protected ObjectId id;\n\n public MongoEntity() {}\n\n public ObjectId getId() {\n return id;\n }\n\n public void setId(ObjectId id) {\n this.id = id;\n }\n\n public String getIdString() {\n return id.toString();\n }\n\n public void setIdString(String id) {\n this.id = new ObjectId(id);\n }\n\n public abstract <T extends MongoEntity> T enhance();\n public abstract DBCollection getCollection();\n public abstract String key();\n\n // TODO error handling\n public static ObjectId toId(String x) {\n ObjectId bubu = null;\n try { bubu = new ObjectId(x);} catch (Exception e ) {};\n return bubu;\n }\n\n public void save() {\n MongoDB.save(this);\n }\n\n public void save(boolean doCache, String cacheTime) {\n MongoDB.save(this);\n if (doCache) \n Cache.replace(key() + getIdString(), this, cacheTime);\n }\n\n public void save(boolean doCache) {\n MongoDB.save(this);\n if (doCache)\n Cache.replace(key() + getIdString(), this);\n }\n\n public void update() {\n MongoDB.update(this);\n }\n\n public void update(boolean doCache, String cacheTime) {\n MongoDB.update(this);\n if (doCache)\n Cache.replace(key() + getIdString(), this, cacheTime);\n }\n\n public void update(boolean doCache) {\n MongoDB.update(this);\n if (doCache)\n Cache.replace(key() + getIdString(), this);\n }\n\n\n /*\n Dirty hacks ftw!\n list Java files (not classes, since they are not going to be there)\n inside a given package directory, and use them as a list of available feeds\n adapted from Jon Peck http://jonpeck.com\n adapted from http://www.javaworld.com/javaworld/javatips/jw-javatip113.html\n */\n public static List<Class> getClasses(String pckgname) {\n List<Class> classes=new LinkedList<Class>();\n try {\n File directory=new File(Thread.currentThread().getContextClassLoader()\n .getResource('/'+pckgname.replace('.', '/')).getFile());\n if(directory.exists()) {\n String[] files=directory.list();\n for( int i=0 ; i < files.length; i++)\n if(files[i].endsWith(\".java\"))\n classes.add(Class.forName(pckgname+'.'+\n files[i].substring(0, files[i].length()-5)));\n } else\n Logger.info(pckgname + \" does not appear to be a valid package\");\n } catch(Exception x) {\n Logger.info(pckgname + \" does not appear to be a valid package\");\n x.printStackTrace();\n Logger.info(x.toString());\n }\n return classes;\n }\n\n}", "@Entity(\"Node\")\npublic class NodeContent extends MongoEntity {\n\n public static DBCollection dbcol = null;\n private static final String key = \"node_\";\n \n private String content = \"\";\n public ObjectId owner ; // mongoid ownera\n private Long created = 0l;\n private String cr_date = \"\"; // transient?\n public String name = \"\";\n public ObjectId par ;\n public ObjectId dfs;\n\n private String template;\n private ObjectId putId;\n\n private Integer accessType = 0;\n private Integer typ = 0;\n\n private Long k = 0l;\n private Long mk = 0l;\n private Long numVisits = 0l; // TODO move this elsewhere\n private Boolean kAllowed = true;\n\n private List<String> tags;\n private List<ObjectId> kgivers; // +k\n private List<ObjectId> mkgivers; // -k\n\n private List<ObjectId> bans;\n private List<ObjectId> access;\n private List<ObjectId> silence;\n private List<ObjectId> masters;\n\n private Map<String,Boolean> fook;\n\n @Transient\n private List<ObjectId> vector;\n\n @Transient\n private ImmutableMap<ObjectId,ACL> acl;\n\n @Transient\n public Integer depth = 1;\n @Transient\n public String parName;\n @Transient\n public String ownerName;\n\n public static final String CONTENT = \"content\";\n public static final String CREATED = \"created\";\n public static final String NAME = \"name\";\n public static final String OWNER = \"owner\";\n\n public static final int PUBLIC = 0;\n public static final int PRIVATE = 1;\n public static final int MODERATED = 2;\n\n // -> plugin?\n private static DateTimeFormatter dateFormatter =\n DateTimeFormat.forPattern(\"dd.MM.YYYY - HH:mm:ss\");\n\n public NodeContent() {}\n\n public NodeContent (ObjectId ownerid,\n Map<String,String> params) {\n content = Validator.validate(params.get(CONTENT));\n created = System.currentTimeMillis();\n cr_date = dateFormatter.print(created);\n typ = Type.NODE.ordinal();\n template = \"Node\";\n String pname = Validator.validateTextonly(params.get(NAME));\n if (pname == null || pname.length() < 1) {\n name = cr_date;\n } else {\n name = pname;\n }\n owner = ownerid;\n\n Logger.info(\"Adding node with content:: \" + content);\n }\n\n public void edit(Map<String,String> params, User user) {\n String accType = params.get(\"access_type\");\n if (accType != null) {\n accessType = Integer.parseInt(accType);\n }\n String addAccess = params.get(\"access\");\n if (addAccess != null ) {\n ObjectId accId = toId(addAccess);\n if (getAccess() == null)\n access = new LinkedList<ObjectId>();\n if (accId != null && ! access.contains(accId))\n getAccess().add(accId);\n }\n String addSilence = params.get(\"silence\");\n if (addSilence != null ) {\n ObjectId silId = toId(addSilence);\n if (getSilence() == null)\n silence = new LinkedList<ObjectId>();\n if (silId != null && ! silence.contains(silId))\n getSilence().add(silId);\n }\n String addMaster = params.get(\"master\");\n if (addMaster != null ) {\n ObjectId masterId = toId(addMaster);\n if (getMasters() == null)\n masters = new LinkedList<ObjectId>();\n if (masterId != null && !masters.contains(masterId) )\n getMasters().add(masterId);\n }\n String ban = params.get(\"ban\");\n if (ban != null ) {\n ObjectId banId = toId(ban);\n if (getBans() == null)\n bans = new LinkedList<ObjectId>();\n if (banId != null && ! bans.contains(banId))\n getBans().add(banId);\n }\n String chOwner = params.get(\"change_owner\");\n ObjectId chOid = toId(chOwner);\n if (chOid != null && User.load(chOid) != null) {\n owner = chOid;\n }\n String chParent = params.get(\"parent\");\n if (chParent != null) {\n NodeContent np = load(chParent);\n if (np != null && ! np.getId().equals(par) )\n moveNode(np.getId(), user);\n }\n String chName = params.get(NAME);\n if (chName != null) {\n name = Validator.validateTextonly(chName);\n }\n String chTemplate = params.get(\"template\");\n if (chTemplate != null ) {\n template = Validator.validateTextonly(chTemplate);\n }\n String chContent = params.get(CONTENT);\n if (chContent != null) {\n content = Validator.validate(chContent);\n }\n update(true);\n }\n\n public String getContent() {\n return content;\n }\n\n /**\n * @return the k\n */\n public Long getK() {\n return k;\n }\n\n public void addTag(String tag) {\n if (tag == null)\n return;\n if (tags == null)\n tags = new LinkedList<String>();\n if (tags.contains(tag))\n return;\n else\n tags.add(tag);\n }\n\n // save to mongodb\n public NodeContent insert() {\n try {\n setId(new ObjectId());\n save();\n enhance();\n Cache.set(\"node_\" + getId(), this);\n return this;\n } catch (Exception ex) {\n Logger.info(\"create failed:\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return null;\n }\n\n private void delete() {\n try {\n Logger.info(\"deleting node\");\n Cache.delete(\"node_\" + getId());\n MongoDB.delete(this);\n } catch (Exception ex) {\n Logger.info(\"delete failed:\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n }\n\n public static NodeContent load(String id, User user) {\n return load(toId(id),user);\n }\n \n private static NodeContent load(String id) {\n ObjectId oid = toId(id);\n if (oid == null)\n return null;\n return load(oid);\n }\n\n public static NodeContent load(ObjectId id, User user) {\n NodeContent node = load(id);\n if ( node != null && node.canRead(user.getId()))\n return node;\n else\n return null;\n }\n\n // TODO parametrize parent loading\n // TODO permissions @Thread\n public static NodeContent load(ObjectId id) {\n // Logger.info(\"About to load node \" + id);\n NodeContent n = Cache.get(\"node_\" + id, NodeContent.class);\n if (n != null )\n return n;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"_id\",id));\n if (iobj != null) {\n n = MongoDB.fromDBObject(NodeContent.class, iobj);\n n.enhance();\n Cache.add(\"node_\" + id, n);\n }\n } catch (Exception ex) {\n Logger.info(\"load node\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return n;\n }\n\n private static NodeContent loadByDfs(ObjectId id) {\n NodeContent n = null;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"dfs\",id));\n if (iobj != null)\n n = MongoDB.fromDBObject(NodeContent.class, iobj);\n } catch (Exception ex) {\n Logger.info(\"load node\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return n;\n }\n\n // apply permissions\n public static List<NodeContent> load(List<ObjectId> nodeIds, User user) {\n // TODO smart caching?\n List<NodeContent> res2 = Lists.newLinkedList();\n /*\n for (ObjectId nodeId : checkNotNull(nodeIds)) {\n NodeContent cachedNode = loadCachedOnly(nodeId);\n }\n */\n List<NodeContent> res = MongoDB.loadIds(nodeIds, MongoDB.CNode, MongoDB.getSelf().toNodeContent());\n ObjectId uid = user.getId();\n for (NodeContent node : res)\n if (node.canRead(uid))\n res2.add(node);\n return res2;\n }\n\n private static List<NodeContent> load(List<ObjectId> nodeIds) {\n return MongoDB.loadIds(nodeIds, MongoDB.CNode, MongoDB.getSelf().toNodeContent());\n }\n\n private static List<NodeContent> loadByPut(ObjectId putId) {\n return MongoDB.transform(dbcol.find(new BasicDBObject(\"putId\", putId)), MongoDB.getSelf().toNodeContent());\n }\n\n private static Map<ObjectId,NodeContent> loadByPar(ObjectId parId) {\n Map<ObjectId,NodeContent> nodes = Maps.newHashMap();\n try {\n DBCursor iobj = dbcol.find(new BasicDBObject(\"par\", parId));\n for (NodeContent node : MongoDB.transform(iobj,\n MongoDB.getSelf().toNodeContent()))\n nodes.put(node.getId(), node);\n } catch (Exception ex) {\n Logger.info(\"load nodes::\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return nodes;\n }\n\n public boolean canRead(ObjectId uid) {\n ACL ur = acl.get(uid);\n if (ACL.BAN == ur)\n return Boolean.FALSE;\n switch (accessType) {\n case MODERATED:\n case PUBLIC:\n return Boolean.TRUE;\n case PRIVATE:\n if (ur == null || ACL.SILENCE == ur )\n return Boolean.FALSE;\n return Boolean.TRUE;\n }\n return Boolean.TRUE;\n }\n\n // moze pridavat reakcie, tagy etc?\n public boolean canWrite(ObjectId uid) {\n ACL ur = acl.get(uid);\n if (ACL.BAN == ur || ACL.SILENCE == ur)\n return Boolean.FALSE;\n switch (accessType) {\n case PUBLIC:\n return Boolean.TRUE;\n case MODERATED:\n case PRIVATE:\n if (ur == null)\n return Boolean.FALSE;\n return Boolean.TRUE;\n }\n return Boolean.TRUE;\n }\n\n // moze editovat properties \n public boolean canEdit(ObjectId uid) {\n return owner.equals(uid) || ACL.MASTER == acl.get(uid);\n }\n\n public boolean canEdit(String uid) {\n return canEdit(toId(uid));\n }\n\n // moze presuvat objekty? tj menit parenta ersp. childy\n // TODO is this right?\n public boolean canMove(ObjectId uid) {\n ACL ur = acl.get(uid);\n return owner.equals(uid) || ACL.MASTER == ur || ACL.HMASTER == ur;\n }\n\n public void fook(ObjectId uid) {\n if (getFook() == null) {\n fook = new HashMap<String,Boolean>();\n } else if (fook.containsKey(uid.toString())) {\n return;\n }\n fook.put(uid.toString(),Boolean.TRUE);\n update();\n }\n\n public void unfook(ObjectId uid) {\n if (fook == null) {\n return;\n } else if (fook.containsKey(uid.toString())) {\n fook.remove(uid.toString());\n }\n update();\n }\n \n /**\n * @return the owner\n */\n public ObjectId getOwner() {\n return owner;\n }\n\n /**\n * @return the created\n */\n public Long getCreated() {\n return created;\n }\n\n /**\n * @return the cr_date\n */\n public String getCr_date() {\n return cr_date;\n }\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @return the parent\n */\n public ObjectId getParent() {\n return par;\n }\n\n /**\n * @return the template\n */\n public String getTemplate() {\n return template;\n }\n\n /**\n * @param k the k to set\n */\n public void setK(Long k) {\n this.k = k;\n }\n\n /**\n * @return the mk\n */\n public Long getMk() {\n return mk;\n }\n\n /**\n * @param mk the mk to set\n */\n public void setMk(Long mk) {\n this.mk = mk;\n }\n\n // TODO - make sure no node is a child of a put node,\n // that would cause serious trouble\n public ObjectId putNode(ObjectId parentId)\n {\n if (parentId == null || load(parentId) == null)\n // put into null makes no sense\n return null;\n NodeContent parent = load(parentId);\n // TODO check & set permissions\n ObjectId pid = null;\n NodeContent putNode = new NodeContent();\n putNode.owner = owner;\n putNode.name = name;\n putNode.created = created;\n putNode.putId = id;\n putNode.par = parent.id;\n putNode = putNode.insert();\n pid = putNode.id;\n if (parent.dfs == null) {\n parent.dfs = pid;\n putNode.dfs = parent.getId();\n } else {\n putNode.dfs = parent.dfs;\n }\n putNode.update(true);\n parent.update(true);\n // Notifications\n List<ObjectId> roots = new LinkedList<ObjectId>();\n NodeContent upnode = parent;\n for (int i = 0; i < 10; i++)\n // 10 - max hier depth for notif update\n {\n roots.add(upnode.getId());\n ObjectId re = upnode.getParent();\n if (re == null) break;\n upnode = NodeContent.load(re);\n }\n Activity.newNodeActivity(pid, putNode, roots, owner, parent.owner);\n \n return pid;\n }\n\n public void unputNode() {\n if (putId != null) {\n // a putNode has no children - just remove from dfs\n if (dfs != null) {\n NodeContent dfsNode = load(dfs);\n // if we have dfs-out, we have a dfs-in too -\n NodeContent dfsSource = loadByDfs(id);\n if (dfsNode != null && dfsSource != null) {\n dfsSource.dfs = dfs;\n dfsSource.update(true);\n }\n }\n delete();\n }\n }\n\n public static String addNode(ObjectId parent,\n Map<String,String> params,\n ObjectId ownerid)\n {\n // TODO check & set permissions\n NodeContent root = null;\n if (parent != null) {\n root = NodeContent.load(parent);\n if (root == null || root.isPut()) { // && check root type too\n return null;\n } else {\n if (!root.canWrite(ownerid)) {\n // no permissions to add Node here\n return null;\n }\n }\n }\n List<ObjectId> roots = new LinkedList<ObjectId>();\n ObjectId parOwner = null;\n NodeContent newnode = new NodeContent(ownerid,params).insert();\n ObjectId mongoId = newnode.getId();\n if (mongoId == null)\n {\n // validation errors...\n return null;\n }\n if (root != null) {\n ObjectId dfs;\n newnode.par = parent;\n // TODO load accType from params if set, override the inherited one\n newnode.accessType = root.accessType;\n Logger.info(\"parent loaded :: \" + root.dfs);\n dfs = root.dfs;\n root.dfs = mongoId;\n root.update();\n if (dfs != null) {\n newnode.dfs = dfs;\n } else {\n newnode.dfs = root.getId();\n }\n Logger.info(\"newnode dfs:: \" + newnode.dfs );\n // TODO change this - load vector etc\n // nizsie su updaty notifikacii\n NodeContent upnode = root;\n for (int i = 0; i < 10; i++)\n // 10 - max hier depth for notif update\n {\n roots.add(upnode.getId());\n ObjectId re = upnode.getParent();\n if (re == null) break;\n upnode = NodeContent.load(re);\n }\n User parentOwner = User.load(root.owner);\n if (parentOwner != null) {\n parOwner = parentOwner.getId();\n }\n } else {\n newnode.accessType = NodeContent.PUBLIC;\n // newnode.typ = NodeContent.CONTENT;\n }\n \n newnode.update(true);\n Activity.newNodeActivity(mongoId, newnode, roots, ownerid, parOwner);\n return mongoId.toString();\n }\n\n public void deleteNode() {\n NodeContent dfsNode = null;\n NodeContent dfsSource = null;\n if (isPut())\n return;\n if (dfs != null) {\n dfsNode = load(dfs);\n // if we have dfs-out, we have a dfs-in too -\n dfsSource = loadByDfs(id);\n }\n for (NodeContent putNode : checkNotNull(loadByPut(id)))\n putNode.unputNode();\n if (dfsNode != null) {\n // dfsSource.dfs = dfs; // !!! unless this is our child\n // we have to unlink all direct children, making them orphans\n Map<ObjectId,NodeContent> children = loadByPar(id);\n if (children == null || children.isEmpty()) {\n dfsSource.dfs = dfs;\n dfsSource.update(true);\n } else {\n for (NodeContent child : children.values()) {\n List<NodeContent> childrenSubtree = child.getTree(children);\n // the last one of this list links either to the next child\n // or somewhere outside the subtree - we don't know exactly\n if (childrenSubtree != null && !childrenSubtree.isEmpty()) {\n NodeContent lastOne = childrenSubtree.\n get(childrenSubtree.size() - 1);\n if (! children.containsKey(lastOne.dfs)) {\n // this one is out of the tree\n dfsSource.dfs = lastOne.dfs;\n dfsSource.update(true);\n }\n // create a subtree\n lastOne.dfs = child.getId();\n lastOne.update(true);\n }\n if (children.containsKey(child.dfs)) {\n child.dfs = null;\n } else {\n // same as above\n dfsSource.dfs = child.dfs;\n dfsSource.update(true);\n child.dfs = null; // sure?\n }\n child.par = null;\n child.update(true);\n }\n }\n }\n\n // + rm bookmarks, perhaps activities too\n delete();\n }\n\n // + add activity to new place, remove from old one\n public void moveNode(ObjectId to, User user) {\n NodeContent toNode = load(to);\n if (toNode == null || !toNode.canMove(user.getId()) || !toNode.isPut())\n return;\n // fix old dfs, if dfs goes out of the subtree;\n // set new dfs, -||-\n NodeContent dfsNode = null;\n NodeContent dfsSource = null;\n NodeContent lastOne = null;\n if (dfs != null) {\n dfsNode = load(dfs);\n dfsSource = loadByDfs(id);\n\n // 1. - remove from the old place\n if (dfsNode != null) {\n List<NodeContent> childrenSubtree = getTree(null);\n if (childrenSubtree != null) {\n lastOne = childrenSubtree.get(childrenSubtree.size() - 1);\n if (lastOne.dfs.equals(id)) {\n // this one is out of the tree\n dfsSource.dfs = lastOne.dfs;\n dfsSource.update(true);\n }\n } else { // no children\n dfsSource.dfs = dfs;\n dfsSource.update(true);\n }\n }\n }\n // 2. - move to the new one - added to the top, not sorted by time!\n if (lastOne == null) \n dfs = toNode.dfs;\n else {\n lastOne.dfs = toNode.dfs;\n lastOne.update(true);\n }\n toNode.dfs = id;\n toNode.update(true);\n par = to;\n update(true);\n }\n\n // returns the whole subtree of a node, optionally stop on stopNodes.\n // with stopNodes being usually either the vector of a node, or its siblings\n private List<NodeContent> getTree(Map<ObjectId,NodeContent> stopNodes)\n {\n List<NodeContent> thread = Lists.newLinkedList();\n HashMap<ObjectId,Integer> roots = Maps.newHashMap();\n int localDepth = 0;\n NodeContent nextnode = this;\n NodeContent lastnode;\n ObjectId parent;\n for (int i = 0; i < 1000000; i++) {\n lastnode = nextnode;\n if (lastnode.dfs == null)\n break;\n if (stopNodes != null && stopNodes.containsKey(lastnode.dfs))\n break;\n nextnode = NodeContent.load(lastnode.dfs);\n if (nextnode == null || nextnode.par == null)\n break;\n parent = nextnode.par;\n if (parent.equals(lastnode.id)) {\n roots.put(parent,localDepth);\n localDepth++;\n } else {\n if (roots.get(parent) == null)\n break;\n localDepth = roots.get(parent) + 1;\n }\n nextnode.depth = localDepth;\n thread.add(nextnode);\n }\n return thread;\n }\n\n protected List<NodeContent> loadVector() {\n List<NodeContent> nodes = null; \n // TODO este predtym by to chcelo vybrat zacachovane a vratit ich tak\n try {\n DBObject query = new BasicDBObject(\"_id\", new BasicDBObject(\"$in\",\n vector.toArray(new ObjectId[vector.size()])));\n DBCursor iobj = dbcol.find(query);\n nodes = MongoDB.transform(iobj, MongoDB.getSelf().toNodeContent());\n } catch (Exception ex) {\n Logger.info(\"load nodes::\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return nodes;\n }\n\n // +K\n public void giveK(User user)\n {\n if (user.getDailyK() < 1)\n return;\n if (kgivers == null)\n kgivers = new LinkedList<ObjectId>();\n else if (kgivers.contains(user.getId()))\n return;\n kgivers.add(user.getId());\n if (getK() == null)\n setK(1l);\n else \n setK(getK() + 1);\n user.setDailyK(user.getDailyK() - 1);\n user.update(true);\n update(true);\n }\n\n // -K\n public void giveMK(User user)\n {\n if (user.getDailyK() < 1)\n return;\n if (kgivers == null)\n kgivers = new LinkedList<ObjectId>();\n else if (kgivers.contains(user.getId()))\n return;\n kgivers.add(user.getId());\n if (getMk() == null)\n setMk(1l);\n else\n setMk(getMk() + 1);\n user.setDailyK(user.getDailyK() - 1);\n user.update(true);\n update(true);\n }\n\n /**\n * @return the bans\n */\n protected List<ObjectId> getBans() {\n return bans;\n }\n\n /**\n * @return the access\n */\n protected List<ObjectId> getAccess() {\n return access;\n }\n\n /**\n * @return the silence\n */\n protected List<ObjectId> getSilence() {\n return silence;\n }\n\n /**\n * @return the masters\n */\n protected List<ObjectId> getMasters() {\n return masters;\n }\n\n /**\n * @return the fook\n */\n protected Map<String, Boolean> getFook() {\n return fook;\n }\n\n public boolean isFook(User user) {\n return fook != null && fook.containsKey(user.getIdString()) ? Boolean.TRUE : Boolean.FALSE;\n }\n\n // Node o 1 vyssie nad nami uz urcite ma vsetko poriesene\n public void loadRights()\n {\n // ImmutableMap.Builder allows duplicate keys but cannot handle them\n // stupid cocks\n Map<ObjectId,ACL> bu = Maps.newHashMap();\n if (accessType == null)\n accessType = 0;\n if (access != null)\n for (ObjectId acc : access)\n bu.put(acc, ACL.ACCESS);\n if (silence != null)\n for (ObjectId sil : silence)\n bu.put(sil, ACL.SILENCE); \n if (masters != null)\n for (ObjectId master : masters)\n bu.put(master, ACL.MASTER);\n if (bans != null)\n for (ObjectId ban : bans)\n bu.put(ban, ACL.BAN);\n if (par != null) {\n NodeContent parent = checkNotNull(load(par));\n if (parent.fook != null) {\n if (fook == null) {\n fook = new HashMap<String,Boolean>();\n }\n fook.putAll(parent.fook);\n }\n if (parent.acl == null) {\n parent.loadRights();\n } \n for (Map.Entry<ObjectId,ACL> e : checkNotNull(parent.acl).entrySet()) {\n switch (e.getValue()) {\n case ACCESS: bu.put(e.getKey(), ACL.ACCESS); break;\n case SILENCE: bu.put(e.getKey(), ACL.SILENCE); break;\n case BAN: bu.put(e.getKey(), ACL.BAN); break;\n case MASTER: bu.put(e.getKey(), ACL.HMASTER); break;\n case OWNER: bu.put(e.getKey(), ACL.HMASTER); break;\n }\n }\n }\n bu.put(owner, ACL.OWNER);\n acl = ImmutableMap.copyOf(bu);\n }\n\n public boolean isPut() {\n return putId == null ? false : true;\n }\n\n // unsafe, should check permissions\n public NodeContent getPutNode() {\n return load(checkNotNull(putId));\n }\n\n @Override\n public NodeContent enhance() {\n ownerName = User.getNameForId(owner);\n if (par != null )\n parName = load(par).name; // checkNotNull?\n else\n parName = \"\";\n loadRights();\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n\n /**\n * @param template the template to set\n */\n public void setTemplate(String template) {\n this.template = template;\n }\n\n public enum Type {\n NODE,\n FORUM,\n CATEGORY,\n USER,\n FRIEND // ?\n };\n\n}", "@Entity(\"Page\")\npublic class Page extends MongoEntity {\n\n public static DBCollection dbcol = null;\n private static final String key = \"page_\";\n\n private String name;\n private String title;\n private String template;\n private ObjectId owner;\n private Map<String,String> blocks;\n private Boolean checkOwner; // check corresponding rights\n private Boolean checkEdit; \n\n @Transient\n private List<Feed> preparedBlocks;\n\n public static final String MAIN = \"main\";\n public static final String NAME = \"name\";\n private static HashMap<String,Page> templateStore;\n\n public Page() {}\n\n public Page(String name, String template) {\n this.name = name;\n this.template = template;\n checkOwner = false;\n checkEdit = false;\n }\n\n public Page(String name, String template, ObjectId owner) {\n this.name = name;\n this.template = template;\n this.owner = owner;\n checkOwner = false;\n checkEdit = false;\n }\n\n /**\n * @return the template\n */\n public String getTemplate() {\n return template;\n }\n\n /**\n * @param template the template to set\n */\n public void setTemplate(String template) {\n this.template = template;\n }\n\n public void removeBlock(String blockName) {\n blocks.remove(blockName);\n save(true);\n enhance();\n }\n\n public static List<Page> loadPages() {\n List<Page> pages = null;\n try {\n DBCursor iobj = dbcol.find();\n pages = MongoDB.transform(iobj, MongoDB.getSelf().toPage());\n } catch (Exception ex) {\n Logger.info(\"Page list load fail\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n return pages;\n }\n\n public static Page loadByName(String name) {\n Page page = templateStore.get(name);\n if (page == null) {\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"name\",name));\n Logger.info(\"Page.loadByName Found:\" + iobj);\n if (iobj != null) {\n page = MongoDB.fromDBObject(Page.class, iobj).enhance();\n templateStore.put(name, page);\n }\n } catch (Exception ex) {\n Logger.info(\"page load fail\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n }\n return page;\n }\n\n public static Page load(String pageId) {\n return load(toId(pageId));\n }\n\n public static Page load(ObjectId oid) {\n Page page = null;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"_id\",oid));\n if (iobj != null) \n page = MongoDB.fromDBObject(Page.class, iobj).enhance();\n } catch (Exception ex) {\n Logger.info(\"page load fail\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n return page;\n }\n\n public void edit(Map<String, String> params) {\n String blockName = params.get(\"blockName\");\n String blockValue = params.get(\"blockValue\");\n boolean doUpdate = false;\n String newTmpl = params.get(\"template\");\n if (newTmpl != null && !newTmpl.equals(template)) {\n template = newTmpl;\n doUpdate = true;\n }\n if (getBlocks() == null)\n blocks = new HashMap<String,String>();\n if (blockName != null && blockValue != null) {\n getBlocks().put(blockName, blockValue);\n doUpdate = true;\n }\n if (doUpdate)\n update(true);\n }\n\n public static Page create(String name, String template, ObjectId owner) {\n Page p = new Page(name, template, owner);\n if (p != null) {\n p.setId(new ObjectId());\n p.save(true);\n }\n return p;\n }\n\n private String getName() {\n return name;\n }\n\n public static void start() {\n templateStore = new HashMap<String,Page>();\n List<Page> allPages = loadPages();\n if (allPages == null)\n return;\n for (Page page : allPages) \n templateStore.put(page.getName(), page);\n Logger.info(\"Pages loaded\");\n }\n\n private void prepareBlocks() {\n preparedBlocks = new LinkedList<Feed>();\n if (getBlocks() == null)\n return;\n for (String blockName : getBlocks().keySet()) {\n Feed f = Feed.getByName(blockName, this);\n if (f != null)\n preparedBlocks.add(f);\n }\n }\n\n public void process(Map<String, String> params,\n Request request,\n Session session,\n User user,\n RenderArgs renderArgs\n ) {\n for (Feed f: preparedBlocks)\n f.getData(params, request, session, user, renderArgs);\n }\n\n /**\n * @return the blocks\n */\n public Map<String, String> getBlocks() {\n return blocks;\n }\n\n @Override\n public Page enhance() {\n prepareBlocks();\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n\n /**\n * @return the checkOwner\n */\n public Boolean getCheckOwner() {\n return checkOwner;\n }\n\n /**\n * @param checkOwner the checkOwner to set\n */\n public void setCheckOwner(Boolean checkOwner) {\n this.checkOwner = checkOwner;\n }\n\n /**\n * @return the checkEdit\n */\n public Boolean getCheckEdit() {\n return checkEdit;\n }\n\n /**\n * @param checkEdit the checkEdit to set\n */\n public void setCheckEdit(Boolean checkEdit) {\n this.checkEdit = checkEdit;\n }\n\n}", "@Entity(\"User\")\npublic class User extends MongoEntity {\n\n public static DBCollection dbcol = null;\n private static final String key = \"user_\";\n\n private String username;\n private String password;\n private ObjectId userinfo; // -> userinfo Node\n private String template; // a ako sa to ma zobrazit\n\n private String view; // userov view\n private Map<String,String> menu; // userovo menu\n \n private List<String> tags; // given tags\n private List<ObjectId> friends; // friends and stuff\n private List<ObjectId> ignores; // users whom this user ignores\n private List<ObjectId> ignoreMail; // users whom this user ignores mail from\n private List<ObjectId> groups; // user groups this user is part of\n\n private Integer dailyK;\n private Integer k;\n\n private Boolean invisible = Boolean.FALSE;\n\n public static final String USERNAME = \"username\";\n public static final String BOOKMARKS = \"bookmarks\";\n public static final String FRIENDS = \"friends\";\n public static final String IGNORES = \"ignores\";\n public static final String FOOKS = \"fooks\";\n public static final String UPDATES = \"udpates\";\n public static final String PASSWORD = \"password\";\n public static final String ID = \"id\";\n\n private static PasswordService pwdService = new PasswordService();\n\n @Transient\n public HashMap<ObjectId,Boolean> prepIgnores;\n @Transient\n public HashMap<ObjectId,Boolean> prepGroups;\n\n public User() {}\n\n public User(String username, String password) {\n this.username = username;\n this.password = pwdService.encrypt(password);\n }\n\n public static User login(String username, String password)\n {\n User u = null;\n boolean pwdOk = false;\n Logger.info(\"user login\");\n try {\n if (username == null || password == null){\n username = \"\";\n password = \"\";\n }\n BasicDBObject query = new BasicDBObject(USERNAME, username).\n append(PASSWORD, pwdService.encrypt(password));\n DBObject iobj = dbcol.findOne(query);\n if (iobj == null) {\n Logger.info(\"login failed\");\n pwdOk = false;\n } else {\n Logger.info(\"login successfull:\" + iobj.get(\"username\").toString());\n pwdOk = true;\n u = MongoDB.fromDBObject(User.class, iobj);\n u.loadUserData(); // ak sa neprihlasuje z RESTu...\n }\n } catch (Exception ex) {\n Logger.info(\"login failed:\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n if (pwdOk) \n {\n return u;\n } \n else \n {\n return null;\n }\n }\n\n public void changePwd(Map<String, String> params )\n {\n String oldPwd = params.get(\"oldPwd\");\n String newPwd1 = params.get(\"newPwd1\");\n String newPwd2 = params.get(\"newPwd2\");\n if (oldPwd!= null && password.equals(pwdService.encrypt(oldPwd))) {\n if (newPwd1 != null && newPwd2 != null && newPwd1.equals(newPwd2)) {\n password = pwdService.encrypt(newPwd1);\n update(true);\n }\n } else {\n // TODO else vynadaj userovi\n }\n }\n\n // TODO cache invalidate + upload/zmena ikonky\n public void edit(String username, String template, String userinfo)\n {\n boolean changed = false;\n if (username != null) {\n this.username = username;\n changed = true;\n }\n if (template != null) {\n this.template = template;\n changed = true;\n }\n if (userinfo != null) {\n this.userinfo = toId(userinfo);\n changed = true;\n }\n if (changed) {\n update(true);\n }\n }\n\n private void loadUserData()\n {\n // mail status,\n // list bookmarks,\n // and possibly more things\n\n prepIgnores = new HashMap<ObjectId,Boolean>();\n if (ignores != null)\n for (ObjectId ignore : ignores)\n prepIgnores.put(ignore, Boolean.TRUE);\n\n prepGroups = new HashMap<ObjectId,Boolean> () ;\n if (groups != null)\n for (ObjectId group : groups)\n prepGroups.put(group, Boolean.TRUE);\n // foreach friend...\n\n }\n\n // false ak uz je username pouzite\n public static boolean usernameAvailable(String username)\n {\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(USERNAME, username));\n if (iobj == null) {\n return true;\n }\n } catch (Exception ex) {\n Logger.info(\"mongo fail @username available\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return false;\n }\n return false;\n }\n\n /**\n * @return the username\n */\n public String getUsername() {\n return username;\n }\n\n public static User load(String id) {\n return load(toId(id));\n }\n\n // load user by id\n public static User load(ObjectId id)\n {\n User u = Cache.get(\"user_\" + id, User.class);\n if (u != null )\n return u;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"_id\",id));\n if (iobj != null) {\n u = MongoDB.fromDBObject(User.class, iobj);\n Cache.set(\"user_\" + id, u);\n Cache.set(ID + u.username, id.toString());\n Cache.set(USERNAME + id, u.username);\n }\n } catch (Exception ex) {\n Logger.info(\"user load fail\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n return u;\n }\n\n public static void refreshDailyK(Integer howMuch) {\n try {\n dbcol.update(new BasicDBObject(), new BasicDBObject(\"$set\",\n new BasicDBObject(\"dailyK\",howMuch)), false, true);\n } catch (Exception ex) {\n Logger.info(\"tag inc fail\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n }\n\n public static List<User> loadUsers(String namePart,\n Integer start,\n Integer count,\n String order)\n {\n List<User> users = null;\n if (namePart != null) {\n // este treba upravit\n BasicDBObject match = new BasicDBObject(USERNAME, namePart);\n }\n try {\n BasicDBObject query = new BasicDBObject(USERNAME, 1);\n DBCursor iobj = dbcol.find().sort(query).\n skip(start == null ? 0 : start).\n limit(count == null ? 0 : count);\n users = MongoDB.transform(iobj, MongoDB.getSelf().toUser());\n } catch (Exception ex) {\n Logger.info(\"mongo fail @loadUsers\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n }\n return users;\n }\n\n // vracia mongo id\n public static String getIdForName(String username)\n {\n // pozor na cudne usernames\n String id = Cache.get(ID + username, String.class); \n if (id != null)\n return id;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(USERNAME, username));\n if (iobj != null)\n {\n id = iobj.get(\"_id\").toString();\n Cache.add(ID + username, id);\n }\n } catch (Exception ex) {\n Logger.info(\"mongo fail @getIdForName\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n return id;\n }\n\n public static String getNameForId(ObjectId id)\n {\n if (id == null || id.toString().length() < 10)\n return \"\";\n String uname = Cache.get(USERNAME + id, String.class);\n if (uname != null)\n return uname;\n try {\n DBObject iobj = dbcol.findOne(new BasicDBObject(\"_id\", id));\n if (iobj != null)\n {\n uname = iobj.get(USERNAME).toString();\n Cache.add(USERNAME + id.toString(), uname);\n }\n } catch (Exception ex) {\n Logger.info(\"mongo fail @getNameForId for id |\" + id + \"|\");\n ex.printStackTrace();\n Logger.info(ex.toString());\n return null;\n }\n return uname;\n }\n\n public void addFriend(ObjectId uid) {\n if (friends == null ) {\n friends = new ArrayList<ObjectId>();\n } else if (friends.contains(uid)) {\n return;\n }\n friends.add(uid);\n update(true);\n loadUserData();\n }\n\n public void removeFriend(ObjectId uid) {\n if (friends != null && friends.contains(uid)) {\n friends.remove(uid);\n update(true);\n loadUserData();\n }\n }\n\n public void addIgnore(ObjectId uid) {\n if (ignores == null ) {\n ignores = new ArrayList<ObjectId>();\n } else if (ignores.contains(uid)) {\n return;\n }\n ignores.add(uid);\n update(true);\n loadUserData();\n }\n\n public void removeIgnore(ObjectId uid) {\n if (ignores != null && ignores.contains(uid)) {\n ignores.remove(uid);\n update(true);\n loadUserData();\n }\n }\n\n public void addIgnoreMail(ObjectId uid) {\n if (ignoreMail == null ) {\n ignoreMail = new ArrayList<ObjectId>();\n } else if (ignoreMail.contains(uid)) {\n return;\n }\n ignoreMail.add(uid);\n update(true);\n }\n\n public void removeIgnoreMail(ObjectId uid) {\n if (ignoreMail != null && ignoreMail.contains(uid)) {\n ignoreMail.add(uid);\n update(true);\n }\n }\n\n\n /**\n * @return the friends\n */\n protected List<ObjectId> getFriends() {\n return friends;\n }\n\n public List<User> listFriends() {\n if (friends == null)\n return new ArrayList<User>();\n else\n return Lists.transform(friends, new ToUser());\n }\n\n public List<User> listIgnores() {\n if (ignores == null)\n return new ArrayList<User>();\n else\n return Lists.transform(ignores, new ToUser());\n }\n\n public boolean ignores(ObjectId uid) {\n return prepIgnores.containsKey(uid);\n }\n\n /**\n * @return the view\n */\n public String getView() {\n return view;\n }\n\n void setDailyK(int i) {\n dailyK = i;\n }\n\n int getDailyK() {\n return dailyK;\n }\n\n public Boolean isInvisible() {\n return invisible;\n }\n\n // transform ObjectId to User\n class ToUser implements Function<ObjectId, User> {\n public User apply(ObjectId arg) {\n return User.load(arg).enhance();\n }\n }\n\n private static final class PasswordService\n {\n MessageDigest md;\n BASE64Encoder enc;\n // TODO eventually salt & multiple hashing?\n \n private PasswordService() {\n try{\n md = MessageDigest.getInstance(\"SHA\");\n } catch(NoSuchAlgorithmException e) {}\n enc = new BASE64Encoder();\n }\n\n private synchronized String encrypt(String plaintext)\n {\n try {\n md.reset();\n md.update(plaintext.getBytes(\"UTF-8\"));\n } catch(UnsupportedEncodingException e) {\n }\n return enc.encode(md.digest());\n }\n }\n\n public static String addUser(Map<String,String> params)\n {\n ObjectId id = null;\n String username = params.get(USERNAME);\n String password = params.get(PASSWORD);\n\n if (! User.usernameAvailable(username)) {\n return null;\n }\n try {\n User u = new User(username, password);\n id = u.getId();\n u.save(true);\n } catch(Exception e) {\n Logger.info(\"addUser failed \" + e.toString() );\n }\n return id == null ? \"\" : id.toString();\n }\n\n @Override\n public User enhance() {\n return this;\n }\n\n @Override\n public DBCollection getCollection() {\n return dbcol;\n }\n\n @Override\n public String key() {\n return key;\n }\n\n}", "public class MongoDB {\n private static MongoDB self;\n private ToMessage message;\n private ToMessageThread messageThread;\n private ToPage page;\n private ToUser user;\n private ToUserGroup userGroup;\n private ToUserLocation userLocation;\n private ToNodeContent nodeContent;\n private ToTag tag;\n private ToBookmark bookmark;\n private ToActivity activity;\n private ToFeed feed;\n private ToViewTemplate viewTemplate;\n\n private static DB db;\n private static Mongo mongo;\n private static Morphia morphia;\n private static String ADDR;\n private static String PORT;\n private static String DBNAME;\n\n // Collection Names\n public static final String CActivity = \"Activity\";\n public static final String CBookmark = \"Bookmark\";\n public static final String CFeed = \"Feed\";\n public static final String CFriend = \"Friend\";\n public static final String CIgnore = \"Ignore\";\n public static final String CMessage = \"Message\";\n public static final String CMessageThread = \"MessageThread\";\n public static final String CNode = \"Node\";\n public static final String CPage = \"Page\";\n public static final String CTag = \"Tag\";\n public static final String CTagNodeUser = \"TagNodeUser\";\n public static final String CUser = \"User\";\n public static final String CUserGroup = \"UserGroup\";\n public static final String CUserLocation = \"UserLocation\";\n public static final String CVote = \"Vote\";\n public static final String CViewTemplate = \"ViewTemplate\";\n\n static {\n if (Play.configuration.containsKey(\"mongodb.addr\"))\n ADDR = Play.configuration.getProperty(\"mongodb.addr\");\n else\n ADDR = \"127.0.0.1\";\n if (Play.configuration.containsKey(\"mongodb.port\"))\n PORT = Play.configuration.getProperty(\"mongodb.port\");\n else\n PORT = \"27017\";\n if (Play.configuration.containsKey(\"mongodb.dbname\"))\n DBNAME = Play.configuration.getProperty(\"mongodb.dbname\");\n else\n DBNAME = \"local\";\n }\n\n private MongoDB() {\n message = new ToMessage();\n messageThread = new ToMessageThread();\n user = new ToUser();\n userGroup = new ToUserGroup();\n userLocation = new ToUserLocation();\n nodeContent = new ToNodeContent();\n tag = new ToTag();\n bookmark = new ToBookmark();\n activity = new ToActivity();\n page = new ToPage();\n feed = new ToFeed();\n viewTemplate = new ToViewTemplate();\n }\n\n public static void start() {\n self = new MongoDB();\n Logger.info(\"Mongo connecting\");\n try {\n mongo = new Mongo(ADDR, Integer.parseInt(PORT));\n db = mongo.getDB(DBNAME);\n \n morphia = new Morphia();\n\n // morphia.mapPackage(\"models\");\n morphia.map(Message.class); \n morphia.map(User.class); \n morphia.map(MessageThread.class);\n morphia.map(Bookmark.class);\n morphia.map(Activity.class);\n morphia.map(NodeContent.class);\n morphia.map(UserLocation.class);\n morphia.map(UserGroup.class);\n morphia.map(Tag.class);\n morphia.map(Vote.class);\n morphia.map(Page.class);\n morphia.map(ViewTemplate.class);\n morphia.map(Feed.class);\n\n User.dbcol = db.getCollection(CUser);\n NodeContent.dbcol = db.getCollection(CNode);\n MessageThread.dbcol = db.getCollection(CMessageThread);\n Bookmark.dbcol = db.getCollection(CBookmark);\n Activity.dbcol = db.getCollection(CActivity);\n \n UserLocation.dbcol = db.getCollection(CUserLocation);\n // Friend.dbcol = db.getCollection(CFriend);\n // Ignore.dbcol = db.getCollection(CIgnore);\n UserGroup.dbcol = db.getCollection(CUserGroup);\n Tag.dbcol = db.getCollection(CTag);\n Vote.dbcol = db.getCollection(CVote);\n Page.dbcol = db.getCollection(CPage);\n ViewTemplate.dbcol = db.getCollection(CViewTemplate);\n Message.dbcol = db.getCollection(CMessage);\n Feed.dbcol = db.getCollection(CFeed);\n\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"created\",\"-1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"owner\",\"1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"par\",\"1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"tags\",\"1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"k\",\"1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"mk\",\"1\"));\n db.getCollection(CNode).ensureIndex(new BasicDBObject(\"name\",\"1\"));\n\n db.getCollection(CUser).ensureIndex(new BasicDBObject(\"username\",\"1\"),\"username_1\",true);\n\n db.getCollection(CMessageThread).ensureIndex(new BasicDBObject(\"users\",\"1\"));\n \n db.getCollection(CTag).ensureIndex(new BasicDBObject(\"tag\",\"1\"),\"tag_1\",true);\n\n db.getCollection(CMessage).ensureIndex(new BasicDBObject(\"threadid\",\"1\"));\n db.getCollection(CMessage).ensureIndex(new BasicDBObject(\"created\",\"-1\")); // alebo composite asi skor?\n db.getCollection(CMessage).ensureIndex(new BasicDBObject(\"from\",\"1\"));\n db.getCollection(CMessage).ensureIndex(new BasicDBObject(\"to\",\"1\")); // + \"key\" : { \"from\" : 1, \"sent\" : -1 }, \"name\" : \"from_1_sent_-1\" }\n\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"owner\",\"1\"));\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"parid\",\"1\"));\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"oid\",\"1\"));\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"date\",\"-1\"));\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"ids\",\"1\"));\n db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"uids\",\"1\"));\n\n db.getCollection(CFeed).ensureIndex(new BasicDBObject(\"name\",\"1\"),\"name_1\",true);\n db.getCollection(CPage).ensureIndex(new BasicDBObject(\"name\",\"1\"),\"name_1\",true);\n db.getCollection(CViewTemplate).ensureIndex(new BasicDBObject(\"name\",\"1\"),\"name_1\",true);\n\n // db.getCollection(CActivity).ensureIndex(new BasicDBObject(\"username\",\"1\"),\"username_1\",true);\n // db.getCollection(CBookmark).ensureIndex({destination: 1, uid:1}, {unique: true});\n\n // find().sort({$natural:-1}) <-- sortovanie an natural colls, mozno aj idne funguje takto?\n // http://www.mongodb.org/display/DOCS/Capped+Collections\n \n } catch (Exception e) {\n Logger.info(\"Brekeke @ mongo:: \" + e.toString());\n }\n }\n\n public static DB getDB() {\n return db;\n }\n\n protected static Mongo getMongo() {\n return mongo;\n }\n\n public static void shutdown() {\n Logger.info(\"Mongo stopping\");\n }\n\n public static Morphia getMorphia() {\n return morphia;\n }\n\n public static void save(MongoEntity m) {\n m.getCollection().insert(morphia.toDBObject(m));\n }\n\n public static void update(MongoEntity m) {\n m.getCollection().save(morphia.toDBObject(m));\n }\n\n public static void delete(MongoEntity m) {\n m.getCollection().remove(morphia.toDBObject(m));\n }\n\n public static <T> T load(String id, String col, Class<T> entityClass) {\n return load(toId(id), col, entityClass);\n }\n\n public static <T> T load(ObjectId id, String col, Class<T> entityClass)\n {\n DBObject DBObj = db.getCollection(col).findOne(new BasicDBObject(\"_id\", id));\n return fromDBObject(entityClass, DBObj);\n }\n\n // TODO variable ordering via BasicDBObject sort as a parameter?\n public static <T> List<T> loadIds(List<ObjectId> fromList, String col,\n Function<DBObject, ? extends T> function)\n {\n DBObject query = new BasicDBObject(\"_id\", new BasicDBObject(\"$in\",\n fromList.toArray(new ObjectId[fromList.size()])));\n DBCursor iobj = db.getCollection(col).find(query);\n List<T> l = Lists.newArrayListWithCapacity(iobj == null ? 0 : iobj.size());\n if (iobj != null)\n for (DBObject f : iobj) \n l.add(function.apply(f));\n return l;\n }\n\n public static <T> List<T> transform( DBCursor fromList,\n Function<DBObject, ? extends T> function) {\n List<T> l = new LinkedList<T>();\n if (fromList != null)\n for (DBObject f : fromList)\n l.add(function.apply(f));\n return l;\n }\n\n public static <T extends MongoEntity> List<T> transformIds(\n List<ObjectId> fromList,\n String col,\n Class<T> entityClass ) {\n List<T> l = Lists.newArrayListWithCapacity(fromList.size());\n if (fromList != null)\n for (ObjectId f : fromList) {\n T t = load(f, col, entityClass);\n t.enhance();\n l.add(t);\n }\n return l;\n }\n\n public static DBCollection getCollection(String name)\n {\n return db.getCollection(name);\n }\n\n public static MongoDB getSelf()\n {\n return self;\n }\n\n public Function<DBObject, Message> toMessage()\n {\n return message;\n }\n\n public Function<DBObject, MessageThread> toMessageThread()\n {\n return messageThread;\n }\n\n public Function<DBObject, User> toUser()\n {\n return user;\n }\n\n public Function<DBObject, UserGroup> toUserGroup()\n {\n return userGroup;\n }\n\n public Function<DBObject, UserLocation> toUserLocation()\n {\n return userLocation;\n }\n\n public Function<DBObject, NodeContent> toNodeContent()\n {\n return nodeContent;\n }\n\n public Function<DBObject, Tag> toTag()\n {\n return tag;\n }\n\n public Function<DBObject, Bookmark> toBookmark()\n {\n return bookmark;\n }\n\n public Function<DBObject, Activity> toActivity()\n {\n return activity;\n }\n\n public Function<DBObject, Feed> toFeed()\n {\n return feed;\n }\n\n public Function<DBObject, Page> toPage()\n {\n return page;\n }\n\n public Function<DBObject, ViewTemplate> toViewTemplate()\n {\n return viewTemplate;\n }\n\n public static <T> T fromDBObject(Class<T> entityClass, DBObject dbObject) {\n return morphia.fromDBObject(entityClass, dbObject,\n morphia.getMapper().createEntityCache());\n }\n\n public class ToMessage implements Function<DBObject, Message> {\n public Message apply(DBObject arg) {\n return fromDBObject(Message.class, arg).enhance();\n }\n }\n\n public class ToMessageThread implements Function<DBObject, MessageThread> {\n public MessageThread apply(DBObject arg) {\n return fromDBObject(MessageThread.class, arg).enhance();\n }\n }\n\n public class ToUser implements Function<DBObject, User> {\n public User apply(DBObject arg) {\n return fromDBObject(User.class, arg).enhance();\n }\n }\n\n public class ToUserGroup implements Function<DBObject, UserGroup> {\n public UserGroup apply(DBObject arg) {\n return fromDBObject(UserGroup.class, arg).enhance();\n }\n }\n\n public class ToUserLocation implements Function<DBObject, UserLocation> {\n public UserLocation apply(DBObject arg) {\n return fromDBObject(UserLocation.class, arg).enhance();\n }\n }\n\n // TODO: caching? to by asi bolo potrebne riesit pred tymto/?\n public class ToNodeContent implements Function<DBObject, NodeContent> {\n public NodeContent apply(DBObject arg) {\n return fromDBObject(NodeContent.class, arg).enhance();\n }\n }\n\n public class ToTag implements Function<DBObject, Tag> {\n public Tag apply(DBObject arg) {\n return fromDBObject(Tag.class, arg).enhance();\n }\n }\n\n public class ToBookmark implements Function<DBObject, Bookmark> {\n public Bookmark apply(DBObject arg) {\n return fromDBObject(Bookmark.class, arg).enhance();\n }\n }\n\n public class ToActivity implements Function<DBObject, Activity> {\n public Activity apply(DBObject arg) {\n return fromDBObject(Activity.class, arg).enhance();\n }\n }\n\n public class ToFeed implements Function<DBObject, Feed> {\n public Feed apply(DBObject arg) {\n return fromDBObject(Feed.class, arg).enhance();\n }\n }\n\n public class ToPage implements Function<DBObject, Page> {\n public Page apply(DBObject arg) {\n return fromDBObject(Page.class, arg).enhance();\n }\n }\n\n public class ToViewTemplate implements Function<DBObject, ViewTemplate> {\n public ViewTemplate apply(DBObject arg) {\n return fromDBObject(ViewTemplate.class, arg).enhance();\n }\n }\n}" ]
import models.MongoEntity; import models.NodeContent; import models.Page; import models.User; import plugins.MongoDB; import com.google.common.collect.Lists; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; import org.bson.types.ObjectId; import java.util.List; import java.util.Map; import models.Activity; import models.Bookmark; import play.Logger; import play.mvc.Http.Request; import play.mvc.Scope.RenderArgs; import play.mvc.Scope.Session; import models.Feed;
/* Kyberia Haiku - advanced community web application Copyright (C) 2010 Robert Hritz This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package models.feeds; // idealne by ma to hodilo na prvych 30 neprecitanych a aj zodpvoedajuco // updatlo lastVisit public class BookmarkUpdates extends Feed{ private static final BasicDBObject sort = new BasicDBObject().append("name", 1); @Override public void getData( Map<String, String> params, Request request, Session session, User user, RenderArgs renderArgs) { ObjectId nodeId = MongoEntity.toId(params.get("id")); ObjectId uid = user.getId(); // 1. get bookmark List<NodeContent> newNodes = null; Bookmark b = Bookmark.getByUserAndDest(uid, nodeId); Long lastVisit = b.getLastVisit(); Bookmark.updateVisit(uid, nodeId.toString()); // 2. load notifications try { BasicDBObject query = new BasicDBObject( b.getTyp() == null ? "ids" : b.getTyp(), nodeId). append("date", new BasicDBObject("$gt",lastVisit)); // Logger.info("getUpdatesForBookmark::" + query.toString()); // BasicDBObject sort = new BasicDBObject().append("date", -1); // vlastne chceme natural sort a iba idcka nodes ktore mame zobrazit DBCursor iobj = Activity.dbcol.find(query).sort(sort); List<Activity> lll = MongoDB.transform(iobj, MongoDB.getSelf().toActivity()); if (! lll.isEmpty()) { List<ObjectId> nodeIds = Lists.newLinkedList(); for (Activity ac : lll) nodeIds.add(ac.getOid()); newNodes = NodeContent.load(nodeIds, user); } } catch (Exception ex) { Logger.info("getUpdatesForBookmark"); ex.printStackTrace(); Logger.info(ex.toString()); } renderArgs.put(dataName, newNodes); } @Override
public void init(Page page) {
5
lixiaocong/lxcCMS
src/main/java/com/lixiaocong/cms/config/WebMvcConfig.java
[ "public class BlogInterceptor extends HandlerInterceptorAdapter {\n\n private final IConfigService configService;\n\n public BlogInterceptor(IConfigService configService) {\n this.configService = configService;\n }\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (this.configService.isBlogEnabled())\n return true;\n throw new ModuleDisabledException(\"blog module is disabled\");\n }\n}", "public class DownloaderInterceptor extends HandlerInterceptorAdapter {\n private final IConfigService configService;\n\n public DownloaderInterceptor(IConfigService configService) {\n this.configService = configService;\n }\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (configService.isDownloaderEnabled())\n return true;\n throw new ModuleDisabledException(\"Downloader is disabled\");\n }\n}", "public class QQInterceptor extends HandlerInterceptorAdapter {\n\n private final IConfigService configService;\n private final ConnectController connectController;\n private final ProviderSignInController signInController;\n private String applicationUrl;\n\n\n public QQInterceptor(IConfigService configService, ConnectController connectController, ProviderSignInController signInController) {\n this.configService = configService;\n this.connectController = connectController;\n this.signInController = signInController;\n this.applicationUrl = configService.getApplicationUrl();\n }\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (this.configService.isQQEnabled()) {\n String newApplicationUrl = this.configService.getApplicationUrl();\n if (!newApplicationUrl.equals(this.applicationUrl)) {\n this.applicationUrl = newApplicationUrl;\n connectController.setApplicationUrl(newApplicationUrl);\n connectController.afterPropertiesSet();\n signInController.setApplicationUrl(newApplicationUrl);\n signInController.afterPropertiesSet();\n }\n return true;\n }\n throw new ModuleDisabledException(\"QQ module is disabled\");\n }\n}", "public class WeixinInterceptor extends HandlerInterceptorAdapter {\n\n private final IConfigService configService;\n\n public WeixinInterceptor(IConfigService configService) {\n this.configService = configService;\n }\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (this.configService.isWeixinEnabled())\n return true;\n throw new ModuleDisabledException(\"Weixin module is disabled\");\n }\n}", "public interface IConfigService {\n String getApplicationUrl();\n\n void setApplicationUrl(String applicationUrl);\n\n boolean isBlogEnabled();\n\n void setBlogEnabled(boolean isEnabled);\n\n boolean isQQEnabled();\n\n void setQQEnabled(boolean isEnabled);\n\n String getQQId();\n\n void setQQId(String qqId);\n\n String getQQSecret();\n\n void setQQSecret(String qqSecret);\n\n boolean isWeixinEnabled();\n\n void setWeixinEnabled(boolean isEnabled);\n\n String getWeixinId();\n\n void setWeixinId(String weixinId);\n\n String getWeixinSecret();\n\n void setWeixinSecret(String weixinSecret);\n\n String getWeixinToken();\n\n void setWeixinToken(String weixinToken);\n\n String getWeixinKey();\n\n void setWeixinKey(String weixinKey);\n\n boolean isDownloaderEnabled();\n\n void setDownloaderEnabled(boolean isEnabled);\n\n String getDownloaderAria2cUrl();\n\n void setDownloaderAria2cUrl(String aria2cUrl);\n\n String getDownloaderAria2cPassword();\n\n void setDownloaderAria2cPassword(String aria2cPassword);\n\n String getDownloaderTransmissionUrl();\n\n void setDownloaderTransmissionUrl(String transmissionUrl);\n\n String getDownloaderTransmissionUsername();\n\n void setDownloaderTransmissionUsername(String transmissionUsername);\n\n String getDownloaderTransmissionPassword();\n\n void setDownloaderTransmissionPassword(String transmissionPassword);\n\n String getStorageDir();\n\n void setStorageDir(String storageDir);\n\n void setValue(String key, String value);\n}" ]
import com.lixiaocong.cms.interceptor.BlogInterceptor; import com.lixiaocong.cms.interceptor.DownloaderInterceptor; import com.lixiaocong.cms.interceptor.QQInterceptor; import com.lixiaocong.cms.interceptor.WeixinInterceptor; import com.lixiaocong.cms.service.IConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.social.connect.web.ConnectController; import org.springframework.social.connect.web.ProviderSignInController; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/* BSD 3-Clause License Copyright (c) 2016, lixiaocong(lxccs@iCloud.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * 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 com.lixiaocong.cms.config; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { private final IConfigService configService; private final ConnectController connectController; private final ProviderSignInController signInController; @Autowired public WebMvcConfig(IConfigService configService, ConnectController connectController, ProviderSignInController signInController) { this.configService = configService; this.connectController = connectController; this.signInController = signInController; } @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BlogInterceptor(this.configService)).addPathPatterns("/blog/**");
0
GoogleCloudPlatform/weasis-chcapi-extension
src/main/java/org/weasis/dicom/google/api/GoogleAPIClient.java
[ "public class Dataset {\n\n private Location parent;\n\n private final String name;\n\n public Dataset(Location parent, String name) {\n this.parent = parent;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public Location getParent() {\n return parent;\n }\n\n public ProjectDescriptor getProject() {\n return parent.getParent();\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 Dataset dataset = (Dataset) o;\n return Objects.equals(parent, dataset.parent) &&\n Objects.equals(name, dataset.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(parent, name);\n }\n}", "public class DicomStore {\n\n private final Dataset parent;\n\n private final String name;\n\n public DicomStore(Dataset parent, String name) {\n this.parent = parent;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public Dataset getParent() {\n return parent;\n }\n\n public ProjectDescriptor getProject() {\n return parent.getProject();\n }\n\n public Location getLocation() {\n return parent.getParent();\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 DicomStore that = (DicomStore) o;\n return Objects.equals(parent, that.parent) &&\n Objects.equals(name, that.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(parent, name);\n }\n}", "public class Location {\n\n private final ProjectDescriptor parent;\n\n private final String name;\n private final String id;\n\n public Location(ProjectDescriptor parent, String name, String id) {\n this.parent = parent;\n this.name = name;\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public String getId() {\n return id;\n }\n\n public ProjectDescriptor getParent() {\n return parent;\n }\n\n @Override\n public String toString() {\n return id;\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 Location location = (Location) o;\n return Objects.equals(parent, location.parent) &&\n Objects.equals(name, location.name) &&\n Objects.equals(id, location.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(parent, name, id);\n }\n}", "public class ProjectDescriptor {\n\n private final String name;\n private final String id;\n\n public ProjectDescriptor(String name, String id) {\n this.name = name;\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public String getId() {\n return id;\n }\n\n @Override\n public String toString() {\n return 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 ProjectDescriptor that = (ProjectDescriptor) o;\n return Objects.equals(name, that.name) &&\n Objects.equals(id, that.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, id);\n }\n}", "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class StudyModel {\n\n @JsonProperty(\"0020000D\")\n private RecordPlain studyInstanceUID;\n\n @JsonProperty(\"00100010\")\n private RecordObjects patientName;\n\n @JsonProperty(\"00100020\")\n private RecordPlain patientId;\n\n @JsonProperty(\"00080050\")\n private RecordPlain accessionNumber;\n\n @JsonProperty(\"00080020\")\n private RecordPlain studyDate;\n\n @JsonProperty(\"00080030\")\n private RecordPlain studyTime;\n\n @JsonProperty(\"00081030\")\n private RecordPlain studyDescription;\n\n @JsonProperty(\"00321032\")\n private RecordObjects reqPhd;\n\n @JsonProperty(\"00080090\")\n private RecordObjects refPhd;\n\n @JsonProperty(\"00200050\")\n private RecordObjects location;\n\n @JsonProperty(\"00100030\")\n private RecordPlain birthDate;\n\n public RecordPlain getStudyInstanceUID() {\n return studyInstanceUID;\n }\n\n public void setStudyInstanceUID(RecordPlain studyInstanceUID) {\n this.studyInstanceUID = studyInstanceUID;\n }\n\n public RecordObjects getPatientName() {\n return patientName;\n }\n\n public void setPatientName(RecordObjects patientName) {\n this.patientName = patientName;\n }\n\n public RecordPlain getPatientId() {\n return patientId;\n }\n\n public void setPatientId(RecordPlain patientId) {\n this.patientId = patientId;\n }\n\n public RecordPlain getAccessionNumber() {\n return accessionNumber;\n }\n\n public void setAccessionNumber(RecordPlain accessionNumber) {\n this.accessionNumber = accessionNumber;\n }\n\n public RecordPlain getStudyDate() {\n return studyDate;\n }\n\n public void setStudyDate(RecordPlain studyDate) {\n this.studyDate = studyDate;\n }\n\n public RecordPlain getStudyTime() {\n return studyTime;\n }\n\n public void setStudyTime(RecordPlain studyTime) {\n this.studyTime = studyTime;\n }\n\n public RecordPlain getStudyDescription() {\n return studyDescription;\n }\n\n public void setStudyDescription(RecordPlain studyDescription) {\n this.studyDescription = studyDescription;\n }\n\n public RecordObjects getReqPhd() {\n return reqPhd;\n }\n\n public void setReqPhd(RecordObjects reqPhd) {\n this.reqPhd = reqPhd;\n }\n\n public RecordObjects getRefPhd() {\n return refPhd;\n }\n\n public void setRefPhd(RecordObjects refPhd) {\n this.refPhd = refPhd;\n }\n\n public RecordObjects getLocation() {\n return location;\n }\n\n public void setLocation(RecordObjects location) {\n this.location = location;\n }\n\n public RecordPlain getBirthDate() {\n return birthDate;\n }\n\n public void setBirthDate(RecordPlain birthDate) {\n this.birthDate = birthDate;\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static class RecordPlain {\n private String vr;\n\n @JsonProperty(\"Value\")\n private List<String> value;\n\n public String getVr() {\n return vr;\n }\n\n public void setVr(String vr) {\n this.vr = vr;\n }\n\n public List<String> getValue() {\n return value;\n }\n\n public void setValue(List<String> value) {\n this.value = value;\n }\n\n public Optional<String> getFirstValue() {\n if (value == null || value.size() == 0) {\n return Optional.empty();\n } else {\n return Optional.ofNullable(value.get(0));\n }\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static class RecordObjects {\n private String vr;\n\n @JsonProperty(\"Value\")\n private List<Value> value;\n\n public String getVr() {\n return vr;\n }\n\n public void setVr(String vr) {\n this.vr = vr;\n }\n\n public List<Value> getValue() {\n return value;\n }\n\n public void setValue(List<Value> value) {\n this.value = value;\n }\n\n public Optional<Value> getFirstValue() {\n if (value == null || value.size() == 0) {\n return Optional.empty();\n } else {\n return Optional.ofNullable(value.get(0));\n }\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static class Value {\n\n @JsonProperty(\"Alphabetic\")\n private String alphabetic;\n\n @JsonProperty(\"Ideographic\")\n private String ideographic;\n\n @JsonProperty(\"Phonetic\")\n private String phonetic;\n\n public String getAlphabetic() {\n return alphabetic;\n }\n\n public void setAlphabetic(String alphabetic) {\n this.alphabetic = alphabetic;\n }\n\n public String getIdeographic() {\n return ideographic;\n }\n\n public void setIdeographic(String ideographic) {\n this.ideographic = ideographic;\n }\n\n public String getPhonetic() {\n return phonetic;\n }\n\n public void setPhonetic(String phonetic) {\n this.phonetic = phonetic;\n }\n }\n}", "public class StudyQuery {\n\n private LocalDate startDate;\n private LocalDate endDate;\n private String patientName;\n private String patientId;\n\n private String accessionNumber;\n private String physicianName;\n private int page;\n private int pageSize;\n private boolean fuzzyMatching;\n\n public String getPatientName() {\n return patientName;\n }\n\n public void setPatientName(String patientName) {\n this.patientName = patientName;\n }\n\n public String getPatientId() {\n return patientId;\n }\n\n public void setPatientId(String patientId) {\n this.patientId = patientId;\n }\n\n public LocalDate getStartDate() {\n return startDate;\n }\n\n public void setStartDate(LocalDate startDate) {\n this.startDate = startDate;\n }\n\n public LocalDate getEndDate() {\n return endDate;\n }\n\n public void setEndDate(LocalDate endDate) {\n this.endDate = endDate;\n }\n\n public String getAccessionNumber() {\n return accessionNumber;\n }\n\n public void setAccessionNumber(String accessionNumber) {\n this.accessionNumber = accessionNumber;\n }\n\n public String getPhysicianName() {\n return physicianName;\n }\n\n public void setPhysicianName(String physicianName) {\n this.physicianName = physicianName;\n }\n\n public void setPage(int offset) {\n this.page = offset;\n }\n\n public int getPage() {\n return this.page;\n }\n\n public int getPageSize() {\n return this.pageSize;\n }\n\n /** Set how many objects will be requested for each page\n * Please note it may be hard for UI to display too many objects\n */\n public void setPageSize(int pageSize) {\n this.pageSize = pageSize;\n }\n\n public void setFuzzyMatching(boolean fuzzyMatching) {\n this.fuzzyMatching = fuzzyMatching;\n }\n\n public boolean getFuzzyMatching() {\n return fuzzyMatching;\n }\n}", "public class OAuth2Browser implements AuthorizationCodeInstalledApp.Browser {\n \n private static final Logger LOGGER =\n Logger.getLogger(OAuth2Browser.class.getName());\n\n /**\n * Single instance of this browser.\n */\n public static final AuthorizationCodeInstalledApp.Browser INSTANCE = new OAuth2Browser();\n \n /**\n * Do not allow more than one instance.\n */\n private OAuth2Browser() {\n super();\n }\n \n /**\n * Opens a browser at the given URL using {@link Desktop} if available, or alternatively copies\n * authorization URL to clipboard and shows notification dialog.\n * \n * @param url URL to browse.\n * @throws IOException if an IO error occurred.\n * @see AuthorizationCodeInstalledApp#browse(String)\n */\n @Override\n public void browse(String url) throws IOException {\n Preconditions.checkNotNull(url);\n // Ask user to open in their browser using copy-paste\n System.out.println(\"Please open the following address in your browser:\");\n System.out.println(\" \" + url);\n // Attempt to open it in the browser\n try {\n if (Desktop.isDesktopSupported()) {\n Desktop desktop = Desktop.getDesktop();\n if (desktop.isSupported(Action.BROWSE)) {\n System.out.println(\"Attempting to open that address in the default browser now...\");\n desktop.browse(URI.create(url));\n } else {\n showNotification(url);\n }\n } else {\n showNotification(url);\n }\n } catch (IOException e) {\n LOGGER.log(Level.WARNING, \"Unable to open browser\", e);\n showNotification(url);\n } catch (InternalError e) {\n // A bug in a JRE can cause Desktop.isDesktopSupported() to throw an\n // InternalError rather than returning false. The error reads,\n // \"Can't connect to X11 window server using ':0.0' as the value of the\n // DISPLAY variable.\" The exact error message may vary slightly.\n LOGGER.log(Level.WARNING, \"Unable to open browser\", e);\n showNotification(url);\n }\n }\n\n /**\n * Copies authorization URL to clipboard and shows notification dialog.\n * \n * @param url URL to browse.\n */\n private static void showNotification(String url) {\n // Copy authorization URL to clipboard\n final StringSelection selection = new StringSelection(url);\n Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);\n // Show notification dialog\n SwingUtilities.invokeLater(() -> {\n JOptionPane.showMessageDialog(null,\n Messages.getString(\"GoogleAPIClient.open_browser_message\"));\n });\n }\n \n}", "public final class StringUtils {\n\n private StringUtils() {\n }\n\n public static boolean isNotBlank(String str) {\n return str != null\n && !str.trim().isEmpty();\n }\n\n public static String urlEncode(String str) {\n try {\n return URLEncoder.encode(str, \"UTF-8\");\n } catch (UnsupportedEncodingException ex) {\n throw new IllegalStateException(\"Error on encoding url \" + str, ex);\n }\n }\n\n public static String join(Collection<String> collection, String joinString) {\n StringBuilder builder = new StringBuilder();\n for (String str : collection) {\n if (builder.length() > 0) {\n builder.append(joinString);\n }\n builder.append(str);\n }\n\n return builder.toString();\n }\n}" ]
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonObject; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.weasis.dicom.google.api.model.Dataset; import org.weasis.dicom.google.api.model.DicomStore; import org.weasis.dicom.google.api.model.Location; import org.weasis.dicom.google.api.model.ProjectDescriptor; import org.weasis.dicom.google.api.model.StudyModel; import org.weasis.dicom.google.api.model.StudyQuery; import org.weasis.dicom.google.api.ui.OAuth2Browser; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.cloudresourcemanager.CloudResourceManager; import com.google.api.services.cloudresourcemanager.model.ListProjectsResponse; import com.google.api.services.cloudresourcemanager.model.Project; import com.google.api.services.oauth2.Oauth2; import com.google.api.services.oauth2.model.Tokeninfo; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.io.*; import java.security.GeneralSecurityException; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.weasis.dicom.google.api.util.StringUtils.*;
private void deleteDir(File file) { if (!file.exists()) { return; } if (file.isDirectory()) { for (File child : file.listFiles()) { deleteDir(child); } } file.delete(); } private static void tokenInfo(String accessToken) throws IOException { Tokeninfo tokeninfo = oauth2.tokeninfo().setAccessToken(accessToken).execute(); if (!tokeninfo.getAudience().equals(clientSecrets.getDetails().getClientId())) { System.err.println("ERROR: audience does not match our client ID!"); } } public List<org.weasis.dicom.google.api.model.ProjectDescriptor> fetchProjects() throws Exception { refresh(); List<org.weasis.dicom.google.api.model.ProjectDescriptor> result = new ArrayList<org.weasis.dicom.google.api.model.ProjectDescriptor>(); CloudResourceManager.Projects.List request = cloudResourceManager.projects().list(); ListProjectsResponse response; do { response = request.execute(); if (response.getProjects() == null) { continue; } for (Project project : response.getProjects()) { String name = project.getName(); String projectId = project.getProjectId(); if (name != null && projectId != null) { result.add(new org.weasis.dicom.google.api.model.ProjectDescriptor(name, projectId)); } } request.setPageToken(response.getNextPageToken()); } while (response.getNextPageToken() != null); return result; } private String parseName(String name) { return name.substring(name.lastIndexOf("/") + 1); } /** * Executes HTTP GET request using the specified URL. * * @param url HTTP request URL. * @return HTTP response. * @throws IOException if an IO error occurred. * @throws HttpResponseException if an error status code is detected in response. * @see #executeGetRequest(String, HttpHeaders) */ public HttpResponse executeGetRequest(String url) throws IOException { return executeGetRequest(url, new HttpHeaders()); } /** * Executes a HTTP GET request with the specified URL and headers. GCP authorization is done * if the user is not already signed in. The access token is refreshed if it has expired * (HTTP 401 is returned from the server) and the request is retried with the new access token. * * @param url HTTP request URL. * @param headers HTTP request headers. * @return HTTP response. * @throws IOException if an IO error occurred. * @throws HttpResponseException if an error status code is detected in response. * @see #signIn() * @see #refresh() */ public HttpResponse executeGetRequest(String url, HttpHeaders headers) throws IOException { signIn(); try { return doExecuteGetRequest(url, headers); } catch (HttpResponseException e) { // Token expired? if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { // Refresh token and try again refresh(); return doExecuteGetRequest(url, headers); } throw e; } } /** * Performs actual HTTP GET request using the specified URL and headers. This method also adds * {@code Authorization} header initialized with OAuth access token. * * @param url HTTP request URL. * @param headers HTTP request headers. * @return HTTP response. * @throws IOException if an IO error occurred. * @throws HttpResponseException if an error status code is detected in response. * @see #doExecuteGetRequest(String, HttpHeaders) */ private HttpResponse doExecuteGetRequest(String url, HttpHeaders headers) throws IOException { final HttpRequest request = httpTransport.createRequestFactory().buildGetRequest( new GenericUrl(url)); headers.setAuthorization("Bearer " + accessToken); request.setHeaders(headers); return request.execute(); } public List<org.weasis.dicom.google.api.model.Location> fetchLocations(ProjectDescriptor project) throws Exception { String url = GOOGLE_API_BASE_PATH + "/projects/" + project.getId() + "/locations"; String data = executeGetRequest(url).parseAsString(); JsonParser parser = new JsonParser(); JsonElement jsonTree = parser.parse(data); JsonArray jsonObject = jsonTree.getAsJsonObject().get("locations").getAsJsonArray(); return StreamSupport.stream(jsonObject.spliterator(), false) .map(JsonElement::getAsJsonObject) .map(obj -> new org.weasis.dicom.google.api.model.Location(project, obj.get("name").getAsString(), obj.get("locationId").getAsString())) .collect(Collectors.toList()); }
public List<Dataset> fetchDatasets(Location location) throws Exception {
0
RandoApp/Rando-android
src/main/java/com/github/randoapp/service/EmailAndPasswordAuthService.java
[ "public class API {\n\n protected static final String PROTOCOL_CHARSET = \"utf-8\";\n\n public static void signup(final String email, final String password, final Context context, final NetworkResultListener resultListener) {\n Map<String, String> params = new HashMap<>();\n params.put(SIGNUP_EMAIL_PARAM, email);\n params.put(SIGNUP_PASSWORD_PARAM, password);\n params.put(FIREBASE_INSTANCE_ID_PARAM, Preferences.getFirebaseInstanceId(context));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(new JsonObjectRequest(Request.Method.POST, SIGNUP_URL, new JSONObject(params), new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n String authToken = response.getString(Constants.AUTH_TOKEN_PARAM);\n Preferences.setAuthToken(context, authToken);\n } catch (JSONException e) {\n Log.e(API.class, \"Parse signup response failed\", e);\n }\n\n if (resultListener != null) {\n resultListener.onOk();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n }));\n }\n\n public static void statistics(final Context context, final NetworkResultListener resultListener) {\n Log.d(API.class, \"API.statistics\");\n\n VolleySingleton.getInstance(context).getRequestQueue().add(new BackgroundPreprocessedRequest(Request.Method.GET, STATISTICS_URL, null, null, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Preferences.setUserStatistics(context, Statistics.from(response));\n Intent intent = new Intent(Constants.SYNC_STATISTICS_EVENT);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);\n if (resultListener != null) {\n resultListener.onOk();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n }).setHeaders(getHeaders(context)));\n }\n\n\n public static void google(String email, String token, final Context context, final NetworkResultListener resultListener) {\n Map<String, String> params = new HashMap<>();\n params.put(GOOGLE_EMAIL_PARAM, email);\n params.put(GOOGLE_TOKEN_PARAM, token);\n params.put(FIREBASE_INSTANCE_ID_PARAM, Preferences.getFirebaseInstanceId(context));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(new JsonObjectRequest(Request.Method.POST, GOOGLE_URL, new JSONObject(params), new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n String authToken = response.getString(Constants.AUTH_TOKEN_PARAM);\n Preferences.setAuthToken(context, authToken);\n } catch (JSONException e) {\n Log.e(API.class, \"Parse google login response failed\", e);\n }\n if (resultListener != null) {\n resultListener.onOk();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n }));\n }\n\n public static void anonymous(String uuid, final Context context, final NetworkResultListener resultListener) {\n Map<String, String> params = new HashMap<>();\n params.put(ANONYMOUS_ID_PARAM, uuid);\n params.put(FIREBASE_INSTANCE_ID_PARAM, Preferences.getFirebaseInstanceId(context));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(new JsonObjectRequest(Request.Method.POST, ANONYMOUS_URL, new JSONObject(params), new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n String authToken = response.getString(Constants.AUTH_TOKEN_PARAM);\n Preferences.setAuthToken(context, authToken);\n } catch (JSONException e) {\n Log.e(API.class, \"Parse anonymous login response failed\", e);\n }\n if (resultListener != null) {\n resultListener.onOk();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n }));\n }\n\n public static void logout(final Context context, final NetworkResultListener resultListener) {\n BackgroundPreprocessedRequest request = new BackgroundPreprocessedRequest(Request.Method.POST, LOGOUT_URL, null, null, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n if (resultListener != null) {\n resultListener.onOk();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n });\n\n request.setHeaders(getHeaders(context));\n request.setRetryPolicy(new DefaultRetryPolicy(API_CONNECTION_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(request);\n }\n\n public static void syncUserAsync(final Context context, final Response.Listener<JSONObject> syncListener, ErrorResponseListener errorResponseListener) {\n Log.d(API.class, \"API.syncUserAsync\");\n BackgroundPreprocessedRequest request = new BackgroundPreprocessedRequest(Request.Method.GET, FETCH_USER_URL, null, new UserFetchResultListener(context, new OnFetchUser() {\n @Override\n public void onFetch(User user) {\n Log.d(API.class, \"Fetched \", user.toString(), \" user. and procesing it in background thread.\");\n List<Rando> dbRandos = RandoDAO.getAllRandos(context);\n int totalUserRandos = user.randosIn.size() + user.randosOut.size();\n if (totalUserRandos != dbRandos.size()\n || !(dbRandos.containsAll(user.randosIn)\n && dbRandos.containsAll(user.randosOut))) {\n RandoDAO.clearRandos(context);\n RandoDAO.insertRandos(context, user.randosIn);\n RandoDAO.insertRandos(context, user.randosOut);\n Notification.sendSyncNotification(context, totalUserRandos, UPDATED);\n } else {\n Notification.sendSyncNotification(context, totalUserRandos, NOT_UPDATED);\n }\n }\n }), syncListener, errorResponseListener);\n request.setHeaders(getHeaders(context));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(request);\n }\n\n public static void uploadImage(final RandoUpload randoUpload, final Context context, final UploadRandoListener uploadListener, final Response.ErrorListener errorListener) {\n\n VolleyMultipartRequest uploadMultipart = new VolleyMultipartRequest(UPLOAD_RANDO_URL, getHeaders(context), new Response.Listener<NetworkResponse>() {\n @Override\n public void onResponse(NetworkResponse response) {\n Log.d(API.class, \"Rando Uploaded Successfully:\", randoUpload.toString());\n String resultResponse = new String(response.data);\n if (uploadListener != null) {\n uploadListener.onUpload(Rando.fromJSON(resultResponse, Rando.Status.OUT));\n }\n }\n }, errorListener) {\n @Override\n protected Map<String, String> getParams() {\n Map<String, String> params = new HashMap<>(2);\n params.put(LATITUDE_PARAM, randoUpload.latitude);\n params.put(LONGITUDE_PARAM, randoUpload.longitude);\n return params;\n }\n\n @Override\n protected Map<String, DataPart> getByteData() {\n Map<String, DataPart> params = new HashMap<>(1);\n File randoFile = new File(randoUpload.file);\n params.put(IMAGE_PARAM, new DataPart(randoFile.getName(), FileUtil.readFile(randoFile), IMAGE_MIME_TYPE));\n\n return params;\n }\n\n @Override\n public Priority getPriority() {\n return Priority.LOW;\n }\n };\n uploadMultipart.setRetryPolicy(new DefaultRetryPolicy(UPLOAD_CONNECTION_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(uploadMultipart);\n }\n\n public static void delete(final String randoId, final Context context, final NetworkResultListener resultListener) throws Exception {\n Log.d(API.class, \"Deleting Rando:\", randoId);\n BackgroundPreprocessedRequest request = new BackgroundPreprocessedRequest(Request.Method.POST, DELETE_URL + randoId, null, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if (\"delete\".equals(response.getString(\"command\")) &&\n \"done\".equals(response.getString(\"result\"))) {\n Log.d(API.class, \"Deleted Rando:\", randoId);\n RandoDAO.deleteRandoByRandoId(context, randoId);\n }\n } catch (JSONException e) {\n Log.e(API.class, \"Error Deleting Rando\", e);\n resultListener.onError(null);\n }\n }\n }, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n resultListener.onOk();\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(API.class, \"Error Deleting Rando\", error);\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n });\n\n request.setHeaders(getHeaders(context));\n request.setRetryPolicy(new DefaultRetryPolicy(API_CONNECTION_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(request);\n }\n\n public static void report(final String randoId, final Context context, final NetworkResultListener resultListener) throws Exception {\n Log.d(API.class, \"Reporting Rando:\", randoId);\n BackgroundPreprocessedRequest request = new BackgroundPreprocessedRequest(Request.Method.POST, REPORT_URL + randoId, null, null, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if (\"report\".equals(response.getString(\"command\")) &&\n \"done\".equals(response.getString(\"result\"))) {\n Log.d(API.class, \"Reported Rando:\", randoId);\n resultListener.onOk();\n }\n } catch (JSONException e) {\n Log.e(API.class, \"Error Reporting Rando\", e);\n resultListener.onError(null);\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(API.class, \"Error Reporting Rando\", error);\n Response<JSONObject> resp = parseNetworkResponse(error.networkResponse);\n if (resultListener != null) {\n resultListener.onError(processServerError(resp.result));\n }\n }\n });\n\n request.setHeaders(getHeaders(context));\n request.setRetryPolicy(new DefaultRetryPolicy(API_CONNECTION_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(request);\n }\n\n public static void rate(final String randoId, final Context context, final int rating, final NetworkResultListener reportRandoListener) {\n Log.d(API.class, \"Rate Rando:\", randoId);\n BackgroundPreprocessedRequest request = new BackgroundPreprocessedRequest(Request.Method.POST, RATE_URL + randoId + \"?rating=\" + rating, null, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if (\"rate\".equals(response.getString(\"command\")) &&\n \"done\".equals(response.getString(\"result\"))) {\n Log.d(API.class, \"Rated Rando:\", randoId);\n Rando rando = RandoDAO.getRandoByRandoId(context, randoId);\n rando.rating = rating;\n RandoDAO.updateRando(context, rando);\n }\n } catch (JSONException e) {\n Log.e(API.class, \"Error Rating Rando\", e);\n reportRandoListener.onError(null);\n }\n }\n }, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n reportRandoListener.onOk();\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(API.class, \"Error Rating Rando\", error);\n reportRandoListener.onError(null);\n }\n });\n\n request.setHeaders(getHeaders(context));\n request.setRetryPolicy(new DefaultRetryPolicy(API_CONNECTION_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));\n\n VolleySingleton.getInstance(context).getRequestQueue().add(request);\n }\n\n private static Map<String, String> getHeaders(Context context) {\n Map<String, String> headers = new HashMap<>(2);\n headers.put(AUTHORIZATION_HEADER, \"Token \" + Preferences.getAuthToken(context));\n if (!Preferences.getFirebaseInstanceId(context).isEmpty()) {\n headers.put(FIREBASE_INSTANCE_ID_HEADER, Preferences.getFirebaseInstanceId(context));\n }\n return headers;\n }\n\n private static Error processServerError(JSONObject json) {\n if (json == null) {\n return new Error().setCode(R.string.error_no_network);\n }\n\n try {\n switch (json.getInt(ERROR_CODE_PARAM)) {\n case Constants.UNAUTHORIZED_CODE:\n return new Error().setCode(R.string.error_400);\n case Constants.FORBIDDEN_CODE: {\n String resetTime = \"\";\n try {\n String message = json.getString(\"message\");\n Matcher matcher = Pattern.compile(\"\\\\d+\").matcher(message);\n if (matcher.find()) {\n long resetTimeUnix = Long.parseLong(matcher.group());\n resetTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(new Date(resetTimeUnix));\n }\n } catch (Exception e) {\n Log.w(API.class, \"Error when try build ban message for user: \", e.getMessage());\n }\n return new Error().setCode(R.string.error_411).setMessage(resetTime);\n }\n default: {\n //TODO: implement all code handling in switch and replace server \"message\" with default value.\n return new Error().setMessage(json.getString(\"message\"));\n }\n }\n } catch (JSONException exc) {\n return processError(exc);\n }\n }\n\n private static Error processError(Exception exc) {\n //We don't want to log Connectivity exceptions\n if (exc instanceof UnknownHostException\n || exc instanceof ConnectException) {\n return new Error().setCode(R.string.error_no_network);\n }\n Crashlytics.logException(exc);\n Log.e(API.class, \"processError method\", exc);\n return new Error().setCode(R.string.error_unknown_err);\n }\n\n public static Response<JSONObject> parseNetworkResponse(NetworkResponse response) {\n if (response == null || response.data == null) {\n return Response.error(new ParseError(new Exception(\"Unknown error or no network\")));\n }\n\n try {\n String jsonString = new String(response.data,\n HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));\n return Response.success(new JSONObject(jsonString),\n HttpHeaderParser.parseCacheHeaders(response));\n } catch (UnsupportedEncodingException e) {\n return Response.error(new ParseError(e));\n } catch (JSONException je) {\n return Response.error(new ParseError(je));\n }\n }\n\n}", "public class Error {\n public String message;\n public int code;\n\n public Error setMessage(String message) {\n this.message = message;\n return this;\n }\n\n public Error setCode(int code) {\n this.code = code;\n return this;\n }\n\n public String buildMessage(Context context) {\n String finalMessage = \"\";\n if (this.code != 0) {\n finalMessage = context.getString(code);\n }\n\n if (this.message != null) {\n finalMessage += \" \" + this.message;\n }\n return finalMessage;\n }\n}", "public abstract class NetworkResultListener {\n\n protected Context context;\n\n public NetworkResultListener(Context context) {\n this.context = context;\n }\n\n public abstract void onOk();\n\n public void onError(Error error) {\n if (error.code == R.string.error_400) {\n Intent intent = new Intent(context, AuthActivity.class);\n intent.putExtra(Constants.LOGOUT_ACTIVITY, true);\n context.startActivity(intent);\n return;\n }\n this.onFail(error);\n }\n\n protected abstract void onFail(Error error);\n}", "public class Preferences {\n public static final String AUTH_TOKEN_DEFAULT_VALUE = \"\";\n public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = \"\";\n public static final String ACCOUNT_DEFAULT_VALUE = \"\";\n public static final int STATISTICS_DEFAULT_VALUE = 0;\n\n private static Object monitor = new Object();\n\n public static String getAuthToken(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(AUTH_TOKEN, AUTH_TOKEN_DEFAULT_VALUE);\n }\n }\n\n public static void setAuthToken(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(AUTH_TOKEN, token).apply();\n }\n }\n }\n\n public static void removeAuthToken(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();\n }\n }\n\n\n public static String getAccount(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);\n }\n }\n\n public static void setAccount(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();\n }\n }\n }\n\n public static void removeAccount(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(ACCOUNT).apply();\n }\n }\n\n public static Location getLocation(Context context) {\n Location location = new Location(LOCATION);\n synchronized (monitor) {\n double lat = Double.valueOf(getSharedPreferences(context).getString(LATITUDE_PARAM, \"0\"));\n double lon = Double.valueOf(getSharedPreferences(context).getString(LONGITUDE_PARAM, \"0\"));\n location.setLatitude(lat);\n location.setLongitude(lon);\n }\n return location;\n }\n\n public static void setLocation(Context context, Location location) {\n if (location != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(LONGITUDE_PARAM, String.valueOf(location.getLongitude())).apply();\n getSharedPreferences(context).edit().putString(LATITUDE_PARAM, String.valueOf(location.getLatitude())).apply();\n }\n }\n }\n\n public static void removeLocation(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply();\n getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply();\n }\n }\n\n public static boolean isTrainingFragmentShown() {\n //TODO: change to return real value when Training will be Implemented.\n return true;\n //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0);\n }\n\n public static void setTrainingFragmentShown(Context context, int i) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply();\n }\n }\n\n public static void removeTrainingFragmentShown(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply();\n }\n }\n\n public static void setBanResetAt(Context context, long resetAt) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply();\n }\n }\n\n public static long getBanResetAt(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L);\n }\n }\n\n private static SharedPreferences getSharedPreferences(Context context) {\n synchronized (monitor) {\n return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);\n }\n }\n\n public static String getFirebaseInstanceId(Context context) {\n synchronized (monitor) {\n return getSharedPreferences(context).getString(FIREBASE_INSTANCE_ID, FIREBASE_INSTANCE_ID_DEFAULT_VALUE);\n }\n }\n\n public static void setFirebaseInstanceId(Context context, String token) {\n if (token != null) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply();\n }\n }\n }\n\n public static void removeFirebaseInstanceId(Context context) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply();\n }\n }\n\n public static Facing getCameraFacing(Context context) {\n synchronized (monitor) {\n Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name()));\n return facing;\n }\n }\n\n public static void setCameraFacing(Context context, Facing facing) {\n synchronized (monitor) {\n if (facing != null) {\n getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply();\n }\n }\n }\n\n public static Grid getCameraGrid(Context context) {\n synchronized (monitor) {\n return Grid.valueOf(getSharedPreferences(context).getString(CAMERA_GRID_STRING, Grid.OFF.name()));\n }\n }\n\n public static void setCameraGrid(Context context, Grid cameraGrid) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply();\n }\n }\n\n public static Flash getCameraFlashMode(Context context, Facing facing) {\n synchronized (monitor) {\n if (facing != null) {\n return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name()));\n } else {\n return Flash.OFF;\n }\n }\n }\n\n public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) {\n synchronized (monitor) {\n if (flashMode != null && facing != null) {\n getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply();\n }\n }\n }\n\n public static void removeCameraFlashMode(Context context, Facing facing) {\n synchronized (monitor) {\n getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply();\n }\n }\n\n public static void setUserStatistics(Context context, Statistics statistics) {\n synchronized (monitor) {\n if (statistics != null) {\n getSharedPreferences(context).edit().putInt(USER_STATISTICS_LIKES, statistics.getLikes()).apply();\n getSharedPreferences(context).edit().putInt(USER_STATISTICS_DISLIKES, statistics.getDislikes()).apply();\n }\n }\n }\n\n public static Statistics getUserStatistics(Context context) {\n synchronized (monitor) {\n return Statistics.of(\n getSharedPreferences(context).getInt(USER_STATISTICS_LIKES, STATISTICS_DEFAULT_VALUE),\n getSharedPreferences(context).getInt(USER_STATISTICS_DISLIKES, STATISTICS_DEFAULT_VALUE));\n }\n }\n}", "public class Analytics {\n\n private static String TAKE_RANDO = \"take_rando\";\n private static String UPLOAD_RANDO = \"upload_rando\";\n private static String SHARE_RANDO = \"share_rando\";\n private static String DELETE_RANDO = \"delete_rando\";\n private static String REPORT_RANDO = \"report_rando\";\n private static String TAP_STRANGER_RANDO = \"tap_stranger_rando\";\n private static String TAP_OWN_RANDO = \"tap_own_rando\";\n private static String FORCE_SYNC = \"force_sync\";\n private static String LOGOUT = \"logout\";\n private static String LOGIN_SKIP = \"login_skip\";\n private static String LOGIN_GOOGLE = \"login_google\";\n private static String LOGIN_EMAIL = \"login_email\";\n private static String OPEN_TAB_OWN_RANDOS = \"open_tab_own_randos\";\n private static String OPEN_TAB_STRANGER_RANDOS = \"open_tab_stranger_randos\";\n private static String OPEN_TAB_SETTINGS = \"open_tab_settings\";\n private static String SWITCH_CAMERA_TO_FRONT = \"switch_camera_to_front\";\n private static String SWITCH_CAMERA_TO_BACK = \"switch_camera_to_back\";\n private static String RATE_RANDO_UP = \"rate_rando_up\";\n private static String RATE_RANDO_NORMAL = \"rate_rando_normal\";\n private static String RATE_RANDO_DOWN = \"rate_rando_down\";\n\n //unwanted rando events\n private static String CLICK_UNWANTED_RANDO = \"click_unwanted_rando\";\n private static String DELETE_UNWANTED_RANDO_DIALOG = \"delete_unwanted_rando_dialog\";\n private static String CANCEL_UNWANTED_RANDO_DIALOG = \"cancel_unwanted_rando_dialog\";\n\n public static void logTakeRando(FirebaseAnalytics analytics) {\n analytics.logEvent(TAKE_RANDO, null);\n }\n\n public static void logUploadRando(FirebaseAnalytics analytics) {\n analytics.logEvent(UPLOAD_RANDO, null);\n }\n\n public static void logShareRando(FirebaseAnalytics analytics) {\n analytics.logEvent(SHARE_RANDO, null);\n }\n\n public static void logDeleteRando(FirebaseAnalytics analytics) {\n analytics.logEvent(DELETE_RANDO, null);\n }\n\n public static void logReportRando(FirebaseAnalytics analytics) {\n analytics.logEvent(REPORT_RANDO, null);\n }\n\n public static void logTapStrangerRando(FirebaseAnalytics analytics) {\n analytics.logEvent(TAP_STRANGER_RANDO, null);\n }\n\n public static void logTapOwnRando(FirebaseAnalytics analytics) {\n analytics.logEvent(TAP_OWN_RANDO, null);\n }\n\n public static void logForceSync(FirebaseAnalytics analytics) {\n analytics.logEvent(FORCE_SYNC, null);\n }\n\n public static void logLogout(FirebaseAnalytics analytics) {\n analytics.logEvent(LOGOUT, null);\n }\n\n public static void logLoginSkip(FirebaseAnalytics analytics) {\n analytics.logEvent(LOGIN_SKIP, null);\n }\n\n public static void logLoginEmail(FirebaseAnalytics analytics) {\n analytics.logEvent(LOGIN_EMAIL, null);\n }\n\n public static void logLoginGoogle(FirebaseAnalytics analytics) {\n analytics.logEvent(LOGIN_GOOGLE, null);\n }\n\n public static void logOpenTabOwnRandos(FirebaseAnalytics analytics) {\n analytics.logEvent(OPEN_TAB_OWN_RANDOS, null);\n }\n\n public static void logOpenTabStrangerRandos(FirebaseAnalytics analytics) {\n analytics.logEvent(OPEN_TAB_STRANGER_RANDOS, null);\n }\n\n public static void logOpenTabSettings(FirebaseAnalytics analytics) {\n analytics.logEvent(OPEN_TAB_SETTINGS, null);\n }\n\n public static void logClickUnwantedRando(FirebaseAnalytics analytics) {\n analytics.logEvent(CLICK_UNWANTED_RANDO, null);\n }\n\n public static void logDeleteUnwantedRandoDialog(FirebaseAnalytics analytics) {\n analytics.logEvent(DELETE_UNWANTED_RANDO_DIALOG, null);\n }\n\n public static void logCancelUnwantedRandoDialog(FirebaseAnalytics analytics) {\n analytics.logEvent(CANCEL_UNWANTED_RANDO_DIALOG, null);\n }\n\n public static void logSwitchCameraToFront(FirebaseAnalytics analytics) {\n analytics.logEvent(SWITCH_CAMERA_TO_FRONT, null);\n }\n\n public static void logSwitchCameraToBack(FirebaseAnalytics analytics) {\n analytics.logEvent(SWITCH_CAMERA_TO_BACK, null);\n }\n\n public static void logRateRandoGood(FirebaseAnalytics analytics) {\n analytics.logEvent(RATE_RANDO_UP, null);\n }\n\n public static void logRateRandoNormal(FirebaseAnalytics analytics) {\n analytics.logEvent(RATE_RANDO_NORMAL, null);\n }\n\n public static void logRateRandoBad(FirebaseAnalytics analytics) {\n analytics.logEvent(RATE_RANDO_DOWN, null);\n }\n\n}", "public class Progress {\n\n private ProgressDialog progress;\n private Activity activity;\n private boolean isShowing = false;\n\n public Progress(Activity activity) {\n this.activity = activity;\n }\n\n public void show(String message) {\n if (progress != null) {\n progress.setMessage(message);\n show();\n } else {\n progress = new ProgressDialog(activity, AlertDialog.THEME_HOLO_DARK);\n progress.setCanceledOnTouchOutside(false);\n progress.setMessage(message);\n show();\n }\n }\n\n private void show() {\n if (!isShowing) {\n progress.show();\n isShowing = true;\n }\n }\n\n public void hide() {\n isShowing = false;\n if (progress != null) {\n progress.hide();\n }\n }\n\n}" ]
import android.app.Activity; import android.util.Patterns; import android.widget.EditText; import android.widget.Toast; import com.github.randoapp.R; import com.github.randoapp.api.API; import com.github.randoapp.api.beans.Error; import com.github.randoapp.api.listeners.NetworkResultListener; import com.github.randoapp.preferences.Preferences; import com.github.randoapp.util.Analytics; import com.github.randoapp.view.Progress; import com.google.firebase.analytics.FirebaseAnalytics;
package com.github.randoapp.service; public class EmailAndPasswordAuthService extends BaseAuthService { private EditText emailText; private EditText passwordText; public EmailAndPasswordAuthService(Activity activity, Progress progress) { super(activity, progress); this.emailText = (EditText) activity.findViewById(R.id.emailEditText); this.passwordText = (EditText) activity.findViewById(R.id.passwordEditText); } public void process() {
Analytics.logLoginEmail(FirebaseAnalytics.getInstance(activity));
4
ptitfred/magrit
server/main/src/main/java/org/kercoin/magrit/Magrit.java
[ "@Singleton\npublic class Context {\n\t\n\tprivate final Configuration configuration = new Configuration();\n\t\n\tprivate Injector injector;\n\t\n\tprivate final GitUtils gitUtils;\n\t\n\tprivate final ExecutorService commandRunnerPool;\n\n\tpublic Context() {\n\t\tgitUtils = null;\n\t\tcommandRunnerPool = null;\n\t}\n\t\n\tpublic Context(GitUtils gitUtils) {\n\t\tthis(gitUtils, null);\n\t}\n\t\n\t@Inject\n\tpublic Context(GitUtils gitUtils,\n\t\t\t@Named(\"commandRunnerPool\") ExecutorService commandRunnerPool) {\n\t\tthis.gitUtils = gitUtils;\n\t\tthis.commandRunnerPool = commandRunnerPool;\n\t}\n\n\tpublic Configuration configuration() {\n\t\treturn configuration;\n\t}\n\t\n\tpublic Injector getInjector() {\n\t\treturn injector;\n\t}\n\t\n\tpublic ExecutorService getCommandRunnerPool() {\n\t\treturn commandRunnerPool;\n\t}\n\t\n\tpublic void setInjector(Injector injector) {\n\t\tthis.injector = injector;\n\t}\n\t\n\tpublic GitUtils getGitUtils() {\n\t\treturn gitUtils;\n\t}\n\n}", "public class CoreModule extends AbstractModule {\n\n\t@Override\n\tprotected void configure() {\n\t\tbind(BuildDAO.class).to(BuildDAOImpl.class);\n\t\tbind(ExecutorService.class).annotatedWith(Names.named(\"commandRunnerPool\")).toInstance(Executors.newCachedThreadPool());\n\t}\n\n}", "public interface Service {\n\n\tString getName();\n\tvoid logConfig(ConfigurationLogger log, Configuration cfg);\n\tvoid start() throws ServiceException;\n\n\tinterface UseTCP extends Service {\n\t\tint getTCPPort();\n\t}\n\n\tinterface ConfigurationLogger {\n\t\tvoid logKey(String key, Object value);\n\t\tvoid logSubKey(String subKey, Object value);\n\t}\n}", "interface ConfigurationLogger {\n\tvoid logKey(String key, Object value);\n\tvoid logSubKey(String subKey, Object value);\n}", "public class ServiceException extends Exception {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic ServiceException() {\n\t\tsuper();\n\t}\n\n\tpublic ServiceException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic ServiceException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic ServiceException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}", "@Singleton\npublic class Server implements Service.UseTCP {\n\t\n\tprotected final Logger log = LoggerFactory.getLogger(getClass());\n\n\tprivate SshServer sshd;\n\n\tprivate final int port;\n\n\t@Inject\n\tpublic Server(final Context ctx, CommandFactory factory) {\n\t\tport = ctx.configuration().getSshPort();\n\t\tsshd = SshServer.setUpDefaultServer();\n\t\t\n if (SecurityUtils.isBouncyCastleRegistered()) {\n sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider(\"key.pem\"));\n } else {\n sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(\"key.ser\"));\n }\n \n PublickeyAuthenticator auth = null;\n if (ctx.configuration().getAuthentication() == Configuration.Authentication.SSH_PUBLIC_KEYS) {\n \tauth = ctx.getInjector().getInstance(PublickeyAuthenticator.class);\n }\n setupUserAuth(auth);\n \n\t\tsshd.setCommandFactory(factory);\n\n\t\tif (!ctx.configuration().isRemoteAllowed()) {\n\t\t\tsshd.setSessionFactory(new LocalOnlySessionFactory());\n\t\t}\n\t\t\n sshd.setForwardingFilter(new ForwardingFilter() {\n public boolean canForwardAgent(ServerSession session) {\n return false;\n }\n\n public boolean canForwardX11(ServerSession session) {\n return false;\n }\n\n public boolean canListen(InetSocketAddress address, ServerSession session) {\n return false;\n }\n\n public boolean canConnect(InetSocketAddress address, ServerSession session) {\n return false;\n }\n });\n \n\t}\n\n\tprivate void setupUserAuth(PublickeyAuthenticator auth) {\n\t\tList<NamedFactory<UserAuth>> list = new ArrayList<NamedFactory<UserAuth>>();\n\t\tif (auth != null) {\n\t\t\tlist.add(new UserAuthPublicKey.Factory());\n\t\t\tsshd.setPublickeyAuthenticator(auth);\n\t\t} else {\n\t\t\tlist.add(new UserAuthNone.Factory());\n\t\t}\n\t\tsshd.setUserAuthFactories(list);\n\t}\n\n\t@Override\n\tpublic void start() throws ServiceException {\n\t\tsshd.setPort(port);\n\t\ttry {\n\t\t\tsshd.start();\n\t\t} catch (IOException e) {\n\t\t\tthrow new ServiceException(e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn \"SSH Service\";\n\t}\n\n\t@Override\n\tpublic int getTCPPort() {\n\t\treturn port;\n\t}\n\n\t@Override\n\tpublic void logConfig(ConfigurationLogger log, Configuration cfg) {\n\t\tlog.logKey(\"SSHd\", cfg.getSshPort());\n\t\tlog.logKey(\"Listening\", cfg.isRemoteAllowed() ? \"everybody\" : \"localhost\");\n\t\tlog.logKey(\"Authent\", cfg.getAuthentication().external());\n\t\tif (cfg.getAuthentication() == Authentication.SSH_PUBLIC_KEYS) {\n\t\t\tlog.logSubKey(\"Keys dir\", cfg.getPublickeyRepositoryDir());\n\t\t}\n\t\tlog.logKey(\"Home dir\", cfg.getRepositoriesHomeDir());\n\t\tlog.logKey(\"Work dir\", cfg.getWorkHomeDir());\n\t}\n}", "public class SshdModule extends AbstractModule {\n\n\t@Override\n\tprotected void configure() {\n\t\tbind(PublickeyAuthenticator.class).to(GitPublickeyAuthenticator.class);\n\t\tbind(CommandFactory.class).to(MagritCommandFactory.class);\n\t}\n\n}" ]
import org.kercoin.magrit.core.services.ServiceException; import org.kercoin.magrit.sshd.Server; import org.kercoin.magrit.sshd.SshdModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Guice; import com.google.inject.Injector; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.cli.ParseException; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.CoreModule; import org.kercoin.magrit.core.services.Service; import org.kercoin.magrit.core.services.Service.ConfigurationLogger;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Magrit 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit; public final class Magrit { private Context ctx; private Injector guice; Magrit() { bootStrap(); } void bootStrap() { guice = Guice.createInjector(new CoreModule(), new SshdModule()); ctx = guice.getInstance(Context.class); ctx.setInjector(guice); } void configure(String[] args) throws ParseException { new ArgumentsParser(args).configure(ctx.configuration()); } Context getCtx() { return ctx; } void tryBind(int port) throws IOException { ServerSocket ss = null; try { ss = new ServerSocket(port); } finally { if (ss!= null && ss.isBound()) { ss.close(); } } } void tryBindOrFail(int port) { try { tryBind(port); } catch (IOException e) { System.exit(1); } } protected final Logger log = LoggerFactory.getLogger(getClass()); private void launch() throws Exception { Service[] services = getServices(); logConfig(services); checkTCPServices(services); startServices(services); log.info("R E A D Y - {}", new Date()); } private Service[] getServices() { List<Service> services = new ArrayList<Service>();
services.add(getService(Server.class));
5
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/model/ModelImpl.java
[ "public interface ApiInterface {\n\n @GET(\"/users/{user}/repos\")\n Observable<List<RepositoryDTO>> getRepositories(@Path(\"user\") String user);\n\n @GET(\"/repos/{owner}/{repo}/contributors\")\n Observable<List<ContributorDTO>> getContributors(@Path(\"owner\") String owner, @Path(\"repo\") String repo);\n\n @GET(\"/repos/{owner}/{repo}/branches\")\n Observable<List<BranchDTO>> getBranches(@Path(\"owner\") String owner, @Path(\"repo\") String repo);\n\n}", "public class BranchDTO {\n\n @SerializedName(\"name\")\n @Expose\n private String name;\n @SerializedName(\"commit\")\n @Expose\n private CommitDTO commit;\n @SerializedName(\"protection\")\n @Expose\n private ProtectionDTO protection;\n\n /**\n * @return The name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name The name\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return The commit\n */\n public CommitDTO getCommit() {\n return commit;\n }\n\n /**\n * @param commit The commit\n */\n public void setCommit(CommitDTO commit) {\n this.commit = commit;\n }\n\n /**\n * @return The protection\n */\n public ProtectionDTO getProtection() {\n return protection;\n }\n\n /**\n * @param protection The protection\n */\n public void setProtection(ProtectionDTO protection) {\n this.protection = protection;\n }\n\n}", "public class ContributorDTO {\n\n @SerializedName(\"login\")\n @Expose\n private String login;\n @SerializedName(\"id\")\n @Expose\n private int id;\n @SerializedName(\"avatar_url\")\n @Expose\n private String avatarUrl;\n @SerializedName(\"gravatar_id\")\n @Expose\n private String gravatarId;\n @SerializedName(\"url\")\n @Expose\n private String url;\n @SerializedName(\"html_url\")\n @Expose\n private String htmlUrl;\n @SerializedName(\"followers_url\")\n @Expose\n private String followersUrl;\n @SerializedName(\"following_url\")\n @Expose\n private String followingUrl;\n @SerializedName(\"gists_url\")\n @Expose\n private String gistsUrl;\n @SerializedName(\"starred_url\")\n @Expose\n private String starredUrl;\n @SerializedName(\"subscriptions_url\")\n @Expose\n private String subscriptionsUrl;\n @SerializedName(\"organizations_url\")\n @Expose\n private String organizationsUrl;\n @SerializedName(\"repos_url\")\n @Expose\n private String reposUrl;\n @SerializedName(\"events_url\")\n @Expose\n private String eventsUrl;\n @SerializedName(\"received_events_url\")\n @Expose\n private String receivedEventsUrl;\n @SerializedName(\"type\")\n @Expose\n private String type;\n @SerializedName(\"site_admin\")\n @Expose\n private Boolean siteAdmin;\n @SerializedName(\"contributions\")\n @Expose\n private Integer contributions;\n\n /**\n * @return The login\n */\n public String getLogin() {\n return login;\n }\n\n /**\n * @param login The login\n */\n public void setLogin(String login) {\n this.login = login;\n }\n\n /**\n * @return The id\n */\n public int getId() {\n return id;\n }\n\n /**\n * @param id The id\n */\n public void setId(int id) {\n this.id = id;\n }\n\n /**\n * @return The avatarUrl\n */\n public String getAvatarUrl() {\n return avatarUrl;\n }\n\n /**\n * @param avatarUrl The avatar_url\n */\n public void setAvatarUrl(String avatarUrl) {\n this.avatarUrl = avatarUrl;\n }\n\n /**\n * @return The gravatarId\n */\n public String getGravatarId() {\n return gravatarId;\n }\n\n /**\n * @param gravatarId The gravatar_id\n */\n public void setGravatarId(String gravatarId) {\n this.gravatarId = gravatarId;\n }\n\n /**\n * @return The url\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * @param url The url\n */\n public void setUrl(String url) {\n this.url = url;\n }\n\n /**\n * @return The htmlUrl\n */\n public String getHtmlUrl() {\n return htmlUrl;\n }\n\n /**\n * @param htmlUrl The html_url\n */\n public void setHtmlUrl(String htmlUrl) {\n this.htmlUrl = htmlUrl;\n }\n\n /**\n * @return The followersUrl\n */\n public String getFollowersUrl() {\n return followersUrl;\n }\n\n /**\n * @param followersUrl The followers_url\n */\n public void setFollowersUrl(String followersUrl) {\n this.followersUrl = followersUrl;\n }\n\n /**\n * @return The followingUrl\n */\n public String getFollowingUrl() {\n return followingUrl;\n }\n\n /**\n * @param followingUrl The following_url\n */\n public void setFollowingUrl(String followingUrl) {\n this.followingUrl = followingUrl;\n }\n\n /**\n * @return The gistsUrl\n */\n public String getGistsUrl() {\n return gistsUrl;\n }\n\n /**\n * @param gistsUrl The gists_url\n */\n public void setGistsUrl(String gistsUrl) {\n this.gistsUrl = gistsUrl;\n }\n\n /**\n * @return The starredUrl\n */\n public String getStarredUrl() {\n return starredUrl;\n }\n\n /**\n * @param starredUrl The starred_url\n */\n public void setStarredUrl(String starredUrl) {\n this.starredUrl = starredUrl;\n }\n\n /**\n * @return The subscriptionsUrl\n */\n public String getSubscriptionsUrl() {\n return subscriptionsUrl;\n }\n\n /**\n * @param subscriptionsUrl The subscriptions_url\n */\n public void setSubscriptionsUrl(String subscriptionsUrl) {\n this.subscriptionsUrl = subscriptionsUrl;\n }\n\n /**\n * @return The organizationsUrl\n */\n public String getOrganizationsUrl() {\n return organizationsUrl;\n }\n\n /**\n * @param organizationsUrl The organizations_url\n */\n public void setOrganizationsUrl(String organizationsUrl) {\n this.organizationsUrl = organizationsUrl;\n }\n\n /**\n * @return The reposUrl\n */\n public String getReposUrl() {\n return reposUrl;\n }\n\n /**\n * @param reposUrl The repos_url\n */\n public void setReposUrl(String reposUrl) {\n this.reposUrl = reposUrl;\n }\n\n /**\n * @return The eventsUrl\n */\n public String getEventsUrl() {\n return eventsUrl;\n }\n\n /**\n * @param eventsUrl The events_url\n */\n public void setEventsUrl(String eventsUrl) {\n this.eventsUrl = eventsUrl;\n }\n\n /**\n * @return The receivedEventsUrl\n */\n public String getReceivedEventsUrl() {\n return receivedEventsUrl;\n }\n\n /**\n * @param receivedEventsUrl The received_events_url\n */\n public void setReceivedEventsUrl(String receivedEventsUrl) {\n this.receivedEventsUrl = receivedEventsUrl;\n }\n\n /**\n * @return The type\n */\n public String getType() {\n return type;\n }\n\n /**\n * @param type The type\n */\n public void setType(String type) {\n this.type = type;\n }\n\n /**\n * @return The siteAdmin\n */\n public Boolean getSiteAdmin() {\n return siteAdmin;\n }\n\n /**\n * @param siteAdmin The site_admin\n */\n public void setSiteAdmin(Boolean siteAdmin) {\n this.siteAdmin = siteAdmin;\n }\n\n /**\n * @return The contributions\n */\n public Integer getContributions() {\n return contributions;\n }\n\n /**\n * @param contributions The contributions\n */\n public void setContributions(Integer contributions) {\n this.contributions = contributions;\n }\n\n}", "public class RepositoryDTO {\n\n @SerializedName(\"id\")\n @Expose\n private int id;\n @SerializedName(\"name\")\n @Expose\n private String name;\n @SerializedName(\"full_name\")\n @Expose\n private String fullName;\n @SerializedName(\"owner\")\n @Expose\n private OwnerDTO owner;\n @SerializedName(\"private\")\n @Expose\n private boolean _private;\n @SerializedName(\"html_url\")\n @Expose\n private String htmlUrl;\n @SerializedName(\"description\")\n @Expose\n private String description;\n @SerializedName(\"fork\")\n @Expose\n private boolean fork;\n @SerializedName(\"url\")\n @Expose\n private String url;\n @SerializedName(\"forks_url\")\n @Expose\n private String forksUrl;\n @SerializedName(\"keys_url\")\n @Expose\n private String keysUrl;\n @SerializedName(\"collaborators_url\")\n @Expose\n private String collaboratorsUrl;\n @SerializedName(\"teams_url\")\n @Expose\n private String teamsUrl;\n @SerializedName(\"hooks_url\")\n @Expose\n private String hooksUrl;\n @SerializedName(\"issue_events_url\")\n @Expose\n private String issueEventsUrl;\n @SerializedName(\"events_url\")\n @Expose\n private String eventsUrl;\n @SerializedName(\"assignees_url\")\n @Expose\n private String assigneesUrl;\n @SerializedName(\"branches_url\")\n @Expose\n private String branchesUrl;\n @SerializedName(\"tags_url\")\n @Expose\n private String tagsUrl;\n @SerializedName(\"blobs_url\")\n @Expose\n private String blobsUrl;\n @SerializedName(\"git_tags_url\")\n @Expose\n private String gitTagsUrl;\n @SerializedName(\"git_refs_url\")\n @Expose\n private String gitRefsUrl;\n @SerializedName(\"trees_url\")\n @Expose\n private String treesUrl;\n @SerializedName(\"statuses_url\")\n @Expose\n private String statusesUrl;\n @SerializedName(\"languages_url\")\n @Expose\n private String languagesUrl;\n @SerializedName(\"stargazers_url\")\n @Expose\n private String stargazersUrl;\n @SerializedName(\"contributors_url\")\n @Expose\n private String contributorsUrl;\n @SerializedName(\"subscribers_url\")\n @Expose\n private String subscribersUrl;\n @SerializedName(\"subscription_url\")\n @Expose\n private String subscriptionUrl;\n @SerializedName(\"commits_url\")\n @Expose\n private String commitsUrl;\n @SerializedName(\"git_commits_url\")\n @Expose\n private String gitCommitsUrl;\n @SerializedName(\"comments_url\")\n @Expose\n private String commentsUrl;\n @SerializedName(\"issue_comment_url\")\n @Expose\n private String issueCommentUrl;\n @SerializedName(\"contents_url\")\n @Expose\n private String contentsUrl;\n @SerializedName(\"compare_url\")\n @Expose\n private String compareUrl;\n @SerializedName(\"merges_url\")\n @Expose\n private String mergesUrl;\n @SerializedName(\"archive_url\")\n @Expose\n private String archiveUrl;\n @SerializedName(\"downloads_url\")\n @Expose\n private String downloadsUrl;\n @SerializedName(\"issues_url\")\n @Expose\n private String issuesUrl;\n @SerializedName(\"pulls_url\")\n @Expose\n private String pullsUrl;\n @SerializedName(\"milestones_url\")\n @Expose\n private String milestonesUrl;\n @SerializedName(\"notifications_url\")\n @Expose\n private String notificationsUrl;\n @SerializedName(\"labels_url\")\n @Expose\n private String labelsUrl;\n @SerializedName(\"releases_url\")\n @Expose\n private String releasesUrl;\n @SerializedName(\"created_at\")\n @Expose\n private String createdAt;\n @SerializedName(\"updated_at\")\n @Expose\n private String updatedAt;\n @SerializedName(\"pushed_at\")\n @Expose\n private String pushedAt;\n @SerializedName(\"git_url\")\n @Expose\n private String gitUrl;\n @SerializedName(\"ssh_url\")\n @Expose\n private String sshUrl;\n @SerializedName(\"clone_url\")\n @Expose\n private String cloneUrl;\n @SerializedName(\"svn_url\")\n @Expose\n private String svnUrl;\n @SerializedName(\"homepage\")\n @Expose\n private String homepage;\n @SerializedName(\"size\")\n @Expose\n private int size;\n @SerializedName(\"stargazers_count\")\n @Expose\n private int stargazersCount;\n @SerializedName(\"watchers_count\")\n @Expose\n private int watchersCount;\n @SerializedName(\"language\")\n @Expose\n private Object language;\n @SerializedName(\"has_issues\")\n @Expose\n private boolean hasIssues;\n @SerializedName(\"has_downloads\")\n @Expose\n private boolean hasDownloads;\n @SerializedName(\"has_wiki\")\n @Expose\n private boolean hasWiki;\n @SerializedName(\"has_pages\")\n @Expose\n private boolean hasPages;\n @SerializedName(\"forks_count\")\n @Expose\n private int forksCount;\n @SerializedName(\"mirror_url\")\n @Expose\n private Object mirrorUrl;\n @SerializedName(\"open_issues_count\")\n @Expose\n private int openIssuesCount;\n @SerializedName(\"forks\")\n @Expose\n private int forks;\n @SerializedName(\"open_issues\")\n @Expose\n private int openIssues;\n @SerializedName(\"watchers\")\n @Expose\n private int watchers;\n @SerializedName(\"default_branch\")\n @Expose\n private String defaultBranch;\n @SerializedName(\"permissions\")\n @Expose\n private PermissionsDTO permissions;\n\n /**\n * @return The id\n */\n public int getId() {\n return id;\n }\n\n /**\n * @param id The id\n */\n public void setId(int id) {\n this.id = id;\n }\n\n /**\n * @return The name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name The name\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return The fullName\n */\n public String getFullName() {\n return fullName;\n }\n\n /**\n * @param fullName The full_name\n */\n public void setFullName(String fullName) {\n this.fullName = fullName;\n }\n\n /**\n * @return The owner\n */\n public OwnerDTO getOwner() {\n return owner;\n }\n\n /**\n * @param owner The owner\n */\n public void setOwner(OwnerDTO owner) {\n this.owner = owner;\n }\n\n /**\n * @return The _private\n */\n public boolean isPrivate() {\n return _private;\n }\n\n /**\n * @param _private The private\n */\n public void setPrivate(boolean _private) {\n this._private = _private;\n }\n\n /**\n * @return The htmlUrl\n */\n public String getHtmlUrl() {\n return htmlUrl;\n }\n\n /**\n * @param htmlUrl The html_url\n */\n public void setHtmlUrl(String htmlUrl) {\n this.htmlUrl = htmlUrl;\n }\n\n /**\n * @return The description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description The description\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return The fork\n */\n public boolean isFork() {\n return fork;\n }\n\n /**\n * @param fork The fork\n */\n public void setFork(boolean fork) {\n this.fork = fork;\n }\n\n /**\n * @return The url\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * @param url The url\n */\n public void setUrl(String url) {\n this.url = url;\n }\n\n /**\n * @return The forksUrl\n */\n public String getForksUrl() {\n return forksUrl;\n }\n\n /**\n * @param forksUrl The forks_url\n */\n public void setForksUrl(String forksUrl) {\n this.forksUrl = forksUrl;\n }\n\n /**\n * @return The keysUrl\n */\n public String getKeysUrl() {\n return keysUrl;\n }\n\n /**\n * @param keysUrl The keys_url\n */\n public void setKeysUrl(String keysUrl) {\n this.keysUrl = keysUrl;\n }\n\n /**\n * @return The collaboratorsUrl\n */\n public String getCollaboratorsUrl() {\n return collaboratorsUrl;\n }\n\n /**\n * @param collaboratorsUrl The collaborators_url\n */\n public void setCollaboratorsUrl(String collaboratorsUrl) {\n this.collaboratorsUrl = collaboratorsUrl;\n }\n\n /**\n * @return The teamsUrl\n */\n public String getTeamsUrl() {\n return teamsUrl;\n }\n\n /**\n * @param teamsUrl The teams_url\n */\n public void setTeamsUrl(String teamsUrl) {\n this.teamsUrl = teamsUrl;\n }\n\n /**\n * @return The hooksUrl\n */\n public String getHooksUrl() {\n return hooksUrl;\n }\n\n /**\n * @param hooksUrl The hooks_url\n */\n public void setHooksUrl(String hooksUrl) {\n this.hooksUrl = hooksUrl;\n }\n\n /**\n * @return The issueEventsUrl\n */\n public String getIssueEventsUrl() {\n return issueEventsUrl;\n }\n\n /**\n * @param issueEventsUrl The issue_events_url\n */\n public void setIssueEventsUrl(String issueEventsUrl) {\n this.issueEventsUrl = issueEventsUrl;\n }\n\n /**\n * @return The eventsUrl\n */\n public String getEventsUrl() {\n return eventsUrl;\n }\n\n /**\n * @param eventsUrl The events_url\n */\n public void setEventsUrl(String eventsUrl) {\n this.eventsUrl = eventsUrl;\n }\n\n /**\n * @return The assigneesUrl\n */\n public String getAssigneesUrl() {\n return assigneesUrl;\n }\n\n /**\n * @param assigneesUrl The assignees_url\n */\n public void setAssigneesUrl(String assigneesUrl) {\n this.assigneesUrl = assigneesUrl;\n }\n\n /**\n * @return The branchesUrl\n */\n public String getBranchesUrl() {\n return branchesUrl;\n }\n\n /**\n * @param branchesUrl The branches_url\n */\n public void setBranchesUrl(String branchesUrl) {\n this.branchesUrl = branchesUrl;\n }\n\n /**\n * @return The tagsUrl\n */\n public String getTagsUrl() {\n return tagsUrl;\n }\n\n /**\n * @param tagsUrl The tags_url\n */\n public void setTagsUrl(String tagsUrl) {\n this.tagsUrl = tagsUrl;\n }\n\n /**\n * @return The blobsUrl\n */\n public String getBlobsUrl() {\n return blobsUrl;\n }\n\n /**\n * @param blobsUrl The blobs_url\n */\n public void setBlobsUrl(String blobsUrl) {\n this.blobsUrl = blobsUrl;\n }\n\n /**\n * @return The gitTagsUrl\n */\n public String getGitTagsUrl() {\n return gitTagsUrl;\n }\n\n /**\n * @param gitTagsUrl The git_tags_url\n */\n public void setGitTagsUrl(String gitTagsUrl) {\n this.gitTagsUrl = gitTagsUrl;\n }\n\n /**\n * @return The gitRefsUrl\n */\n public String getGitRefsUrl() {\n return gitRefsUrl;\n }\n\n /**\n * @param gitRefsUrl The git_refs_url\n */\n public void setGitRefsUrl(String gitRefsUrl) {\n this.gitRefsUrl = gitRefsUrl;\n }\n\n /**\n * @return The treesUrl\n */\n public String getTreesUrl() {\n return treesUrl;\n }\n\n /**\n * @param treesUrl The trees_url\n */\n public void setTreesUrl(String treesUrl) {\n this.treesUrl = treesUrl;\n }\n\n /**\n * @return The statusesUrl\n */\n public String getStatusesUrl() {\n return statusesUrl;\n }\n\n /**\n * @param statusesUrl The statuses_url\n */\n public void setStatusesUrl(String statusesUrl) {\n this.statusesUrl = statusesUrl;\n }\n\n /**\n * @return The languagesUrl\n */\n public String getLanguagesUrl() {\n return languagesUrl;\n }\n\n /**\n * @param languagesUrl The languages_url\n */\n public void setLanguagesUrl(String languagesUrl) {\n this.languagesUrl = languagesUrl;\n }\n\n /**\n * @return The stargazersUrl\n */\n public String getStargazersUrl() {\n return stargazersUrl;\n }\n\n /**\n * @param stargazersUrl The stargazers_url\n */\n public void setStargazersUrl(String stargazersUrl) {\n this.stargazersUrl = stargazersUrl;\n }\n\n /**\n * @return The contributorsUrl\n */\n public String getContributorsUrl() {\n return contributorsUrl;\n }\n\n /**\n * @param contributorsUrl The contributors_url\n */\n public void setContributorsUrl(String contributorsUrl) {\n this.contributorsUrl = contributorsUrl;\n }\n\n /**\n * @return The subscribersUrl\n */\n public String getSubscribersUrl() {\n return subscribersUrl;\n }\n\n /**\n * @param subscribersUrl The subscribers_url\n */\n public void setSubscribersUrl(String subscribersUrl) {\n this.subscribersUrl = subscribersUrl;\n }\n\n /**\n * @return The subscriptionUrl\n */\n public String getSubscriptionUrl() {\n return subscriptionUrl;\n }\n\n /**\n * @param subscriptionUrl The subscription_url\n */\n public void setSubscriptionUrl(String subscriptionUrl) {\n this.subscriptionUrl = subscriptionUrl;\n }\n\n /**\n * @return The commitsUrl\n */\n public String getCommitsUrl() {\n return commitsUrl;\n }\n\n /**\n * @param commitsUrl The commits_url\n */\n public void setCommitsUrl(String commitsUrl) {\n this.commitsUrl = commitsUrl;\n }\n\n /**\n * @return The gitCommitsUrl\n */\n public String getGitCommitsUrl() {\n return gitCommitsUrl;\n }\n\n /**\n * @param gitCommitsUrl The git_commits_url\n */\n public void setGitCommitsUrl(String gitCommitsUrl) {\n this.gitCommitsUrl = gitCommitsUrl;\n }\n\n /**\n * @return The commentsUrl\n */\n public String getCommentsUrl() {\n return commentsUrl;\n }\n\n /**\n * @param commentsUrl The comments_url\n */\n public void setCommentsUrl(String commentsUrl) {\n this.commentsUrl = commentsUrl;\n }\n\n /**\n * @return The issueCommentUrl\n */\n public String getIssueCommentUrl() {\n return issueCommentUrl;\n }\n\n /**\n * @param issueCommentUrl The issue_comment_url\n */\n public void setIssueCommentUrl(String issueCommentUrl) {\n this.issueCommentUrl = issueCommentUrl;\n }\n\n /**\n * @return The contentsUrl\n */\n public String getContentsUrl() {\n return contentsUrl;\n }\n\n /**\n * @param contentsUrl The contents_url\n */\n public void setContentsUrl(String contentsUrl) {\n this.contentsUrl = contentsUrl;\n }\n\n /**\n * @return The compareUrl\n */\n public String getCompareUrl() {\n return compareUrl;\n }\n\n /**\n * @param compareUrl The compare_url\n */\n public void setCompareUrl(String compareUrl) {\n this.compareUrl = compareUrl;\n }\n\n /**\n * @return The mergesUrl\n */\n public String getMergesUrl() {\n return mergesUrl;\n }\n\n /**\n * @param mergesUrl The merges_url\n */\n public void setMergesUrl(String mergesUrl) {\n this.mergesUrl = mergesUrl;\n }\n\n /**\n * @return The archiveUrl\n */\n public String getArchiveUrl() {\n return archiveUrl;\n }\n\n /**\n * @param archiveUrl The archive_url\n */\n public void setArchiveUrl(String archiveUrl) {\n this.archiveUrl = archiveUrl;\n }\n\n /**\n * @return The downloadsUrl\n */\n public String getDownloadsUrl() {\n return downloadsUrl;\n }\n\n /**\n * @param downloadsUrl The downloads_url\n */\n public void setDownloadsUrl(String downloadsUrl) {\n this.downloadsUrl = downloadsUrl;\n }\n\n /**\n * @return The issuesUrl\n */\n public String getIssuesUrl() {\n return issuesUrl;\n }\n\n /**\n * @param issuesUrl The issues_url\n */\n public void setIssuesUrl(String issuesUrl) {\n this.issuesUrl = issuesUrl;\n }\n\n /**\n * @return The pullsUrl\n */\n public String getPullsUrl() {\n return pullsUrl;\n }\n\n /**\n * @param pullsUrl The pulls_url\n */\n public void setPullsUrl(String pullsUrl) {\n this.pullsUrl = pullsUrl;\n }\n\n /**\n * @return The milestonesUrl\n */\n public String getMilestonesUrl() {\n return milestonesUrl;\n }\n\n /**\n * @param milestonesUrl The milestones_url\n */\n public void setMilestonesUrl(String milestonesUrl) {\n this.milestonesUrl = milestonesUrl;\n }\n\n /**\n * @return The notificationsUrl\n */\n public String getNotificationsUrl() {\n return notificationsUrl;\n }\n\n /**\n * @param notificationsUrl The notifications_url\n */\n public void setNotificationsUrl(String notificationsUrl) {\n this.notificationsUrl = notificationsUrl;\n }\n\n /**\n * @return The labelsUrl\n */\n public String getLabelsUrl() {\n return labelsUrl;\n }\n\n /**\n * @param labelsUrl The labels_url\n */\n public void setLabelsUrl(String labelsUrl) {\n this.labelsUrl = labelsUrl;\n }\n\n /**\n * @return The releasesUrl\n */\n public String getReleasesUrl() {\n return releasesUrl;\n }\n\n /**\n * @param releasesUrl The releases_url\n */\n public void setReleasesUrl(String releasesUrl) {\n this.releasesUrl = releasesUrl;\n }\n\n /**\n * @return The createdAt\n */\n public String getCreatedAt() {\n return createdAt;\n }\n\n /**\n * @param createdAt The created_at\n */\n public void setCreatedAt(String createdAt) {\n this.createdAt = createdAt;\n }\n\n /**\n * @return The updatedAt\n */\n public String getUpdatedAt() {\n return updatedAt;\n }\n\n /**\n * @param updatedAt The updated_at\n */\n public void setUpdatedAt(String updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n /**\n * @return The pushedAt\n */\n public String getPushedAt() {\n return pushedAt;\n }\n\n /**\n * @param pushedAt The pushed_at\n */\n public void setPushedAt(String pushedAt) {\n this.pushedAt = pushedAt;\n }\n\n /**\n * @return The gitUrl\n */\n public String getGitUrl() {\n return gitUrl;\n }\n\n /**\n * @param gitUrl The git_url\n */\n public void setGitUrl(String gitUrl) {\n this.gitUrl = gitUrl;\n }\n\n /**\n * @return The sshUrl\n */\n public String getSshUrl() {\n return sshUrl;\n }\n\n /**\n * @param sshUrl The ssh_url\n */\n public void setSshUrl(String sshUrl) {\n this.sshUrl = sshUrl;\n }\n\n /**\n * @return The cloneUrl\n */\n public String getCloneUrl() {\n return cloneUrl;\n }\n\n /**\n * @param cloneUrl The clone_url\n */\n public void setCloneUrl(String cloneUrl) {\n this.cloneUrl = cloneUrl;\n }\n\n /**\n * @return The svnUrl\n */\n public String getSvnUrl() {\n return svnUrl;\n }\n\n /**\n * @param svnUrl The svn_url\n */\n public void setSvnUrl(String svnUrl) {\n this.svnUrl = svnUrl;\n }\n\n /**\n * @return The homepage\n */\n public String getHomepage() {\n return homepage;\n }\n\n /**\n * @param homepage The homepage\n */\n public void setHomepage(String homepage) {\n this.homepage = homepage;\n }\n\n /**\n * @return The size\n */\n public int getSize() {\n return size;\n }\n\n /**\n * @param size The size\n */\n public void setSize(int size) {\n this.size = size;\n }\n\n /**\n * @return The stargazersCount\n */\n public int getStargazersCount() {\n return stargazersCount;\n }\n\n /**\n * @param stargazersCount The stargazers_count\n */\n public void setStargazersCount(int stargazersCount) {\n this.stargazersCount = stargazersCount;\n }\n\n /**\n * @return The watchersCount\n */\n public int getWatchersCount() {\n return watchersCount;\n }\n\n /**\n * @param watchersCount The watchers_count\n */\n public void setWatchersCount(int watchersCount) {\n this.watchersCount = watchersCount;\n }\n\n /**\n * @return The language\n */\n public Object getLanguage() {\n return language;\n }\n\n /**\n * @param language The language\n */\n public void setLanguage(Object language) {\n this.language = language;\n }\n\n /**\n * @return The hasIssues\n */\n public boolean isHasIssues() {\n return hasIssues;\n }\n\n /**\n * @param hasIssues The has_issues\n */\n public void setHasIssues(boolean hasIssues) {\n this.hasIssues = hasIssues;\n }\n\n /**\n * @return The hasDownloads\n */\n public boolean isHasDownloads() {\n return hasDownloads;\n }\n\n /**\n * @param hasDownloads The has_downloads\n */\n public void setHasDownloads(boolean hasDownloads) {\n this.hasDownloads = hasDownloads;\n }\n\n /**\n * @return The hasWiki\n */\n public boolean isHasWiki() {\n return hasWiki;\n }\n\n /**\n * @param hasWiki The has_wiki\n */\n public void setHasWiki(boolean hasWiki) {\n this.hasWiki = hasWiki;\n }\n\n /**\n * @return The hasPages\n */\n public boolean isHasPages() {\n return hasPages;\n }\n\n /**\n * @param hasPages The has_pages\n */\n public void setHasPages(boolean hasPages) {\n this.hasPages = hasPages;\n }\n\n /**\n * @return The forksCount\n */\n public int getForksCount() {\n return forksCount;\n }\n\n /**\n * @param forksCount The forks_count\n */\n public void setForksCount(int forksCount) {\n this.forksCount = forksCount;\n }\n\n /**\n * @return The mirrorUrl\n */\n public Object getMirrorUrl() {\n return mirrorUrl;\n }\n\n /**\n * @param mirrorUrl The mirror_url\n */\n public void setMirrorUrl(Object mirrorUrl) {\n this.mirrorUrl = mirrorUrl;\n }\n\n /**\n * @return The openIssuesCount\n */\n public int getOpenIssuesCount() {\n return openIssuesCount;\n }\n\n /**\n * @param openIssuesCount The open_issues_count\n */\n public void setOpenIssuesCount(int openIssuesCount) {\n this.openIssuesCount = openIssuesCount;\n }\n\n /**\n * @return The forks\n */\n public int getForks() {\n return forks;\n }\n\n /**\n * @param forks The forks\n */\n public void setForks(int forks) {\n this.forks = forks;\n }\n\n /**\n * @return The openIssues\n */\n public int getOpenIssues() {\n return openIssues;\n }\n\n /**\n * @param openIssues The open_issues\n */\n public void setOpenIssues(int openIssues) {\n this.openIssues = openIssues;\n }\n\n /**\n * @return The watchers\n */\n public int getWatchers() {\n return watchers;\n }\n\n /**\n * @param watchers The watchers\n */\n public void setWatchers(int watchers) {\n this.watchers = watchers;\n }\n\n /**\n * @return The defaultBranch\n */\n public String getDefaultBranch() {\n return defaultBranch;\n }\n\n /**\n * @param defaultBranch The default_branch\n */\n public void setDefaultBranch(String defaultBranch) {\n this.defaultBranch = defaultBranch;\n }\n\n /**\n * @return The permissions\n */\n public PermissionsDTO getPermissions() {\n return permissions;\n }\n\n /**\n * @param permissions The permissions\n */\n public void setPermissions(PermissionsDTO permissions) {\n this.permissions = permissions;\n }\n\n}", "public class App extends Application {\n\n private static AppComponent component;\n\n public static AppComponent getComponent() {\n return component;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n component = buildComponent();\n }\n\n protected AppComponent buildComponent() {\n return DaggerAppComponent.builder()\n .build();\n }\n\n\n}", "public interface Const {\n String UI_THREAD = \"UI_THREAD\";\n String IO_THREAD = \"IO_THREAD\";\n\n String BASE_URL = \"https://api.github.com/\";\n\n}" ]
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.dto.BranchDTO; import com.andrey7mel.stepbystep.model.dto.ContributorDTO; import com.andrey7mel.stepbystep.model.dto.RepositoryDTO; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.Const; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler;
package com.andrey7mel.stepbystep.model; public class ModelImpl implements Model { private final Observable.Transformer schedulersTransformer; @Inject protected ApiInterface apiInterface; @Inject @Named(Const.UI_THREAD) Scheduler uiThread; @Inject @Named(Const.IO_THREAD) Scheduler ioThread; public ModelImpl() { App.getComponent().inject(this); schedulersTransformer = o -> ((Observable) o).subscribeOn(ioThread) .observeOn(uiThread) .unsubscribeOn(ioThread); // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed } @Override public Observable<List<RepositoryDTO>> getRepoList(String name) { return apiInterface .getRepositories(name) .compose(applySchedulers()); } @Override
public Observable<List<BranchDTO>> getRepoBranches(String owner, String name) {
1
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/players/KExoPlayer.java
[ "public class ExoplayerWrapper implements ExoPlayer.Listener, ChunkSampleSource.EventListener,\n DefaultBandwidthMeter.EventListener, MediaCodecVideoTrackRenderer.EventListener,\n MediaCodecAudioTrackRenderer.EventListener, TextRenderer,\n StreamingDrmSessionManager.EventListener, DashChunkSource.EventListener,\n HlsChunkSource.EventListener, HlsSampleSource.EventListener, MetadataRenderer<List<Id3Frame>> {\n\n /**\n * Builds renderers for the player.\n */\n public interface RendererBuilder {\n /**\n * Constructs the necessary components for playback.\n *\n * @param player The parent player.\n */\n void buildRenderers(ExoplayerWrapper player);\n\n /**\n * Cancels the current build operation, if there is one. Else does nothing.\n */\n void cancel();\n }\n\n /**\n * A listener for basic playback events.\n */\n public interface PlaybackListener {\n void onStateChanged(boolean playWhenReady, int playbackState);\n void onError(Exception e);\n void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,\n float pixelWidthHeightRatio);\n }\n\n /**\n * A listener for internal errors.\n * <p>\n * These errors are not visible to the user, and hence this listener is provided for\n * informational purposes only. Note however that an internal error may cause a fatal\n * error if the player fails to recover. If this happens,\n * {@link PlaybackListener#onError(Exception)} will be invoked.\n *\n * <p>\n * Implementing an {@link InternalErrorListener} is a good way to identify why ExoPlayer may be\n * behaving in an undesired way.\n */\n public interface InternalErrorListener {\n\n /**\n * Respond to error in renderer initialization.\n * @param e The error.\n */\n void onRendererInitializationError(Exception e);\n\n /**\n * Respond to error in initializing the audio track.\n * @param e The error.\n */\n void onAudioTrackInitializationError(AudioTrack.InitializationException e);\n\n /**\n * Respond to error when writing the audio track.\n * @param e The error.\n */\n void onAudioTrackWriteError(AudioTrack.WriteException e);\n\n /**\n * Respond to error in initializing the decoder.\n * @param e The error.\n */\n void onDecoderInitializationError(DecoderInitializationException e);\n\n /**\n * Respond to error in setting up security of video.\n * @param e The error.\n */\n void onCryptoError(CryptoException e);\n\n /**\n * Respond to error that occurs at the source of the video.\n * @param sourceId The id of the source of the video.\n * @param e The error.\n */\n void onUpstreamError(int sourceId, IOException e);\n\n /**\n * Respond to error when consuming video data from a source.\n * @param sourceId The id of the source of the video.\n * @param e The error.\n */\n void onConsumptionError(int sourceId, IOException e);\n\n /**\n * Respond to error in DRM setup.\n * @param e The error.\n */\n void onDrmSessionManagerError(Exception e);\n\n void onLoadError(int sourceId, IOException e);\n\n /**\n * Respond to error when running the audio track.\n * @param bufferSize The buffer size.\n * @param bufferSizeMs The buffer size in Ms.\n * @param elapsedSinceLastFeedMs The time elapsed since last feed in Ms.\n */\n void onAudioTrackUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs);\n\n }\n\n /**\n * A listener for debugging information.\n */\n public interface InfoListener {\n\n /**\n * Respond to a change in the format of the video.\n * @param format The new format of the video.\n * @param trigger The reason for a chunk being selected.\n * @param mediaTimeMs The start time of the media contained by the chunk, in microseconds.\n */\n void onVideoFormatEnabled(Format format, int trigger, long mediaTimeMs);\n\n /**\n * Respond to a change in the audio format.\n * @param format The new format of the audio.\n * @param trigger The reason for a chunk being selected.\n * @param mediaTimeMs The start time of the media contained by the chunk, in microseconds.\n */\n void onAudioFormatEnabled(Format format, int trigger, long mediaTimeMs);\n\n /**\n * Respond to frame drops.\n * @param count The number of dropped frames.\n * @param elapsed The number of milliseconds in which the frames were dropped.\n */\n void onDroppedFrames(int count, long elapsed);\n\n /**\n * Respond to a new estimate of the bandwidth.\n * @param elapsedMs The duration of the sampling period in milliseconds.\n * @param bytes The number of bytes received during the sampling period.\n * @param bandwidthEstimate The estimated bandwidth in bytes/sec, or\n * {@link com.google.android.exoplayer.upstream.DefaultBandwidthMeter\n * #NO_ESTIMATE} if no estimate is available. Note that this estimate\n * is typically derived from more information than {@code bytes} and\n * {@code elapsedMs}.\n */\n void onBandwidthSample(int elapsedMs, long bytes, long bandwidthEstimate);\n\n /**\n * Respond to starting a load of data.\n * @param sourceId The id of the source of the video.\n * @param length The length of the audio.\n * @param type The type of the audio\n * @param trigger The reason for a chunk being selected.\n * @param format The format of the source.\n * @param mediaStartTimeMs The time point of the media where we start loading.\n * @param mediaEndTimeMs The time point of the media where we end loading.\n */\n void onLoadStarted(int sourceId, long length, int type, int trigger, Format format,\n long mediaStartTimeMs, long mediaEndTimeMs);\n\n /**\n * Respond to a successful load of data.\n * @param sourceId The id of the source of the video.\n */\n void onLoadCompleted(int sourceId, long bytesLoaded, int type, int trigger, Format format,\n long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs,\n long loadDurationMs);\n\n void onDecoderInitialized(String decoderName, long elapsedRealtimeMs,\n long initializationDurationMs);\n void onAvailableRangeChanged(int sourceId, TimeRange availableRange);\n void onAvailableRangeChanged(TimeRange availableRange);\n\n\n }\n\n /**\n * A listener for receiving notifications of id3Frames.\n */\n @Override\n public void onMetadata(List<Id3Frame> id3Frames) {\n if (id3MetadataListener != null && getSelectedTrack(TYPE_METADATA) != TRACK_DISABLED) {\n id3MetadataListener.onId3Metadata(id3Frames);\n }\n }\n\n\n /**\n * A listener for receiving notifications of timed text.\n */\n public interface CaptionListener {\n void onCues(List<Cue> cues);\n }\n\n /**\n * A listener for receiving ID3 metadata parsed from the media stream.\n */\n public interface Id3MetadataListener {\n void onId3Metadata(List<Id3Frame> id3Frames);\n\n }\n\n /**\n * Exoplayer renderers are managed in an array (the array representation is used throughout the\n * Exoplayer library).\n *\n * <p>There are RENDERER_COUNT elements in the array.\n */\n public static final int RENDERER_COUNT = 5;\n\n /**\n * The element at index TYPE_VIDEO is a video type renderer.\n */\n public static final int TYPE_VIDEO = 0;\n\n /**\n * The element at index TYPE_AUDIO is an audio type renderer.\n */\n public static final int TYPE_AUDIO = 1;\n\n /**\n * The element at index TYPE_TEXT is a text type renderer.\n */\n public static final int TYPE_TEXT = 2;\n public static final int TYPE_METADATA = 3;\n\n public static final int TRACK_DISABLED = ExoPlayer.TRACK_DISABLED;\n\n /**\n * For id3 metadata.\n */\n public static final int TYPE_TIMED_METADATA = 3;\n\n /**\n * The element at index TYPE_DEBUG is a debug type renderer.\n */\n public static final int TYPE_DEBUG = 4;\n\n /**\n * This variable must be an int, not part of an enum because it has significance within the\n * Exoplayer library.\n */\n private static final int RENDERER_BUILDING_STATE_IDLE = 1;\n\n /**\n * This variable must be an int, not part of an enum because it has significance within the\n * Exoplayer library.\n */\n private static final int RENDERER_BUILDING_STATE_BUILDING = 2;\n\n /**\n * This variable must be an int, not part of an enum because it has significance within the\n * Exoplayer library.\n */\n private static final int RENDERER_BUILDING_STATE_BUILT = 3;\n\n /**\n * This variable must be an int, not part of an enum because it has significance within the\n * Exoplayer library.\n */\n public static final int DISABLED_TRACK = -1;\n\n /**\n * This variable must be an int, not part of an enum because it has significance within the\n * Exoplayer library.\n */\n public static final int PRIMARY_TRACK = 0;\n\n /**\n * Responsible for loading the data from the source, processing it, and providing byte streams.\n * By modifying the renderer builder, we can support different video formats like DASH, MP4, and\n * SmoothStreaming.\n */\n private final RendererBuilder rendererBuilder;\n\n /**\n * The underlying Exoplayer instance responsible for playing the video.\n */\n private final ExoPlayer player;\n\n /**\n * Used to control the playback (ex play, pause, get duration, get elapsed time, seek to time).\n */\n private final ObservablePlayerControl playerControl;\n\n /**\n * Used by track renderers to send messages to the event listeners within this class.\n */\n private final Handler mainHandler;\n\n /**\n * Listeners are notified when the video size changes, when the underlying player's state changes,\n * or when an error occurs.\n */\n private final CopyOnWriteArrayList<PlaybackListener> playbackListeners;\n\n /**\n * States are idle, building, or built.\n */\n private int rendererBuildingState;\n\n /**\n * States are idle, prepared, buffering, ready, or ended. This is an integer (instead of an enum)\n * because the Exoplayer library uses integers.\n */\n private int lastReportedPlaybackState;\n\n /**\n * Whether the player was in a playWhenReady state the last time we checked.\n */\n private boolean lastReportedPlayWhenReady;\n\n /**\n * The surface on which the video is rendered.\n */\n private Surface surface;\n\n /**\n * Renders the video data.\n */\n private TrackRenderer videoRenderer;\n\n private CodecCounters codecCounters;\n private Format videoFormat;\n private int videoTrackToRestore;\n private BandwidthMeter bandwidthMeter;\n private boolean backgrounded;\n\n /**\n * The names of the available tracks, indexed by ExoplayerWrapper INDEX_* constants.\n * May be null if the track names are unknown. An individual element may be null if the track\n * names are unknown for the corresponding type.\n */\n private String[][] trackNames;\n\n /**\n * A list of enabled or disabled tracks to render.\n */\n private int[] selectedTracks;\n\n /**\n * The state of a track at a given index (one of the TYPE_* constants).\n */\n private int[] trackStateForType;\n\n /**\n * Respond to text (ex subtitle or closed captioning) events.\n */\n private CaptionListener captionListener;\n private Id3MetadataListener id3MetadataListener;\n\n /**\n * Respond to errors that occur in Exoplayer.\n */\n private InternalErrorListener internalErrorListener;\n\n /**\n * Respond to changes in media format changes, load events, bandwidth estimates,\n * and dropped frames.\n */\n private InfoListener infoListener;\n\n /**\n * @param rendererBuilder Responsible for loading the data from the source, processing it,\n * and providing byte streams. By modifying the renderer builder, we can\n * support different video formats like DASH, MP4, and SmoothStreaming.\n */\n public ExoplayerWrapper(RendererBuilder rendererBuilder) {\n this.rendererBuilder = rendererBuilder;\n player = ExoPlayer.Factory.newInstance(RENDERER_COUNT, 1000, 5000);\n player.addListener(this);\n playerControl = new ObservablePlayerControl(player);\n mainHandler = new Handler();\n playbackListeners = new CopyOnWriteArrayList<PlaybackListener>();\n lastReportedPlaybackState = ExoPlayer.STATE_IDLE;\n rendererBuildingState = RENDERER_BUILDING_STATE_IDLE;\n trackStateForType = new int[RENDERER_COUNT];\n // Disable text initially.\n trackStateForType[TYPE_TEXT] = DISABLED_TRACK;\n player.setSelectedTrack(TYPE_TEXT, TRACK_DISABLED);\n }\n\n /**\n * Returns the player control which can be used to play, pause, seek, get elapsed time, and get\n * elapsed duration.\n */\n public ObservablePlayerControl getPlayerControl() {\n return playerControl;\n }\n\n /**\n * Add a listener to respond to size change and error events.\n *\n * @param playbackListener\n */\n public void addListener(PlaybackListener playbackListener) {\n if (!playbackListeners.contains(playbackListener)) {\n playbackListeners.add(playbackListener);\n }\n }\n\n /**\n * Remove a listener from notifications about size changes and errors.\n *\n * @param playbackListener\n */\n public void removeListener(PlaybackListener playbackListener) {\n playbackListeners.remove(playbackListener);\n }\n\n /**\n * Set a listener to respond to errors within Exoplayer.\n * @param listener The listener which responds to the error events.\n */\n public void setInternalErrorListener(InternalErrorListener listener) {\n internalErrorListener = listener;\n }\n\n /**\n * Set a listener to respond to media format changes, bandwidth samples, load events, and dropped\n * frames.\n * @param listener Listens to media format changes, bandwidth samples, load events, and dropped\n * frames.\n */\n public void setInfoListener(InfoListener listener) {\n infoListener = listener;\n }\n\n public void setCaptionListener(CaptionListener listener) {\n captionListener = listener;\n }\n\n public void setMetadataListener(Id3MetadataListener listener) {\n id3MetadataListener = listener;\n }\n\n public void setSurface(Surface surface) {\n this.surface = surface;\n pushSurfaceAndVideoTrack(false);\n }\n\n /**\n * Returns the surface on which the video is rendered.\n */\n public Surface getSurface() {\n return surface;\n }\n\n /**\n * Clear the video surface.\n *\n * <p>In order to clear the surface, a message must be sent to the playback thread. To guarantee\n * that this message is delivered, Exoplayer uses a blocking operation. Therefore, this method is\n * blocking.\n */\n public void blockingClearSurface() {\n surface = null;\n pushSurfaceAndVideoTrack(true);\n }\n\n /**\n * Returns the name of the track at the given index.\n * @param type The index indicating the type of video (ex {@link #TYPE_VIDEO})\n */\n public String[] getTracks(int type) {\n return trackNames == null ? null : trackNames[type];\n }\n\n /**\n * Returns whether the track is {@link #PRIMARY_TRACK} or {@link #DISABLED_TRACK).\n * @param type The index indicating the type of video (ex {@link #TYPE_VIDEO}).\n */\n public int getStateForTrackType(int type) {\n return trackStateForType[type];\n }\n\n public int getSelectedTrack(int type) {\n return player.getSelectedTrack(type);\n }\n\n public void setSelectedTrack(int type, int index) {\n player.setSelectedTrack(type, index);\n if (type == TYPE_TEXT && index < 0 && captionListener != null) {\n captionListener.onCues(Collections.<Cue>emptyList());\n }\n }\n\n public boolean getBackgrounded() {\n return backgrounded;\n }\n\n public void setBackgrounded(boolean backgrounded) {\n if (this.backgrounded == backgrounded) {\n return;\n }\n this.backgrounded = backgrounded;\n if (backgrounded) {\n videoTrackToRestore = getSelectedTrack(TYPE_VIDEO);\n setSelectedTrack(TYPE_VIDEO, TRACK_DISABLED);\n blockingClearSurface();\n } else {\n setSelectedTrack(TYPE_VIDEO, videoTrackToRestore);\n }\n }\n\n /**\n * Build the renderers.\n */\n public void prepare() {\n if (rendererBuildingState == RENDERER_BUILDING_STATE_BUILT) {\n player.stop();\n }\n rendererBuilder.cancel();\n videoFormat = null;\n videoRenderer = null;\n rendererBuildingState = RENDERER_BUILDING_STATE_BUILDING;\n maybeReportPlayerState();\n rendererBuilder.buildRenderers(this);\n }\n\n /**\n * Invoked with the results from a {@link RendererBuilder}.\n *\n * @param renderers Renderers indexed by {@link ExoplayerWrapper} TYPE_* constants. An\n * individual element may be null if there do not exist tracks of the\n * corresponding type.\n * @param bandwidthMeter Provides an estimate of the currently available bandwidth. May be null.\n */\n public void onRenderers(TrackRenderer[] renderers, BandwidthMeter bandwidthMeter) {\n // Normalize the results.\n if (trackNames == null) {\n trackNames = new String[RENDERER_COUNT][];\n }\n\n for (int i = 0; i < RENDERER_COUNT; i++) {\n if (renderers[i] == null) {\n // Convert a null renderer to a dummy renderer.\n renderers[i] = new DummyTrackRenderer();\n }\n }\n\n // Complete preparation.\n this.videoRenderer = renderers[TYPE_VIDEO];\n this.codecCounters = videoRenderer instanceof MediaCodecTrackRenderer\n ? ((MediaCodecTrackRenderer) videoRenderer).codecCounters\n : renderers[TYPE_AUDIO] instanceof MediaCodecTrackRenderer\n ? ((MediaCodecTrackRenderer) renderers[TYPE_AUDIO]).codecCounters : null;\n rendererBuildingState = RENDERER_BUILDING_STATE_BUILT;\n this.bandwidthMeter = bandwidthMeter;\n maybeReportPlayerState();\n pushSurfaceAndVideoTrack(false);\n player.prepare(renderers);\n }\n\n /**\n * Notify the listeners when an exception is thrown.\n * @param e The exception that has been thrown.\n */\n public void onRenderersError(Exception e) {\n if (internalErrorListener != null) {\n internalErrorListener.onRendererInitializationError(e);\n }\n for (PlaybackListener playbackListener : playbackListeners) {\n playbackListener.onError(e);\n }\n rendererBuildingState = RENDERER_BUILDING_STATE_IDLE;\n maybeReportPlayerState();\n }\n\n /**\n * Set whether the player should begin as soon as it is setup.\n * @param playWhenReady If true, playback will start as soon as the player is setup. If false, it\n * must be started programmatically.\n */\n public void setPlayWhenReady(boolean playWhenReady) {\n player.setPlayWhenReady(playWhenReady);\n }\n\n /**\n * Move the seek head to the given position.\n * @param positionMs A number of milliseconds after the start of the video.\n */\n public void seekTo(long positionMs) {\n player.seekTo(positionMs);\n }\n\n /**\n * When you are finished using this object, make sure to call this method.\n */\n public void release() {\n rendererBuilder.cancel();\n rendererBuildingState = RENDERER_BUILDING_STATE_IDLE;\n surface = null;\n player.release();\n }\n\n /**\n * Returns the state of the Exoplayer instance.\n */\n public int getPlaybackState() {\n if (rendererBuildingState == RENDERER_BUILDING_STATE_BUILDING) {\n return ExoPlayer.STATE_PREPARING;\n }\n int playerState = player.getPlaybackState();\n if (rendererBuildingState == RENDERER_BUILDING_STATE_BUILT\n && rendererBuildingState == RENDERER_BUILDING_STATE_IDLE) {\n // This is an edge case where the renderers are built, but are still being passed to the\n // player's playback thread.\n return ExoPlayer.STATE_PREPARING;\n }\n return playerState;\n }\n\n public Format getFormat() {\n return videoFormat;\n }\n\n public BandwidthMeter getBandwidthMeter() {\n return bandwidthMeter;\n }\n\n public CodecCounters getCodecCounters() {\n return codecCounters;\n }\n\n /**\n * Returns the position of the seek head in the number of\n * milliseconds after the start of the video.\n */\n public long getCurrentPosition() {\n return player.getCurrentPosition();\n }\n\n /**\n * Returns the duration of the video in milliseconds.\n */\n public long getDuration() {\n return player.getDuration();\n }\n\n /**\n * Returns the number of the milliseconds of the video that has been buffered.\n */\n public int getBufferedPercentage() {\n return player.getBufferedPercentage();\n }\n\n /**\n * Returns true if the video is set to start as soon as it is set up, returns false otherwise.\n */\n public boolean getPlayWhenReady() {\n return player.getPlayWhenReady();\n }\n\n /**\n * Return the looper of the Exoplayer instance which sits and waits for messages.\n */\n Looper getPlaybackLooper() {\n return player.getPlaybackLooper();\n }\n\n /**\n * Returns the handler which responds to messages.\n */\n Handler getMainHandler() {\n return mainHandler;\n }\n\n public int getTrackCount(int trackType){\n return player.getTrackCount(trackType);\n }\n\n public MediaFormat getTrackFormat(int trackType, int trackIndex){\n return player.getTrackFormat(trackType, trackIndex);\n }\n\n\n @Override\n public void onPlayerStateChanged(boolean playWhenReady, int state) {\n maybeReportPlayerState();\n }\n\n @Override\n public void onPlayerError(ExoPlaybackException exception) {\n rendererBuildingState = RENDERER_BUILDING_STATE_IDLE;\n for (PlaybackListener playbackListener : playbackListeners) {\n playbackListener.onError(exception);\n }\n }\n\n @Override\n public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,\n float pixelWidthHeightRatio) {\n for (PlaybackListener listener : playbackListeners) {\n listener.onVideoSizeChanged(width, height, unappliedRotationDegrees, pixelWidthHeightRatio);\n }\n }\n\n @Override\n public void onDroppedFrames(int count, long elapsed) {\n if (infoListener != null) {\n infoListener.onDroppedFrames(count, elapsed);\n }\n }\n\n @Override\n public void onBandwidthSample(int elapsedMs, long bytes, long bandwidthEstimate) {\n if (infoListener != null) {\n infoListener.onBandwidthSample(elapsedMs, bytes, bandwidthEstimate);\n }\n }\n\n @Override\n public void onDownstreamFormatChanged(int sourceId, Format format, int trigger,\n long mediaTimeMs) {\n if (infoListener == null) {\n return;\n }\n if (sourceId == TYPE_VIDEO) {\n videoFormat = format;\n infoListener.onVideoFormatEnabled(format, trigger, mediaTimeMs);\n } else if (sourceId == TYPE_AUDIO) {\n infoListener.onAudioFormatEnabled(format, trigger, mediaTimeMs);\n }\n }\n\n @Override\n public void onLoadStarted(int sourceId, long length, int type, int trigger, Format format,\n long mediaStartTimeMs, long mediaEndTimeMs) {\n if (infoListener != null) {\n infoListener.onLoadStarted(sourceId, length, type, trigger, format, mediaStartTimeMs,\n mediaEndTimeMs);\n }\n }\n\n @Override\n public void onLoadCompleted(int sourceId, long bytesLoaded, int type, int trigger, Format format,\n long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs,\n long loadDurationMs) {\n if (infoListener != null) {\n infoListener.onLoadCompleted(sourceId, bytesLoaded, type, trigger, format, mediaStartTimeMs,\n mediaEndTimeMs, elapsedRealtimeMs, loadDurationMs);\n }\n }\n\n @Override\n public void onLoadCanceled(int sourceId, long bytesLoaded) {\n // Do nothing.\n }\n\n @Override\n public void onDrmSessionManagerError(Exception e) {\n if (internalErrorListener != null) {\n internalErrorListener.onDrmSessionManagerError(e);\n }\n }\n\n @Override\n public void onDecoderInitializationError(DecoderInitializationException e) {\n if (internalErrorListener != null) {\n internalErrorListener.onDecoderInitializationError(e);\n }\n }\n\n @Override\n public void onAudioTrackInitializationError(AudioTrack.InitializationException e) {\n if (internalErrorListener != null) {\n internalErrorListener.onAudioTrackInitializationError(e);\n }\n }\n\n @Override\n public void onAudioTrackWriteError(AudioTrack.WriteException e) {\n if (internalErrorListener != null) {\n internalErrorListener.onAudioTrackWriteError(e);\n }\n }\n\n @Override\n public void onAudioTrackUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {\n if (internalErrorListener != null) {\n internalErrorListener.onAudioTrackUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);\n }\n }\n\n\n @Override\n public void onCryptoError(CryptoException e) {\n if (internalErrorListener != null) {\n internalErrorListener.onCryptoError(e);\n }\n }\n\n @Override\n public void onDrmKeysLoaded() {\n // Do nothing.\n }\n\n /* package */ MetadataTrackRenderer.MetadataRenderer<List<Id3Frame>> getId3MetadataRenderer() {\n return new MetadataTrackRenderer.MetadataRenderer<List<Id3Frame>>() {\n @Override\n public void onMetadata(List<Id3Frame> metadata) {\n if (id3MetadataListener != null) {\n id3MetadataListener.onId3Metadata(metadata);\n }\n }\n };\n }\n\n @Override\n public void onDecoderInitialized(String decoderName, long elapsedRealtimeMs,\n long initializationDurationMs) {\n if (infoListener != null) {\n infoListener.onDecoderInitialized(decoderName, elapsedRealtimeMs, initializationDurationMs);\n }\n }\n\n @Override\n public void onLoadError(int sourceId, IOException e) {\n if (internalErrorListener != null) {\n internalErrorListener.onLoadError(sourceId, e);\n }\n }\n\n @Override\n public void onCues(List<Cue> cues) {\n if (captionListener != null && getSelectedTrack(TYPE_TEXT) != TRACK_DISABLED) {\n captionListener.onCues(cues);\n }\n }\n\n @Override\n public void onAvailableRangeChanged(int sourceId, TimeRange availableRange) {\n if (infoListener != null) {\n infoListener.onAvailableRangeChanged(sourceId, availableRange);\n }\n }\n\n @Override\n public void onAvailableRangeChanged(TimeRange availableRange){\n if (infoListener != null) {\n infoListener.onAvailableRangeChanged(availableRange);\n }\n }\n\n @Override\n public void onMediaPlaylistLoadCompleted(byte[] bytes) {\n\n }\n\n\n @Override\n public void onPlayWhenReadyCommitted() {\n // Do nothing.\n }\n\n @Override\n public void onDrawnToSurface(Surface surface) {\n // Do nothing.\n }\n\n @Override\n public void onUpstreamDiscarded(int sourceId, long mediaStartTimeMs, long mediaEndTimeMs) {\n // Do nothing.\n }\n\n /**\n * If either playback state or the play when ready values have changed, notify all the playback\n * listeners.\n */\n private void maybeReportPlayerState() {\n boolean playWhenReady = player.getPlayWhenReady();\n int playbackState = getPlaybackState();\n if (lastReportedPlayWhenReady != playWhenReady || lastReportedPlaybackState != playbackState) {\n for (PlaybackListener playbackListener : playbackListeners) {\n playbackListener.onStateChanged(playWhenReady, playbackState);\n }\n lastReportedPlayWhenReady = playWhenReady;\n lastReportedPlaybackState = playbackState;\n }\n }\n\n /**\n * Updated the playback thread with the latest video renderer and surface.\n * @param blockForSurfacePush If true, then message sent to the underlying playback thread is\n * guaranteed to be delivered. However, this is a blocking operation\n */\n private void pushSurfaceAndVideoTrack(boolean blockForSurfacePush) {\n if (rendererBuildingState != RENDERER_BUILDING_STATE_BUILT) {\n return;\n }\n\n if (blockForSurfacePush) {\n player.blockingSendMessage(\n videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface);\n } else {\n player.sendMessage(\n videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface);\n }\n }\n}", "public class RendererBuilderFactory {\n\n /**\n * Create a renderer builder which can build the given video.\n * @param ctx The context (ex {@link android.app.Activity} in whicb the video has been created.\n * @param video The video which will be played.\n * @param mediaDrmCallback DRM Callback.\n * @param preferSoftwareDecoder true if softwareDecoder is requred.\n */\n public static ExoplayerWrapper.RendererBuilder createRendererBuilder(Context ctx,\n Video video,\n MediaDrmCallback mediaDrmCallback,\n boolean preferSoftwareDecoder) {\n switch (video.getVideoType()) {\n case HLS:\n return new HlsRendererBuilder(ctx, ExoplayerUtil.getUserAgent(ctx),\n video.getUrl());\n case DASH:\n return new DashRendererBuilder(ctx, ExoplayerUtil.getUserAgent(ctx),\n video.getUrl(),\n mediaDrmCallback);\n case MP4:\n return new ExtractorRendererBuilder(ctx, ExoplayerUtil.getUserAgent(ctx), Uri.parse(video.getUrl()), preferSoftwareDecoder);\n case OTHER:\n return new ExtractorRendererBuilder(ctx, ExoplayerUtil.getUserAgent(ctx), Uri.parse(video.getUrl()), preferSoftwareDecoder);\n default:\n return null;\n }\n }\n\n\n /**\n * Create a renderer builder which can build the given video.\n * @param ctx The context (ex {@link android.app.Activity} in whicb the video has been created.\n * @param video The video which will be played.\n */\n public static ExoplayerWrapper.RendererBuilder createRendererBuilder(Context ctx,\n Video video,\n MediaDrmCallback mediaDrmCallback) {\n return createRendererBuilder(ctx, video, mediaDrmCallback, false);\n }\n\n public static ExoplayerWrapper.RendererBuilder createRendererBuilder(Context ctx,\n Video video,\n boolean preferSoftwareDecoder) {\n \n return createRendererBuilder(ctx, video, null, preferSoftwareDecoder);\n }\n\n public static ExoplayerWrapper.RendererBuilder createRendererBuilder(Context ctx,\n Video video) {\n\n return createRendererBuilder(ctx, video, null, false);\n }\n}", "public class Video {\n\n /**\n * A list of available video formats which Exoplayer can play.\n */\n public static enum VideoType {\n DASH,\n MP4,\n HLS,\n OTHER\n }\n\n /**\n * The URL pointing to the video.\n */\n private final String url;\n\n /**\n * The video format of the video.\n */\n private final VideoType videoType;\n\n /**\n * ID of content (for DASH).\n */\n private final String contentId;\n\n /**\n * @param url The URL pointing to the video.\n * @param videoType The video format of the video.\n */\n public Video(String url, VideoType videoType) {\n this(url, videoType, null);\n }\n\n /**\n * @param url The URL pointing to the video.\n * @param videoType The video format of the video.\n * @param contentId ID of content (for DASH).\n */\n public Video(String url, VideoType videoType, String contentId) {\n this.url = url;\n this.videoType = videoType;\n this.contentId = contentId;\n }\n\n /**\n * Returns ID of content (for DASH).\n */\n public String getContentId() {\n return contentId;\n }\n\n /**\n * Returns the URL pointing to the video.\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Returns the video format of the video.\n */\n public VideoType getVideoType() {\n return videoType;\n }\n}", "public class PlayerViewController extends RelativeLayout implements KControlsView.KControlsViewClient, KPlayerListener {\n public static String TAG = \"PlayerViewController\";\n\n\n\n private KPlayerController playerController;\n public KControlsView mWebView = null;\n private double mCurSec;\n private Activity mActivity;\n // private OnShareListener mShareListener;\n private JSONObject nativeActionParams;\n private KPPlayerConfig mConfig;\n\n\n private String mIframeUrl = null;\n\n private boolean mWvMinimized = false;\n\n private int newWidth, newHeight;\n\n private boolean mIsJsCallReadyRegistration = false;\n private Set<ReadyEventListener> mCallBackReadyRegistrations;\n private final HashMap<String, ArrayList<HashMap<String, EventListener>>> mPlayerEventsHash = new HashMap<>();\n private HashMap<String, EvaluateListener> mPlayerEvaluatedHash;\n private Set<KPEventListener> eventListeners;\n\n private KPErrorEventListener mOnKPErrorEventListener;\n private KPFullScreenToggledEventListener mOnKPFullScreenToggledEventListener;\n private KPStateChangedEventListener mOnKPStateChangedEventListener;\n private KPPlayheadUpdateEventListener mOnKPPlayheadUpdateEventListener;\n\n private SourceURLProvider mCustomSourceURLProvider;\n private boolean isFullScreen = false;\n private boolean isMediaChanged = false;\n private boolean shouldReplay = false;\n private boolean prepareWithConfigurationMode = false;\n\n private KCastProvider mCastProvider;\n\n public static void prefetchPlayerResources(KPPlayerConfig config, final List<Uri> uriItemsList, final KPrefetchListener prefetchListener, Activity activity) {\n LOGD(TAG, \"Start prefetchPlayerResources\");\n\n final PlayerViewController player = new PlayerViewController(activity);\n\n player.loadPlayerIntoActivity(activity);\n\n config.addConfig(\"EmbedPlayer.PreloadNativeComponent\", \"true\");\n\n player.initWithConfiguration(config);\n\n final CacheManager cacheManager = new CacheManager(activity.getApplicationContext());\n cacheManager.setBaseURL(Utilities.stripLastUriPathSegment(config.getServerURL()));\n cacheManager.setCacheSize(config.getCacheSize());\n if (uriItemsList != null && !uriItemsList.isEmpty()) {\n Thread thread = new Thread(new Runnable() {\n public void run() {\n try {\n for (Uri uriItem : uriItemsList)\n cacheManager.cacheResponse(uriItem);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n thread.start();\n }\n\n player.registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n LOGD(TAG, \"Player ready after prefetch - will now destroy player\");\n player.removePlayer();\n if (prefetchListener != null) {\n prefetchListener.onPrefetchFinished();\n }\n }\n });\n }\n\n public KCastProvider setCastProvider(KCastProvider castProvider) {\n boolean isFirstSetup = true;\n if (mCastProvider != null) { //From 2.50 - //if (mCastProvider != null || (castProvider != null && castProvider.getNumOfConnectedSenders() > 1)) {\n isFirstSetup = false;\n }\n\n mCastProvider = castProvider;\n if (mCastProvider == null) {\n return null;\n }\n mCastProvider.init(mActivity);\n boolean isReconnect = mCastProvider.isReconnected() || mCastProvider.getSelectedCastDevice() != null;\n boolean isCasting = mCastProvider.isCasting();\n if (isCasting || mCastProvider.getSelectedCastDevice() != null) {\n mCastProvider.startReceiver(mActivity);\n }\n\n playerController.setCastProvider(mCastProvider);\n if (isReconnect) {\n mWebView.triggerEvent(\"chromecastDeviceDisConnected\", null);\n }\n mWebView.triggerEvent(\"chromecastDeviceConnected\", \"\" + getCurrentPlaybackTime());\n\n if(isReconnect) { // From 2.50 if(isReconnect && (isCasting || !isFirstSetup)) { // && !isFirstSetup) || mCastProvider.getSessionEntryID() != null) {\n asyncEvaluate(\"{mediaProxy.entry.id}\", \"EntryId\", new PlayerViewController.EvaluateListener() {\n @Override\n public void handler(final String idEvaluateResponse) {\n if (idEvaluateResponse != null && !\"null\".equals(idEvaluateResponse)) {\n pause();\n if (mCastProvider != null && mCastProvider.isCasting()) {\n LOGD(TAG, \"----- Before Sending new AD Tag on CC --------\");\n String newAdTag = getConfig().getConfigValueString(\"doubleClick.adTagUrl\");\n if (newAdTag != null) {\n LOGD(TAG, \"----- Sending new AD Tag to CC --------\");\n ((KCastProviderV3Impl)mCastProvider).sendMessage(\"{\\\"type\\\":\\\"setKDPAttribute\\\",\\\"plugin\\\":\\\"doubleClick\\\",\\\"property\\\":\\\"adTagUrl\\\",\\\"value\\\":\\\"\" + newAdTag + \"\\\"}\");\n }\n }\n if (getConfig().getConfigValueString(\"proxyData\") == null || \"\".equals(getConfig().getConfigValueString(\"proxyData\"))) {\n castChangeMedia(idEvaluateResponse);\n } else {\n try {\n JSONObject changeMediaJSON = new JSONObject();\n JSONObject proxyData = new JSONObject(getConfig().getConfigValueString(\"proxyData\"));\n changeMediaJSON.put(\"entryId\", idEvaluateResponse);\n changeMediaJSON.put(\"proxyData\", proxyData);\n castChangeMedia(changeMediaJSON);\n } catch (JSONException e) {\n LOGE(TAG, \"Error could not create change media proxy dat object\");\n }\n }\n\n }\n }\n });\n }\n return mCastProvider;\n }\n\n public KCastProvider getCastProvider() {\n return mCastProvider;\n }\n\n @Override\n public void setOnTouchListener(OnTouchListener l) {\n if (mWebView != null) {\n mWebView.setOnTouchListener(l);\n }\n }\n\n // trigger timeupdate events\n public interface EventListener {\n void handler(String eventName, String params);\n }\n\n public interface ReadyEventListener {\n void handler();\n }\n\n public interface EvaluateListener {\n void handler(String evaluateResponse);\n }\n\n public interface SourceURLProvider {\n String getURL(String entryId, String currentURL);\n }\n\n public PlayerViewController(Context context) {\n super(context);\n }\n\n public PlayerViewController(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public PlayerViewController(Context context, AttributeSet attrs,\n int defStyle) {\n super(context, attrs, defStyle);\n }\n\n public KMediaControl getMediaControl() {\n return playerController;\n }\n\n public KTrackActions getTrackManager(){\n return playerController.getTracksManager();\n }\n\n public void initWithConfiguration(KPPlayerConfig configuration) {\n mConfig = configuration;\n if (mConfig != null) {\n setComponents(mConfig.getVideoURL());\n }\n }\n\n public void setPrepareWithConfigurationMode(boolean prepareWithConfigurationMode) {\n this.prepareWithConfigurationMode = prepareWithConfigurationMode;\n }\n\n public void loadPlayerIntoActivity(Activity activity) {\n registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n if (eventListeners != null) {\n for (KPEventListener listener: eventListeners) {\n listener.onKPlayerStateChanged(PlayerViewController.this, KPlayerState.PRE_LOADED);\n }\n }\n if (mOnKPStateChangedEventListener != null) {\n mOnKPStateChangedEventListener.onKPlayerStateChanged(PlayerViewController.this, KPlayerState.PRE_LOADED);\n }\n }\n });\n mActivity = activity;\n }\n\n @Deprecated\n public void addEventListener(KPEventListener listener) {\n if (listener != null) {\n if (eventListeners == null) {\n eventListeners = new HashSet<>();\n }\n eventListeners.add(listener);\n }\n }\n\n public void setOnKPErrorEventListener(KPErrorEventListener kpErrorEventListener) {\n mOnKPErrorEventListener = kpErrorEventListener;\n }\n\n public void setOnKPFullScreenToggledEventListener(KPFullScreenToggledEventListener kpFullScreenToggledEventListener) {\n mOnKPFullScreenToggledEventListener = kpFullScreenToggledEventListener;\n }\n\n public void setOnKPStateChangedEventListener(KPStateChangedEventListener kpStateChangedEventListener) {\n mOnKPStateChangedEventListener = kpStateChangedEventListener;\n }\n\n public void setOnKPPlayheadUpdateEventListener(KPPlayheadUpdateEventListener kpPlayheadUpdateEventListener) {\n mOnKPPlayheadUpdateEventListener = kpPlayheadUpdateEventListener;\n }\n\n public KPPlayerConfig getConfig() {\n return mConfig;\n }\n\n public void changeMedia(String entryId) {\n if (entryId != null && entryId.length() > 0) {\n JSONObject entryJson = new JSONObject();\n try {\n isMediaChanged = true;\n entryJson.put(\"entryId\", entryId);\n String jsonString = entryJson.toString();\n playerController.changeMedia();\n sendNotification(\"changeMedia\",jsonString);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void changeMedia(JSONObject proxyData) {\n if (proxyData == null) {\n return;\n }\n isMediaChanged = true;\n playerController.changeMedia();\n sendNotification(\"changeMedia\", proxyData.toString());\n }\n\n public void castChangeMedia(String entryId) {\n if (entryId != null && entryId.length() > 0) {\n JSONObject entryJson = new JSONObject();\n try {\n isMediaChanged = true;\n entryJson.put(\"entryId\", entryId);\n String jsonString = entryJson.toString();\n playerController.castChangeMedia();\n sendNotification(\"changeMedia\",jsonString);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void castChangeMedia(JSONObject proxyData) {\n if (proxyData == null) {\n return;\n }\n isMediaChanged = true;\n playerController.castChangeMedia();\n sendNotification(\"changeMedia\", proxyData.toString());\n }\n\n public void changeConfiguration(KPPlayerConfig config) {\n if (config != null) {\n resetPlayer();\n mConfig = config;\n mWebView.setVisibility(INVISIBLE);\n mWebView.clearCache(true);\n mWebView.clearHistory();\n mWebView.loadUrl(\"about:blank\");\n mWebView.loadUrl(config.getVideoURL() + buildSupportedMediaFormats());\n mIsJsCallReadyRegistration = false;\n registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n mWebView.setVisibility(VISIBLE);\n if (mPlayerEventsHash != null) {\n for (String event : mPlayerEventsHash.keySet()) {\n mWebView.addEventListener(event);\n }\n }\n }\n });\n }\n }\n\n @Deprecated\n public void removeEventListener(KPEventListener listener) {\n if (listener != null && eventListeners != null && eventListeners.contains(listener)) {\n eventListeners.remove(listener);\n }\n }\n\n public void setCustomSourceURLProvider(SourceURLProvider provider) {\n mCustomSourceURLProvider = provider;\n }\n\n private String getOverrideURL(String entryId, String currentURL) {\n if (mCustomSourceURLProvider != null) {\n String overrideURL = mCustomSourceURLProvider.getURL(entryId, currentURL);\n if (overrideURL != null) {\n return overrideURL;\n }\n }\n return currentURL;\n }\n\n public void freeze(){\n if(playerController != null) {\n playerController.pause();\n }\n }\n\n public void saveState() {\n saveState(false);\n }\n\n public void saveState(boolean isOnBackground) {\n playerController.savePlayerState();\n }\n\n public void resumeState() {\n playerController.recoverPlayerState();\n }\n\n /**\n * Release player's instance and save its last position for resuming later on.\n * This method should be called when the main activity is paused.\n */\n public void releaseAndSavePosition() {\n releaseAndSavePosition(false);\n }\n\n public void releaseAndSavePosition(boolean shouldResumeState) {\n if (playerController != null) {\n playerController.removePlayer(shouldResumeState);\n }\n }\n\n public void releaseAndSavePosition(boolean shouldResumeState, boolean mShouldPauseChromecastInBg) {\n if (playerController != null) {\n playerController.removePlayer(shouldResumeState, mShouldPauseChromecastInBg);\n }\n }\n\n public void resetPlayer() {\n if (playerController != null) {\n playerController.reset();\n }\n }\n\n /**\n * Recover from \"releaseAndSavePosition\", reload the player from previous position.\n * This method should be called when the main activity is resumed.\n */\n public void resumePlayer() {\n if (playerController != null) {\n playerController.recoverPlayer();\n }\n }\n\n public void removePlayer() {\n if (playerController != null) {\n playerController.destroy();\n }\n if (mWebView != null) {\n try {\n mWebView.loadUrl(\"about:blank\");\n } catch(NullPointerException e){\n LOGE(TAG, \"WebView NullPointerException caught \" + e.getMessage());\n }\n removeView(mWebView);\n mWebView.destroy();\n }\n }\n\n public void setActivity( Activity activity ) {\n mActivity = activity;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n }\n\n\n// public void setOnShareListener(OnShareListener listener) {\n// mShareListener = listener;\n// }\n\n private void setVolumeLevel(double percent) {//Itay\n AudioManager mgr = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);\n if (percent > 0.01) {\n while (percent < 1.0) {\n percent *= 10;\n }\n }\n mgr.setStreamVolume(AudioManager.STREAM_MUSIC, (int) percent, 0);\n }\n @SuppressLint(\"NewApi\") private Point getRealScreenSize(){\n Display display = mActivity.getWindowManager().getDefaultDisplay();\n int realWidth = 0;\n int realHeight = 0;\n\n if (Build.VERSION.SDK_INT >= 17){\n //new pleasant way to get real metrics\n DisplayMetrics realMetrics = new DisplayMetrics();\n display.getRealMetrics(realMetrics);\n realWidth = realMetrics.widthPixels;\n realHeight = realMetrics.heightPixels;\n\n } else {\n try {\n Method mGetRawH = Display.class.getMethod(\"getRawHeight\");\n Method mGetRawW = Display.class.getMethod(\"getRawWidth\");\n realWidth = (Integer) mGetRawW.invoke(display);\n realHeight = (Integer) mGetRawH.invoke(display);\n } catch (Exception e) {\n realWidth = display.getWidth();\n realHeight = display.getHeight();\n LOGE(TAG, \"Display Info - Couldn't use reflection to get the real display metrics.\");\n }\n\n }\n return new Point(realWidth,realHeight);\n }\n\n /**\n * Sets the player's dimensions. Should be called for any player redraw\n * (for example, in screen rotation, if supported by the main activity)\n * @param width player's width\n * @param height player's height\n * @param xPadding player's X position\n * @param yPadding player's Y position\n * @deprecated Use {@link #setLayoutParams(ViewGroup.LayoutParams)} instead.\n */\n @Deprecated\n public void setPlayerViewDimensions(int width, int height, int xPadding, int yPadding) {\n setPadding(xPadding, yPadding, 0, 0);\n newWidth = width + xPadding;\n newHeight = height + yPadding;\n\n ViewGroup.LayoutParams lp = getLayoutParams();\n if ( lp == null ) {\n lp = new ViewGroup.LayoutParams( newWidth, newHeight );\n } else {\n lp.width = newWidth;\n lp.height = newHeight;\n }\n\n this.setLayoutParams(lp);\n for ( int i = 0; i < this.getChildCount(); i++ ) {\n\n View v = getChildAt(i);\n if( v == playerController.getPlayer() )\n {\n continue;\n }\n ViewGroup.LayoutParams vlp = v.getLayoutParams();\n vlp.width = newWidth;\n if ( (!mWvMinimized || !v.equals( mWebView)) ) {//\n vlp.height = newHeight;\n }\n updateViewLayout(v, vlp);\n }\n\n\n if(mWebView != null) {\n// mWebView.loadUrl(\"javascript:android.onData(NativeBridge.videoPlayer.getControlBarHeight())\");\n mWebView.fetchControlsBarHeight(new KControlsView.ControlsBarHeightFetcher() {\n @Override\n public void fetchHeight(int controlBarHeight) {\n if ( playerController.getPlayer() != null && playerController.getPlayer() instanceof FrameLayout && ((FrameLayout)playerController.getPlayer()).getParent() == PlayerViewController.this ) {\n LayoutParams wvLp = (LayoutParams) ((View) playerController.getPlayer()).getLayoutParams();\n\n if (getPaddingLeft() == 0 && getPaddingTop() == 0) {\n wvLp.addRule(CENTER_IN_PARENT);\n } else {\n wvLp.addRule(CENTER_IN_PARENT, 0);\n }\n float scale = mActivity.getResources().getDisplayMetrics().density;\n controlBarHeight = (int) (controlBarHeight * scale + 0.5f);\n wvLp.height = newHeight - controlBarHeight;\n wvLp.width = newWidth;\n wvLp.addRule(RelativeLayout.ALIGN_PARENT_TOP);\n final LayoutParams lp = wvLp;\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n updateViewLayout((View) playerController.getPlayer(), lp);\n invalidate();\n }\n });\n\n }\n }\n });\n }\n invalidate();\n }\n\n\n /**\n * Sets the player's dimensions. Should be called for any player redraw\n * (for example, in screen rotation, if supported by the main activity)\n * Player's X and Y position will be 0\n * @param width player's width\n * @param height player's height\n * @deprecated Use {@link #setLayoutParams(ViewGroup.LayoutParams)} instead.\n */\n @Deprecated\n public void setPlayerViewDimensions(int width, int height) {\n //noinspection deprecation\n setPlayerViewDimensions(width, height, 0, 0);\n }\n\n private void setChromecastVisiblity() {\n// mWebView.setKDPAttribute(\"chromecast\", \"visible\", ChromecastHandler.routeInfos.size() > 0 ? \"true\" : \"false\");\n }\n\n /*\n * Build player URL and load it to player view\n * @param requestDataSource - RequestDataSource object\n */\n\n /**\n * Build player URL and load it to player view\n * param iFrameUrl- String url\n */\n public void setComponents(String iframeUrl) {\n if(mWebView == null) {\n mWebView = new KControlsView(this.mActivity);\n mWebView.setId(R.id.webView_1);\n mWebView.setKControlsViewClient(this);\n\n mCurSec = 0;\n LayoutParams wvLp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);\n mWebView.setLayoutParams(wvLp);\n setBackgroundColor(Color.BLACK);\n playerController = new KPlayerController(this);\n if (prepareWithConfigurationMode){\n LOGD(TAG,\"setComponents prepareWithConfigurationMode = \" + prepareWithConfigurationMode);\n playerController.setPrepareWithConfigurationMode(true);\n }\n\n this.addView(mWebView);\n\n }\n\n iframeUrl += buildSupportedMediaFormats();\n\n if( mIframeUrl == null || !mIframeUrl.equals(iframeUrl) ) {\n mIframeUrl = iframeUrl;\n Uri uri = Uri.parse(iframeUrl);\n if (mConfig.getCacheSize() > 0) {\n CacheManager cacheManager = new CacheManager(mActivity.getApplicationContext());\n cacheManager.setBaseURL(Utilities.stripLastUriPathSegment(mConfig.getServerURL()));\n cacheManager.setCacheSize(mConfig.getCacheSize());\n cacheManager.setIncludePatterns(mConfig.getCacheConfig().includePatterns);\n mWebView.setCacheManager(cacheManager);\n }\n\n mWebView.loadUrl(iframeUrl);\n }\n }\n\n\n /**\n * create PlayerView / CastPlayer instance according to cast status\n */\n\n private void replacePlayerViewChild( View newChild, View oldChild ) {\n if ( oldChild.getParent().equals( this ) ) {\n this.removeView( oldChild );\n }\n\n if ( this.getChildCount() > 1 ) {\n //last child is the KMediaControl webview\n this.addView( newChild , this.getChildCount() -1, oldChild.getLayoutParams() );\n }\n }\n\n /**\n * slides with animation according the given values\n *\n * @param x\n * x offset to slide\n * @param duration\n * animation time in milliseconds\n */\n public void slideView(int x, int duration) {\n this.animate().xBy(x).setDuration(duration)\n .setInterpolator(new BounceInterpolator());\n }\n\n\n\n // /////////////////////////////////////////////////////////////////////////////////////////////\n // VideoPlayerInterface methods\n // /////////////////////////////////////////////////////////////////////////////////////////////\n// public boolean isPlaying() {\n// return (playerController.getPlayer() != null && playerController.getPlayer().isPlaying());\n// }\n\n /**\n *\n * @return duration in seconds\n */\n public double getDurationSec() {\n double duration = 0;\n if (playerController != null) {\n duration = playerController.getDuration() / 1000;\n }\n return duration;\n }\n\n public String getVideoUrl() {\n String url = null;\n if (playerController != null)\n url = playerController.getSrc();\n\n return url;\n }\n\n public double getCurrentPlaybackTime() {\n if (playerController != null) {\n return playerController.getCurrentPlaybackTime();\n }\n return 0.0;\n }\n\n\n // /////////////////////////////////////////////////////////////////////////////////////////////\n // Kaltura Player external API\n // /////////////////////////////////////////////////////////////////////////////////////////////\n\n// public void sendNotification(String noteName, JSONObject noteBody) {\n// notifyKPlayer(\"sendNotification\", new String[]{noteName, noteBody.toString()});\n// }\n\n\n\n\n /////////////////////////////////////////////////////////////////////////////////////////////////\n /**\n * call js function on NativeBridge.videoPlayer\n *\n * @param action\n * function name\n * @param eventValues\n * function arguments\n */\n private void notifyKPlayer(final String action, final Object[] eventValues) {\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n String values = \"\";\n\n if (eventValues != null) {\n for (int i = 0; i < eventValues.length; i++) {\n if (eventValues[i] instanceof String) {\n values += \"'\" + eventValues[i] + \"'\";\n } else {\n values += eventValues[i].toString();\n }\n if (i < eventValues.length - 1) {\n values += \", \";\n }\n }\n // values = TextUtils.join(\"', '\", eventValues);\n }\n if (mWebView != null) {\n LOGD(TAG, \"NotifyKplayer: \" + values);\n mWebView.loadUrl(\"javascript:NativeBridge.videoPlayer.\"\n + action + \"(\" + values + \");\");\n }\n\n }\n });\n }\n\n\n @Override\n public void handleHtml5LibCall(String functionName, int callbackId, String args) {\n LOGD(TAG + \" handleHtml5LibCall\", functionName + \" \" + args);\n Method bridgeMethod = KStringUtilities.isMethodImplemented(this, functionName);\n Object object = this;\n if (bridgeMethod == null) {\n KPlayer player = playerController.getPlayer();\n bridgeMethod = KStringUtilities.isMethodImplemented(player, functionName);\n object = player;\n }\n if (bridgeMethod != null) {\n try {\n if (args == null) {\n Class<?>[] params = bridgeMethod.getParameterTypes(); // protect case for params mismatch\n if (params.length != 1){\n bridgeMethod.invoke(object);\n }\n else {\n LOGE(TAG, \"Error, handleHtml5LibCall Parameters mismatch for method: \" + functionName + \" number of params = \" + params.length);\n }\n } else {\n bridgeMethod.invoke(object, args);\n }\n } catch (Exception e) {\n LOGE(TAG, \"Error calling bridgeMethod \" + bridgeMethod, e);\n }\n }\n }\n\n @Override\n public void openURL(String url) {\n final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));\n mActivity.startActivity(intent);\n }\n\n @Override\n public void handleKControlsError(KPError error) {\n sendOnKPlayerError(error.getErrorMsg());\n }\n\n //\n @Override\n public void eventWithValue(KPlayer player, String eventName, String eventValue) {\n LOGD(TAG, \"EventWithValue Name: \" + eventName + \" Value: \" + eventValue);\n KStringUtilities event = new KStringUtilities(eventName);\n KPlayerState kState = KPlayerState.getStateForEventName(eventName);\n if ((isMediaChanged && kState == KPlayerState.READY && getConfig().isAutoPlay())) {\n isMediaChanged = false;\n play();\n }\n if (kState == KPlayerState.SEEKED && shouldReplay) {\n shouldReplay = false;\n play();\n }\n if (eventListeners != null) {\n for (KPEventListener listener : eventListeners) {\n if (!KPlayerState.UNKNOWN.equals(kState)) {\n if (kState == KPlayerState.READY && \"CC\".equals(eventValue)) {\n listener.onKPlayerStateChanged(this, KPlayerState.CC_READY);\n eventValue = null;\n } else {\n listener.onKPlayerStateChanged(this, kState);\n }\n } else if (event.isTimeUpdate()) {\n listener.onKPlayerPlayheadUpdate(this, Float.parseFloat(eventValue));\n } else if (event.isEnded()) {\n listener.onKPlayerStateChanged(this, KPlayerState.ENDED);\n }\n }\n }\n\n if (mOnKPStateChangedEventListener != null) {\n if (!KPlayerState.UNKNOWN.equals(kState)) {\n if (kState == KPlayerState.READY && \"CC\".equals(eventValue)) {\n mOnKPStateChangedEventListener.onKPlayerStateChanged(this, KPlayerState.CC_READY);\n eventValue = null;\n } else {\n mOnKPStateChangedEventListener.onKPlayerStateChanged(this, kState);\n }\n }\n }\n\n if (mOnKPPlayheadUpdateEventListener != null) {\n if (event.isTimeUpdate()) {\n mOnKPPlayheadUpdateEventListener.onKPlayerPlayheadUpdate(this, (long) (Float.parseFloat(eventValue) * 1000));\n }\n }\n\n if(KPlayerListener.ErrorKey.equals(eventName) && !getConfig().isWebDialogEnabled()) {\n LOGE(TAG, \"blocking Dialog for: \" + eventValue);\n if (eventValue.contains(\"Socket\")) {\n String isExternalAdPlayer = getConfig().getConfigValueString(\"EmbedPlayer.UseExternalAdPlayer\");\n if (player != null && isExternalAdPlayer != null && \"true\".equals(isExternalAdPlayer)) {\n setPrepareWithConfigurationMode(false);\n player.setPrepareWithConfigurationModeOff();\n }\n asyncEvaluate(\"{mediaProxy.entry.id}\", \"EntryId\", new PlayerViewController.EvaluateListener() {\n @Override\n public void handler(final String idEvaluateResponse) {\n if (idEvaluateResponse != null && !\"null\".equals(idEvaluateResponse)) {\n if (getConfig().getConfigValueString(\"proxyData\") == null || \"\".equals(getConfig().getConfigValueString(\"proxyData\"))) {\n changeMedia(idEvaluateResponse);\n } else {\n try {\n JSONObject changeMediaJSON = new JSONObject();\n JSONObject proxyData = new JSONObject(getConfig().getConfigValueString(\"proxyData\"));\n changeMediaJSON.put(\"entryId\", idEvaluateResponse);\n changeMediaJSON.put(\"proxyData\", proxyData);\n changeMedia(changeMediaJSON);\n } catch (JSONException e) {\n LOGE(TAG, \"Error could not create change media proxy dat object\");\n }\n }\n }\n }\n });\n }\n\n sendOnKPlayerError(eventValue);\n return;\n }\n this.mWebView.triggerEvent(eventName, eventValue);\n }\n\n @Override\n public void eventWithJSON(KPlayer player, String eventName, String jsonValue) {\n this.mWebView.triggerEventWithJSON(eventName, jsonValue);\n }\n\n private void play() {\n playerController.play();\n }\n\n private void pause() {\n playerController.pause();\n }\n\n public void registerReadyEvent(ReadyEventListener listener) {\n if (mIsJsCallReadyRegistration) {\n listener.handler();\n } else {\n if (mCallBackReadyRegistrations == null && listener != null) {\n mCallBackReadyRegistrations = new HashSet<>();\n }\n mCallBackReadyRegistrations.add(listener);\n }\n }\n\n public void addKPlayerEventListener(final String event, final String eventID, final EventListener listener) {\n this.registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n ArrayList<HashMap<String, EventListener>> listenerArr = (ArrayList)mPlayerEventsHash.get(event);\n if (listenerArr == null) {\n listenerArr = new ArrayList();\n }\n HashMap<String, EventListener> addedEvent = new HashMap();\n addedEvent.put(eventID, listener);\n listenerArr.add(addedEvent);\n mPlayerEventsHash.put(event, listenerArr);\n if (listenerArr.size() == 1 && !KStringUtilities.isToggleFullScreen(event)) {\n mWebView.addEventListener(event);\n }\n }\n });\n }\n\n public void removeKPlayerEventListener(String event,String eventID) {\n if (mPlayerEventsHash == null) {\n return;\n }\n ArrayList<HashMap<String, EventListener>> listenerArr = mPlayerEventsHash.get(event);\n if (listenerArr == null || listenerArr.size() == 0) {\n return;\n }\n ArrayList<HashMap<String, EventListener>> temp = new ArrayList<HashMap<String, EventListener>>(listenerArr);\n for (HashMap<String, EventListener> hash: temp) {\n if (hash.keySet().toArray()[hash.keySet().size() - 1].equals(eventID)) {\n listenerArr.remove(hash);\n }\n }\n if (listenerArr.size() == 0) {\n listenerArr = null;\n if (!KStringUtilities.isToggleFullScreen(event)) {\n mWebView.removeEventListener(event);\n }\n }\n }\n\n @Override\n public void asyncEvaluate(String expression, String expressionID, EvaluateListener evaluateListener) {\n if (mPlayerEvaluatedHash == null) {\n mPlayerEvaluatedHash = new HashMap<String, EvaluateListener>();\n }\n mPlayerEvaluatedHash.put(expressionID, evaluateListener);\n //mWebView.triggerEvent(\"asyncEvaluate\", expression);\n mWebView.evaluate(expression, expressionID);\n }\n\n public void sendNotification(String notificationName,@Nullable String params) {\n if (mWebView != null) {\n if (notificationName == null) {\n notificationName = \"null\";\n }\n mWebView.sendNotification(notificationName, params);\n }\n }\n\n public void setKDPAttribute(final String pluginName, final String propertyName, final String value) {\n registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n mWebView.setKDPAttribute(pluginName, propertyName, value);\n }\n });\n }\n\n public void setStringKDPAttribute(final String pluginName, final String propertyName, final String value) {\n registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n mWebView.setStringKDPAttribute(pluginName, propertyName, value);\n }\n });\n }\n\n public void setKDPAttribute(final String pluginName, final String propertyName, final JSONObject value) {\n registerReadyEvent(new ReadyEventListener() {\n @Override\n public void handler() {\n mWebView.setKDPAttribute(pluginName, propertyName, value);\n }\n });\n }\n\n public void triggerEvent(String event, String value) {\n mWebView.triggerEvent(event, value);\n }\n\n /// Bridge methods\n private void setAttribute(String argsString) {\n String[] args = KStringUtilities.fetchArgs(argsString);\n if (args != null && args.length == 2) {\n String attributeName = args[0];\n String attributeValue = args[1];\n\n KStringUtilities.Attribute attribute = KStringUtilities.attributeEnumFromString(attributeName);\n if (attribute == null) {\n return;\n }\n LOGD(TAG, \"setAttribute Attribute: \" + attribute + \" \" + attributeValue);\n switch (attribute) {\n case src:\n playerController.setEntryMetadata();\n // attributeValue is the selected source -- allow override.\n attributeValue = getOverrideURL(mConfig.getEntryId(), attributeValue);\n playerController.setSrc(attributeValue);\n if (mConfig.getContentPreferredBitrate() != -1) {\n playerController.setContentPreferredBitrate(mConfig.getContentPreferredBitrate());\n }\n if (mConfig.getMediaPlayFrom() > 0) {\n playerController.setCurrentPlaybackTime((float) mConfig.getMediaPlayFrom());\n }\n break;\n case currentTime:\n if (eventListeners != null) {\n for (KPEventListener listener : eventListeners) {\n listener.onKPlayerStateChanged(this, KPlayerState.SEEKING);\n }\n }\n if (mOnKPStateChangedEventListener != null) {\n mOnKPStateChangedEventListener.onKPlayerStateChanged(this, KPlayerState.SEEKING);\n }\n float time = Float.parseFloat(attributeValue);\n playerController.setCurrentPlaybackTime(time);\n break;\n case visible:\n this.triggerEvent(\"visible\", attributeValue);\n break;\n case licenseUri:\n playerController.setLicenseUri(attributeValue);\n break;\n case nativeAction:\n doNativeAction(attributeValue);\n break;\n case language:\n playerController.setLocale(attributeValue);\n break;\n case doubleClickRequestAds:\n String useExternalAdPlayer = getConfig().getConfigValueString(\"EmbedPlayer.UseExternalAdPlayer\");\n if(\"true\".equals(useExternalAdPlayer)) {\n return;\n }\n LOGD(TAG, \"IMA doubleClickRequestAds initialize:\" + attributeValue);\n playerController.initIMA(attributeValue, mConfig.getAdMimeType(), mConfig.getAdPreferredBitrate(), mActivity);\n break;\n case goLive:\n (playerController.getPlayer()).switchToLive();\n break;\n case chromecastAppId:\n //getRouterManager().initialize(attributeValue);\n LOGD(TAG, \"chromecast.initialize:\" + attributeValue);\n break;\n case playerError:\n sendOnKPlayerError(attributeValue);\n break;\n case textTrackSelected:\n LOGD(TAG, \"textTrackSelected\");\n if (attributeValue == null){\n return;\n }\n if (mCastProvider != null) {\n if (\"Off\".equalsIgnoreCase(attributeValue)) {\n mCastProvider.getCastMediaRemoteControl().switchTextTrack(0);\n } else {\n for (String lang : mCastProvider.getCastMediaRemoteControl().getTextTracks().keySet()) {\n if (lang.equals(attributeValue)) {\n mCastProvider.getCastMediaRemoteControl().switchTextTrack(mCastProvider.getCastMediaRemoteControl().getTextTracks().get(lang));\n break;\n }\n }\n }\n }\n\n if (\"Off\".equalsIgnoreCase(attributeValue)) {\n getTrackManager().switchTrack(TrackType.TEXT, -1);\n return;\n }\n for (int index = 0; index < getTrackManager().getTextTrackList().size(); index++) {\n //LOGD(TAG, \"<\" + getTrackManager().getTextTrackList().get(index) + \">/<\" + attributeValue + \">\");\n if ((getTrackManager().getTextTrackList().get(index).trackLabel).equals(attributeValue)) {\n getTrackManager().switchTrack(TrackType.TEXT, index);\n return;\n }\n }\n\n break;\n case audioTrackSelected:\n LOGD(TAG, \"audioTrackSelected\");\n switchAudioTrack(attributeValue);\n break;\n }\n }\n }\n\n\n private void sendOnKPlayerError(String attributeValue) {\n if (eventListeners != null) {\n for (KPEventListener listener : eventListeners) {\n LOGD(TAG, \"sendOnKPlayerError:\" + attributeValue);\n listener.onKPlayerError(this, new KPError(attributeValue));\n }\n }\n if (mOnKPErrorEventListener != null){\n mOnKPErrorEventListener.onKPlayerError(this, new KPError(attributeValue));\n }\n }\n\n private void switchFlavor(String index) {\n try {\n index = URLDecoder.decode(index, \"UTF-8\").replaceAll(\"\\\"\", \"\"); // neend to unescape\n\n } catch (UnsupportedEncodingException e) {\n return;\n }\n switchTrack(TrackType.VIDEO,index);\n }\n\n private void switchAudioTrack(String index) {\n\n switchTrack(TrackType.AUDIO,index);\n }\n\n private void selectClosedCaptions(String index) {\n switchTrack(TrackType.TEXT, index);\n }\n\n\n private void switchTrack(TrackType trackType, String index) {\n int trackIndex = -1;\n\n try {\n trackIndex = Integer.parseInt(index);\n if (TrackType.VIDEO.equals(trackType) || TrackType.AUDIO.equals(trackType)) {\n if (mCastProvider != null && mCastProvider.isCasting()) {\n LOGD(TAG, \"switchTrack \" + trackType.name() + \" is not supported while casting...\");\n return;\n }\n if (trackIndex < 0) {\n trackIndex = 0;\n }\n }\n } catch (NumberFormatException e) {\n LOGE(TAG, \"switchTrack \" + trackType.name() + \" failed parsing index, ignoring request\" + index);\n return;\n }\n getTrackManager().switchTrack(trackType, trackIndex);\n }\n\n public void setTracksEventListener(KTrackActions.EventListener tracksEventListener){\n playerController.setTracksEventListener(tracksEventListener);\n }\n\n public void removeTracksEventListener(){\n playerController.setTracksEventListener(null);\n }\n\n public void setVideoTrackEventListener(KTrackActions.VideoTrackEventListener videoTrackEventListener){\n playerController.setVideoTrackEventListener(videoTrackEventListener);\n }\n\n public void removeVideoTrackEventListener(){\n playerController.setVideoTrackEventListener(null);\n }\n\n public void setAudioTrackEventListener(KTrackActions.AudioTrackEventListener audioTrackEventListener){\n playerController.setAudioTrackEventListener(audioTrackEventListener);\n }\n\n public void removeAusioTrackEventListener(){\n playerController.setAudioTrackEventListener(null);\n }\n\n public void setTextTrackEventListener(KTrackActions.TextTrackEventListener textTrackEventListener){\n playerController.setTextTrackEventListener(textTrackEventListener);\n }\n\n public void removeTextTrackEventListener(){\n playerController.setTextTrackEventListener(null);\n }\n\n private void notifyJsReady() {\n mIsJsCallReadyRegistration = true;\n if (mCallBackReadyRegistrations != null) {\n ArrayList<ReadyEventListener> temp = new ArrayList<ReadyEventListener>(mCallBackReadyRegistrations);\n for (ReadyEventListener listener: temp) {\n listener.handler();\n mCallBackReadyRegistrations.remove(listener);\n }\n temp = null;\n mCallBackReadyRegistrations = null;\n }\n }\n\n private void notifyKPlayerEvent(String args) {\n String[] arguments = KStringUtilities.fetchArgs(args);\n if (arguments.length == 2) {\n String eventName = arguments[0];\n String params = arguments[1];\n ArrayList<HashMap<String, EventListener>> listenerArr = mPlayerEventsHash.get(eventName);\n if (listenerArr != null) {\n for (HashMap<String, EventListener> hash: listenerArr) {\n ((EventListener)hash.values().toArray()[hash.values().size() - 1]).handler(eventName, params);\n }\n }\n }\n }\n\n private void notifyKPlayerEvaluated(String args) {\n String[] arguments = KStringUtilities.fetchArgs(args);\n if (arguments.length == 2) {\n EvaluateListener listener = mPlayerEvaluatedHash.get(arguments[0]);\n if (listener != null) {\n listener.handler(arguments[1]);\n }\n } else {\n LOGD(TAG, \"AsyncEvaluate Error Missing evaluate params\");\n }\n }\n\n private void notifyLayoutReady() {\n setChromecastVisiblity();\n }\n\n private void toggleFullscreen() {\n isFullScreen = !isFullScreen;\n if (eventListeners != null) {\n for (KPEventListener listener : eventListeners) {\n listener.onKPlayerFullScreenToggeled(this, isFullScreen);\n }\n }\n if (mOnKPFullScreenToggledEventListener != null) {\n mOnKPFullScreenToggledEventListener.onKPlayerFullScreenToggled(this, isFullScreen);\n }\n\n if (eventListeners == null && mOnKPFullScreenToggledEventListener == null) {\n defaultFullscreenToggle();\n }\n }\n\n\n private void defaultFullscreenToggle() {\n\n int uiOptions = mActivity.getWindow().getDecorView().getSystemUiVisibility();\n int newUiOptions = uiOptions;\n newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;\n newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;\n newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n if (isFullScreen) {\n LOGD(TAG,\"Set to onOpenFullScreen\");\n sendNotification(\"onOpenFullScreen\", null);\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {\n mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);\n mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);\n\n }else{\n mActivity.getWindow().getDecorView().setSystemUiVisibility(newUiOptions);\n }\n ((AppCompatActivity) mActivity).getSupportActionBar().hide();\n } else {\n LOGD(TAG,\"Set to onCloseFullScreen\");\n sendNotification(\"onCloseFullScreen\", null);\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {\n mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);\n mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);\n }else{\n mActivity.getWindow().getDecorView().setSystemUiVisibility(newUiOptions);\n }\n ((AppCompatActivity) mActivity).getSupportActionBar().show();\n }\n // set landscape\n // if(fullscreen) activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);\n // else activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);\n }\n\n\n private void sendCCRecieverMessage(String args) {\n if (mCastProvider == null) {\n return;\n }\n\n String decodeArgs = null;\n try {\n decodeArgs = URLDecoder.decode(args, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n LOGD(TAG, \"sendCCRecieverMessage : \" + decodeArgs);\n ((KCastProviderV3Impl)mCastProvider).sendMessage(decodeArgs);\n }\n\n private void loadCCMedia() {\n// getRouterManager().sendMessage(jsonArgs.getString(0), jsonArgs.getString(1));\n }\n\n private void bindPlayerEvents() {\n\n }\n\n private void doNativeAction(String params) {\n try {\n nativeActionParams = new JSONObject(params);\n LOGD(TAG, \"doNativeAction: \" + nativeActionParams.toString());\n String actionTypeJSONValue = null;\n actionTypeJSONValue = nativeActionParams.getString(\"actionType\");\n if (actionTypeJSONValue.equals(NativeActionType.OPEN_URL.toString())) {\n String urlJSONValue = nativeActionParams.getString(\"url\");\n openURL(urlJSONValue);\n } else {\n LOGE(TAG, \"Error, action type: \" + nativeActionParams.getString(\"actionType\") + \" is not supported\");\n }\n\n if (actionTypeJSONValue.equals(NativeActionType.SHARE.toString())) {\n if (nativeActionParams.has(NativeActionType.SHARE_NETWORK.toString())) {\n // if (!mShareListener.onShare(videoUrl, type, videoName)){\n ShareManager.share(nativeActionParams, mActivity);\n //}\n }\n else{\n share(nativeActionParams);\n }\n return;\n }\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n private String buildSupportedMediaFormats() {\n Set<KMediaFormat> supportedFormats = KPlayerController.supportedFormats(getContext());\n\n Set<String> drmTypes = new HashSet<>();\n Set<String> allTypes = new HashSet<>();\n\n for (KMediaFormat format : supportedFormats) {\n if (format.drm != null) {\n drmTypes.add(format.shortName);\n }\n allTypes.add(format.shortName);\n }\n\n return new Uri.Builder()\n .appendQueryParameter(\"nativeSdkDrmFormats\", TextUtils.join(\",\", drmTypes))\n .appendQueryParameter(\"nativeSdkAllFormats\", TextUtils.join(\",\", allTypes))\n .build().getQuery();\n }\n\n // Native actions\n private void share(JSONObject shareParams) {\n// if(mShareListener != null){\n// try {\n// String videoUrl = (String)shareParams.get(\"sharedLink\");\n// String videoName = (String)shareParams.get(\"videoName\");\n// ShareManager.SharingType type = ShareStrategyFactory.getType(shareParams);\n// if (!mShareListener.onShare(videoUrl, type, videoName)){\n// ShareManager.share(shareParams, mActivity);\n// }\n// } catch (JSONException e) {\n// e.printStackTrace();\n// }\n// }else {\n// ShareManager.share(shareParams, mActivity);\n// }\n }\n\n public void attachView() {\n playerController.attachView();\n }\n\n public void detachView() {\n playerController.detachView();\n }\n\n}", "public class TrackFormat {\n public static String TAG = \"TrackFormat\";\n\n public int index;\n public TrackType trackType;\n public String trackId;\n public int bitrate;\n public int channelCount;\n public int sampleRate;\n public int height;\n public int width;\n public String mimeType;\n public String trackLabel;\n public String language;\n public boolean adaptive;\n\n\n public TrackFormat(TrackType trackType, int index, MediaFormat mediaFormat){\n this.index = index;\n this.trackType = trackType;\n if (mediaFormat != null) {\n this.trackId = mediaFormat.trackId;\n this.bitrate = mediaFormat.bitrate;\n this.channelCount = mediaFormat.channelCount;\n this.sampleRate = mediaFormat.sampleRate;\n this.height = mediaFormat.height;\n this.width = mediaFormat.width;\n this.mimeType = mediaFormat.mimeType;\n this.language = mediaFormat.language;\n this.adaptive = mediaFormat.adaptive;\n this.trackLabel = getTrackName();\n }\n\n }\n\n public void setTrackLabel(String newLabel) {\n this.trackLabel = newLabel;\n }\n\n public String getTrackName() {\n if (adaptive) {\n return \"auto\" + \"-\" + index;\n }\n String trackName;\n if (MimeTypes.isVideo(mimeType)) {\n trackName = joinWithSeparator(joinWithSeparator(buildResolutionString(),\n buildBitrateString()), buildTrackIdString());\n\n } else if (MimeTypes.isAudio(mimeType)) {\n trackName = buildTrackIdString();\n if (!\"\".equals(buildLanguageString())){\n trackName = buildLanguageString();\n }\n } else {\n trackName = buildTrackIdString();\n if (!\"\".equals(buildLanguageString())){\n trackName = buildLanguageString();\n }\n }\n return trackName.length() == 0 ? \"unknown\" : trackName;\n }\n\n public String getTrackLanguage() {\n return this.language.length() == 0 ? \"unknown\" : this.language;\n }\n\n public String getTrackFullName() {\n if (adaptive) {\n return \"auto\" + \"-\" + index;\n }\n String trackName;\n if (MimeTypes.isVideo(mimeType)) {\n trackName = joinWithSeparator(joinWithSeparator(buildResolutionString(),\n buildBitrateString()), buildTrackIdString());\n\n } else if (MimeTypes.isAudio(mimeType)) {\n trackName = buildTrackIdString();\n } else {\n trackName = buildTrackIdString();\n }\n return trackName.length() == 0 ? \"unknown\" : trackName;\n\n }\n\n private String buildResolutionString() {\n return this.width == MediaFormat.NO_VALUE || this.height == MediaFormat.NO_VALUE\n ? \"\" : this.width + \"x\" + this.height;\n }\n\n private String buildAudioPropertyString() {\n return this.channelCount == MediaFormat.NO_VALUE || this.sampleRate == MediaFormat.NO_VALUE\n ? \"\" : this.channelCount + \"ch, \" + this.sampleRate + \"Hz\";\n }\n\n private String buildLanguageString() {\n return TextUtils.isEmpty(this.language) || \"und\".equals(this.language) ? \"\"\n : this.language;\n }\n\n private String buildBitrateString() {\n return this.bitrate == MediaFormat.NO_VALUE ? \"\"\n : String.format(Locale.US, \"%.2fMbit\", this.bitrate / 1000000f);\n }\n\n private String joinWithSeparator(String first, String second) {\n return first.length() == 0 ? second : (second.length() == 0 ? first : first + \", \" + second);\n }\n\n private String buildTrackIdString() {\n return this.trackId == null ? \"\" : this.trackId;\n }\n\n private int getExoTrackType(TrackType trackType) {\n int exoTrackType = ExoplayerWrapper.TRACK_DISABLED;\n switch (trackType){\n case AUDIO:\n exoTrackType = ExoplayerWrapper.TYPE_AUDIO;\n break;\n case VIDEO:\n exoTrackType = ExoplayerWrapper.TYPE_VIDEO;\n break;\n case TEXT:\n exoTrackType = ExoplayerWrapper.TYPE_TEXT;\n break;\n }\n return exoTrackType;\n }\n\n public JSONObject toJSONObject() {\n JSONObject jsonObject = new JSONObject();\n try {\n if (TrackType.VIDEO.equals(trackType)) {\n jsonObject.put(\"assetid\", String.valueOf(this.index));\n jsonObject.put(\"originalIndex\", this.index);\n jsonObject.put(\"bandwidth\", this.bitrate);\n jsonObject.put(\"type\", this.mimeType);\n jsonObject.put(\"height\", this.height);\n jsonObject.put(\"width\", this.width);\n } else if (TrackType.AUDIO.equals(trackType) || TrackType.TEXT.equals(trackType)){\n // need id???\n // need mode???\n jsonObject.put(\"index\", this.index);\n jsonObject.put(\"kind\", \"subtitle\");\n jsonObject.put(\"label\", this.trackLabel);\n jsonObject.put(\"language\", this.language);\n jsonObject.put(\"title\", getTrackFullName());\n String trackId = (this.trackId != null) ? this.trackId: \"Auto\";\n jsonObject.put(\"srclang\", this.trackLabel); // maybe trackId???\n }\n } catch (JSONException e) {\n e.printStackTrace();\n return null;\n }\n return jsonObject;\n }\n\n public static TrackFormat getDefaultTrackFormat(TrackType trackType) {\n TrackFormat defaultTrackFormat = new TrackFormat(trackType, -1, null);\n defaultTrackFormat.trackLabel = \"Off\";\n return defaultTrackFormat;\n }\n\n @Override\n public String toString() {\n return \"TrackFormat{\" +\n \"index=\" + index +\n \", trackType=\" + trackType +\n \", trackId='\" + trackId + '\\'' +\n \", bitrate=\" + bitrate +\n \", channelCount=\" + channelCount +\n \", sampleRate=\" + sampleRate +\n \", height=\" + height +\n \", width=\" + width +\n \", mimeType='\" + mimeType + '\\'' +\n \", trackLabel='\" + trackLabel + '\\'' +\n \", language='\" + language + '\\'' +\n \", adaptive=\" + adaptive +\n '}';\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 TrackFormat that = (TrackFormat) o;\n\n if (index != that.index) return false;\n if (bitrate != that.bitrate) return false;\n if (channelCount != that.channelCount) return false;\n if (sampleRate != that.sampleRate) return false;\n if (height != that.height) return false;\n if (width != that.width) return false;\n if (adaptive != that.adaptive) return false;\n if (trackType != that.trackType) return false;\n if (!trackId.equals(that.trackId)) return false;\n if (mimeType != null ? !mimeType.equals(that.mimeType) : that.mimeType != null)\n return false;\n if (!trackLabel.equals(that.trackLabel)) return false;\n return language != null ? language.equals(that.language) : that.language == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = index;\n result = 31 * result + trackType.hashCode();\n result = 31 * result + trackId.hashCode();\n result = 31 * result + bitrate;\n result = 31 * result + channelCount;\n result = 31 * result + sampleRate;\n result = 31 * result + height;\n result = 31 * result + width;\n result = 31 * result + (mimeType != null ? mimeType.hashCode() : 0);\n result = 31 * result + trackLabel.hashCode();\n result = 31 * result + (language != null ? language.hashCode() : 0);\n result = 31 * result + (adaptive ? 1 : 0);\n return result;\n }\n}" ]
import android.annotation.TargetApi; import android.content.Context; import android.media.MediaDrm; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.Surface; import android.view.SurfaceHolder; import android.view.accessibility.CaptioningManager; import android.widget.FrameLayout; import com.google.android.exoplayer.BehindLiveWindowException; import com.google.android.exoplayer.ExoPlaybackException; import com.google.android.exoplayer.ExoPlayer; import com.google.android.exoplayer.MediaCodecTrackRenderer; import com.google.android.exoplayer.MediaCodecUtil; import com.google.android.exoplayer.drm.UnsupportedDrmException; import com.google.android.exoplayer.metadata.id3.GeobFrame; import com.google.android.exoplayer.metadata.id3.Id3Frame; import com.google.android.exoplayer.metadata.id3.PrivFrame; import com.google.android.exoplayer.metadata.id3.TxxxFrame; import com.google.android.exoplayer.text.CaptionStyleCompat; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.SubtitleLayout; import com.google.android.exoplayer.util.Util; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerUtil; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerWrapper; import com.google.android.libraries.mediaframework.exoplayerextensions.RendererBuilderFactory; import com.google.android.libraries.mediaframework.exoplayerextensions.Video; import com.google.android.libraries.mediaframework.layeredvideo.VideoSurfaceView; import com.kaltura.playersdk.PlayerViewController; import com.kaltura.playersdk.tracks.TrackFormat; import com.kaltura.playersdk.tracks.TrackType; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE;
package com.kaltura.playersdk.players; /** * Created by noamt on 18/01/2016. */ public class KExoPlayer extends FrameLayout implements KPlayer, ExoplayerWrapper.PlaybackListener ,ExoplayerWrapper.CaptionListener, ExoplayerWrapper.Id3MetadataListener { private static final String TAG = "KExoPlayer"; private static final long PLAYHEAD_UPDATE_INTERVAL = 200; @NonNull private KPlayerListener mPlayerListener = noopPlayerListener(); @NonNull private KPlayerCallback mPlayerCallback = noopEventListener(); @NonNull private PlayerState mSavedState = new PlayerState(); @NonNull private Handler mPlaybackTimeReporter = new Handler(Looper.getMainLooper()); private String mSourceURL; private boolean mShouldCancelPlay; private ExoplayerWrapper mExoPlayer; private KState mReadiness = KState.IDLE; private KPlayerExoDrmCallback mDrmCallback; private VideoSurfaceView mSurfaceView; private com.google.android.exoplayer.text.SubtitleLayout mSubtView; private boolean mSeeking; private boolean mBuffering = false; private boolean mPassedPlay = false; private boolean prepareWithConfigurationMode = false; private boolean isFirstPlayback = true; private SurfaceHolder.Callback mSurfaceCallback; public static Set<KMediaFormat> supportedFormats(Context context) { Set<KMediaFormat> set = new HashSet<>(); // Clear dash and mp4 are always supported by this player. set.add(KMediaFormat.dash_clear); set.add(KMediaFormat.mp4_clear); set.add(KMediaFormat.hls_clear); // Encrypted dash is only supported in Android v4.3 and up -- needs MediaDrm class. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { // Make sure Widevine is supported. if (MediaDrm.isCryptoSchemeSupported(ExoplayerUtil.WIDEVINE_UUID)) { set.add(KMediaFormat.dash_widevine); } } return set; } public KExoPlayer(Context context) { super(context); } private KPlayerListener noopPlayerListener() { return new KPlayerListener() { public void eventWithValue(KPlayer player, String eventName, String eventValue) {} public void eventWithJSON(KPlayer player, String eventName, String jsonValue) {} public void asyncEvaluate(String expression, String expressionID, PlayerViewController.EvaluateListener evaluateListener) {} public void contentCompleted(KPlayer currentPlayer) {} }; } private KPlayerCallback noopEventListener() { return new KPlayerCallback() { public void playerStateChanged(int state) {} }; } // KPlayer implementation @Override public void setPlayerListener(@NonNull KPlayerListener listener) { mPlayerListener = listener; } @Override public void setPlayerCallback(@NonNull KPlayerCallback callback) { mPlayerCallback = callback; } @Override public void setPlayerSource(String playerSource) { mSourceURL = playerSource; mReadiness = KState.IDLE; isFirstPlayback = true; prepare(); } private Video.VideoType getVideoType() { String videoFileName = Uri.parse(mSourceURL).getLastPathSegment(); switch (videoFileName.substring(videoFileName.lastIndexOf('.')).toLowerCase()) { case ".mpd": return Video.VideoType.DASH; case ".mp4": return Video.VideoType.MP4; case ".m3u8": return Video.VideoType.HLS; default: return Video.VideoType.OTHER; } } @Override public boolean isPlaying() { return mExoPlayer != null && mExoPlayer.getPlayWhenReady(); } @Override public void switchToLive() { mExoPlayer.seekTo(0); } private void prepare() { if (mReadiness != KState.IDLE) { LOGD(TAG, "Already preparing"); return; } mReadiness = KState.PREPARING; boolean offline = mSourceURL.startsWith("file://"); mDrmCallback = new KPlayerExoDrmCallback(getContext(), offline); Video video = new Video(mSourceURL, getVideoType());
final ExoplayerWrapper.RendererBuilder rendererBuilder = RendererBuilderFactory
1
gomathi/merkle-tree
test/org/hashtrees/test/HashTreesStoreTest.java
[ "@ThreadSafe\npublic class HashTreesMemStore extends HashTreesBaseStore {\n\n\tprivate final ConcurrentMap<Long, HashTreeMemStore> treeIdAndIndHashTree = new ConcurrentHashMap<>();\n\n\tprivate static class HashTreeMemStore {\n\t\tprivate final ConcurrentMap<Integer, ByteBuffer> segmentHashes = new ConcurrentSkipListMap<Integer, ByteBuffer>();\n\t\tprivate final ConcurrentSkipListMap<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>> segDataBlocks = new ConcurrentSkipListMap<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>();\n\t\tprivate final AtomicLong lastRebuiltTS = new AtomicLong(0);\n\t\tprivate final AtomicBitSet markedSegments = new AtomicBitSet();\n\t}\n\n\tprivate HashTreeMemStore getIndHTree(long treeId) {\n\t\tif (!treeIdAndIndHashTree.containsKey(treeId))\n\t\t\ttreeIdAndIndHashTree.putIfAbsent(treeId, new HashTreeMemStore());\n\t\treturn treeIdAndIndHashTree.get(treeId);\n\t}\n\n\t@Override\n\tpublic SegmentData getSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tConcurrentSkipListMap<ByteBuffer, ByteBuffer> segDataBlock = getIndHTree(treeId).segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock != null) {\n\t\t\tByteBuffer value = segDataBlock.get(key);\n\t\t\tif (value != null) {\n\t\t\t\tByteBuffer intKey = ByteBuffer.wrap(key.array());\n\t\t\t\treturn new SegmentData(segId, intKey, value);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) {\n\t\tHashTreeMemStore hTreeStore = getIndHTree(treeId);\n\t\tif (!hTreeStore.segDataBlocks.containsKey(segId))\n\t\t\thTreeStore.segDataBlocks.putIfAbsent(segId,\n\t\t\t\t\tnew ConcurrentSkipListMap<ByteBuffer, ByteBuffer>());\n\t\thTreeStore.segDataBlocks.get(segId).put(key.duplicate(),\n\t\t\t\tdigest.duplicate());\n\t}\n\n\t@Override\n\tpublic void deleteSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tMap<ByteBuffer, ByteBuffer> segDataBlock = indPartition.segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock != null)\n\t\t\tsegDataBlock.remove(key.duplicate());\n\t}\n\n\t@Override\n\tpublic List<SegmentData> getSegment(long treeId, int segId) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tConcurrentMap<ByteBuffer, ByteBuffer> segDataBlock = indPartition.segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock == null)\n\t\t\treturn Collections.emptyList();\n\t\tList<SegmentData> result = new ArrayList<SegmentData>();\n\t\tfor (Map.Entry<ByteBuffer, ByteBuffer> entry : segDataBlock.entrySet())\n\t\t\tresult.add(new SegmentData(segId, entry.getKey(), entry.getValue()));\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterator returned by this method is not thread safe.\n\t */\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId) {\n\t\tfinal HashTreeMemStore memStore = getIndHTree(treeId);\n\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr = memStore.segDataBlocks\n\t\t\t\t.entrySet().iterator();\n\t\treturn convertMapEntriesToSegmentData(dataBlocksItr);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId,\n\t\t\tint fromSegId, int toSegId) throws IOException {\n\t\tfinal HashTreeMemStore memStore = getIndHTree(treeId);\n\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr = memStore.segDataBlocks\n\t\t\t\t.subMap(fromSegId, true, toSegId, true).entrySet().iterator();\n\t\treturn convertMapEntriesToSegmentData(dataBlocksItr);\n\t}\n\n\tprivate static Iterator<SegmentData> convertMapEntriesToSegmentData(\n\t\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr) {\n\t\treturn new Iterator<SegmentData>() {\n\n\t\t\tvolatile int segId;\n\t\t\tvolatile Iterator<Map.Entry<ByteBuffer, ByteBuffer>> itr = null;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\tif (itr == null || !itr.hasNext()) {\n\t\t\t\t\twhile (dataBlocksItr.hasNext()) {\n\t\t\t\t\t\tMap.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>> entry = dataBlocksItr\n\t\t\t\t\t\t\t\t.next();\n\t\t\t\t\t\tsegId = entry.getKey();\n\t\t\t\t\t\titr = entry.getValue().entrySet().iterator();\n\t\t\t\t\t\tif (itr.hasNext())\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (itr != null) && itr.hasNext();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic SegmentData next() {\n\t\t\t\tif (itr == null || !itr.hasNext())\n\t\t\t\t\tthrow new NoSuchElementException(\n\t\t\t\t\t\t\t\"No more elements exist to return.\");\n\t\t\t\tMap.Entry<ByteBuffer, ByteBuffer> entry = itr.next();\n\t\t\t\treturn new SegmentData(segId, entry.getKey(), entry.getValue());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void remove() {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic void putSegmentHash(long treeId, int nodeId, ByteBuffer digest) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tindPartition.segmentHashes.put(nodeId, digest.duplicate());\n\t}\n\n\t@Override\n\tpublic SegmentHash getSegmentHash(long treeId, int nodeId) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tByteBuffer hash = indPartition.segmentHashes.get(nodeId);\n\t\tif (hash == null)\n\t\t\treturn null;\n\t\treturn new SegmentHash(nodeId, hash);\n\t}\n\n\t@Override\n\tpublic List<SegmentHash> getSegmentHashes(long treeId,\n\t\t\tCollection<Integer> nodeIds) {\n\t\tList<SegmentHash> result = new ArrayList<SegmentHash>();\n\t\tfor (int nodeId : nodeIds) {\n\t\t\tByteBuffer hash = getIndHTree(treeId).segmentHashes.get(nodeId);\n\t\t\tif (hash != null)\n\t\t\t\tresult.add(new SegmentHash(nodeId, hash));\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void setCompleteRebuiltTimestamp(long treeId, long timestamp) {\n\t\tHashTreeMemStore indTree = getIndHTree(treeId);\n\t\tindTree.lastRebuiltTS.set(timestamp);\n\t}\n\n\t@Override\n\tpublic long getCompleteRebuiltTimestamp(long treeId) {\n\t\tlong value = getIndHTree(treeId).lastRebuiltTS.get();\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic void deleteTree(long treeId) {\n\t\ttreeIdAndIndHashTree.remove(treeId);\n\t}\n\n\t@Override\n\tpublic void markSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds)\n\t\t\tgetIndHTree(treeId).markedSegments.set(segId);\n\t}\n\n\t@Override\n\tpublic void unmarkSegments(long treeId, List<Integer> segIds) {\n\t\tgetIndHTree(treeId).markedSegments.clearBits(segIds);\n\t}\n\n\t@Override\n\tpublic List<Integer> getMarkedSegments(long treeId) {\n\t\treturn getIndHTree(treeId).markedSegments.getAllSetBits();\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\t// Nothing to stop.\n\t}\n\n\t@Override\n\tpublic void start() {\n\t\t// Nothing to initialize\n\t}\n\n\t@Override\n\tprotected void setDirtySegmentInternal(long treeId, int segId) {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tprotected void clearDirtySegmentInternal(long treeId, int segId) {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tprotected List<Integer> getDirtySegmentsInternal(long treeId) {\n\t\treturn Collections.emptyList();\n\t}\n}", "public class HashTreesPersistentStore extends HashTreesBaseStore {\n\n\tprivate static final Logger LOG = LoggerFactory\n\t\t\t.getLogger(HashTreesPersistentStore.class);\n\tprivate static final byte[] EMPTY_VALUE = new byte[0];\n\n\tprivate final String dbDir;\n\tprivate final DB dbObj;\n\n\tpublic HashTreesPersistentStore(String dbDir) throws IOException {\n\t\tthis.dbDir = dbDir;\n\t\tthis.dbObj = initDB(dbDir);\n\t}\n\n\tprivate static boolean createDir(String dirName) {\n\t\tFile file = new File(dirName);\n\t\tif (file.exists())\n\t\t\treturn true;\n\t\treturn file.mkdirs();\n\t}\n\n\tprivate static DB initDB(String dbDir) throws IOException {\n\t\tcreateDir(dbDir);\n\t\tOptions options = new Options();\n\t\toptions.createIfMissing(true);\n\t\treturn new JniDBFactory().open(new File(dbDir), options);\n\t}\n\n\tpublic String getDbDir() {\n\t\treturn dbDir;\n\t}\n\n\t@Override\n\tprotected void setDirtySegmentInternal(long treeId, int segId) {\n\t\tdbObj.put(generateDirtySegmentKey(treeId, segId), EMPTY_VALUE);\n\t}\n\n\t@Override\n\tprotected void clearDirtySegmentInternal(long treeId, int segId) {\n\t\tbyte[] key = generateDirtySegmentKey(treeId, segId);\n\t\tdbObj.delete(key);\n\t}\n\n\t@Override\n\tprotected List<Integer> getDirtySegmentsInternal(long treeId) {\n\t\tDBIterator itr = dbObj.iterator();\n\t\tbyte[] prefixKey = generateBaseKey(BaseKey.DIRTY_SEG, treeId);\n\t\titr.seek(prefixKey);\n\t\tIterator<Integer> dirtySegmentsItr = new DataFilterableIterator<>(\n\t\t\t\tprefixKey, true, KVBYTES_TO_SEGID_CONVERTER, itr);\n\t\tList<Integer> dirtySegments = new ArrayList<>();\n\t\twhile (dirtySegmentsItr.hasNext()) {\n\t\t\tInteger treeIdAndDirtySeg = dirtySegmentsItr.next();\n\t\t\tdirtySegments.add(treeIdAndDirtySeg);\n\t\t}\n\t\treturn dirtySegments;\n\t}\n\n\t@Override\n\tpublic void putSegmentHash(long treeId, int nodeId, ByteBuffer digest) {\n\t\tdbObj.put(generateSegmentHashKey(treeId, nodeId), digest.array());\n\t}\n\n\t@Override\n\tpublic SegmentHash getSegmentHash(long treeId, int nodeId) {\n\t\tbyte[] value = dbObj.get(generateSegmentHashKey(treeId, nodeId));\n\t\tif (value != null)\n\t\t\treturn new SegmentHash(nodeId, ByteBuffer.wrap(value));\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic List<SegmentHash> getSegmentHashes(long treeId,\n\t\t\tCollection<Integer> nodeIds) {\n\t\tList<SegmentHash> result = new ArrayList<SegmentHash>();\n\t\tSegmentHash temp;\n\t\tfor (int nodeId : nodeIds) {\n\t\t\ttemp = getSegmentHash(treeId, nodeId);\n\t\t\tif (temp != null)\n\t\t\t\tresult.add(temp);\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void setCompleteRebuiltTimestamp(long treeId, long ts) {\n\t\tbyte[] value = new byte[ByteUtils.SIZEOF_LONG];\n\t\tByteBuffer bbValue = ByteBuffer.wrap(value);\n\t\tbbValue.putLong(ts);\n\t\tbyte[] key = generateMetaDataKey(MetaDataKey.FULL_REBUILT_TS, treeId);\n\t\tdbObj.put(key, value);\n\t}\n\n\t@Override\n\tpublic long getCompleteRebuiltTimestamp(long treeId) {\n\t\tbyte[] key = generateMetaDataKey(MetaDataKey.FULL_REBUILT_TS, treeId);\n\t\tbyte[] value = dbObj.get(key);\n\t\treturn (value == null) ? 0 : ByteUtils.toLong(value, 0);\n\t}\n\n\t@Override\n\tpublic void deleteTree(long treeId) {\n\t\tDBIterator dbItr;\n\t\tbyte[] temp = new byte[LEN_BASEKEY_AND_TREEID];\n\t\tfor (BaseKey keyPrefix : BaseKey.values()) {\n\t\t\tdbItr = dbObj.iterator();\n\t\t\tByteBuffer wrap = ByteBuffer.wrap(temp);\n\t\t\tfillBaseKey(wrap, keyPrefix, treeId);\n\t\t\tdbItr.seek(wrap.array());\n\t\t\tfor (; dbItr.hasNext(); dbItr.next()) {\n\t\t\t\tif (ByteUtils.compareTo(temp, 0, temp.length, dbItr.peekNext()\n\t\t\t\t\t\t.getKey(), 0, temp.length) != 0)\n\t\t\t\t\tbreak;\n\t\t\t\tdbObj.delete(dbItr.peekNext().getKey());\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tdbObj.put(dbKey, digest.array());\n\t}\n\n\t@Override\n\tpublic SegmentData getSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tbyte[] value = dbObj.get(dbKey);\n\t\tif (value != null) {\n\t\t\tByteBuffer intKeyBB = ByteBuffer.wrap(key.array());\n\t\t\tByteBuffer valueBB = ByteBuffer.wrap(value);\n\t\t\treturn new SegmentData(segId, intKeyBB, valueBB);\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void deleteSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tdbObj.delete(dbKey);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId) {\n\t\tbyte[] startKey = generateBaseKey(BaseKey.SEG_DATA, treeId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn new DataFilterableIterator<>(startKey, false,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId,\n\t\t\tint fromSegId, int toSegId) throws IOException {\n\t\tbyte[] startKey = generateSegmentDataKey(treeId, fromSegId);\n\t\tbyte[] endKey = generateSegmentDataKey(treeId, toSegId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn new DataFilterableIterator<>(endKey, false,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator);\n\t}\n\n\t@Override\n\tpublic List<SegmentData> getSegment(long treeId, int segId) {\n\t\tbyte[] startKey = generateSegmentDataKey(treeId, segId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn Lists.newArrayList(new DataFilterableIterator<>(startKey, true,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator));\n\t}\n\n\t@Override\n\tpublic void markSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds) {\n\t\t\tbyte[] key = generateRebuildMarkerKey(treeId, segId);\n\t\t\tdbObj.put(key, EMPTY_VALUE);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void unmarkSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds) {\n\t\t\tbyte[] key = generateRebuildMarkerKey(treeId, segId);\n\t\t\tdbObj.delete(key);\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Integer> getMarkedSegments(long treeId) {\n\t\tbyte[] startKey = generateBaseKey(BaseKey.REBUILD_MARKER, treeId);\n\t\tDBIterator itr = dbObj.iterator();\n\t\titr.seek(startKey);\n\n\t\treturn Lists.newArrayList(new DataFilterableIterator<>(startKey, true,\n\t\t\t\tKVBYTES_TO_SEGID_CONVERTER, itr));\n\t}\n\n\t/**\n\t * Deletes the db files.\n\t * \n\t */\n\tpublic void delete() {\n\t\tstop();\n\t\tFile dbDirObj = new File(dbDir);\n\t\tif (dbDirObj.exists())\n\t\t\tFileUtils.deleteQuietly(dbDirObj);\n\t}\n\n\t@Override\n\tpublic void start() {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\ttry {\n\t\t\tdbObj.close();\n\t\t} catch (IOException e) {\n\t\t\tLOG.warn(\"Exception occurred while closing leveldb connection.\");\n\t\t}\n\t}\n\n}", "public interface HashTreesStore extends Service {\n\n\t/**\n\t * A segment data is the value inside a segment block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t * @param digest\n\t */\n\tvoid putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) throws IOException;\n\n\t/**\n\t * Returns the SegmentData for the given key if available, otherwise returns\n\t * null.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t * @return\n\t */\n\tSegmentData getSegmentData(long treeId, int segId, ByteBuffer key)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Deletes the given segement data from the block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t */\n\tvoid deleteSegmentData(long treeId, int segId, ByteBuffer key)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns an iterator to read all the segment data of the given tree id.\n\t * \n\t * Note: Iterator implementations should throw\n\t * {@link HashTreesCustomRuntimeException} so that failure cases can be\n\t * handled properly by {@link HashTrees}\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tIterator<SegmentData> getSegmentDataIterator(long treeId)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns an iterator to read all the segment data of the given tree id,\n\t * and starting from a given segId and to segId.\n\t * \n\t * Note: Iterator implementations should throw\n\t * {@link HashTreesCustomRuntimeException} so that failure cases can be\n\t * handled properly by {@link HashTrees}\n\t * \n\t * @param treeId\n\t * @param fromSegId\n\t * , inclusive\n\t * @param toSegId\n\t * , inclusive\n\t * @return\n\t * @throws IOException\n\t */\n\tIterator<SegmentData> getSegmentDataIterator(long treeId, int fromSegId,\n\t\t\tint toSegId) throws IOException;\n\n\t/**\n\t * Given a segment id, returns the list of all segment data in the\n\t * individual segment block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return\n\t */\n\tList<SegmentData> getSegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Segment hash is the hash of all data inside a segment block. A segment\n\t * hash is stored on a tree node.\n\t * \n\t * @param treeId\n\t * @param nodeId\n\t * , identifier of the node in the hash tree.\n\t * @param digest\n\t */\n\tvoid putSegmentHash(long treeId, int nodeId, ByteBuffer digest)\n\t\t\tthrows IOException;\n\n\t/**\n\t * \n\t * @param treeId\n\t * @param nodeId\n\t * @return\n\t */\n\tSegmentHash getSegmentHash(long treeId, int nodeId) throws IOException;\n\n\t/**\n\t * Returns the data inside the nodes of the hash tree. If the node id is not\n\t * present in the hash tree, the entry will be missing in the result.\n\t * \n\t * @param treeId\n\t * @param nodeIds\n\t * , internal tree node ids.\n\t * @return\n\t */\n\tList<SegmentHash> getSegmentHashes(long treeId, Collection<Integer> nodeIds)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Marks a segment as a dirty.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return previousValue\n\t */\n\tboolean setDirtySegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Clears the segments, which are passed as an argument.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return previousValue\n\t */\n\tboolean clearDirtySegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Gets the dirty segments without clearing those bits.\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tList<Integer> getDirtySegments(long treeId) throws IOException;\n\n\t/**\n\t * Sets flags for the given segments. Used during rebuild process by\n\t * {@link HashTrees#rebuildHashTree(long, boolean)}. If the process crashes\n\t * in the middle of rebuilding we don't want to loose track. This has to\n\t * persist that information, so that we can reuse it after the process\n\t * recovery.\n\t * \n\t * @param segIds\n\t */\n\tvoid markSegments(long treeId, List<Integer> segIds) throws IOException;\n\n\t/**\n\t * Gets the marked segments for the given treeId.\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tList<Integer> getMarkedSegments(long treeId) throws IOException;\n\n\t/**\n\t * Unsets flags for the given segments. Used during rebuild process by\n\t * {@link HashTrees#rebuildHashTree(long, boolean)}. After rebuilding is\n\t * done, this will be cleared.\n\t * \n\t * @param segIds\n\t */\n\tvoid unmarkSegments(long treeId, List<Integer> segIds) throws IOException;\n\n\t/**\n\t * Deletes the segment hashes, and segment data for the given treeId.\n\t * \n\t * @param treeId\n\t */\n\tvoid deleteTree(long treeId) throws IOException;\n\n\t/**\n\t * Stores the timestamp at which the complete HashTree was rebuilt. This\n\t * method updates the value in store only if the given value is higher than\n\t * the existing timestamp, otherwise a noop.\n\t * \n\t * @param timestamp\n\t */\n\tvoid setCompleteRebuiltTimestamp(long treeId, long timestamp)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns the timestamp at which the complete HashTree was rebuilt.\n\t * \n\t * @return\n\t */\n\tlong getCompleteRebuiltTimestamp(long treeId) throws IOException;\n}", "public class HashTreesImplTestUtils {\n\n\tprivate static final Random RANDOM = new Random(System.currentTimeMillis());\n\tpublic static final int ROOT_NODE = 0;\n\tpublic static final int DEFAULT_TREE_ID = 1;\n\tpublic static final int DEFAULT_SEG_DATA_BLOCKS_COUNT = 1 << 5;\n\tpublic static final int DEFAULT_HTREE_SERVER_PORT_NO = 11111;\n\tpublic static final SegIdProviderTest SEG_ID_PROVIDER = new SegIdProviderTest();\n\tpublic static final SimpleTreeIdProvider TREE_ID_PROVIDER = new SimpleTreeIdProvider();\n\n\t/**\n\t * Default SegId provider which expects the key to be an integer wrapped as\n\t * bytes.\n\t * \n\t */\n\tpublic static class SegIdProviderTest implements SegmentIdProvider {\n\n\t\t@Override\n\t\tpublic int getSegmentId(byte[] key) {\n\t\t\ttry {\n\t\t\t\tByteBuffer bb = ByteBuffer.wrap(key);\n\t\t\t\treturn bb.getInt();\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Exception occurred while converting the string\");\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static class HTreeComponents {\n\n\t\tpublic final HashTreesStore hTStore;\n\t\tpublic final SimpleMemStore store;\n\t\tpublic final HashTreesImpl hTree;\n\n\t\tpublic HTreeComponents(final HashTreesStore hTStore,\n\t\t\t\tfinal SimpleMemStore store, final HashTreesImpl hTree) {\n\t\t\tthis.hTStore = hTStore;\n\t\t\tthis.store = store;\n\t\t\tthis.hTree = hTree;\n\t\t}\n\t}\n\n\tpublic static byte[] randomBytes() {\n\t\tbyte[] emptyBuffer = new byte[8];\n\t\tRANDOM.nextBytes(emptyBuffer);\n\t\treturn emptyBuffer;\n\t}\n\n\tpublic static ByteBuffer randomByteBuffer() {\n\t\tbyte[] random = new byte[8];\n\t\tRANDOM.nextBytes(random);\n\t\treturn ByteBuffer.wrap(random);\n\t}\n\n\tpublic static String randomDirName() {\n\t\treturn \"/tmp/test/random\" + RANDOM.nextInt();\n\t}\n\n\tpublic static HTreeComponents createHashTree(int noOfSegDataBlocks,\n\t\t\tboolean enabledNonBlockingCalls,\n\t\t\tfinal HashTreesIdProvider treeIdProv,\n\t\t\tfinal SegmentIdProvider segIdPro, final HashTreesStore hTStore) {\n\t\tSimpleMemStore store = new SimpleMemStore();\n\t\tHashTreesImpl hTree = new HashTreesImpl.Builder(store, treeIdProv,\n\t\t\t\thTStore).setNoOfSegments(noOfSegDataBlocks)\n\t\t\t\t.setEnabledNonBlockingCalls(enabledNonBlockingCalls)\n\t\t\t\t.setSegmentIdProvider(segIdPro).build();\n\t\tstore.registerHashTrees(hTree);\n\t\treturn new HTreeComponents(hTStore, store, hTree);\n\t}\n\n\tpublic static HTreeComponents createHashTree(int noOfSegments,\n\t\t\tboolean enabledNonBlockingCalls, final HashTreesStore hTStore) {\n\t\tSimpleMemStore store = new SimpleMemStore();\n\t\tModuloSegIdProvider segIdProvider = new ModuloSegIdProvider(\n\t\t\t\tnoOfSegments);\n\t\tHashTreesImpl hTree = new HashTreesImpl.Builder(store,\n\t\t\t\tTREE_ID_PROVIDER, hTStore).setNoOfSegments(noOfSegments)\n\t\t\t\t.setEnabledNonBlockingCalls(enabledNonBlockingCalls)\n\t\t\t\t.setSegmentIdProvider(segIdProvider).build();\n\t\tstore.registerHashTrees(hTree);\n\t\treturn new HTreeComponents(hTStore, store, hTree);\n\t}\n\n\tpublic static HashTreesMemStore generateInMemoryStore() {\n\t\treturn new HashTreesMemStore();\n\t}\n\n\tpublic static HashTreesPersistentStore generatePersistentStore()\n\t\t\tthrows IOException {\n\t\treturn new HashTreesPersistentStore(randomDirName());\n\t}\n\n\tpublic static HashTreesStore[] generateInMemoryAndPersistentStores()\n\t\t\tthrows IOException {\n\t\tHashTreesStore[] stores = new HashTreesStore[2];\n\t\tstores[0] = generateInMemoryStore();\n\t\tstores[1] = generatePersistentStore();\n\t\treturn stores;\n\t}\n\n\tpublic static void closeStores(HashTreesStore... stores) {\n\t\tfor (HashTreesStore store : stores) {\n\t\t\tif (store instanceof HashTreesPersistentStore) {\n\t\t\t\tHashTreesPersistentStore pStore = (HashTreesPersistentStore) store;\n\t\t\t\tFileUtils.deleteQuietly(new File(pStore.getDbDir()));\n\t\t\t}\n\t\t}\n\t}\n}", "public class SegmentData implements org.apache.thrift.TBase<SegmentData, SegmentData._Fields>, java.io.Serializable, Cloneable {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"SegmentData\");\n\n private static final org.apache.thrift.protocol.TField SEG_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"segId\", org.apache.thrift.protocol.TType.I32, (short)1);\n private static final org.apache.thrift.protocol.TField KEY_FIELD_DESC = new org.apache.thrift.protocol.TField(\"key\", org.apache.thrift.protocol.TType.STRING, (short)2);\n private static final org.apache.thrift.protocol.TField DIGEST_FIELD_DESC = new org.apache.thrift.protocol.TField(\"digest\", org.apache.thrift.protocol.TType.STRING, (short)3);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new SegmentDataStandardSchemeFactory());\n schemes.put(TupleScheme.class, new SegmentDataTupleSchemeFactory());\n }\n\n public int segId; // required\n public ByteBuffer key; // required\n public ByteBuffer digest; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SEG_ID((short)1, \"segId\"),\n KEY((short)2, \"key\"),\n DIGEST((short)3, \"digest\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // SEG_ID\n return SEG_ID;\n case 2: // KEY\n return KEY;\n case 3: // DIGEST\n return DIGEST;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __SEGID_ISSET_ID = 0;\n private BitSet __isset_bit_vector = new BitSet(1);\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SEG_ID, new org.apache.thrift.meta_data.FieldMetaData(\"segId\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.KEY, new org.apache.thrift.meta_data.FieldMetaData(\"key\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n tmpMap.put(_Fields.DIGEST, new org.apache.thrift.meta_data.FieldMetaData(\"digest\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SegmentData.class, metaDataMap);\n }\n\n public SegmentData() {\n }\n\n public SegmentData(\n int segId,\n ByteBuffer key,\n ByteBuffer digest)\n {\n this();\n this.segId = segId;\n setSegIdIsSet(true);\n this.key = key;\n this.digest = digest;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public SegmentData(SegmentData other) {\n __isset_bit_vector.clear();\n __isset_bit_vector.or(other.__isset_bit_vector);\n this.segId = other.segId;\n if (other.isSetKey()) {\n this.key = org.apache.thrift.TBaseHelper.copyBinary(other.key);\n;\n }\n if (other.isSetDigest()) {\n this.digest = org.apache.thrift.TBaseHelper.copyBinary(other.digest);\n;\n }\n }\n\n public SegmentData deepCopy() {\n return new SegmentData(this);\n }\n\n @Override\n public void clear() {\n setSegIdIsSet(false);\n this.segId = 0;\n this.key = null;\n this.digest = null;\n }\n\n public int getSegId() {\n return this.segId;\n }\n\n public SegmentData setSegId(int segId) {\n this.segId = segId;\n setSegIdIsSet(true);\n return this;\n }\n\n public void unsetSegId() {\n __isset_bit_vector.clear(__SEGID_ISSET_ID);\n }\n\n /** Returns true if field segId is set (has been assigned a value) and false otherwise */\n public boolean isSetSegId() {\n return __isset_bit_vector.get(__SEGID_ISSET_ID);\n }\n\n public void setSegIdIsSet(boolean value) {\n __isset_bit_vector.set(__SEGID_ISSET_ID, value);\n }\n\n public byte[] getKey() {\n setKey(org.apache.thrift.TBaseHelper.rightSize(key));\n return key == null ? null : key.array();\n }\n\n public ByteBuffer bufferForKey() {\n return key;\n }\n\n public SegmentData setKey(byte[] key) {\n setKey(key == null ? (ByteBuffer)null : ByteBuffer.wrap(key));\n return this;\n }\n\n public SegmentData setKey(ByteBuffer key) {\n this.key = key;\n return this;\n }\n\n public void unsetKey() {\n this.key = null;\n }\n\n /** Returns true if field key is set (has been assigned a value) and false otherwise */\n public boolean isSetKey() {\n return this.key != null;\n }\n\n public void setKeyIsSet(boolean value) {\n if (!value) {\n this.key = null;\n }\n }\n\n public byte[] getDigest() {\n setDigest(org.apache.thrift.TBaseHelper.rightSize(digest));\n return digest == null ? null : digest.array();\n }\n\n public ByteBuffer bufferForDigest() {\n return digest;\n }\n\n public SegmentData setDigest(byte[] digest) {\n setDigest(digest == null ? (ByteBuffer)null : ByteBuffer.wrap(digest));\n return this;\n }\n\n public SegmentData setDigest(ByteBuffer digest) {\n this.digest = digest;\n return this;\n }\n\n public void unsetDigest() {\n this.digest = null;\n }\n\n /** Returns true if field digest is set (has been assigned a value) and false otherwise */\n public boolean isSetDigest() {\n return this.digest != null;\n }\n\n public void setDigestIsSet(boolean value) {\n if (!value) {\n this.digest = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SEG_ID:\n if (value == null) {\n unsetSegId();\n } else {\n setSegId((Integer)value);\n }\n break;\n\n case KEY:\n if (value == null) {\n unsetKey();\n } else {\n setKey((ByteBuffer)value);\n }\n break;\n\n case DIGEST:\n if (value == null) {\n unsetDigest();\n } else {\n setDigest((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SEG_ID:\n return Integer.valueOf(getSegId());\n\n case KEY:\n return getKey();\n\n case DIGEST:\n return getDigest();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SEG_ID:\n return isSetSegId();\n case KEY:\n return isSetKey();\n case DIGEST:\n return isSetDigest();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof SegmentData)\n return this.equals((SegmentData)that);\n return false;\n }\n\n public boolean equals(SegmentData that) {\n if (that == null)\n return false;\n\n boolean this_present_segId = true;\n boolean that_present_segId = true;\n if (this_present_segId || that_present_segId) {\n if (!(this_present_segId && that_present_segId))\n return false;\n if (this.segId != that.segId)\n return false;\n }\n\n boolean this_present_key = true && this.isSetKey();\n boolean that_present_key = true && that.isSetKey();\n if (this_present_key || that_present_key) {\n if (!(this_present_key && that_present_key))\n return false;\n if (!this.key.equals(that.key))\n return false;\n }\n\n boolean this_present_digest = true && this.isSetDigest();\n boolean that_present_digest = true && that.isSetDigest();\n if (this_present_digest || that_present_digest) {\n if (!(this_present_digest && that_present_digest))\n return false;\n if (!this.digest.equals(that.digest))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return 0;\n }\n\n public int compareTo(SegmentData other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n SegmentData typedOther = (SegmentData)other;\n\n lastComparison = Boolean.valueOf(isSetSegId()).compareTo(typedOther.isSetSegId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSegId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.segId, typedOther.segId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetKey()).compareTo(typedOther.isSetKey());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetKey()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.key, typedOther.key);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetDigest()).compareTo(typedOther.isSetDigest());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetDigest()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.digest, typedOther.digest);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"SegmentData(\");\n boolean first = true;\n\n sb.append(\"segId:\");\n sb.append(this.segId);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"key:\");\n if (this.key == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.key, sb);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"digest:\");\n if (this.digest == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.digest, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // alas, we cannot check 'segId' because it's a primitive and you chose the non-beans generator.\n if (key == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'key' was not present! Struct: \" + toString());\n }\n if (digest == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'digest' was not present! Struct: \" + toString());\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bit_vector = new BitSet(1);\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class SegmentDataStandardSchemeFactory implements SchemeFactory {\n public SegmentDataStandardScheme getScheme() {\n return new SegmentDataStandardScheme();\n }\n }\n\n private static class SegmentDataStandardScheme extends StandardScheme<SegmentData> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, SegmentData struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // SEG_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.segId = iprot.readI32();\n struct.setSegIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // KEY\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.key = iprot.readBinary();\n struct.setKeyIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // DIGEST\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.digest = iprot.readBinary();\n struct.setDigestIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n if (!struct.isSetSegId()) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'segId' was not found in serialized data! Struct: \" + toString());\n }\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, SegmentData struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldBegin(SEG_ID_FIELD_DESC);\n oprot.writeI32(struct.segId);\n oprot.writeFieldEnd();\n if (struct.key != null) {\n oprot.writeFieldBegin(KEY_FIELD_DESC);\n oprot.writeBinary(struct.key);\n oprot.writeFieldEnd();\n }\n if (struct.digest != null) {\n oprot.writeFieldBegin(DIGEST_FIELD_DESC);\n oprot.writeBinary(struct.digest);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class SegmentDataTupleSchemeFactory implements SchemeFactory {\n public SegmentDataTupleScheme getScheme() {\n return new SegmentDataTupleScheme();\n }\n }\n\n private static class SegmentDataTupleScheme extends TupleScheme<SegmentData> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, SegmentData struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n oprot.writeI32(struct.segId);\n oprot.writeBinary(struct.key);\n oprot.writeBinary(struct.digest);\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, SegmentData struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n struct.segId = iprot.readI32();\n struct.setSegIdIsSet(true);\n struct.key = iprot.readBinary();\n struct.setKeyIsSet(true);\n struct.digest = iprot.readBinary();\n struct.setDigestIsSet(true);\n }\n }\n\n}", "public class SegmentHash implements org.apache.thrift.TBase<SegmentHash, SegmentHash._Fields>, java.io.Serializable, Cloneable {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"SegmentHash\");\n\n private static final org.apache.thrift.protocol.TField NODE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"nodeId\", org.apache.thrift.protocol.TType.I32, (short)1);\n private static final org.apache.thrift.protocol.TField HASH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"hash\", org.apache.thrift.protocol.TType.STRING, (short)2);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new SegmentHashStandardSchemeFactory());\n schemes.put(TupleScheme.class, new SegmentHashTupleSchemeFactory());\n }\n\n public int nodeId; // required\n public ByteBuffer hash; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n NODE_ID((short)1, \"nodeId\"),\n HASH((short)2, \"hash\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // NODE_ID\n return NODE_ID;\n case 2: // HASH\n return HASH;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __NODEID_ISSET_ID = 0;\n private BitSet __isset_bit_vector = new BitSet(1);\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.NODE_ID, new org.apache.thrift.meta_data.FieldMetaData(\"nodeId\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.HASH, new org.apache.thrift.meta_data.FieldMetaData(\"hash\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SegmentHash.class, metaDataMap);\n }\n\n public SegmentHash() {\n }\n\n public SegmentHash(\n int nodeId,\n ByteBuffer hash)\n {\n this();\n this.nodeId = nodeId;\n setNodeIdIsSet(true);\n this.hash = hash;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public SegmentHash(SegmentHash other) {\n __isset_bit_vector.clear();\n __isset_bit_vector.or(other.__isset_bit_vector);\n this.nodeId = other.nodeId;\n if (other.isSetHash()) {\n this.hash = org.apache.thrift.TBaseHelper.copyBinary(other.hash);\n;\n }\n }\n\n public SegmentHash deepCopy() {\n return new SegmentHash(this);\n }\n\n @Override\n public void clear() {\n setNodeIdIsSet(false);\n this.nodeId = 0;\n this.hash = null;\n }\n\n public int getNodeId() {\n return this.nodeId;\n }\n\n public SegmentHash setNodeId(int nodeId) {\n this.nodeId = nodeId;\n setNodeIdIsSet(true);\n return this;\n }\n\n public void unsetNodeId() {\n __isset_bit_vector.clear(__NODEID_ISSET_ID);\n }\n\n /** Returns true if field nodeId is set (has been assigned a value) and false otherwise */\n public boolean isSetNodeId() {\n return __isset_bit_vector.get(__NODEID_ISSET_ID);\n }\n\n public void setNodeIdIsSet(boolean value) {\n __isset_bit_vector.set(__NODEID_ISSET_ID, value);\n }\n\n public byte[] getHash() {\n setHash(org.apache.thrift.TBaseHelper.rightSize(hash));\n return hash == null ? null : hash.array();\n }\n\n public ByteBuffer bufferForHash() {\n return hash;\n }\n\n public SegmentHash setHash(byte[] hash) {\n setHash(hash == null ? (ByteBuffer)null : ByteBuffer.wrap(hash));\n return this;\n }\n\n public SegmentHash setHash(ByteBuffer hash) {\n this.hash = hash;\n return this;\n }\n\n public void unsetHash() {\n this.hash = null;\n }\n\n /** Returns true if field hash is set (has been assigned a value) and false otherwise */\n public boolean isSetHash() {\n return this.hash != null;\n }\n\n public void setHashIsSet(boolean value) {\n if (!value) {\n this.hash = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case NODE_ID:\n if (value == null) {\n unsetNodeId();\n } else {\n setNodeId((Integer)value);\n }\n break;\n\n case HASH:\n if (value == null) {\n unsetHash();\n } else {\n setHash((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case NODE_ID:\n return Integer.valueOf(getNodeId());\n\n case HASH:\n return getHash();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case NODE_ID:\n return isSetNodeId();\n case HASH:\n return isSetHash();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof SegmentHash)\n return this.equals((SegmentHash)that);\n return false;\n }\n\n public boolean equals(SegmentHash that) {\n if (that == null)\n return false;\n\n boolean this_present_nodeId = true;\n boolean that_present_nodeId = true;\n if (this_present_nodeId || that_present_nodeId) {\n if (!(this_present_nodeId && that_present_nodeId))\n return false;\n if (this.nodeId != that.nodeId)\n return false;\n }\n\n boolean this_present_hash = true && this.isSetHash();\n boolean that_present_hash = true && that.isSetHash();\n if (this_present_hash || that_present_hash) {\n if (!(this_present_hash && that_present_hash))\n return false;\n if (!this.hash.equals(that.hash))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return 0;\n }\n\n public int compareTo(SegmentHash other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n SegmentHash typedOther = (SegmentHash)other;\n\n lastComparison = Boolean.valueOf(isSetNodeId()).compareTo(typedOther.isSetNodeId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetNodeId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeId, typedOther.nodeId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetHash()).compareTo(typedOther.isSetHash());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetHash()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.hash, typedOther.hash);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"SegmentHash(\");\n boolean first = true;\n\n sb.append(\"nodeId:\");\n sb.append(this.nodeId);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"hash:\");\n if (this.hash == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.hash, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // alas, we cannot check 'nodeId' because it's a primitive and you chose the non-beans generator.\n if (hash == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'hash' was not present! Struct: \" + toString());\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bit_vector = new BitSet(1);\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class SegmentHashStandardSchemeFactory implements SchemeFactory {\n public SegmentHashStandardScheme getScheme() {\n return new SegmentHashStandardScheme();\n }\n }\n\n private static class SegmentHashStandardScheme extends StandardScheme<SegmentHash> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, SegmentHash struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // NODE_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.nodeId = iprot.readI32();\n struct.setNodeIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // HASH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.hash = iprot.readBinary();\n struct.setHashIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n if (!struct.isSetNodeId()) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'nodeId' was not found in serialized data! Struct: \" + toString());\n }\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, SegmentHash struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldBegin(NODE_ID_FIELD_DESC);\n oprot.writeI32(struct.nodeId);\n oprot.writeFieldEnd();\n if (struct.hash != null) {\n oprot.writeFieldBegin(HASH_FIELD_DESC);\n oprot.writeBinary(struct.hash);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class SegmentHashTupleSchemeFactory implements SchemeFactory {\n public SegmentHashTupleScheme getScheme() {\n return new SegmentHashTupleScheme();\n }\n }\n\n private static class SegmentHashTupleScheme extends TupleScheme<SegmentHash> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, SegmentHash struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n oprot.writeI32(struct.nodeId);\n oprot.writeBinary(struct.hash);\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, SegmentHash struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n struct.nodeId = iprot.readI32();\n struct.setNodeIdIsSet(true);\n struct.hash = iprot.readBinary();\n struct.setHashIsSet(true);\n }\n }\n\n}", "public class ByteUtils {\n\n\t// ensuring non instantiability\n\tprivate ByteUtils() {\n\n\t}\n\n\t/**\n\t * Size of boolean in bytes\n\t */\n\tpublic static final int SIZEOF_BOOLEAN = Byte.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of byte in bytes\n\t */\n\tpublic static final int SIZEOF_BYTE = SIZEOF_BOOLEAN;\n\n\t/**\n\t * Size of char in bytes\n\t */\n\tpublic static final int SIZEOF_CHAR = Character.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of double in bytes\n\t */\n\tpublic static final int SIZEOF_DOUBLE = Double.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of float in bytes\n\t */\n\tpublic static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of int in bytes\n\t */\n\tpublic static final int SIZEOF_INT = Integer.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of long in bytes\n\t */\n\tpublic static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of short in bytes\n\t */\n\tpublic static final int SIZEOF_SHORT = Short.SIZE / Byte.SIZE;\n\n\tpublic static byte[] sha1(byte[] input) {\n\t\treturn getDigest(\"SHA-1\").digest(input);\n\t}\n\n\tpublic static MessageDigest getDigest(String algorithm) {\n\t\ttry {\n\t\t\treturn MessageDigest.getInstance(algorithm);\n\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\tthrow new IllegalStateException(\"Unknown algorithm: \" + algorithm,\n\t\t\t\t\te);\n\t\t}\n\t}\n\n\t/**\n\t * @param left\n\t * left operand\n\t * @param right\n\t * right operand\n\t * @return 0 if equal, < 0 if left is less than right, etc.\n\t */\n\tpublic static int compareTo(final byte[] left, final byte[] right) {\n\t\treturn compareTo(left, 0, left.length, right, 0, right.length);\n\t}\n\n\t/**\n\t * Lexographically compare two arrays.\n\t * \n\t * @param buffer1\n\t * left operand\n\t * @param buffer2\n\t * right operand\n\t * @param offset1\n\t * Where to start comparing in the left buffer\n\t * @param offset2\n\t * Where to start comparing in the right buffer\n\t * @param length1\n\t * How much to compare from the left buffer\n\t * @param length2\n\t * How much to compare from the right buffer\n\t * @return 0 if equal, < 0 if left is less than right, etc.\n\t */\n\tpublic static int compareTo(byte[] buffer1, int offset1, int length1,\n\t\t\tbyte[] buffer2, int offset2, int length2) {\n\t\t// Bring WritableComparator code local\n\t\tint end1 = offset1 + length1;\n\t\tint end2 = offset2 + length2;\n\t\tfor (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {\n\t\t\tint a = (buffer1[i] & 0xff);\n\t\t\tint b = (buffer2[j] & 0xff);\n\t\t\tif (a != b) {\n\t\t\t\treturn a - b;\n\t\t\t}\n\t\t}\n\t\treturn length1 - length2;\n\t}\n\n\t/**\n\t * Converts a byte array to a long value. Reverses {@link #toBytes(long)}\n\t * \n\t * @param bytes\n\t * array\n\t * @return the long value\n\t */\n\tpublic static long toLong(byte[] bytes) {\n\t\treturn toLong(bytes, 0, SIZEOF_LONG);\n\t}\n\n\t/**\n\t * Converts a byte array to a long value. Assumes there will be\n\t * {@link #SIZEOF_LONG} bytes available.\n\t * \n\t * @param bytes\n\t * bytes\n\t * @param offset\n\t * offset\n\t * @return the long value\n\t */\n\tpublic static long toLong(byte[] bytes, int offset) {\n\t\treturn toLong(bytes, offset, SIZEOF_LONG);\n\t}\n\n\t/**\n\t * Converts a byte array to a long value.\n\t * \n\t * @param bytes\n\t * array of bytes\n\t * @param offset\n\t * offset into array\n\t * @param length\n\t * length of data (must be {@link #SIZEOF_LONG})\n\t * @return the long value\n\t * @throws IllegalArgumentException\n\t * if length is not {@link #SIZEOF_LONG} or if there's not\n\t * enough room in the array at the offset indicated.\n\t */\n\tpublic static long toLong(byte[] bytes, int offset, final int length) {\n\t\tif (length != SIZEOF_LONG || offset + length > bytes.length) {\n\t\t\tthrow explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG);\n\t\t}\n\t\tlong l = 0;\n\t\tfor (int i = offset; i < offset + length; i++) {\n\t\t\tl <<= 8;\n\t\t\tl ^= bytes[i] & 0xFF;\n\t\t}\n\t\treturn l;\n\t}\n\n\tprivate static IllegalArgumentException explainWrongLengthOrOffset(\n\t\t\tfinal byte[] bytes, final int offset, final int length,\n\t\t\tfinal int expectedLength) {\n\t\tString reason;\n\t\tif (length != expectedLength) {\n\t\t\treason = \"Wrong length: \" + length + \", expected \" + expectedLength;\n\t\t} else {\n\t\t\treason = \"offset (\" + offset + \") + length (\" + length\n\t\t\t\t\t+ \") exceed the\" + \" capacity of the array: \"\n\t\t\t\t\t+ bytes.length;\n\t\t}\n\t\treturn new IllegalArgumentException(reason);\n\t}\n\n\t/**\n\t * Copy the specified bytes into a new array\n\t * \n\t * @param array\n\t * The array to copy from\n\t * @param from\n\t * The index in the array to begin copying from\n\t * @param to\n\t * The least index not copied\n\t * @return A new byte[] containing the copied bytes\n\t */\n\tpublic static byte[] copy(byte[] array, int from, int to) {\n\t\tif (to - from < 0) {\n\t\t\treturn new byte[0];\n\t\t} else {\n\t\t\tbyte[] a = new byte[to - from];\n\t\t\tSystem.arraycopy(array, from, a, 0, to - from);\n\t\t\treturn a;\n\t\t}\n\t}\n\n\tpublic static int roundUpToPowerOf2(int number) {\n\t\treturn (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;\n\t}\n}" ]
import org.hashtrees.thrift.generated.SegmentData; import org.hashtrees.thrift.generated.SegmentHash; import org.hashtrees.util.ByteUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hashtrees.store.HashTreesMemStore; import org.hashtrees.store.HashTreesPersistentStore; import org.hashtrees.store.HashTreesStore; import org.hashtrees.test.utils.HashTreesImplTestUtils;
/* * 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.hashtrees.test; public class HashTreesStoreTest { private static final int DEF_TREE_ID = 1; private static final int DEF_SEG_ID = 0; private static interface HTStoreHelper { HashTreesStore getInstance() throws IOException; HashTreesStore restartInstance(HashTreesStore htStore) throws IOException; void cleanup(HashTreesStore htStore) throws IOException; } private static class HTPersistentStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesPersistentStore( HashTreesImplTestUtils.randomDirName()); } @Override public void cleanup(HashTreesStore htStore) { ((HashTreesPersistentStore) htStore).delete(); } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { ((HashTreesPersistentStore) htStore).stop(); return new HashTreesPersistentStore( ((HashTreesPersistentStore) htStore).getDbDir()); } } private static class HTMemStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesMemStore(); } @Override public void cleanup(HashTreesStore htStore) { // nothing to do. } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { return htStore; } } private static final Set<HTStoreHelper> helpers = new HashSet<>(); static { helpers.add(new HTPersistentStoreHelper()); helpers.add(new HTMemStoreHelper()); } @Test public void testSegmentData() throws IOException { for (HTStoreHelper helper : helpers) { HashTreesStore htStore = helper.getInstance(); try { ByteBuffer key = ByteBuffer.wrap("key1".getBytes()); ByteBuffer digest = ByteBuffer.wrap(ByteUtils.sha1("digest1" .getBytes())); htStore.putSegmentData(DEF_TREE_ID, DEF_SEG_ID, key, digest);
SegmentData sd = htStore.getSegmentData(DEF_TREE_ID,
4
ZinoKader/SpotiQ
app/src/main/java/se/zinokader/spotiq/feature/party/PartyActivity.java
[ "public class ApplicationConstants {\n\n private ApplicationConstants() {}\n\n /* Request codes */\n public static final int LOGIN_INTENT_REQUEST_CODE = 5473;\n public static final int SEARCH_INTENT_REQUEST_CODE = 3125;\n\n /* Time and timing-related */\n public static final int DEFER_SNACKBAR_DELAY = 1000;\n public static final int REQUEST_RETRY_DELAY_SEC = 3;\n public static final int SHORT_VIBRATION_DURATION_MS = 30;\n public static final int SHORT_ACTION_DELAY_SEC = 1;\n public static final int MEDIUM_ACTION_DELAY_SEC = 2;\n public static final int LONG_ACTION_DELAY_SEC = 3;\n public static final int LONG_TOAST_DURATION_SEC = 5;\n\n /* Image-related */\n //Placeholders\n public static final String ALBUM_ART_PLACEHOLDER_URL = \"https://www.zinokader.se/img/spotiq-album-placeholder.png\";\n public static final String PLAYLIST_IMAGE_PLACEHOLDER_URL = \"https://www.zinokader.se/img/spotiq-playlist-placeholder.png\";\n public static final String PROFILE_IMAGE_PLACEHOLDER_URL = \"https://www.zinokader.se/img/spotiq-profile-placeholder.png\";\n //Dimensions\n public static final int DEFAULT_TRACKLIST_CROP_WIDTH = 600;\n public static final int DEFAULT_TRACKLIST_CROP_HEIGHT = 200;\n public static final int DEFAULT_TRACKLIST_BLUR_RADIUS = 100;\n public static final int LOW_QUALITY_ALBUM_ART_DIMENSION = 100;\n public static final int MEDIUM_QUALITY_ALBUM_ART_DIMENSION = 200;\n\n /* Notification-related */\n public static final String MEDIA_NOTIFICATION_CHANNEL_ID = \"media_notification_channel\";\n public static final String MEDIA_SESSSION_TAG = \"spotiq_media\";\n\n /* App shortcut-related */\n public static final String SEARCH_SHORTCUT_ID = \"spotiq_search_shortcut\";\n\n /* Activity & Lifecycle-related */\n\n //Splash-related\n public static final float ANIMATION_LOGO_SCALE_DOWN = 0.7f;\n public static final float ANIMATION_LOGO_SCALE_UP = 100f;\n public static final int ANIMATION_LOGO_SCALE_DOWN_DURATION_MS = 750;\n public static final int ANIMATION_LOGO_SCALE_UP_DURATION_MS = 200;\n\n //Lobby-related\n public static final int DIALOG_ANIMATION_DURATION = 650;\n\n //Party-related\n public static final String PARTY_NAME_EXTRA = \"party_name_extra\";\n public static final int PLAY_PAUSE_BUTTON_SYNCHRONIZATION_DELAY_MS = 800;\n public static final int DEFAULT_NEW_ITEM_DELAY_MS = 0;\n public static final int DEFAULT_LIST_ANIMATION_DURATION_MS = 400;\n public static final int DEFAULT_LIST_ANIMATION_ITEM_POSITION_START = 6;\n public static final int DEFAULT_ITEM_ADD_DURATION_MS = 1200;\n public static final int DEFAULT_ITEM_REMOVE_DURATION_MS = 350;\n public static final int DEFAULT_ITEM_MOVE_DURATION_MS = 900;\n\n /* Search-related */\n public static final String SONG_REQUESTS_EXTRA = \"song_requests_extra\";\n public static final int DEFAULT_DEBOUNCE_MS = 600;\n public static final int MAX_SONG_SUGGESTIONS = 50;\n\n}", "public class ServiceConstants {\n\n private ServiceConstants() {}\n\n /* Authentication-service */\n public static final long TOKEN_EXPIRY_CUTOFF = TimeUnit.MINUTES.toSeconds(20);\n\n /* Player-service */\n public static final int NOTIFICATION_SEND_DELAY_MS = 2000;\n public static final String ACTION_INIT = \"spotiq.ACTION_INIT\";\n public static final String ACTION_PLAY_PAUSE = \"spotiq.ACTION_PLAY_PAUSE\";\n public static final String PLAYING_STATUS_BROADCAST_NAME = \"spotiq.PLAYING_STATUS_BROADCAST\";\n public static final String PLAYING_STATUS_ISPLAYING_EXTRA = \"playing_status_isplaying_extra\";\n\n}", "public abstract class BaseActivity<P extends Presenter> extends NucleusAppCompatActivity<P> implements BaseView {\n\n private boolean snackbarShowing = false;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n overridePendingTransition(R.anim.fade_in, R.anim.fade_out);\n final PresenterFactory<P> superFactory = super.getPresenterFactory();\n setPresenterFactory(superFactory == null ? null : (PresenterFactory<P>) () -> {\n P presenter = superFactory.createPresenter();\n ((Injector) getApplication()).inject(presenter);\n return presenter;\n });\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.fade_in, R.anim.fade_out);\n }\n\n @Override\n public void onPause() {\n hideKeyboard();\n super.onPause();\n }\n\n\n @Override\n public void onBackPressed() {\n List<Fragment> fragmentList = getSupportFragmentManager().getFragments();\n boolean handled = false;\n for (Fragment fragment : fragmentList) {\n if (fragment instanceof BaseFragment) {\n handled = ((BaseFragment) fragment).onBackPressed();\n if (handled) {\n break;\n }\n }\n }\n\n if(!handled) {\n super.onBackPressed();\n }\n }\n\n public void showMessage(String message) {\n if (snackbarShowing) {\n deferMessage(message);\n }\n else {\n snackbarShowing = true;\n new SnackbarBuilder(getRootView())\n .message(message)\n .dismissCallback((snackbar, i) -> snackbarShowing = false)\n .build()\n .show();\n }\n }\n\n private void deferMessage(String message) {\n new Handler().postDelayed(() -> {\n snackbarShowing = true;\n new SnackbarBuilder(getRootView())\n .message(message)\n .dismissCallback((snackbar, i) -> snackbarShowing = false)\n .build()\n .show();\n }, ApplicationConstants.DEFER_SNACKBAR_DELAY);\n }\n\n public void finishWithSuccess(String message) {\n new SnackbarBuilder(getRootView())\n .duration(Snackbar.LENGTH_SHORT)\n .message(message)\n .dismissCallback((snackbar, i) -> finish())\n .build()\n .show();\n }\n\n public void hideKeyboard() {\n InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.hideSoftInputFromWindow(getRootView().getWindowToken(), 0);\n }\n\n public void startForegroundTokenRenewalService() {\n startService(new Intent(this, SpotifyAuthenticationService.class));\n }\n\n public void stopForegroundTokenRenewalService() {\n stopService(new Intent(this, SpotifyAuthenticationService.class));\n }\n\n}", "public class PartyMemberFragment extends Fragment {\n\n FragmentPartyMembersBinding binding;\n\n @Inject\n PartiesRepository partiesRepository;\n\n private CompositeDisposable subscriptions = new CompositeDisposable();\n\n private PartyMemberRecyclerAdapter partyMemberRecyclerAdapter;\n\n private List<User> partyMembers = new ArrayList<>();\n\n public static PartyMemberFragment newInstance(String partyTitle) {\n PartyMemberFragment partyMemberFragment = new PartyMemberFragment();\n Bundle newInstanceArguments = new Bundle();\n newInstanceArguments.putString(ApplicationConstants.PARTY_NAME_EXTRA, partyTitle);\n partyMemberFragment.setArguments(newInstanceArguments);\n return partyMemberFragment;\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n ((Injector) getContext().getApplicationContext()).inject(this);\n super.onCreate(savedInstanceState);\n String partyTitle = getArguments().getString(ApplicationConstants.PARTY_NAME_EXTRA);\n\n subscriptions.add(partiesRepository.listenToPartyMemberChanges(partyTitle)\n .delay(ApplicationConstants.DEFAULT_NEW_ITEM_DELAY_MS, TimeUnit.MILLISECONDS)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(childEvent -> {\n User partyMember = childEvent.getDataSnapshot().getValue(User.class);\n switch (childEvent.getChangeType()) {\n case ADDED:\n addMember(partyMember);\n break;\n case CHANGED:\n changePartyMember(partyMember);\n break;\n }\n }));\n }\n\n @Override\n public void onDestroy() {\n subscriptions.clear();\n super.onDestroy();\n }\n\n @Override\n public void onSaveInstanceState(Bundle bundle) {\n super.onSaveInstanceState(bundle);\n bundle.putString(ApplicationConstants.PARTY_NAME_EXTRA, getArguments().getString(ApplicationConstants.PARTY_NAME_EXTRA));\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n binding = DataBindingUtil.inflate(inflater, R.layout.fragment_party_members, container, false);\n\n partyMemberRecyclerAdapter = new PartyMemberRecyclerAdapter(partyMembers);\n binding.membersRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));\n binding.membersRecyclerView.addItemDecoration(new CustomDividerItemDecoration(getContext()\n .getDrawable(R.drawable.search_list_divider),false, false));\n\n AlphaInAnimationAdapter animatedAdapter =\n new AlphaInAnimationAdapter(partyMemberRecyclerAdapter);\n animatedAdapter.setInterpolator(new AccelerateDecelerateInterpolator());\n animatedAdapter.setHasStableIds(true);\n animatedAdapter.setStartPosition(ApplicationConstants.DEFAULT_LIST_ANIMATION_ITEM_POSITION_START);\n animatedAdapter.setDuration(ApplicationConstants.DEFAULT_LIST_ANIMATION_DURATION_MS);\n\n binding.membersRecyclerView.setAdapter(animatedAdapter);\n return binding.getRoot();\n }\n\n public void scrollToTop() {\n binding.membersRecyclerView.smoothScrollToPosition(0);\n }\n\n private void addMember(User partyMember) {\n partyMembers.add(partyMember);\n Collections.sort(partyMembers, PartyMemberComparator.getByJoinedTimeComparator());\n partyMemberRecyclerAdapter.notifyDataSetChanged();\n }\n\n private void changePartyMember(User changedPartyMember) {\n List<User> toRemove = new ArrayList<>();\n for (User existingPartyMember : partyMembers) {\n if (existingPartyMember.getUserId().equals(changedPartyMember.getUserId())) {\n toRemove.add(existingPartyMember);\n }\n }\n partyMembers.removeAll(toRemove);\n addMember(changedPartyMember);\n }\n\n}", "public class TracklistFragment extends Fragment {\n\n FragmentTracklistBinding binding;\n\n @Inject\n TracklistRepository tracklistRepository;\n\n private CompositeDisposable subscriptions = new CompositeDisposable();\n\n private FadeInDownAnimator itemAnimator = new FadeInDownAnimator();\n\n private List<Song> songs = new ArrayList<>();\n\n public static TracklistFragment newInstance(String partyTitle) {\n TracklistFragment tracklistFragment = new TracklistFragment();\n Bundle newInstanceArguments = new Bundle();\n newInstanceArguments.putString(ApplicationConstants.PARTY_NAME_EXTRA, partyTitle);\n tracklistFragment.setArguments(newInstanceArguments);\n return tracklistFragment;\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n ((Injector) getContext().getApplicationContext()).inject(this);\n super.onCreate(savedInstanceState);\n String partyTitle = getArguments().getString(ApplicationConstants.PARTY_NAME_EXTRA);\n\n itemAnimator.setInterpolator(new DecelerateInterpolator());\n itemAnimator.setAddDuration(ApplicationConstants.DEFAULT_ITEM_ADD_DURATION_MS);\n itemAnimator.setRemoveDuration(ApplicationConstants.DEFAULT_ITEM_REMOVE_DURATION_MS);\n itemAnimator.setMoveDuration(ApplicationConstants.DEFAULT_ITEM_MOVE_DURATION_MS);\n\n subscriptions.add(tracklistRepository.listenToTracklistChanges(partyTitle)\n .delay(ApplicationConstants.DEFAULT_NEW_ITEM_DELAY_MS, TimeUnit.MILLISECONDS)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(childEvent -> {\n Song song = childEvent.getDataSnapshot().getValue(Song.class);\n switch (childEvent.getChangeType()) {\n case ADDED:\n addSong(song);\n break;\n case REMOVED:\n removeSong(song);\n break;\n }}));\n }\n\n @Override\n public void onDestroy() {\n subscriptions.clear();\n super.onDestroy();\n }\n\n @Override\n public void onSaveInstanceState(Bundle bundle) {\n super.onSaveInstanceState(bundle);\n bundle.putString(ApplicationConstants.PARTY_NAME_EXTRA, getArguments().getString(ApplicationConstants.PARTY_NAME_EXTRA));\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup parentContainer, Bundle savedInstanceState) {\n binding = DataBindingUtil.inflate(inflater, R.layout.fragment_tracklist, parentContainer, false);\n\n binding.tracklistRecyclerView.setLayoutManager(new LinearLayoutManager(inflater.getContext()));\n binding.tracklistRecyclerView.setEmptyView(binding.tracklistEmptyView);\n binding.tracklistRecyclerView.setItemAnimator(itemAnimator);\n binding.tracklistRecyclerView.addItemDecoration(new CustomDividerItemDecoration(\n getResources().getDrawable(R.drawable.track_list_padding_divider), true, true));\n binding.tracklistRecyclerView.setAdapter(new TracklistRecyclerAdapter(songs));\n\n return binding.getRoot();\n }\n\n public void scrollToTop() {\n binding.tracklistRecyclerView.smoothScrollToPosition(0);\n }\n\n private void addSong(Song song) {\n songs.add(song);\n int songPosition = getSongPosition(song);\n binding.tracklistRecyclerView.getAdapter().notifyItemInserted(songPosition);\n }\n\n private void removeSong(Song song) {\n int songPosition = getSongPosition(song);\n songs.remove(songPosition);\n binding.tracklistRecyclerView.getAdapter().notifyItemRemoved(songPosition);\n }\n\n private int getSongPosition(Song song) {\n for (int position = 0; position < songs.size(); position++) {\n if (song.getSongSpotifyId().equals(songs.get(position).getSongSpotifyId())) {\n return position;\n }\n }\n return -1;\n }\n\n}", "@RequiresPresenter(SearchPresenter.class)\npublic class SearchActivity extends BaseActivity<SearchPresenter> implements SearchView, SearchFragmentParent {\n\n ActivitySearchBinding binding;\n private BottomSheetBehavior bottomSheetBehavior;\n private SongRequestArrayAdapter songRequestArrayAdapter;\n private PublishSubject<Song> removeFromRequestsPublisher = PublishSubject.create();\n private ArrayList<Song> songRequests;\n\n private CompositeDisposable subscriptions = new CompositeDisposable();\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = DataBindingUtil.setContentView(this, R.layout.activity_search);\n bottomSheetBehavior = BottomSheetBehavior.from(binding.songRequestsBottomSheet);\n Bundle partyInfo = getIntent().getExtras();\n songRequests = new ArrayList<>();\n\n if (partyInfo != null) {\n getPresenter().setPartyTitle(partyInfo.getString(ApplicationConstants.PARTY_NAME_EXTRA));\n }\n\n setVolumeControlStream(AudioManager.STREAM_MUSIC);\n\n //setup viewpager and tabs\n binding.tabHolder.addTab(binding.tabHolder.newTab());\n binding.tabHolder.addTab(binding.tabHolder.newTab());\n SearchTabPagerAdapter searchTabPagerAdapter = new SearchTabPagerAdapter(getSupportFragmentManager(),\n partyInfo, binding.tabHolder.getTabCount());\n binding.fragmentPager.setAdapter(searchTabPagerAdapter);\n binding.fragmentPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(binding.tabHolder));\n binding.fragmentPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n KeyboardUtils.forceCloseKeyboard(binding.getRoot()); //close keyboard when swiping between pager tabs\n }\n\n @Override\n public void onPageSelected(int position) {\n\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n\n }\n });\n binding.tabHolder.setupWithViewPager(binding.fragmentPager);\n\n //bottom sheet setup\n binding.addFab.setOnClickListener(view -> getPresenter().queueRequestedSongs());\n binding.getRoot().post(() -> { //set the height of the content to span to the top of the bottom-sheet\n ViewGroup.LayoutParams adjustedParams = binding.fragmentHolder.getLayoutParams();\n adjustedParams.height = getRootView().getHeight() - bottomSheetBehavior.getPeekHeight();\n binding.fragmentHolder.setLayoutParams(adjustedParams);\n });\n\n //bottom sheet listview setup\n songRequestArrayAdapter = new SongRequestArrayAdapter(this, songRequests);\n songRequestArrayAdapter.setRemovalPublisher(removeFromRequestsPublisher);\n binding.bottomSheetContent.requestedSongsListView.setAdapter(songRequestArrayAdapter);\n\n //bottom sheet listview request removal-listener\n subscriptions.add(removeFromRequestsPublisher.subscribe(this::removeRequest));\n\n //handle hiding/showing bottom sheet on keyboard show/dismiss\n KeyboardUtils.addKeyboardToggleListener(this, isShowing -> {\n if (isShowing) {\n bottomSheetBehavior.setHideable(true);\n bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);\n binding.addFab.setVisibility(View.INVISIBLE);\n }\n else {\n bottomSheetBehavior.setHideable(false);\n bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);\n binding.addFab.setVisibility(View.VISIBLE);\n }\n });\n }\n\n @Override\n protected void onDestroy() {\n subscriptions.clear();\n super.onDestroy();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n super.startForegroundTokenRenewalService();\n }\n\n @Override\n public void onPause() {\n super.onPause();\n super.stopForegroundTokenRenewalService();\n }\n\n @Override\n public void finishRequest() {\n //hide bottom sheet\n bottomSheetBehavior.setHideable(true);\n bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);\n binding.addFab.setVisibility(View.INVISIBLE);\n\n //show snackbar and finish\n new SnackbarBuilder(getRootView())\n .duration(Snackbar.LENGTH_LONG)\n .message(\"Requesting songs...\")\n .dismissCallback((snackbar, event) -> finish())\n .build()\n .show();\n }\n\n @Override\n public void addRequest(Song song) {\n getPresenter().addRequest(song);\n }\n\n @Override\n public void removeRequest(Song song) {\n getPresenter().removeRequest(song);\n }\n\n @Override\n public void updateRequestList(ArrayList<Song> songRequests) {\n this.songRequests.clear();\n this.songRequests.addAll(songRequests);\n songRequestArrayAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void updateSongRequestsLabel() {\n if (songRequests.isEmpty()) {\n binding.bottomSheetContent.requestedSongsLabel.setText(R.string.selected_songs_hint_label);\n }\n else {\n binding.bottomSheetContent.requestedSongsLabel.setText(getResources().getQuantityString(\n R.plurals.selected_songs_amount_label, songRequests.size(), songRequests.size()));\n }\n }\n\n @Override\n public View getRootView() {\n return binding.getRoot();\n }\n\n}", "public class SpotiqHostService extends Service implements ConnectionStateCallback, Player.NotificationCallback {\n\n @Inject\n TracklistRepository tracklistRepository;\n\n @Inject\n SpotifyAuthenticationService spotifyCommunicatorService;\n\n private CompositeDisposable subscriptions = new CompositeDisposable();\n private Disposable autoPlayTask;\n private Handler mainThreadHandler = new Handler(Looper.getMainLooper());\n\n private Config playerConfig;\n private SpotifyPlayer spotifyPlayer;\n private boolean isTracklistEmpty = true;\n private String partyTitle;\n\n private boolean inForeground;\n private boolean changingConfiguration;\n\n private MediaSessionHandler mediaSessionHandler;\n private static final int ONGOING_NOTIFICATION_ID = 821;\n\n private IBinder binder = new HostServiceBinder();\n\n public class HostServiceBinder extends Binder {\n public SpotiqHostService getService() {\n return SpotiqHostService.this;\n }\n }\n\n private BroadcastReceiver connectionReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n if (!NetworkUtil.isConnected(context)) {\n handleLostConnection();\n }\n }\n };\n\n @Override\n public IBinder onBind(Intent intent) {\n stopForeground(true);\n changingConfiguration = false;\n inForeground = false;\n sendPlayingStatusBroadcast(isPlaying());\n return binder;\n }\n\n @Override\n public void onRebind(Intent intent) {\n stopForeground(true);\n changingConfiguration = false;\n inForeground = false;\n sendPlayingStatusBroadcast(isPlaying());\n super.onRebind(intent);\n }\n\n @Override\n public boolean onUnbind(Intent intent) {\n if (!changingConfiguration) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Starting host service in foreground\");\n inForeground = true;\n updatePlayerNotification();\n }\n return true;\n }\n\n @Override\n public void onCreate() {\n ((Injector) getApplicationContext()).inject(this);\n mediaSessionHandler = new MediaSessionHandler(this);\n Log.d(LogTag.LOG_HOST_SERVICE, \"SpotiQ Host service created\");\n }\n\n @Override\n public void onDestroy() {\n Log.d(LogTag.LOG_HOST_SERVICE, \"SpotiQ Host service destroyed\");\n stopForeground(true);\n mediaSessionHandler.releaseSessions();\n subscriptions.clear();\n if (connectionReceiver != null) {\n try {\n unregisterReceiver(connectionReceiver);\n }\n catch (IllegalArgumentException e) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Connection receiver was not registered on unregistration\");\n }\n }\n if (spotifyPlayer != null) {\n try {\n Spotify.awaitDestroyPlayer(SpotiqHostService.this, 5, TimeUnit.SECONDS);\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void onTaskRemoved(Intent rootIntent) {\n //Called when application closes by user interaction\n stopForeground(true);\n stopSelf();\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n changingConfiguration = true;\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Host service initialization started\");\n\n if (intent == null || intent.getAction() == null) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Start command intent was null, killing service\");\n stopSelf();\n return START_NOT_STICKY;\n }\n\n switch (intent.getAction()) {\n case ServiceConstants.ACTION_INIT:\n partyTitle = intent.getStringExtra(ApplicationConstants.PARTY_NAME_EXTRA);\n if (partyTitle.isEmpty()) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Host service could not be initialized - Received empty party title\");\n stopSelf();\n break;\n }\n initPlayer().subscribe(didInit -> {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Host initialization status: \" + didInit);\n if (!didInit) {\n stopSelf();\n return;\n }\n registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));\n setupServiceSettings();\n });\n break;\n case ServiceConstants.ACTION_PLAY_PAUSE:\n if (spotifyPlayer == null) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"SpotifyPlayer was null - stopping service\");\n stopSelf();\n return START_NOT_STICKY;\n }\n musicAction();\n break;\n }\n return START_STICKY;\n }\n\n private void updatePlayerNotification() {\n if (!inForeground) return;\n String title;\n String description;\n Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.image_album_placeholder);\n\n if (isPlaying() && !isTracklistEmpty) {\n Metadata.Track currentTrack = spotifyPlayer.getMetadata().currentTrack;\n title = currentTrack.name;\n description = currentTrack.artistName + \" - \" + currentTrack.albumName;\n Glide.with(this)\n .load(currentTrack.albumCoverWebUrl)\n .asBitmap()\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap albumArt, GlideAnimation<? super Bitmap> glideAnimation) {\n Notification playerNotification;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n mediaSessionHandler.setMetaData(NotificationUtil.buildMediaMetadata(currentTrack, albumArt));\n playerNotification = NotificationUtil.buildPlayerNotification(SpotiqHostService.this,\n mediaSessionHandler.getMediaSession(), title, description, albumArt);\n } else {\n mediaSessionHandler.setMetaData(NotificationUtil.buildMediaMetadataCompat(currentTrack, albumArt));\n playerNotification = NotificationUtil.buildPlayerNotificationCompat(SpotiqHostService.this,\n mediaSessionHandler.getMediaSessionCompat(), title, description, albumArt);\n }\n startForeground(ONGOING_NOTIFICATION_ID, playerNotification);\n }\n });\n }\n else {\n title = \"Hosting party \" + partyTitle;\n description = \"Player is idle\";\n Notification playerNotification;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n playerNotification = NotificationUtil.buildPlayerNotification(SpotiqHostService.this,\n mediaSessionHandler.getMediaSession(), title, description, largeIcon);\n }\n else {\n playerNotification = NotificationUtil.buildPlayerNotificationCompat(SpotiqHostService.this,\n mediaSessionHandler.getMediaSessionCompat(), title, description, largeIcon);\n }\n startForeground(ONGOING_NOTIFICATION_ID, playerNotification);\n }\n }\n\n private void sendPlayingStatusBroadcast(boolean isPlaying) {\n Intent playingStatusIntent = new Intent(ServiceConstants.PLAYING_STATUS_BROADCAST_NAME);\n playingStatusIntent.putExtra(ServiceConstants.PLAYING_STATUS_ISPLAYING_EXTRA, isPlaying);\n LocalBroadcastManager.getInstance(this).sendBroadcast(playingStatusIntent);\n }\n\n private Single<Boolean> initPlayer() {\n return Single.create(subscriber -> {\n\n playerConfig = new Config(SpotiqHostService.this,\n spotifyCommunicatorService.getAuthenticator().getAccessToken(),\n BuildConfig.SPOTIFY_CLIENT_ID);\n playerConfig.useCache(false);\n\n spotifyPlayer = Spotify.getPlayer(playerConfig, SpotiqHostService.this, new SpotifyPlayer.InitializationObserver() {\n @Override\n public void onInitialized(SpotifyPlayer player) {\n spotifyPlayer.addConnectionStateCallback(SpotiqHostService.this);\n spotifyPlayer.addNotificationCallback(SpotiqHostService.this);\n spotifyPlayer.setPlaybackBitrate(new Player.OperationCallback() {\n @Override\n public void onSuccess() {\n subscriber.onSuccess(true);\n Log.d(LogTag.LOG_HOST_SERVICE, \"Set Spotify Player custom playback bitrate successfully\");\n sendPlayingStatusBroadcast(false); //make sure all listeners are up to sync with an inititally paused status\n mediaSessionHandler.setSessionActive();\n }\n\n @Override\n public void onError(Error error) {\n subscriber.onError(new PlayerInitializationException(error.name()));\n Log.d(LogTag.LOG_HOST_SERVICE, \"Failed to set Spotify Player playback bitrate. Cause: \" + error.toString());\n\n }\n }, PlaybackBitrate.BITRATE_HIGH);\n\n }\n\n @Override\n public void onError(Throwable throwable) {\n subscriber.onError(throwable);\n Log.d(LogTag.LOG_HOST_SERVICE, \"Could not initialize Spotify Player: \" + throwable.getMessage());\n stopSelf();\n }\n\n });\n });\n }\n\n public boolean isPlaying() {\n return !(spotifyPlayer == null || spotifyPlayer.getPlaybackState() == null) && spotifyPlayer.getPlaybackState().isPlaying;\n }\n\n public void musicAction() {\n if (isPlaying()) {\n pause();\n }\n else {\n play();\n }\n }\n\n private void play() {\n if (!NetworkUtil.isConnected(this)) {\n handleLostConnection();\n return;\n }\n if (!isTracklistEmpty && spotifyPlayer.getMetadata().currentTrack != null) {\n resume();\n }\n else {\n playNext();\n }\n }\n\n private void pause() {\n spotifyPlayer.pause(new Player.OperationCallback() {\n @Override\n public void onSuccess() {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Paused music successfully\");\n }\n\n @Override\n public void onError(Error error) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Failed to pause music\");\n }\n });\n }\n\n private void resume() {\n spotifyPlayer.resume(new Player.OperationCallback() {\n @Override\n public void onSuccess() {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Resumed music successfully\");\n }\n\n @Override\n public void onError(Error error) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Failed to resume music\");\n }\n });\n }\n\n private void playNext() {\n tracklistRepository.getFirstSong(partyTitle)\n .subscribe(song -> {\n spotifyPlayer.playUri(new Player.OperationCallback() {\n @Override\n public void onSuccess() {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Playing next song in tracklist\");\n isTracklistEmpty = false;\n }\n\n @Override\n public void onError(Error error) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Failed to play next song in tracklist: \" + error.name());\n sendPlayingStatusBroadcast(false);\n }\n }, song.getSongUri(), 0, 0);\n }, throwable -> {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Could not play next song: \" + throwable.getMessage());\n sendPlayingStatusBroadcast(false);\n if (throwable instanceof EmptyTracklistException) {\n isTracklistEmpty = true;\n }\n });\n }\n\n private void setupServiceSettings() {\n //synchronize tracklist status\n tracklistRepository.getFirstSong(partyTitle)\n .subscribe((song, throwable) -> {\n if (!(throwable instanceof EmptyTracklistException)) {\n isTracklistEmpty = false;\n }\n });\n\n //setup auto playing the first track\n if (PreferenceUtil.isAutoPlayEnabled(this)) {\n autoPlayTask = tracklistRepository.listenToTracklistChanges(partyTitle)\n .subscribe(childEvent -> {\n if (childEvent.getChangeType().equals(ChildEvent.Type.ADDED) && isTracklistEmpty) {\n play();\n }\n });\n subscriptions.add(autoPlayTask);\n }\n }\n\n private void handlePlaybackEnd() {\n tracklistRepository.removeFirstSong(partyTitle)\n .subscribe(wasRemoved -> {\n if (spotifyPlayer == null) return;\n if (wasRemoved) playNext();\n }, throwable -> {\n if (throwable instanceof EmptyTracklistException) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Tracklist empty, next song not played\");\n isTracklistEmpty = true;\n }\n });\n }\n\n private void handlePlaybackError() {\n sendPlayingStatusBroadcast(false);\n showPlaybackFailedToast();\n handlePlaybackEnd();\n }\n\n private void handleLostConnection() {\n if (isPlaying()) pause();\n sendPlayingStatusBroadcast(false);\n mediaSessionHandler.setPlaybackStatePaused();\n mainThreadHandler.post(() -> {\n new ToastBuilder(getApplicationContext())\n .customView(LayoutInflater.from(getApplicationContext()).inflate(getResources().getLayout(R.layout.toast_lost_connection_container), null))\n .duration(ApplicationConstants.LONG_TOAST_DURATION_SEC)\n .build()\n .show();\n });\n }\n\n @Override\n public void onPlaybackEvent(PlayerEvent playerEvent) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Playback event: \" + playerEvent.name());\n switch (playerEvent) {\n case kSpPlaybackNotifyLostPermission:\n showLostPlaybackPermissionToast();\n break;\n case kSpPlaybackNotifyTrackDelivered:\n handlePlaybackEnd();\n break;\n case kSpPlaybackNotifyPlay:\n updatePlayerNotification();\n sendPlayingStatusBroadcast(true);\n mediaSessionHandler.setPlaybackStatePlaying();\n break;\n case kSpPlaybackNotifyPause:\n updatePlayerNotification();\n sendPlayingStatusBroadcast(false);\n mediaSessionHandler.setPlaybackStatePaused();\n break;\n }\n }\n\n private void showLostPlaybackPermissionToast() {\n mainThreadHandler.post(() -> {\n new ToastBuilder(this)\n .customView(LayoutInflater.from(this).inflate(getResources().getLayout(R.layout.toast_lost_permission_container), null))\n .duration(ApplicationConstants.LONG_TOAST_DURATION_SEC)\n .build()\n .show();\n });\n }\n\n private void showPlaybackFailedToast() {\n mainThreadHandler.post(() -> {\n new ToastBuilder(this)\n .customView(LayoutInflater.from(this).inflate(getResources().getLayout(R.layout.toast_playback_failed_container), null))\n .duration(ApplicationConstants.LONG_TOAST_DURATION_SEC)\n .build()\n .show();\n });\n }\n\n public boolean isPartyInformationMissing() {\n return partyTitle == null;\n }\n\n @Override\n public void onPlaybackError(Error error) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Spotify playback error: \" + error.toString());\n handlePlaybackError();\n }\n\n @Override\n public void onLoggedIn() {\n\n }\n\n @Override\n public void onLoggedOut() {\n }\n\n @Override\n public void onLoginFailed(Error error) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Spotify login failed: \" + error.toString());\n /*\n switch (error) {\n case kSpErrorNeedsPremium:\n break;\n }\n */\n }\n\n @Override\n public void onTemporaryError() {\n\n }\n\n @Override\n public void onConnectionMessage(String message) {\n Log.d(LogTag.LOG_HOST_SERVICE, \"Spotify connection message: \" + message);\n }\n\n}", "public class ShortcutUtil {\n\n @RequiresApi(api = Build.VERSION_CODES.N_MR1)\n public static void addSearchShortcut(Context context, String searchWithPartyTitle) {\n ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);\n\n Intent openSearch = new Intent(context.getApplicationContext(), SearchActivity.class);\n openSearch.putExtra(ApplicationConstants.PARTY_NAME_EXTRA, searchWithPartyTitle);\n openSearch.setAction(Intent.ACTION_VIEW);\n\n ShortcutInfo shortcut = new ShortcutInfo.Builder(context, ApplicationConstants.SEARCH_SHORTCUT_ID)\n .setShortLabel(\"Search songs\")\n .setLongLabel(\"Search for songs to add to the queue\")\n .setIcon(Icon.createWithResource(context, R.drawable.ic_shortcut_search))\n .setIntent(openSearch)\n .build();\n\n shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));\n }\n\n\n @RequiresApi(api = Build.VERSION_CODES.N_MR1)\n public static void removeAllShortcuts(Context context) {\n ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);\n shortcutManager.disableShortcuts(Arrays.asList(ApplicationConstants.SEARCH_SHORTCUT_ID));\n shortcutManager.removeAllDynamicShortcuts();\n }\n\n}" ]
import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.databinding.DataBindingUtil; import android.media.AudioManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.view.View; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import nucleus5.factory.RequiresPresenter; import se.zinokader.spotiq.R; import se.zinokader.spotiq.constant.ApplicationConstants; import se.zinokader.spotiq.constant.ServiceConstants; import se.zinokader.spotiq.databinding.ActivityPartyBinding; import se.zinokader.spotiq.feature.base.BaseActivity; import se.zinokader.spotiq.feature.party.partymember.PartyMemberFragment; import se.zinokader.spotiq.feature.party.tracklist.TracklistFragment; import se.zinokader.spotiq.feature.search.SearchActivity; import se.zinokader.spotiq.service.player.SpotiqHostService; import se.zinokader.spotiq.util.ShortcutUtil;
package se.zinokader.spotiq.feature.party; @RequiresPresenter(PartyPresenter.class) public class PartyActivity extends BaseActivity<PartyPresenter> implements PartyView { ActivityPartyBinding binding; private String partyTitle; private boolean userDetailsLoaded = false; private boolean hostProvilegesLoaded = false;
private SpotiqHostService hostService;
6
Tonius/SimplyJetpacks
src/main/java/tonius/simplyjetpacks/SimplyJetpacks.java
[ "public class Config {\n \n public static final List<Section> configSections = new ArrayList<Section>();\n private static final Section sectionItem = new Section(false, \"Item Settings\", \"item\");\n private static final Section sectionIntegration = new Section(false, \"Integration Settings\", \"integration\");\n private static final Section sectionControls = new Section(true, \"Controls Settings\", \"controls\");\n private static final Section sectionAesthetics = new Section(true, \"Aesthetics Settings\", \"aesthetics\");\n private static final Section sectionSounds = new Section(true, \"Sound Settings\", \"sounds\");\n private static final Section sectionGui = new Section(true, \"GUI Settings\", \"gui\");\n public static Configuration config;\n public static Configuration configClient;\n \n // item\n public static int enchantFuelEfficiencyID = Defaults.enchantFuelEfficiencyID;\n public static boolean flammableFluidsExplode = Defaults.flammableFluidsExplode;\n public static boolean addRAItemsIfNotInstalled = Defaults.addRAItemsIfNotInstalled;\n \n // integration\n public static boolean enableIntegrationTE = Defaults.enableIntegrationTE;\n public static boolean enableIntegrationEIO = Defaults.enableIntegrationEIO;\n public static boolean enableIntegrationBC = Defaults.enableIntegrationBC;\n \n // controls\n public static boolean customControls = Defaults.customControls;\n public static String flyKey = Defaults.flyKey;\n public static String descendKey = Defaults.descendKey;\n public static boolean invertHoverSneakingBehavior = Defaults.invertHoverSneakingBehavior;\n public static boolean doubleTapSprintInAir = Defaults.doubleTapSprintInAir;\n \n // aesthetics\n public static boolean enableArmor3DModels = Defaults.enableArmor3DModels;\n \n // sounds\n public static boolean jetpackSounds = Defaults.jetpackSounds;\n \n // gui\n public static boolean holdShiftForDetails = Defaults.holdShiftForDetails;\n public static int HUDPosition = Defaults.HUDPosition;\n public static int HUDOffsetX = Defaults.HUDOffsetX;\n public static int HUDOffsetY = Defaults.HUDOffsetY;\n public static double HUDScale = Defaults.HUDScale;\n public static boolean showHUDWhileChatting = Defaults.showHUDWhileChatting;\n public static boolean enableFuelHUD = Defaults.enableFuelHUD;\n public static boolean minimalFuelHUD = Defaults.minimalFuelHUD;\n public static boolean showExactFuelInHUD = Defaults.showExactFuelInHUD;\n public static boolean enableStateHUD = Defaults.enableStateHUD;\n public static boolean enableStateChatMessages = Defaults.enableStateChatMessages;\n \n public static void preInit(FMLPreInitializationEvent evt) {\n FMLCommonHandler.instance().bus().register(new Config());\n \n config = new Configuration(new File(evt.getModConfigurationDirectory(), SimplyJetpacks.MODID + \".cfg\"));\n configClient = new Configuration(new File(evt.getModConfigurationDirectory(), SimplyJetpacks.MODID + \"-client.cfg\"));\n \n syncConfig();\n SimplyJetpacks.proxy.updateCustomKeybinds(flyKey, descendKey);\n }\n \n private static void syncConfig() {\n SimplyJetpacks.logger.info(\"Loading configuration files\");\n try {\n processConfig();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (config.hasChanged()) {\n config.save();\n }\n if (configClient.hasChanged()) {\n configClient.save();\n }\n }\n }\n \n public static void onConfigChanged(String modid) {\n if (modid.equals(SimplyJetpacks.MODID)) {\n syncConfig();\n SimplyJetpacks.proxy.updateCustomKeybinds(flyKey, descendKey);\n }\n }\n \n private static void processConfig() {\n enchantFuelEfficiencyID = config.get(sectionItem.name, \"Fuel Efficiency enchant ID\", Defaults.enchantFuelEfficiencyID, \"The ID of the Fuel Efficiency enchantment. Set to 0 to disable.\").setMinValue(0).setMaxValue(255).setRequiresMcRestart(true).getInt();\n flammableFluidsExplode = config.get(sectionItem.name, \"Jetpacks explode in flammable fluid blocks\", Defaults.flammableFluidsExplode, \"When enabled, jetpacks will explode and kill their users when they are being used to fly through flammable fluid blocks.\").getBoolean(Defaults.flammableFluidsExplode);\n addRAItemsIfNotInstalled = config.get(sectionItem.name, \"Add Redstone Arsenal items if not installed\", Defaults.addRAItemsIfNotInstalled, \"When enabled, Simply Jetpacks will register some crafting components from Redstone Arsenal to make the Flux-Infused JetPlate craftable if Redstone Arsenal is not installed.\").setRequiresMcRestart(true).getBoolean(Defaults.addRAItemsIfNotInstalled);\n \n enableIntegrationTE = config.get(sectionIntegration.name, \"Thermal Expansion integration\", Defaults.enableIntegrationTE, \"When enabled, Simply Jetpacks will register its Thermal Expansion-based jetpacks and flux packs.\").setRequiresMcRestart(true).getBoolean(Defaults.enableIntegrationTE);\n enableIntegrationEIO = config.get(sectionIntegration.name, \"Ender IO integration\", Defaults.enableIntegrationEIO, \"When enabled, Simply Jetpacks will register its Ender IO-based jetpacks and flux packs.\").setRequiresMcRestart(true).getBoolean(Defaults.enableIntegrationEIO);\n enableIntegrationBC = config.get(sectionIntegration.name, \"BuildCraft integration\", Defaults.enableIntegrationBC, \"When enabled, Simply Jetpacks will register its BuildCraft-based jetpacks.\").setRequiresMcRestart(true).getBoolean(Defaults.enableIntegrationBC);\n \n customControls = configClient.get(sectionControls.name, \"Custom controls\", Defaults.customControls, \"When enabled, the key codes specified here will be used for the fly and descend keys. Otherwise, the vanilla jump and sneak keys will be used.\").getBoolean(Defaults.customControls);\n flyKey = configClient.get(sectionControls.name, \"Custom Fly key\", Defaults.flyKey, \"The name of the Fly key when custom controls are enabled.\").getString();\n descendKey = configClient.get(sectionControls.name, \"Custom Descend key\", Defaults.descendKey, \"The name of the Descend key when custom controls are enabled.\").getString();\n invertHoverSneakingBehavior = configClient.get(sectionControls.name, \"Invert Hover Mode sneaking behavior\", Defaults.invertHoverSneakingBehavior, \"Invert Hover Mode sneaking behavior\").getBoolean(Defaults.invertHoverSneakingBehavior);\n doubleTapSprintInAir = configClient.get(sectionControls.name, \"Allow double-tap sprinting while flying\", Defaults.doubleTapSprintInAir, \"When enabled, sprinting by double-tapping the forward key will work while flying with a jetpack. Can be used as an easier way to activate a jetpack's boost while airborne (the sprint key also works).\").getBoolean(Defaults.doubleTapSprintInAir);\n \n enableArmor3DModels = configClient.get(sectionAesthetics.name, \"Enable Armor 3D Models\", Defaults.enableArmor3DModels, \"When enabled, worn jetpacks and flux packs will have a 3D armor model. Otherwise, flat textures will be used.\").getBoolean(Defaults.enableArmor3DModels);\n \n jetpackSounds = configClient.get(sectionSounds.name, \"Jetpack Sounds\", Defaults.jetpackSounds, \"When enabled, jetpacks will make sounds when used.\").getBoolean(Defaults.jetpackSounds);\n \n holdShiftForDetails = configClient.get(sectionGui.name, \"Hold Shift for Details\", Defaults.holdShiftForDetails, \"When enabled, item details are only shown in the tooltip when holding Shift.\").getBoolean(Defaults.holdShiftForDetails);\n HUDPosition = configClient.get(sectionGui.name, \"HUD Base Position\", Defaults.HUDPosition, \"The base position of the HUD on the screen. 0 = top left, 1 = top center, 2 = top right, 3 = left, 4 = right, 5 = bottom left, 6 = bottom right\").setMinValue(0).setMaxValue(HUDPositions.values().length - 1).getInt(Defaults.HUDPosition);\n HUDOffsetX = configClient.get(sectionGui.name, \"HUD Offset - X\", Defaults.HUDOffsetX, \"The HUD display will be shifted horizontally by this value. This value may be negative.\").getInt(Defaults.HUDOffsetX);\n HUDOffsetY = configClient.get(sectionGui.name, \"HUD Offset - Y\", Defaults.HUDOffsetY, \"The HUD display will be shifted vertically by this value. This value may be negative.\").getInt(Defaults.HUDOffsetY);\n HUDScale = Math.abs(configClient.get(sectionGui.name, \"HUD Scale\", Defaults.HUDScale, \"How large the HUD will be rendered. Default is 1.0, can be bigger or smaller\").setMinValue(0.001D).getDouble(Defaults.HUDScale));\n showHUDWhileChatting = configClient.get(sectionGui.name, \"Show HUD while chatting\", Defaults.showHUDWhileChatting, \"When enabled, the HUD will display even when the chat window is opened.\").getBoolean(Defaults.showHUDWhileChatting);\n enableFuelHUD = configClient.get(sectionGui.name, \"Enable Fuel HUD\", Defaults.enableFuelHUD, \"When enabled, a HUD that displays the fuel level of the currently worn jetpack or flux pack will show.\").getBoolean(Defaults.enableFuelHUD);\n minimalFuelHUD = configClient.get(sectionGui.name, \"Minimal Fuel HUD\", Defaults.minimalFuelHUD, \"When enabled, only the fuel amounts themselves will be rendered on the fuel HUD.\").getBoolean(Defaults.minimalFuelHUD);\n showExactFuelInHUD = configClient.get(sectionGui.name, \"Exact fuel amounts in HUD\", Defaults.showExactFuelInHUD, \"When enabled, the fuel HUD will display the exact amount of RF or mB other than just a percentage.\").getBoolean(Defaults.showExactFuelInHUD);\n enableStateHUD = configClient.get(sectionGui.name, \"Enable State HUD\", Defaults.enableStateHUD, \"When enabled, a HUD that displays the states (engine/mode/etc.) of the currently worn jetpack or flux pack will show.\").getBoolean(Defaults.enableStateHUD);\n enableStateChatMessages = configClient.get(sectionGui.name, \"Enable State Chat Messages\", Defaults.enableStateChatMessages, \"When enabled, switching jetpacks or flux packs on or off will display chat messages.\").getBoolean(Defaults.enableStateChatMessages);\n \n PackBase.loadAllConfigs(config);\n }\n \n @SubscribeEvent\n public void onConfigChanged(OnConfigChangedEvent evt) {\n onConfigChanged(evt.modID);\n }\n \n}", "public class UpgradingRecipe extends ShapedOreRecipe {\n \n private final IEnergyContainerItem resultItem;\n private final int resultMeta;\n \n public UpgradingRecipe(ItemStack result, Object... recipe) {\n super(result, recipe);\n this.resultItem = (IEnergyContainerItem) result.getItem();\n this.resultMeta = result.getItemDamage();\n result.getEnchantmentTagList();\n }\n \n @Override\n public ItemStack getCraftingResult(InventoryCrafting inventoryCrafting) {\n int addedEnergy = 0;\n ParticleType particleType = null;\n NBTTagCompound tags = null;\n boolean enderiumUpgrade = false;\n \n ItemStack slotStack;\n for (int i = 0; i < inventoryCrafting.getSizeInventory(); i++) {\n slotStack = inventoryCrafting.getStackInSlot(i);\n if (slotStack != null && slotStack.getItem() != null) {\n if (slotStack.getItem() instanceof ItemPack) {\n tags = (NBTTagCompound) NBTHelper.getNBT(slotStack).copy();\n }\n if (slotStack.getItem() instanceof IEnergyContainerItem) {\n addedEnergy += ((IEnergyContainerItem) slotStack.getItem()).getEnergyStored(slotStack);\n } else if (slotStack.getItem() == ModItems.particleCustomizers) {\n particleType = ParticleType.values()[slotStack.getItemDamage()];\n } else if (ModItems.enderiumUpgrade != null && slotStack.getItem() == ModItems.enderiumUpgrade.getItem() && slotStack.getItemDamage() == ModItems.enderiumUpgrade.getItemDamage()) {\n enderiumUpgrade = true;\n }\n }\n }\n \n ItemStack result = new ItemStack((Item) this.resultItem, 1, this.resultMeta);\n \n if (tags != null) {\n result.setTagCompound(tags);\n }\n \n NBTHelper.getNBT(result).setInteger(\"Energy\", Math.min(addedEnergy, this.resultItem.getMaxEnergyStored(result)));\n \n if (this.resultItem instanceof ItemJetpack && particleType != null) {\n ((ItemJetpack) this.resultItem).getPack(result).setParticleType(result, particleType);\n }\n \n if (enderiumUpgrade && this.resultItem instanceof ItemPack) {\n PackBase pack = ((ItemPack) this.resultItem).getPack(result);\n if (pack instanceof JetPlate) {\n ((JetPlate) pack).setEnderiumUpgrade(result, true);\n }\n }\n \n return result;\n }\n}", "public class SyncHandler {\n \n private static final Map<EntityPlayer, Boolean> flyKeyState = new HashMap<EntityPlayer, Boolean>();\n private static final Map<EntityPlayer, Boolean> descendKeyState = new HashMap<EntityPlayer, Boolean>();\n \n private static final Map<EntityPlayer, Boolean> forwardKeyState = new HashMap<EntityPlayer, Boolean>();\n private static final Map<EntityPlayer, Boolean> backwardKeyState = new HashMap<EntityPlayer, Boolean>();\n private static final Map<EntityPlayer, Boolean> leftKeyState = new HashMap<EntityPlayer, Boolean>();\n private static final Map<EntityPlayer, Boolean> rightKeyState = new HashMap<EntityPlayer, Boolean>();\n \n private static final Map<Integer, ParticleType> jetpackState = new HashMap<Integer, ParticleType>();\n \n public static boolean isFlyKeyDown(EntityLivingBase user) {\n return !(user instanceof EntityPlayer) || flyKeyState.containsKey(user) && flyKeyState.get(user);\n }\n \n public static boolean isDescendKeyDown(EntityLivingBase user) {\n return user instanceof EntityPlayer && descendKeyState.containsKey(user) && descendKeyState.get(user);\n }\n \n public static boolean isForwardKeyDown(EntityLivingBase user) {\n return !(user instanceof EntityPlayer) || forwardKeyState.containsKey(user) && forwardKeyState.get(user);\n }\n \n public static boolean isBackwardKeyDown(EntityLivingBase user) {\n return user instanceof EntityPlayer && backwardKeyState.containsKey(user) && backwardKeyState.get(user);\n }\n \n public static boolean isLeftKeyDown(EntityLivingBase user) {\n return user instanceof EntityPlayer && leftKeyState.containsKey(user) && leftKeyState.get(user);\n }\n \n public static boolean isRightKeyDown(EntityLivingBase user) {\n return user instanceof EntityPlayer && rightKeyState.containsKey(user) && rightKeyState.get(user);\n }\n \n public static void processKeyUpdate(EntityPlayer player, boolean keyFly, boolean keyDescend, boolean keyForward, boolean keyBackward, boolean keyLeft, boolean keyRight) {\n flyKeyState.put(player, keyFly);\n descendKeyState.put(player, keyDescend);\n \n forwardKeyState.put(player, keyForward);\n backwardKeyState.put(player, keyBackward);\n leftKeyState.put(player, keyLeft);\n rightKeyState.put(player, keyRight);\n }\n \n public static void processJetpackUpdate(int entityId, ParticleType particleType) {\n if (particleType != null) {\n jetpackState.put(entityId, particleType);\n } else {\n jetpackState.remove(entityId);\n }\n }\n \n public static Map<Integer, ParticleType> getJetpackStates() {\n return jetpackState;\n }\n \n public static void clearAll() {\n flyKeyState.clear();\n forwardKeyState.clear();\n backwardKeyState.clear();\n leftKeyState.clear();\n rightKeyState.clear();\n }\n \n private static void removeFromAll(EntityPlayer player) {\n flyKeyState.remove(player);\n forwardKeyState.remove(player);\n backwardKeyState.remove(player);\n leftKeyState.remove(player);\n rightKeyState.remove(player);\n }\n \n @SubscribeEvent\n public void onPlayerLoggedIn(PlayerLoggedInEvent evt) {\n PacketHandler.instance.sendTo(new MessageConfigSync(), (EntityPlayerMP) evt.player);\n }\n \n @SubscribeEvent\n public void onPlayerLoggedOut(PlayerLoggedOutEvent evt) {\n removeFromAll(evt.player);\n }\n \n @SubscribeEvent\n public void onDimChanged(PlayerChangedDimensionEvent evt) {\n removeFromAll(evt.player);\n }\n \n @SubscribeEvent\n public void onClientDisconnectedFromServer(ClientDisconnectionFromServerEvent evt) {\n SoundJetpack.clearPlayingFor();\n Config.onConfigChanged(SimplyJetpacks.MODID);\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 abstract class ModEnchantments {\n \n public static final EnumEnchantmentType enchantType = EnumHelper.addEnchantmentType(SimplyJetpacks.MODID);\n public static Enchantment fuelEffeciency = null;\n \n public static void init() {\n int id = Config.enchantFuelEfficiencyID;\n \n if (id > 0) {\n fuelEffeciency = new EnchantmentFuelEfficiency(id);\n }\n }\n \n}", "public abstract class ModItems {\n \n private static boolean integrateTE = false;\n private static boolean integrateTD = false;\n private static boolean integrateRA = false;\n private static boolean integrateEIO = false;\n private static boolean integrateBC = false;\n \n public static void preInit() {\n integrateTE = ModType.THERMAL_EXPANSION.loaded && Config.enableIntegrationTE;\n integrateTD = ModType.THERMAL_DYNAMICS.loaded && integrateTE;\n integrateRA = ModType.REDSTONE_ARSENAL.loaded && integrateTE;\n integrateEIO = ModType.ENDER_IO.loaded && Config.enableIntegrationEIO;\n integrateBC = ModType.BUILDCRAFT.loaded && Config.enableIntegrationBC;\n \n registerItems();\n }\n \n public static void init() {\n if (integrateTE) {\n TEItems.init();\n if (integrateTD) {\n TDItems.init();\n }\n if (integrateRA) {\n RAItems.init();\n }\n }\n if (integrateEIO) {\n EIOItems.init();\n }\n if (integrateBC) {\n BCItems.init();\n }\n \n registerRecipes();\n doIMC();\n }\n \n private static void registerItems() {\n SimplyJetpacks.logger.info(\"Registering items\");\n \n // For compatibility, do not change item IDs until 1.8+\n \n jetpacksCommon = new ItemJetpack(ModType.SIMPLY_JETPACKS, \"jetpacksCommon\");\n jetpackPotato = jetpacksCommon.putPack(0, Packs.jetpackPotato, true);\n jetpackCreative = jetpacksCommon.putPack(9001, Packs.jetpackCreative);\n fluxPacksCommon = new ItemFluxPack(ModType.SIMPLY_JETPACKS, \"fluxpacksCommon\");\n fluxPackCreative = fluxPacksCommon.putPack(9001, Packs.fluxPackCreative);\n \n if (integrateTE) {\n jetpacksTE = new ItemJetpack(ModType.THERMAL_EXPANSION, \"jetpacks\");\n jetpackTE1 = jetpacksTE.putPack(1, Packs.jetpackTE1);\n jetpackTE1Armored = jetpacksTE.putPack(101, Packs.jetpackTE1Armored);\n jetpackTE2 = jetpacksTE.putPack(2, Packs.jetpackTE2);\n jetpackTE2Armored = jetpacksTE.putPack(102, Packs.jetpackTE2Armored);\n jetpackTE3 = jetpacksTE.putPack(3, Packs.jetpackTE3);\n jetpackTE3Armored = jetpacksTE.putPack(103, Packs.jetpackTE3Armored);\n jetpackTE4 = jetpacksTE.putPack(4, Packs.jetpackTE4);\n jetpackTE4Armored = jetpacksTE.putPack(104, Packs.jetpackTE4Armored);\n if (integrateRA || Config.addRAItemsIfNotInstalled) {\n jetpackTE5 = jetpacksTE.putPack(5, Packs.jetpackTE5);\n }\n fluxPacksTE = new ItemFluxPack(ModType.THERMAL_EXPANSION, \"fluxpacks\");\n fluxPackTE1 = fluxPacksTE.putPack(1, Packs.fluxPackTE1);\n fluxPackTE2 = fluxPacksTE.putPack(2, Packs.fluxPackTE2);\n fluxPackTE2Armored = fluxPacksTE.putPack(102, Packs.fluxPackTE2Armored);\n fluxPackTE3 = fluxPacksTE.putPack(3, Packs.fluxPackTE3);\n fluxPackTE3Armored = fluxPacksTE.putPack(103, Packs.fluxPackTE3Armored);\n fluxPackTE4 = fluxPacksTE.putPack(4, Packs.fluxPackTE4);\n fluxPackTE4Armored = fluxPacksTE.putPack(104, Packs.fluxPackTE4Armored);\n }\n if (integrateEIO) {\n jetpacksEIO = new ItemJetpack(ModType.ENDER_IO, \"jetpacksEIO\");\n jetpackEIO1 = jetpacksEIO.putPack(1, Packs.jetpackEIO1);\n jetpackEIO1Armored = jetpacksEIO.putPack(101, Packs.jetpackEIO1Armored);\n jetpackEIO2 = jetpacksEIO.putPack(2, Packs.jetpackEIO2);\n jetpackEIO2Armored = jetpacksEIO.putPack(102, Packs.jetpackEIO2Armored);\n jetpackEIO3 = jetpacksEIO.putPack(3, Packs.jetpackEIO3);\n jetpackEIO3Armored = jetpacksEIO.putPack(103, Packs.jetpackEIO3Armored);\n jetpackEIO4 = jetpacksEIO.putPack(4, Packs.jetpackEIO4);\n jetpackEIO4Armored = jetpacksEIO.putPack(104, Packs.jetpackEIO4Armored);\n jetpackEIO5 = jetpacksEIO.putPack(5, Packs.jetpackEIO5);\n fluxPacksEIO = new ItemFluxPack(ModType.ENDER_IO, \"fluxpacksEIO\");\n fluxPackEIO1 = fluxPacksEIO.putPack(1, Packs.fluxPackEIO1);\n fluxPackEIO2 = fluxPacksEIO.putPack(2, Packs.fluxPackEIO2);\n fluxPackEIO2Armored = fluxPacksEIO.putPack(102, Packs.fluxPackEIO2Armored);\n fluxPackEIO3 = fluxPacksEIO.putPack(3, Packs.fluxPackEIO3);\n fluxPackEIO3Armored = fluxPacksEIO.putPack(103, Packs.fluxPackEIO3Armored);\n fluxPackEIO4 = fluxPacksEIO.putPack(4, Packs.fluxPackEIO4);\n fluxPackEIO4Armored = fluxPacksEIO.putPack(104, Packs.fluxPackEIO4Armored);\n }\n if (integrateBC) {\n jetpacksBC = new ItemJetpack(ModType.BUILDCRAFT, \"jetpacksBC\");\n if (Loader.isModLoaded(\"BuildCraft|Energy\") && Loader.isModLoaded(\"BuildCraft|Factory\")) {\n jetpackBC1 = jetpacksBC.putPack(1, Packs.jetpackBC1);\n jetpackBC1Armored = jetpacksBC.putPack(101, Packs.jetpackBC1Armored);\n }\n jetpackBC2 = jetpacksBC.putPack(2, Packs.jetpackBC2);\n jetpackBC2Armored = jetpacksBC.putPack(102, Packs.jetpackBC2Armored);\n }\n \n components = new ItemMeta(\"components\");\n armorPlatings = new ItemMeta(\"armorPlatings\");\n particleCustomizers = new ItemMeta(\"particleCustomizers\");\n jetpackFueller = new ItemJetpackFueller(\"jetpackFueller\");\n mysteriousPotato = new ItemMysteriousPotato(\"mysteriousPotato\");\n \n leatherStrap = components.addMetaItem(0, new MetaItem(\"leatherStrap\", null, EnumRarity.common), true, false);\n jetpackIcon = components.addMetaItem(1, new MetaItem(\"jetpack.icon\", null, EnumRarity.common, false, true), false, false);\n \n if (integrateTE) {\n thrusterTE1 = components.addMetaItem(11, new MetaItem(\"thruster.te.1\", null, EnumRarity.common), true, false);\n thrusterTE2 = components.addMetaItem(12, new MetaItem(\"thruster.te.2\", null, EnumRarity.common), true, false);\n thrusterTE3 = components.addMetaItem(13, new MetaItem(\"thruster.te.3\", null, EnumRarity.uncommon), true, false);\n thrusterTE4 = components.addMetaItem(14, new MetaItem(\"thruster.te.4\", null, EnumRarity.rare), true, false);\n if (integrateRA || Config.addRAItemsIfNotInstalled) {\n thrusterTE5 = components.addMetaItem(15, new MetaItem(\"thruster.te.5\", null, EnumRarity.epic), true, false);\n unitGlowstoneEmpty = components.addMetaItem(60, new MetaItem(\"unitGlowstone.empty\", null, EnumRarity.common), true, false);\n unitGlowstone = components.addMetaItem(61, new MetaItem(\"unitGlowstone\", null, EnumRarity.uncommon), true, false);\n unitCryotheumEmpty = components.addMetaItem(62, new MetaItem(\"unitCryotheum.empty\", null, EnumRarity.common), true, false);\n unitCryotheum = components.addMetaItem(63, new MetaItem(\"unitCryotheum\", null, EnumRarity.rare), true, false);\n }\n if (!integrateRA && Config.addRAItemsIfNotInstalled) {\n dustElectrumFlux = components.addMetaItem(64, new MetaItem(\"dustElectrumFlux\", \"raReplacement\", EnumRarity.uncommon), true, true);\n ingotElectrumFlux = components.addMetaItem(65, new MetaItem(\"ingotElectrumFlux\", \"raReplacement\", EnumRarity.uncommon), true, true);\n nuggetElectrumFlux = components.addMetaItem(66, new MetaItem(\"nuggetElectrumFlux\", \"raReplacement\", EnumRarity.uncommon), true, true);\n gemCrystalFlux = components.addMetaItem(67, new MetaItem(\"gemCrystalFlux\", \"raReplacement\", EnumRarity.uncommon), true, true);\n plateFlux = components.addMetaItem(68, new MetaItem(\"plateFlux\", \"raReplacement\", EnumRarity.uncommon), true, false);\n armorFluxPlate = components.addMetaItem(69, new MetaItem(\"armorFluxPlate\", \"raReplacement\", EnumRarity.uncommon), true, false);\n }\n if (ModType.REDSTONE_ARMORY.loaded) {\n enderiumUpgrade = components.addMetaItem(59, new MetaItem(\"enderiumUpgrade\", \"enderiumUpgrade\", EnumRarity.rare), true, false);\n }\n \n armorPlatingTE1 = armorPlatings.addMetaItem(1, new MetaItem(\"armorPlating.te.1\", null, EnumRarity.common), true, false);\n armorPlatingTE2 = armorPlatings.addMetaItem(2, new MetaItem(\"armorPlating.te.2\", null, EnumRarity.common), true, false);\n armorPlatingTE3 = armorPlatings.addMetaItem(3, new MetaItem(\"armorPlating.te.3\", null, EnumRarity.common), true, false);\n armorPlatingTE4 = armorPlatings.addMetaItem(4, new MetaItem(\"armorPlating.te.4\", null, EnumRarity.rare), true, false);\n }\n if (integrateEIO) {\n thrusterEIO1 = components.addMetaItem(21, new MetaItem(\"thruster.eio.1\", null, EnumRarity.common), true, false);\n thrusterEIO2 = components.addMetaItem(22, new MetaItem(\"thruster.eio.2\", null, EnumRarity.common), true, false);\n thrusterEIO3 = components.addMetaItem(23, new MetaItem(\"thruster.eio.3\", null, EnumRarity.uncommon), true, false);\n thrusterEIO4 = components.addMetaItem(24, new MetaItem(\"thruster.eio.4\", null, EnumRarity.rare), true, false);\n thrusterEIO5 = components.addMetaItem(25, new MetaItem(\"thruster.eio.5\", null, EnumRarity.epic), true, false);\n ingotDarkSoularium = components.addMetaItem(70, new MetaItem(\"ingotDarkSoularium\", null, EnumRarity.uncommon, true, false), true, true);\n reinforcedGliderWing = components.addMetaItem(71, new MetaItem(\"reinforcedGliderWing\", null, EnumRarity.uncommon), true, false);\n unitFlightControlEmpty = components.addMetaItem(72, new MetaItem(\"unitFlightControl.empty\", null, EnumRarity.common), true, false);\n unitFlightControl = components.addMetaItem(73, new MetaItem(\"unitFlightControl\", null, EnumRarity.uncommon), true, false);\n \n armorPlatingEIO1 = armorPlatings.addMetaItem(11, new MetaItem(\"armorPlating.eio.1\", null, EnumRarity.common), true, false);\n armorPlatingEIO2 = armorPlatings.addMetaItem(12, new MetaItem(\"armorPlating.eio.2\", null, EnumRarity.common), true, false);\n armorPlatingEIO3 = armorPlatings.addMetaItem(13, new MetaItem(\"armorPlating.eio.3\", null, EnumRarity.common), true, false);\n armorPlatingEIO4 = armorPlatings.addMetaItem(14, new MetaItem(\"armorPlating.eio.4\", null, EnumRarity.common), true, false);\n }\n if (integrateBC) {\n if (Loader.isModLoaded(\"BuildCraft|Energy\") && Loader.isModLoaded(\"BuildCraft|Factory\")) {\n thrusterBC1 = components.addMetaItem(31, new MetaItem(\"thruster.bc.1\", null, EnumRarity.common), true, false);\n }\n thrusterBC2 = components.addMetaItem(32, new MetaItem(\"thruster.bc.2\", null, EnumRarity.uncommon), true, false);\n \n armorPlatingBC1 = armorPlatings.addMetaItem(21, new MetaItem(\"armorPlating.bc.1\", null, EnumRarity.common), true, false);\n armorPlatingBC2 = armorPlatings.addMetaItem(22, new MetaItem(\"armorPlating.bc.2\", null, EnumRarity.uncommon), true, false);\n }\n \n particleDefault = particleCustomizers.addMetaItem(0, new MetaItem(\"particle.0\", \"particleCustomizers\", EnumRarity.common), true, false);\n particleNone = particleCustomizers.addMetaItem(1, new MetaItem(\"particle.1\", \"particleCustomizers\", EnumRarity.common), true, false);\n particleSmoke = particleCustomizers.addMetaItem(2, new MetaItem(\"particle.2\", \"particleCustomizers\", EnumRarity.common), true, false);\n particleRainbowSmoke = particleCustomizers.addMetaItem(3, new MetaItem(\"particle.3\", \"particleCustomizers\", EnumRarity.common), true, false);\n }\n \n private static void registerRecipes() {\n SimplyJetpacks.logger.info(\"Registering recipes\");\n \n ItemHelper.addShapedOreRecipe(jetpackPotato, \"S S\", \"NPN\", \"R R\", 'S', Items.string, 'N', \"nuggetGold\", 'P', Items.potato, 'R', \"dustRedstone\");\n ItemHelper.addShapedOreRecipe(jetpackPotato, \"S S\", \"NPN\", \"R R\", 'S', Items.string, 'N', \"nuggetGold\", 'P', Items.poisonous_potato, 'R', \"dustRedstone\");\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackCreative, \"J\", \"P\", 'J', jetpackCreative, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n \n ItemHelper.addShapedOreRecipe(leatherStrap, \"LIL\", \"LIL\", 'L', Items.leather, 'I', \"ingotIron\");\n \n Object dustCoal = OreDictionary.getOres(\"dustCoal\").size() > 0 ? \"dustCoal\" : new ItemStack(Items.coal);\n ItemHelper.addShapedOreRecipe(particleDefault, \" D \", \"DCD\", \" D \", 'C', dustCoal, 'D', Blocks.torch);\n ItemHelper.addShapedOreRecipe(particleNone, \" D \", \"DCD\", \" D \", 'C', dustCoal, 'D', \"blockGlass\");\n ItemHelper.addShapedOreRecipe(particleSmoke, \" C \", \"CCC\", \" C \", 'C', dustCoal);\n ItemHelper.addShapedOreRecipe(particleRainbowSmoke, \" R \", \" C \", \"G B\", 'C', dustCoal, 'R', \"dyeRed\", 'G', \"dyeLime\", 'B', \"dyeBlue\");\n \n ItemHelper.addShapedOreRecipe(jetpackFueller, \"IY \", \" IY\", \" SI\", 'I', \"ingotIron\", 'Y', \"dyeYellow\", 'S', \"stickWood\");\n \n if (integrateTE) {\n if (!integrateRA && Config.addRAItemsIfNotInstalled) {\n ItemHelper.addReverseStorageRecipe(nuggetElectrumFlux, \"ingotElectrumFlux\");\n ItemHelper.addStorageRecipe(ingotElectrumFlux, \"nuggetElectrumFlux\");\n ItemHelper.addShapedOreRecipe(plateFlux, \"NNN\", \"GIG\", \"NNN\", 'G', \"gemCrystalFlux\", 'I', \"ingotElectrumFlux\", 'N', \"nuggetElectrumFlux\");\n ItemHelper.addShapedOreRecipe(armorFluxPlate, \"I I\", \"III\", \"III\", 'I', plateFlux);\n }\n \n Object ductFluxLeadstone = integrateTD ? TDItems.ductFluxLeadstone : \"blockGlass\";\n Object ductFluxHardened = integrateTD ? TDItems.ductFluxHardened : \"blockGlass\";\n Object ductFluxRedstoneEnergy = integrateTD ? TDItems.ductFluxRedstoneEnergy : \"blockGlassHardened\";\n Object ductFluxResonant = integrateTD ? TDItems.ductFluxResonant : \"blockGlassHardened\";\n \n ItemHelper.addShapedOreRecipe(thrusterTE1, \"ICI\", \"PDP\", \"IRI\", 'I', \"ingotLead\", 'P', ductFluxLeadstone, 'C', TEItems.powerCoilGold, 'D', TEItems.dynamoSteam, 'R', \"dustRedstone\");\n ItemHelper.addShapedOreRecipe(thrusterTE2, \"ICI\", \"PDP\", \"IRI\", 'I', \"ingotInvar\", 'P', ductFluxHardened, 'C', TEItems.powerCoilGold, 'D', TEItems.dynamoReactant, 'R', \"dustRedstone\");\n ItemHelper.addShapedOreRecipe(thrusterTE3, \"ICI\", \"PDP\", \"IRI\", 'I', \"ingotElectrum\", 'P', ductFluxRedstoneEnergy, 'C', TEItems.powerCoilGold, 'D', TEItems.dynamoMagmatic, 'R', \"bucketRedstone\");\n ItemHelper.addShapedOreRecipe(thrusterTE4, \"ICI\", \"PDP\", \"IRI\", 'I', \"ingotEnderium\", 'P', ductFluxResonant, 'C', TEItems.powerCoilGold, 'D', TEItems.dynamoEnervation, 'R', \"bucketRedstone\");\n \n ItemHelper.addShapedOreRecipe(armorPlatingTE1, \"TIT\", \"III\", \"TIT\", 'I', \"ingotIron\", 'T', \"ingotTin\");\n \n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE1, \"ICI\", \"ISI\", 'I', \"ingotLead\", 'C', TEItems.cellBasic, 'S', leatherStrap));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE2, \" I \", \"ISI\", \" I \", 'I', \"ingotInvar\", 'S', fluxPackTE1));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE3, \" C \", \"ISI\", \"LOL\", 'I', \"ingotElectrum\", 'L', \"ingotLead\", 'C', TEItems.frameCellReinforcedFull, 'S', fluxPackTE2, 'O', TEItems.powerCoilElectrum));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE4, \" I \", \"ISI\", \" I \", 'I', \"ingotEnderium\", 'S', fluxPackTE3));\n \n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE2Armored, \"P\", \"J\", 'J', fluxPackTE2, 'P', armorPlatingTE1));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE2, \"J\", 'J', fluxPackTE2Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE3Armored, \"P\", \"J\", 'J', fluxPackTE3, 'P', armorPlatingTE2));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE3, \"J\", 'J', fluxPackTE3Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE4Armored, \"P\", \"J\", 'J', fluxPackTE4, 'P', armorPlatingTE3));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackTE4, \"J\", 'J', fluxPackTE4Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE1, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotLead\", 'B', TEItems.capacitorBasic, 'T', thrusterTE1, 'J', leatherStrap));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE2, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotInvar\", 'B', TEItems.capacitorHardened, 'T', thrusterTE2, 'J', jetpackTE1));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE3, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotElectrum\", 'B', TEItems.capacitorReinforced, 'T', thrusterTE3, 'J', jetpackTE2));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE4, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotEnderium\", 'B', TEItems.capacitorResonant, 'T', thrusterTE4, 'J', jetpackTE3));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE1Armored, \"P\", \"J\", 'J', jetpackTE1, 'P', armorPlatingTE1));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE1, \"J\", 'J', jetpackTE1Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE2Armored, \"P\", \"J\", 'J', jetpackTE2, 'P', armorPlatingTE2));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE2, \"J\", 'J', jetpackTE2Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE3Armored, \"P\", \"J\", 'J', jetpackTE3, 'P', armorPlatingTE3));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE3, \"J\", 'J', jetpackTE3Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE4Armored, \"P\", \"J\", 'J', jetpackTE4, 'P', armorPlatingTE4));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE4, \"J\", 'J', jetpackTE4Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE1, \"J\", \"P\", 'J', jetpackTE1, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE2, \"J\", \"P\", 'J', jetpackTE2, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE3, \"J\", \"P\", 'J', jetpackTE3, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE4, \"J\", \"P\", 'J', jetpackTE4, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n \n if (integrateRA || Config.addRAItemsIfNotInstalled) {\n ItemHelper.addShapedOreRecipe(unitGlowstoneEmpty, \"FLF\", \"LHL\", \"FLF\", 'L', \"ingotLumium\", 'F', \"ingotElectrumFlux\", 'H', TEItems.frameIlluminator);\n ItemHelper.addShapedOreRecipe(unitCryotheumEmpty, \"FTF\", \"THT\", \"FTF\", 'T', \"ingotTin\", 'F', \"ingotElectrumFlux\", 'H', \"blockGlassHardened\");\n ItemHelper.addShapedOreRecipe(thrusterTE5, \"FPF\", \"GRG\", 'G', unitGlowstone, 'P', RAItems.plateFlux != null ? RAItems.plateFlux : plateFlux, 'R', thrusterTE4, 'F', \"ingotElectrumFlux\");\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE5, \"PAP\", \"OJO\", \"TCT\", 'A', RAItems.armorFluxPlate != null ? RAItems.armorFluxPlate : armorFluxPlate, 'J', jetpackTE4Armored, 'O', unitCryotheum, 'C', fluxPackTE4Armored, 'T', thrusterTE5, 'P', RAItems.plateFlux != null ? RAItems.plateFlux : plateFlux));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE5, \"J\", \"P\", 'J', jetpackTE5, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n \n if (ModType.REDSTONE_ARMORY.loaded) {\n ItemHelper.addGearRecipe(enderiumUpgrade, \"ingotEnderium\", \"slimeball\");\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackTE5, \"U\", \"J\", 'J', jetpackTE5, 'U', enderiumUpgrade));\n }\n }\n }\n \n if (integrateEIO) {\n ItemHelper.addShapedOreRecipe(thrusterEIO1, \"ICI\", \"PCP\", \"DSD\", 'I', \"ingotConductiveIron\", 'P', EIOItems.redstoneConduit, 'C', EIOItems.basicCapacitor, 'D', EIOItems.basicGear, 'S', \"dustRedstone\");\n ItemHelper.addShapedOreRecipe(thrusterEIO2, \"ICI\", \"PCP\", \"DSD\", 'I', \"ingotElectricalSteel\", 'P', EIOItems.energyConduit1, 'C', EIOItems.basicCapacitor, 'D', EIOItems.machineChassis, 'S', \"dustRedstone\");\n ItemHelper.addShapedOreRecipe(thrusterEIO3, \"ICI\", \"PCP\", \"DSD\", 'I', \"ingotEnergeticAlloy\", 'P', EIOItems.energyConduit2, 'C', EIOItems.doubleCapacitor, 'D', EIOItems.pulsatingCrystal, 'S', \"ingotRedstoneAlloy\");\n ItemHelper.addShapedOreRecipe(thrusterEIO4, \"ICI\", \"PCP\", \"DSD\", 'I', \"ingotPhasedGold\", 'P', EIOItems.energyConduit3, 'C', EIOItems.octadicCapacitor, 'D', EIOItems.vibrantCrystal, 'S', \"ingotRedstoneAlloy\");\n \n ItemHelper.addShapedOreRecipe(armorPlatingEIO1, \"SIS\", \"ISI\", \"SIS\", 'I', \"ingotIron\", 'S', \"itemSilicon\");\n \n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO1, \"CIC\", \"ISI\", \"IPI\", 'S', leatherStrap, 'C', EIOItems.basicCapacitor, 'I', \"ingotConductiveIron\", 'P', \"dustCoal\"));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO2, \"DCD\", \"ISI\", \"IPI\", 'S', fluxPackEIO1, 'C', EIOItems.basicCapacitor, 'D', EIOItems.doubleCapacitor, 'I', \"ingotElectricalSteel\", 'P', \"dustGold\"));\n if (EIOItems.capacitorBank != null && EIOItems.capacitorBank.getItem() != null) {\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO3, \"CBC\", \"ISI\", \"IPI\", 'S', fluxPackEIO2, 'C', EIOItems.doubleCapacitor, 'B', EIOItems.capacitorBank, 'I', \"ingotEnergeticAlloy\", 'P', EIOItems.pulsatingCrystal));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO4, \"BCB\", \"ISI\", \"CPC\", 'S', fluxPackEIO3, 'C', EIOItems.octadicCapacitor, 'B', EIOItems.capacitorBankVibrant, 'I', \"ingotPhasedGold\", 'P', EIOItems.vibrantCrystal));\n } else {\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO3, \"CBC\", \"ISI\", \"IPI\", 'S', fluxPackEIO2, 'C', EIOItems.doubleCapacitor, 'B', EIOItems.capacitorBankOld, 'I', \"ingotEnergeticAlloy\", 'P', EIOItems.pulsatingCrystal));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO4, \"CBC\", \"ISI\", \"BPB\", 'S', fluxPackEIO3, 'C', EIOItems.octadicCapacitor, 'B', EIOItems.capacitorBankOld, 'I', \"ingotPhasedGold\", 'P', EIOItems.vibrantCrystal));\n }\n \n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO2Armored, \"P\", \"J\", 'J', fluxPackEIO2, 'P', armorPlatingEIO1));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO2, \"J\", 'J', fluxPackEIO2Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO3Armored, \"P\", \"J\", 'J', fluxPackEIO3, 'P', armorPlatingEIO2));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO3, \"J\", 'J', fluxPackEIO3Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO4Armored, \"P\", \"J\", 'J', fluxPackEIO4, 'P', armorPlatingEIO3));\n GameRegistry.addRecipe(new UpgradingRecipe(fluxPackEIO4, \"J\", 'J', fluxPackEIO4Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO1, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotConductiveIron\", 'B', EIOItems.basicCapacitor, 'T', thrusterEIO1, 'J', leatherStrap));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO2, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotElectricalSteel\", 'B', EIOItems.basicCapacitor, 'T', thrusterEIO2, 'J', jetpackEIO1));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO3, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotEnergeticAlloy\", 'B', EIOItems.doubleCapacitor, 'T', thrusterEIO3, 'J', jetpackEIO2));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO4, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotPhasedGold\", 'B', EIOItems.octadicCapacitor, 'T', thrusterEIO4, 'J', jetpackEIO3));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO1Armored, \"P\", \"J\", 'J', jetpackEIO1, 'P', armorPlatingEIO1));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO1, \"J\", 'J', jetpackEIO1Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO2Armored, \"P\", \"J\", 'J', jetpackEIO2, 'P', armorPlatingEIO2));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO2, \"J\", 'J', jetpackEIO2Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO3Armored, \"P\", \"J\", 'J', jetpackEIO3, 'P', armorPlatingEIO3));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO3, \"J\", 'J', jetpackEIO3Armored));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO4Armored, \"P\", \"J\", 'J', jetpackEIO4, 'P', armorPlatingEIO4));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO4, \"J\", 'J', jetpackEIO4Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO1, \"J\", \"P\", 'J', jetpackEIO1, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO2, \"J\", \"P\", 'J', jetpackEIO2, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO3, \"J\", \"P\", 'J', jetpackEIO3, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO4, \"J\", \"P\", 'J', jetpackEIO4, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n \n ItemHelper.addShapedOreRecipe(unitFlightControlEmpty, \"FLF\", \"LHL\", \"FLF\", 'L', \"ingotElectricalSteel\", 'F', \"ingotDarkSoularium\", 'H', \"blockGlassHardened\");\n ItemHelper.addShapedOreRecipe(thrusterEIO5, \"SES\", \"CTC\", 'T', thrusterEIO4, 'S', \"ingotDarkSoularium\", 'E', unitFlightControl, 'C', EIOItems.octadicCapacitor);\n ItemHelper.addShapedOreRecipe(reinforcedGliderWing, \" S\", \" SP\", \"SPP\", 'S', \"ingotDarkSoularium\", 'P', armorPlatingEIO2);\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO5, \"OAO\", \"PJP\", \"TCT\", 'A', EIOItems.enderCrystal, 'J', jetpackEIO4Armored, 'O', \"ingotDarkSoularium\", 'C', fluxPackEIO4Armored, 'T', thrusterEIO5, 'P', reinforcedGliderWing));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackEIO5, \"J\", \"P\", 'J', jetpackEIO5, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n }\n \n if (integrateBC) {\n ItemHelper.addShapedOreRecipe(armorPlatingBC1, /* listen here u */\"LIL\"/* shit */, \"ILI\", \"LIL\", 'I', \"ingotIron\", 'L', Items.leather);\n ItemHelper.addSurroundRecipe(armorPlatingBC2, armorPlatingBC1, \"gemDiamond\");\n \n if (jetpackBC1 != null) {\n ItemHelper.addShapedOreRecipe(thrusterBC1, \"IGI\", \"PEP\", \"IBI\", 'I', \"ingotIron\", 'G', \"gearIron\", 'P', BCItems.pipeFluidStone, 'E', BCItems.engineCombustion, 'B', Blocks.iron_bars);\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC1, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotIron\", 'B', BCItems.tank, 'T', thrusterBC1, 'J', leatherStrap));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC1Armored, \"P\", \"J\", 'J', jetpackBC1, 'P', armorPlatingBC1));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC1, \"J\", 'J', jetpackBC1Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC1, \"J\", \"P\", 'J', jetpackBC1, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n }\n \n Object jetpack = jetpackBC1 != null ? jetpackBC1 : leatherStrap;\n Object thruster = thrusterBC1 != null ? thrusterBC1 : \"gearIron\";\n if (Loader.isModLoaded(\"BuildCraft|Silicon\")) {\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotGold\", 'B', \"crystalRedstone\" /* BC7 */, 'T', thrusterBC2, 'J', jetpack));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotGold\", 'B', \"redstoneCrystal\" /* BC6 */, 'T', thrusterBC2, 'J', jetpack));\n } else {\n ItemHelper.addShapedOreRecipe(thrusterBC2, \"IGI\", \"PEP\", \"IBI\", 'I', \"ingotGold\", 'G', \"gearGold\", 'P', BCItems.pipeEnergyGold, 'E', thruster, 'B', Blocks.iron_bars);\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2, \"IBI\", \"IJI\", \"T T\", 'I', \"ingotGold\", 'B', \"gearDiamond\", 'T', thrusterBC2, 'J', jetpack));\n }\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2Armored, \"P\", \"J\", 'J', jetpackBC2, 'P', armorPlatingBC2));\n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2, \"J\", 'J', jetpackBC2Armored));\n \n GameRegistry.addRecipe(new UpgradingRecipe(jetpackBC2, \"J\", \"P\", 'J', jetpackBC2, 'P', new ItemStack(particleCustomizers, 1, OreDictionary.WILDCARD_VALUE)));\n }\n }\n \n private static void doIMC() {\n SimplyJetpacks.logger.info(\"Doing intermod communication\");\n \n if (integrateTE) {\n if (!integrateRA && Config.addRAItemsIfNotInstalled) {\n TERecipes.addTransposerFill(8000, new ItemStack(Items.diamond), gemCrystalFlux, new FluidStack(FluidRegistry.getFluid(\"redstone\"), 200), false);\n TERecipes.addTransposerFill(4000, OreDictionary.getOres(\"dustElectrum\").get(0), dustElectrumFlux, new FluidStack(FluidRegistry.getFluid(\"redstone\"), 200), false);\n TERecipes.addSmelterBlastOre(\"ElectrumFlux\");\n }\n \n ItemStack i = OreDictionary.getOres(\"ingotBronze\").get(0).copy();\n i.stackSize = 10;\n TERecipes.addSmelterRecipe(3200, armorPlatingTE1, i, armorPlatingTE2, null, 0);\n \n i = OreDictionary.getOres(\"ingotInvar\").get(0).copy();\n i.stackSize = 10;\n TERecipes.addSmelterRecipe(4800, armorPlatingTE2, i, armorPlatingTE3, null, 0);\n \n i = OreDictionary.getOres(\"ingotEnderium\").get(0).copy();\n i.stackSize = 10;\n TERecipes.addSmelterRecipe(6400, armorPlatingTE3, i, armorPlatingTE4, null, 0);\n \n if (integrateRA || Config.addRAItemsIfNotInstalled) {\n TERecipes.addTransposerFill(6400, unitGlowstoneEmpty, unitGlowstone, new FluidStack(FluidRegistry.getFluid(\"glowstone\"), 4000), false);\n TERecipes.addTransposerFill(6400, unitCryotheumEmpty, unitCryotheum, new FluidStack(FluidRegistry.getFluid(\"cryotheum\"), 4000), false);\n }\n }\n if (integrateEIO) {\n ItemStack ingotConductiveIron = OreDictionary.getOres(\"ingotConductiveIron\").get(0).copy();\n ingotConductiveIron.stackSize = 10;\n EIORecipes.addAlloySmelterRecipe(\"Conductive Iron Armor Plating\", 3200, armorPlatingEIO1, ingotConductiveIron, null, armorPlatingEIO2);\n \n ItemStack ingotElectricalSteel = OreDictionary.getOres(\"ingotElectricalSteel\").get(0).copy();\n ingotElectricalSteel.stackSize = 10;\n EIORecipes.addAlloySmelterRecipe(\"Electrical Steel Armor Plating\", 4800, armorPlatingEIO2, ingotElectricalSteel, null, armorPlatingEIO3);\n \n ItemStack ingotDarkSteel = OreDictionary.getOres(\"ingotDarkSteel\").get(0).copy();\n ingotDarkSteel.stackSize = 10;\n EIORecipes.addAlloySmelterRecipe(\"Dark Steel Armor Plating\", 6400, armorPlatingEIO3, ingotDarkSteel, null, armorPlatingEIO4);\n \n ItemStack ingotSoularium = OreDictionary.getOres(\"ingotSoularium\").get(0).copy();\n ingotDarkSteel.stackSize = 1;\n EIORecipes.addAlloySmelterRecipe(\"Enriched Soularium Alloy\", 32000, ingotDarkSteel, ingotSoularium, EIOItems.pulsatingCrystal, ingotDarkSoularium);\n \n EIORecipes.addSoulBinderRecipe(\"Flight Control Unit\", 75000, 8, \"Bat\", unitFlightControlEmpty, unitFlightControl);\n }\n if (integrateBC && Loader.isModLoaded(\"BuildCraft|Silicon\")) {\n ItemStack pipeEnergyGold = BCItems.getStack(BCItems.pipeEnergyGold);\n pipeEnergyGold.stackSize = 2;\n ItemStack[] inputs;\n if (thrusterBC1 != null) {\n inputs = new ItemStack[] { thrusterBC1.copy(), new ItemStack(Items.gold_ingot, 4), pipeEnergyGold, BCItems.getStack(BCItems.chipsetGold) };\n } else {\n inputs = new ItemStack[] { BCItems.getStack(BCItems.engineCombustion), new ItemStack(Items.gold_ingot, 4), pipeEnergyGold, BCItems.getStack(BCItems.chipsetGold), new ItemStack(Blocks.iron_bars) };\n }\n BCRecipes.addAssemblyRecipe(\"kineticThruster\", 1200000, inputs, thrusterBC2.copy());\n }\n }\n \n public static ItemJetpack jetpacksCommon = null;\n public static ItemFluxPack fluxPacksCommon = null;\n public static ItemJetpack jetpacksTE = null;\n public static ItemFluxPack fluxPacksTE = null;\n public static ItemJetpack jetpacksEIO = null;\n public static ItemFluxPack fluxPacksEIO = null;\n public static ItemJetpack jetpacksBC = null;\n public static ItemMeta components = null;\n public static ItemMeta armorPlatings = null;\n public static ItemMeta particleCustomizers = null;\n public static ItemJetpackFueller jetpackFueller = null;\n public static ItemMysteriousPotato mysteriousPotato = null;\n \n public static ItemStack jetpackPotato = null;\n public static ItemStack jetpackCreative = null;\n public static ItemStack fluxPackCreative = null;\n \n public static ItemStack jetpackTE1 = null;\n public static ItemStack jetpackTE1Armored = null;\n public static ItemStack jetpackTE2 = null;\n public static ItemStack jetpackTE2Armored = null;\n public static ItemStack jetpackTE3 = null;\n public static ItemStack jetpackTE3Armored = null;\n public static ItemStack jetpackTE4 = null;\n public static ItemStack jetpackTE4Armored = null;\n public static ItemStack jetpackTE5 = null;\n public static ItemStack fluxPackTE1 = null;\n public static ItemStack fluxPackTE2 = null;\n public static ItemStack fluxPackTE2Armored = null;\n public static ItemStack fluxPackTE3 = null;\n public static ItemStack fluxPackTE3Armored = null;\n public static ItemStack fluxPackTE4 = null;\n public static ItemStack fluxPackTE4Armored = null;\n \n public static ItemStack jetpackEIO1 = null;\n public static ItemStack jetpackEIO1Armored = null;\n public static ItemStack jetpackEIO2 = null;\n public static ItemStack jetpackEIO2Armored = null;\n public static ItemStack jetpackEIO3 = null;\n public static ItemStack jetpackEIO3Armored = null;\n public static ItemStack jetpackEIO4 = null;\n public static ItemStack jetpackEIO4Armored = null;\n public static ItemStack jetpackEIO5 = null;\n public static ItemStack fluxPackEIO1 = null;\n public static ItemStack fluxPackEIO2 = null;\n public static ItemStack fluxPackEIO2Armored = null;\n public static ItemStack fluxPackEIO3 = null;\n public static ItemStack fluxPackEIO3Armored = null;\n public static ItemStack fluxPackEIO4 = null;\n public static ItemStack fluxPackEIO4Armored = null;\n \n public static ItemStack jetpackBC1 = null;\n public static ItemStack jetpackBC1Armored = null;\n public static ItemStack jetpackBC2 = null;\n public static ItemStack jetpackBC2Armored = null;\n \n public static ItemStack leatherStrap = null;\n public static ItemStack jetpackIcon = null;\n public static ItemStack thrusterTE1 = null;\n public static ItemStack thrusterTE2 = null;\n public static ItemStack thrusterTE3 = null;\n public static ItemStack thrusterTE4 = null;\n public static ItemStack thrusterTE5 = null;\n public static ItemStack thrusterEIO1 = null;\n public static ItemStack thrusterEIO2 = null;\n public static ItemStack thrusterEIO3 = null;\n public static ItemStack thrusterEIO4 = null;\n public static ItemStack thrusterEIO5 = null;\n public static ItemStack thrusterBC1 = null;\n public static ItemStack thrusterBC2 = null;\n public static ItemStack unitGlowstoneEmpty = null;\n public static ItemStack unitGlowstone = null;\n public static ItemStack unitCryotheumEmpty = null;\n public static ItemStack unitCryotheum = null;\n public static ItemStack dustElectrumFlux = null;\n public static ItemStack ingotElectrumFlux = null;\n public static ItemStack nuggetElectrumFlux = null;\n public static ItemStack gemCrystalFlux = null;\n public static ItemStack plateFlux = null;\n public static ItemStack armorFluxPlate = null;\n public static ItemStack enderiumUpgrade = null;\n public static ItemStack ingotDarkSoularium = null;\n public static ItemStack reinforcedGliderWing = null;\n public static ItemStack unitFlightControlEmpty = null;\n public static ItemStack unitFlightControl = null;\n \n public static ItemStack armorPlatingTE1 = null;\n public static ItemStack armorPlatingTE2 = null;\n public static ItemStack armorPlatingTE3 = null;\n public static ItemStack armorPlatingTE4 = null;\n public static ItemStack armorPlatingEIO1 = null;\n public static ItemStack armorPlatingEIO2 = null;\n public static ItemStack armorPlatingEIO3 = null;\n public static ItemStack armorPlatingEIO4 = null;\n public static ItemStack armorPlatingBC1 = null;\n public static ItemStack armorPlatingBC2 = null;\n \n public static ItemStack particleDefault = null;\n public static ItemStack particleNone = null;\n public static ItemStack particleSmoke = null;\n public static ItemStack particleRainbowSmoke = null;\n \n}", "public class Packs {\n \n public static void preInit() {\n jetpackPotato = new JetpackPotato(0, EnumRarity.common, \"jetpackPotato\");\n jetpackCreative = (Jetpack) new JetPlate(9001, EnumRarity.epic, \"jetpackCreative\").setDefaultParticleType(ParticleType.RAINBOW_SMOKE).setUsesFuel(false).setHasFuelIndicator(false).setShowEmptyInCreativeTab(false);\n fluxPackCreative = (FluxPack) new FluxPack(9001, EnumRarity.epic, \"fluxPackCreative\").setUsesFuel(false).setHasFuelIndicator(false).setShowEmptyInCreativeTab(false).setIsArmored(true).setShowArmored(false);\n \n if (ModType.THERMAL_EXPANSION.loaded) {\n jetpackTE1 = new Jetpack(1, EnumRarity.common, \"jetpackTE1\");\n jetpackTE1Armored = (Jetpack) new Jetpack(1, EnumRarity.common, \"jetpackTE1\").setIsArmored(true).setPlatingMeta(1);\n jetpackTE2 = new Jetpack(2, EnumRarity.common, \"jetpackTE2\");\n jetpackTE2Armored = (Jetpack) new Jetpack(2, EnumRarity.common, \"jetpackTE2\").setIsArmored(true).setPlatingMeta(2);\n jetpackTE3 = new Jetpack(3, EnumRarity.uncommon, \"jetpackTE3\");\n jetpackTE3Armored = (Jetpack) new Jetpack(3, EnumRarity.uncommon, \"jetpackTE3\").setIsArmored(true).setPlatingMeta(3);\n jetpackTE4 = new Jetpack(4, EnumRarity.rare, \"jetpackTE4\");\n jetpackTE4Armored = (Jetpack) new Jetpack(4, EnumRarity.rare, \"jetpackTE4\").setIsArmored(true).setPlatingMeta(4);\n jetpackTE5 = (Jetpack) new JetPlate(5, EnumRarity.epic, \"jetpackTE5\").setFluxBased(true);\n fluxPackTE1 = new FluxPack(1, EnumRarity.common, \"fluxPackTE1\");\n fluxPackTE2 = new FluxPack(2, EnumRarity.common, \"fluxPackTE2\");\n fluxPackTE2Armored = (FluxPack) new FluxPack(2, EnumRarity.common, \"fluxPackTE2\").setIsArmored(true).setPlatingMeta(1);\n fluxPackTE3 = new FluxPack(3, EnumRarity.uncommon, \"fluxPackTE3\");\n fluxPackTE3Armored = (FluxPack) new FluxPack(3, EnumRarity.uncommon, \"fluxPackTE3\").setIsArmored(true).setPlatingMeta(2);\n fluxPackTE4 = new FluxPack(4, EnumRarity.rare, \"fluxPackTE4\");\n fluxPackTE4Armored = (FluxPack) new FluxPack(4, EnumRarity.rare, \"fluxPackTE4\").setIsArmored(true).setPlatingMeta(3);\n }\n \n if (ModType.ENDER_IO.loaded) {\n jetpackEIO1 = new Jetpack(1, EnumRarity.common, \"jetpackEIO1\");\n jetpackEIO1Armored = (Jetpack) new Jetpack(1, EnumRarity.common, \"jetpackEIO1\").setIsArmored(true).setPlatingMeta(11);\n jetpackEIO2 = new Jetpack(2, EnumRarity.common, \"jetpackEIO2\");\n jetpackEIO2Armored = (Jetpack) new Jetpack(2, EnumRarity.common, \"jetpackEIO2\").setIsArmored(true).setPlatingMeta(12);\n jetpackEIO3 = new Jetpack(3, EnumRarity.uncommon, \"jetpackEIO3\");\n jetpackEIO3Armored = (Jetpack) new Jetpack(3, EnumRarity.uncommon, \"jetpackEIO3\").setIsArmored(true).setPlatingMeta(13);\n jetpackEIO4 = new Jetpack(4, EnumRarity.rare, \"jetpackEIO4\");\n jetpackEIO4Armored = (Jetpack) new Jetpack(4, EnumRarity.rare, \"jetpackEIO4\").setIsArmored(true).setPlatingMeta(14);\n jetpackEIO5 = new JetPlate(5, EnumRarity.epic, \"jetpackEIO5\");\n fluxPackEIO1 = new FluxPack(1, EnumRarity.common, \"fluxPackEIO1\");\n fluxPackEIO2 = new FluxPack(2, EnumRarity.common, \"fluxPackEIO2\");\n fluxPackEIO2Armored = (FluxPack) new FluxPack(2, EnumRarity.common, \"fluxPackEIO2\").setIsArmored(true).setPlatingMeta(11);\n fluxPackEIO3 = new FluxPack(3, EnumRarity.uncommon, \"fluxPackEIO3\");\n fluxPackEIO3Armored = (FluxPack) new FluxPack(3, EnumRarity.uncommon, \"fluxPackEIO3\").setIsArmored(true).setPlatingMeta(12);\n fluxPackEIO4 = new FluxPack(4, EnumRarity.rare, \"fluxPackEIO4\");\n fluxPackEIO4Armored = (FluxPack) new FluxPack(4, EnumRarity.rare, \"fluxPackEIO4\").setIsArmored(true).setPlatingMeta(13);\n }\n \n if (ModType.BUILDCRAFT.loaded) {\n boolean energyFactoryLoaded = Loader.isModLoaded(\"BuildCraft|Energy\") && Loader.isModLoaded(\"BuildCraft|Factory\");\n if (energyFactoryLoaded) {\n jetpackBC1 = (Jetpack) new Jetpack(1, EnumRarity.common, \"jetpackBC1\").setFuelFluid(\"fuel\");\n jetpackBC1Armored = (Jetpack) new Jetpack(1, EnumRarity.common, \"jetpackBC1\").setFuelFluid(\"fuel\").setIsArmored(true).setPlatingMeta(21);\n }\n jetpackBC2 = (Jetpack) new Jetpack(2, EnumRarity.uncommon, \"jetpackBC2\").setShowTier(energyFactoryLoaded);\n jetpackBC2Armored = (Jetpack) new Jetpack(2, EnumRarity.uncommon, \"jetpackBC2\").setIsArmored(true).setPlatingMeta(22).setShowTier(energyFactoryLoaded);\n }\n }\n \n public static Jetpack jetpackPotato;\n public static Jetpack jetpackCreative;\n public static FluxPack fluxPackCreative;\n \n public static Jetpack jetpackTE1;\n public static Jetpack jetpackTE1Armored;\n public static Jetpack jetpackTE2;\n public static Jetpack jetpackTE2Armored;\n public static Jetpack jetpackTE3;\n public static Jetpack jetpackTE3Armored;\n public static Jetpack jetpackTE4;\n public static Jetpack jetpackTE4Armored;\n public static Jetpack jetpackTE5;\n public static FluxPack fluxPackTE1;\n public static FluxPack fluxPackTE2;\n public static FluxPack fluxPackTE2Armored;\n public static FluxPack fluxPackTE3;\n public static FluxPack fluxPackTE3Armored;\n public static FluxPack fluxPackTE4;\n public static FluxPack fluxPackTE4Armored;\n \n public static Jetpack jetpackEIO1;\n public static Jetpack jetpackEIO1Armored;\n public static Jetpack jetpackEIO2;\n public static Jetpack jetpackEIO2Armored;\n public static Jetpack jetpackEIO3;\n public static Jetpack jetpackEIO3Armored;\n public static Jetpack jetpackEIO4;\n public static Jetpack jetpackEIO4Armored;\n public static Jetpack jetpackEIO5;\n public static FluxPack fluxPackEIO1;\n public static FluxPack fluxPackEIO2;\n public static FluxPack fluxPackEIO2Armored;\n public static FluxPack fluxPackEIO3;\n public static FluxPack fluxPackEIO3Armored;\n public static FluxPack fluxPackEIO4;\n public static FluxPack fluxPackEIO4Armored;\n \n public static Jetpack jetpackBC1;\n public static Jetpack jetpackBC1Armored;\n public static Jetpack jetpackBC2;\n public static Jetpack jetpackBC2Armored;\n \n}" ]
import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.RecipeSorter.Category; import org.apache.logging.log4j.Logger; import tonius.simplyjetpacks.config.Config; import tonius.simplyjetpacks.crafting.UpgradingRecipe; import tonius.simplyjetpacks.handler.SyncHandler; import tonius.simplyjetpacks.network.PacketHandler; import tonius.simplyjetpacks.setup.ModEnchantments; import tonius.simplyjetpacks.setup.ModItems; import tonius.simplyjetpacks.setup.Packs; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStoppingEvent;
package tonius.simplyjetpacks; @Mod(modid = SimplyJetpacks.MODID, version = SimplyJetpacks.VERSION, dependencies = SimplyJetpacks.DEPENDENCIES, guiFactory = SimplyJetpacks.GUI_FACTORY) public class SimplyJetpacks { public static final String MODID = "simplyjetpacks"; public static final String VERSION = "@VERSION@"; public static final String PREFIX = MODID + "."; public static final String RESOURCE_PREFIX = MODID + ":"; public static final String DEPENDENCIES = "required-after:Forge@[10.13.2.1291,);after:ThermalExpansion;after:RedstoneArsenal;after:RArm;after:EnderIO@[1.7.10-2.1.3.243,);after:BuildCraft|Core@[6.4.15,7.0.0),[7.0.4,)"; public static final String GUI_FACTORY = "tonius.simplyjetpacks.config.ConfigGuiFactory"; @Instance(MODID) public static SimplyJetpacks instance; @SidedProxy(clientSide = "tonius.simplyjetpacks.client.ClientProxy", serverSide = "tonius.simplyjetpacks.CommonProxy") public static CommonProxy proxy; public static Logger logger; public static SyncHandler keyboard; @EventHandler public static void preInit(FMLPreInitializationEvent evt) { logger = evt.getModLog(); logger.info("Starting Simply Jetpacks"); checkCoFHLib();
Packs.preInit();
6
hamadmarri/Biscuit
main/java/com/biscuit/commands/planner/ShowPlan.java
[ "public class ColorCodes {\n\n\t// with normal background\n\tpublic static final String RESET = \"\\u001B[0m\";\n\tpublic static final String BLACK = \"\\u001B[30;1m\";\n\tpublic static final String RED = \"\\u001B[31;1m\";\n\tpublic static final String GREEN = \"\\u001B[32;1m\";\n\tpublic static final String YELLOW = \"\\u001B[33;1m\";\n\tpublic static final String BLUE = \"\\u001B[34;1m\";\n\tpublic static final String PURPLE = \"\\u001B[35;1m\";\n\tpublic static final String CYAN = \"\\u001B[36;1m\";\n\tpublic static final String WHITE = \"\\u001B[37;1m\";\n\n\t// with black background\n\tpublic static final String B_RESET = \"\\u001B[0m\";\n\tpublic static final String B_BLACK = \"\\u001B[30;40;1m\";\n\tpublic static final String B_RED = \"\\u001B[31;40;1m\";\n\tpublic static final String B_GREEN = \"\\u001B[32;40;1m\";\n\tpublic static final String B_YELLOW = \"\\u001B[33;40;1m\";\n\tpublic static final String B_BLUE = \"\\u001B[34;40;1m\";\n\tpublic static final String B_PURPLE = \"\\u001B[35;40;1m\";\n\tpublic static final String B_CYAN = \"\\u001B[36;40;1m\";\n\tpublic static final String B_WHITE = \"\\u001B[37;40;1m\";\n\n}", "public interface Command {\n\n\tboolean execute() throws IOException;\n}", "public class Project {\n\n\tpublic String name;\n\tpublic String description;\n\tpublic Backlog backlog = new Backlog();\n\tpublic List<Release> releases = new ArrayList<>();\n\tpublic List<Sprint> sprints = new ArrayList<>();\n\n\n\tpublic void save() {\n\t\tModelHelper.save(this, name);\n\t}\n\n\n\tpublic void delete() {\n\t\tModelHelper.delete(name);\n\t}\n\n\n\tstatic public Project load(String name) {\n\t\treturn ModelHelper.loadProject(name);\n\t}\n\n\n\tpublic void updateChildrenReferences() {\n\n\t\tthis.backlog.project = this;\n\n\t\tfor (Release r : releases) {\n\t\t\tr.project = this;\n\t\t\tupdateSprintReferences(r.sprints);\n\t\t}\n\n\t\tupdateSprintReferences(sprints);\n\t\tupdateUserStoryReferences(backlog.userStories);\n\t}\n\n\n\tprivate void updateSprintReferences(List<Sprint> sprints) {\n\t\tfor (Sprint s : sprints) {\n\t\t\ts.project = this;\n\t\t\tupdateUserStoryReferences(s.userStories);\n\t\t}\n\t}\n\n\n\tprivate void updateUserStoryReferences(List<UserStory> userStories) {\n\t\tfor (UserStory us : userStories) {\n\t\t\tus.project = this;\n\n\t\t\tfor (Task t : us.tasks) {\n\t\t\t\tt.project = this;\n\t\t\t}\n\n\t\t\t// for (Bug b : us.bugs) {\n\t\t\t// b.project = this;\n\t\t\t// }\n\n\t\t\t// for (Test t : us.tests) {\n\t\t\t// t.project = this;\n\t\t\t// }\n\t\t}\n\t}\n\n\n\tpublic void addRelease(Release r) {\n\t\treleases.add(r);\n\t}\n\n\n\tpublic void addSprint(Sprint s) {\n\t\tsprints.add(s);\n\t}\n\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"project name: \" + name + \"\\n\\ndescription:-\\n\" + description;\n\t}\n\n}", "public class Release {\n\n\tpublic transient Project project;\n\n\t// info\n\tpublic String name;\n\tpublic String description;\n\tpublic Status state;\n\tpublic Date startDate;\n\tpublic Date dueDate;\n\tpublic int assignedEffort;\n\n\tpublic List<Sprint> sprints = new ArrayList<>();\n\tpublic List<Bug> bugs;\n\tpublic List<Test> tests;\n\n\t// Completed 0pt 0% ToDo 8pt\n\n\tpublic static String[] fields;\n\tpublic static String[] fieldsAsHeader;\n\tstatic {\n\t\tfields = new String[] { \"name\", \"description\", \"state\", \"start_date\", \"due_date\", \"assigned_effort\" };\n\t\tfieldsAsHeader = new String[] { \"Name\", \"Description\", \"State\", \"Start Date\", \"Due Date\", \"Assigned Effort\" };\n\t}\n\n\tpublic void save() {\n\t\tproject.save();\n\t}\n}", "public class Sprint {\n\n\tpublic transient Project project;\n\n\t// info\n\tpublic String name;\n\tpublic String description;\n\tpublic Status state;\n\tpublic Date startDate;\n\tpublic Date dueDate;\n\tpublic int assignedEffort;\n\tpublic int velocity;\n\n\tpublic List<UserStory> userStories = new ArrayList<>();\n\tpublic List<Bug> bugs;\n\tpublic List<Test> tests;\n\n\t// Completed 0pt 0% ToDo 8pt\n\n\tpublic static String[] fields;\n\tpublic static String[] fieldsAsHeader;\n\n\tstatic {\n\t\tfields = new String[] { \"name\", \"description\", \"state\", \"start_date\", \"due_date\", \"assigned_effort\", \"velocity\" };\n\t\tfieldsAsHeader = new String[] { \"Name\", \"Description\", \"State\", \"Start Date\", \"Due Date\", \"Assigned Effort\", \"Velocity\" };\n\t}\n\n\tpublic void addUserStory(UserStory userStory) {\n\t\tthis.userStories.add(userStory);\n\t}\n\n\tpublic void save() {\n\t\tproject.save();\n\t}\n\n}", "public class UserStory {\n\n\tpublic transient Project project;\n\n\tpublic String title;\n\tpublic String description;\n\tpublic Status state;\n\tpublic BusinessValue businessValue;\n\tpublic Date initiatedDate = null;\n\tpublic Date plannedDate = null;\n\tpublic Date dueDate = null;\n\tpublic int points;\n\n\tpublic static String[] fields;\n\n\tpublic List<Task> tasks = new ArrayList<>();\n\tpublic List<Bug> bugs = new ArrayList<>();\n\tpublic List<Test> tests = new ArrayList<>();\n\n\tstatic {\n\t\tfields = new String[] { \"title\", \"description\", \"state\", \"business_value\", \"initiated_date\", \"planned_date\", \"due_date\", \"tasks\", \"points\" };\n\t}\n\n\n\tpublic void save() {\n\t\tproject.save();\n\t}\n\n}" ]
import java.io.IOException; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import com.biscuit.ColorCodes; import com.biscuit.commands.Command; import com.biscuit.models.Project; import com.biscuit.models.Release; import com.biscuit.models.Sprint; import com.biscuit.models.UserStory;
package com.biscuit.commands.planner; public class ShowPlan implements Command { Project project; public ShowPlan(Project project) { super(); this.project = project; } @Override public boolean execute() throws IOException { printPlanned(); System.out.println(); printUnplanned(); return true; } private void printUnplanned() { System.out.println("Backlog"); for (Iterator<UserStory> usItr = project.backlog.userStories.iterator(); usItr.hasNext();) { UserStory us = usItr.next(); boolean isLastUserStory = !usItr.hasNext(); printUserStoryTree(us, isLastUserStory, " "); } System.out.println(); System.out.println("Sprints"); for (Iterator<Sprint> sItr = project.sprints.iterator(); sItr.hasNext();) { Sprint s = sItr.next(); boolean isLastSprint = (!sItr.hasNext() && s.userStories.isEmpty()); printSprintTree(s, isLastSprint, " "); } } private void printPlanned() { Comparator<Release> byStartDate = (r1, r2) -> r1.startDate.compareTo(r2.startDate); List<Release> sortedByStartDate = project.releases.stream().sorted(byStartDate).collect(Collectors.toList()); System.out.println("########## PLAN ##########"); System.out.println(project.name); for (Iterator<Release> rItr = sortedByStartDate.iterator(); rItr.hasNext();) { Release r = rItr.next(); boolean isLastRelease = (!rItr.hasNext() && r.sprints.isEmpty()); printReleaseTree(r, isLastRelease, " "); } } private void printReleaseTree(Release r, boolean isLastRelease, String indent) { Comparator<Sprint> byStartDate = (s1, s2) -> s1.startDate.compareTo(s2.startDate); List<Sprint> sortedByStartDate = r.sprints.stream().sorted(byStartDate).collect(Collectors.toList()); // print release name if (isLastRelease) {
System.out.println(indent + "└ " + ColorCodes.PURPLE + r.name + ColorCodes.RESET);
0
javaFunAgain/ratpong
src/main/java/pl/setblack/pongi/users/UsersService.java
[ "public class JsonMapping {\n\n private static final ObjectMapper MAPPER = configureMapping();\n\n private static ObjectMapper configureMapping() {\n return new ObjectMapper()\n .registerModule(new ParameterNamesModule())\n .registerModule(new Jdk8Module())\n .registerModule(new JavaTimeModule())\n .registerModule(new JavaslangModule());\n }\n\n\n public static final ObjectMapper getJsonMapping() {\n return JsonMapping.MAPPER;\n }\n\n public static Promise<JsonRender> toJsonPromise(CompletionStage<?> future) {\n return Promise.async(\n d -> d.accept(future.thenApply(Jackson::json))\n );\n }\n}", "@Immutable\n@JsonDeserialize\npublic class LoginData {\n public final String password;\n\n @JsonCreator\n public LoginData(String password) {\n this.password = password;\n }\n}", "@Immutable\n@JsonDeserialize\npublic class NewUser {\n public final String password;\n\n @JsonCreator\n public NewUser(String password) {\n this.password = password;\n }\n\n}", "public class SessionsRepo {\n private AtomicReference<HashMap<String, Session>> activeSesssions =\n new AtomicReference<>(HashMap.empty());\n\n private final Clock clock;\n\n public SessionsRepo(Clock clock) {\n this.clock = clock;\n }\n\n\n public Session startSession(String userId) {\n final UUID uuid = UUID.randomUUID();\n final LocalDateTime now = LocalDateTime.now(this.clock);\n final LocalDateTime expirationTime = now.plusDays(1);\n final Session sess = new Session(userId, uuid, expirationTime);\n this.activeSesssions.updateAndGet(map -> map.put(uuid.toString(), sess));\n return sess;\n }\n\n public Option<Session> getSession(final String uuid) {\n return this.activeSesssions.get().get(uuid);\n }\n\n}", "public interface UsersRepository {\n\n RegUserStatus addUser(final String login, final String pass);\n\n boolean login(final String login, final String password);\n}", "public class UsersRepositoryProcessor {\n private final UsersRepository usersRepository;\n\n private final Executor writesExecutor = Executors.newSingleThreadExecutor();\n\n\n public UsersRepositoryProcessor(UsersRepository usersRepository) {\n this.usersRepository = usersRepository;\n }\n\n public CompletionStage<RegUserStatus> addUser(final String login, final String pass) {\n final CompletableFuture<RegUserStatus> result = new CompletableFuture<>();\n writesExecutor.execute(() -> {\n result.complete(this.usersRepository.addUser(login, pass));\n });\n return result;\n }\n\n public boolean login(final String login, final String pass) {\n return this.usersRepository.login(login, pass);\n }\n}" ]
import javaslang.control.Option; import pl.setblack.pongi.JsonMapping; import pl.setblack.pongi.users.api.LoginData; import pl.setblack.pongi.users.api.NewUser; import pl.setblack.pongi.users.repo.SessionsRepo; import pl.setblack.pongi.users.repo.UsersRepository; import pl.setblack.pongi.users.repo.UsersRepositoryProcessor; import ratpack.func.Action; import ratpack.handling.Chain; import ratpack.handling.Handler; import ratpack.jackson.Jackson;
package pl.setblack.pongi.users; /** * Created by jarek on 1/29/17. */ public class UsersService { private final UsersRepositoryProcessor usersRepo; private final SessionsRepo sessionsRepo;
public UsersService(UsersRepository usersRepo, SessionsRepo sessionsRepo) {
4
tmorcinek/android-codegenerator-library
src/test/java/com/morcinek/android/codegenerator/codegeneration/MenuTemplateCodeGeneratorTest.java
[ "public class MenuResourceProvidersFactory implements ResourceProvidersFactory {\n\n @Override\n public ResourceProvider createResourceProvider(Resource resource) {\n return new MenuProvider(resource);\n }\n}", "public class ResourceTemplatesProvider implements TemplatesProvider {\n\n @Override\n public String provideTemplateForName(String templateName) {\n URL url = Resources.getResource(templateName);\n try {\n return Resources.toString(url, Charset.defaultCharset());\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n}", "public interface TemplatesProvider {\n\n String provideTemplateForName(String templateName);\n}", "public class Resource {\n\n private ResourceId resourceId;\n\n private ResourceType resourceType;\n\n public Resource(ResourceId resourceId, ResourceType resourceType) {\n this.resourceId = resourceId;\n this.resourceType = resourceType;\n }\n\n public ResourceId getResourceId() {\n return resourceId;\n }\n\n public ResourceType getResourceType() {\n return resourceType;\n }\n}", "public class ResourceId {\n\n private String name;\n\n private String namespace;\n\n public ResourceId(String name) {\n this.name = name;\n }\n\n public ResourceId(String name, String namespace) {\n this.name = name;\n this.namespace = namespace;\n }\n\n public String getName() {\n return name;\n }\n\n public String getNamespace() {\n return namespace;\n }\n}", "public class ResourceType {\n\n private String className;\n\n private String packageName;\n\n public ResourceType(String className) {\n this.className = className;\n }\n\n public ResourceType(String className, String packageName) {\n this.className = className;\n this.packageName = packageName;\n }\n\n public String getClassName() {\n return className;\n }\n\n public String getPackageName() {\n return packageName;\n }\n\n public String getFullName() {\n if (packageName != null) {\n return packageName + \".\" + className;\n }\n return className;\n }\n}" ]
import com.google.common.collect.Lists; import com.morcinek.android.codegenerator.codegeneration.providers.factories.MenuResourceProvidersFactory; import com.morcinek.android.codegenerator.codegeneration.templates.ResourceTemplatesProvider; import com.morcinek.android.codegenerator.codegeneration.templates.TemplatesProvider; import com.morcinek.android.codegenerator.extractor.model.Resource; import com.morcinek.android.codegenerator.extractor.model.ResourceId; import com.morcinek.android.codegenerator.extractor.model.ResourceType; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import java.util.List;
package com.morcinek.android.codegenerator.codegeneration; public class MenuTemplateCodeGeneratorTest { private TemplatesProvider templatesProvider = new ResourceTemplatesProvider(); private TemplateCodeGenerator templateCodeGenerator; @Before public void setUp() throws Exception {
templateCodeGenerator = new TemplateCodeGenerator("Menu_template", new MenuResourceProvidersFactory(), new ResourceTemplatesProvider());
0
gazbert/bxbot-ui-server
bxbot-ui-server-services/src/test/java/com/gazbert/bxbot/ui/server/services/config/TestEmailAlertsConfigService.java
[ "public class BotConfig {\n\n private String id;\n private String alias;\n private String baseUrl;\n private String username;\n private String password;\n\n // required for Jackson\n public BotConfig() {\n }\n\n public BotConfig(BotConfig other) {\n this.id = other.id;\n this.alias = other.alias;\n this.baseUrl = other.baseUrl;\n this.username = other.username;\n this.password = other.password;\n }\n\n public BotConfig(String id, String alias, String baseUrl, String username, String password) {\n this.id = id;\n this.alias = alias;\n this.baseUrl = baseUrl;\n this.username = username;\n this.password = password;\n }\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 getAlias() {\n return alias;\n }\n\n public void setAlias(String alias) {\n this.alias = alias;\n }\n\n public String getBaseUrl() {\n return baseUrl;\n }\n\n public void setBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this)\n .add(\"id\", id)\n .add(\"alias\", alias)\n .add(\"baseUrl\", baseUrl)\n .add(\"username\", username)\n .add(\"password\", password)\n .toString();\n }\n}", "public class EmailAlertsConfig {\n\n private String id;\n private boolean enabled;\n private SmtpConfig smtpConfig;\n\n // required for jackson\n public EmailAlertsConfig() {\n }\n\n public EmailAlertsConfig(String id, boolean enabled, SmtpConfig smtpConfig) {\n this.id = id;\n this.enabled = enabled;\n this.smtpConfig = smtpConfig;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public SmtpConfig getSmtpConfig() {\n return smtpConfig;\n }\n\n public void setSmtpConfig(SmtpConfig smtpConfig) {\n this.smtpConfig = smtpConfig;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this)\n .add(\"id\", id)\n .add(\"enabled\", enabled)\n .add(\"smtpConfig\", smtpConfig)\n .toString();\n }\n}", "public class SmtpConfig {\n\n private String host;\n private int tlsPort;\n private String accountUsername;\n private String accountPassword;\n private String fromAddress;\n private String toAddress;\n\n // required for jackson\n public SmtpConfig() {\n }\n\n public SmtpConfig(String host, int tlsPort, String accountUsername, String accountPassword, String fromAddress, String toAddress) {\n this.host = host;\n this.tlsPort = tlsPort;\n this.accountUsername = accountUsername;\n this.accountPassword = accountPassword;\n this.fromAddress = fromAddress;\n this.toAddress = toAddress;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public int getTlsPort() {\n return tlsPort;\n }\n\n public void setTlsPort(int tlsPort) {\n this.tlsPort = tlsPort;\n }\n\n public String getAccountUsername() {\n return accountUsername;\n }\n\n public void setAccountUsername(String accountUsername) {\n this.accountUsername = accountUsername;\n }\n\n public String getAccountPassword() {\n return accountPassword;\n }\n\n public void setAccountPassword(String accountPassword) {\n this.accountPassword = accountPassword;\n }\n\n public String getFromAddress() {\n return fromAddress;\n }\n\n public void setFromAddress(String fromAddress) {\n this.fromAddress = fromAddress;\n }\n\n public String getToAddress() {\n return toAddress;\n }\n\n public void setToAddress(String toAddress) {\n this.toAddress = toAddress;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this)\n .add(\"host\", host)\n .add(\"tlsPort\", tlsPort)\n .add(\"accountUsername\", accountUsername)\n // Careful with the password!\n// .add(\"accountPassword\", accountPassword)\n .add(\"fromAddress\", fromAddress)\n .add(\"toAddress\", toAddress)\n .toString();\n }\n}", "public interface BotConfigRepository {\n\n List<BotConfig> findAll();\n\n BotConfig findById(String id);\n\n BotConfig save(BotConfig config);\n\n BotConfig delete(String id);\n}", "public interface EmailAlertsConfigRepository {\n\n EmailAlertsConfig get(BotConfig botConfig);\n\n EmailAlertsConfig save(BotConfig botConfig, EmailAlertsConfig config);\n}", "public interface EmailAlertsConfigService {\n\n EmailAlertsConfig getEmailAlertsConfig(String botId);\n\n EmailAlertsConfig updateEmailAlertsConfig(String botId, EmailAlertsConfig config);\n}", "@Service(\"emailAlertsConfigService\")\n@Transactional\n@ComponentScan(basePackages = {\"com.gazbert.bxbot.ui.server.repository\"})\npublic class EmailAlertsConfigServiceImpl implements EmailAlertsConfigService {\n\n private static final Logger LOG = LogManager.getLogger();\n\n private final EmailAlertsConfigRepository emailAlertsConfigRepository;\n private final BotConfigRepository botConfigRepository;\n\n @Autowired\n public EmailAlertsConfigServiceImpl(EmailAlertsConfigRepository emailAlertsConfigRepository,\n BotConfigRepository botConfigRepository) {\n\n this.emailAlertsConfigRepository = emailAlertsConfigRepository;\n this.botConfigRepository = botConfigRepository;\n }\n\n @Override\n public EmailAlertsConfig getEmailAlertsConfig(String botId) {\n\n LOG.info(() -> \"About to fetch Email Alerts config for botId: \" + botId);\n\n final BotConfig botConfig = botConfigRepository.findById(botId);\n if (botConfig == null) {\n LOG.warn(\"Failed to find BotConfig for botId: \" + botId);\n return null;\n } else {\n return emailAlertsConfigRepository.get(botConfig);\n }\n }\n\n @Override\n public EmailAlertsConfig updateEmailAlertsConfig(String botId, EmailAlertsConfig emailAlertsConfig) {\n\n LOG.info(() -> \"About to update bot \" + botId + \" Email Alerts config: \" + emailAlertsConfig);\n\n final BotConfig botConfig = botConfigRepository.findById(botId);\n if (botConfig == null) {\n LOG.warn(\"Failed to find BotConfig for botId: \" + botId);\n return null;\n } else {\n return emailAlertsConfigRepository.save(botConfig, emailAlertsConfig);\n }\n }\n}" ]
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.gazbert.bxbot.ui.server.domain.bot.BotConfig; import com.gazbert.bxbot.ui.server.domain.emailalerts.EmailAlertsConfig; import com.gazbert.bxbot.ui.server.domain.emailalerts.SmtpConfig; import com.gazbert.bxbot.ui.server.repository.local.BotConfigRepository; import com.gazbert.bxbot.ui.server.repository.remote.config.EmailAlertsConfigRepository; import com.gazbert.bxbot.ui.server.services.config.EmailAlertsConfigService; import com.gazbert.bxbot.ui.server.services.config.impl.EmailAlertsConfigServiceImpl;
/* * The MIT License (MIT) * * Copyright (c) 2017 Gareth Jon Lynch * * 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 com.gazbert.bxbot.ui.server.services.config; /** * Tests the Email Alerts configuration service behaves as expected. * * @author gazbert */ @RunWith(SpringRunner.class) public class TestEmailAlertsConfigService { private static final String UNKNOWN_BOT_ID = "unknown-or-new-bot-id"; private static final String BOT_ID = "bitstamp-bot-1"; private static final String BOT_NAME = "Bitstamp Bot"; private static final String BOT_BASE_URL = "https://hostname.one/api"; private static final String BOT_USERNAME = "admin"; private static final String BOT_PASSWORD = "password"; private static final boolean ENABLED = true; private static final String HOST = "smtp.host.deathstar.com"; private static final int TLS_PORT = 573; private static final String ACCOUNT_USERNAME = "boba@google.com"; private static final String ACCOUNT_PASSWORD = "bounty"; private static final String FROM_ADDRESS = "boba.fett@Mandalore.com"; private static final String TO_ADDRESS = "darth.vader@deathstar.com"; private BotConfig knownBotConfig;
private EmailAlertsConfig emailAlertsConfig;
1
huijimuhe/common-layout-android
CommonLayout/app/src/main/java/com/huijimuhe/commonlayout/adapter/render/xcArticleSectionTextRender.java
[ "public abstract class AbstractRender{\n\n public abstract<T extends AbstractViewHolder> T getReusableComponent();\n public abstract void bindData(int position);\n\n}", "public abstract class AbstractRenderAdapter<T> extends RecyclerView.Adapter<AbstractViewHolder> {\n\n public static final int RENDER_TYPE_HEADER = 110 << 1;\n public static final int RENDER_TYPE_NORMAL = 110 << 2;\n public List<T> mDataset;\n\n public onItemClickListener mOnItemClickListener;\n public onItemFunctionClickListener mOnItemFunctionClickListener;\n\n private View mHeaderView;\n public boolean mIsSectionHeadShown;\n\n @Override\n public int getItemViewType(int position) {\n if (position == 0 && mHeaderView != null) {\n return RENDER_TYPE_HEADER;\n }\n return RENDER_TYPE_NORMAL;\n }\n\n @TargetApi(4)\n public AbstractViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n switch (viewType) {\n case RENDER_TYPE_HEADER: {\n HeaderRender head = new HeaderRender(mHeaderView);\n AbstractViewHolder headHolder = head.getReusableComponent();\n headHolder.itemView.setTag(android.support.design.R.id.list_item, head);\n return headHolder;\n }\n default:\n return null;\n }\n }\n\n @Override\n public int getItemCount() {\n return hasHeaderView() ? mDataset.size() + 1 : mDataset.size();\n }\n\n public void replace(List<T> data) {\n this.mDataset = data;\n notifyDataSetChanged();\n }\n\n public void replace(List<T> data, boolean isSectionHeadShown) {\n this.mDataset = data;\n this.mIsSectionHeadShown = isSectionHeadShown;\n notifyDataSetChanged();\n }\n\n public void remove(T data) {\n this.mDataset.remove(data);\n notifyDataSetChanged();\n }\n\n public void addAll(List<T> data) {\n this.mDataset.addAll(data);\n notifyDataSetChanged();\n }\n\n public List<T> getList() {\n return this.mDataset;\n }\n\n public int getRealPosition(int position) {\n return hasHeaderView() && position != 0 ? position - 1 : position;\n }\n\n public T getItem(int position) {\n return mDataset.get(getRealPosition(position));\n }\n\n\n public boolean hasHeaderView() {\n return mHeaderView != null;\n }\n\n public void setHeaderView(View view) {\n mHeaderView = view;\n }\n\n public void setOnItemClickListener(onItemClickListener l) {\n mOnItemClickListener = l;\n }\n\n public void setOnItemFunctionClickListener(onItemFunctionClickListener l) {\n mOnItemFunctionClickListener = l;\n }\n\n public interface onItemClickListener {\n void onItemClick(View view, int postion);\n }\n\n public interface onItemFunctionClickListener {\n void onClick(View view, int postion, int type);\n }\n}", "public abstract class AbstractViewHolder extends RecyclerView.ViewHolder{\n\n public AbstractViewHolder(View itemView) {\n super(itemView);\n }\n\n}", "public class xcArticleSectionAdapter extends AbstractRenderAdapter<xcArticleSection> {\n public static final int TYPE_TEXT = 1 << 1;\n public static final int TYPE_IMAGE = 1 << 2;\n\n private ArrayMap<Integer, Integer> mSection;\n\n public xcArticleSectionAdapter(List<xcArticleSection> data) {\n this.mDataset = data;\n mSection = new ArrayMap<>();\n }\n\n @Override\n public int getItemCount() {\n int size = 0;\n\n //list头\n if (hasHeaderView()) {\n size++;\n }\n mSection.clear();\n for (int i = 0; i < mDataset.size(); i++) {\n\n switch (mDataset.get(i).getType()) {\n case 2:\n case 3:\n size += mDataset.get(i).getContentArray().size();\n break;\n default:\n size++;\n break;\n }\n //分段,根据position知道是第几个section\n mSection.put(size, i);\n }\n\n return size;\n }\n\n /**\n * 根据列表实际位置计算是第几个section\n *\n * @param position\n * @return\n */\n @Override\n public int getRealPosition(int position) {\n synchronized (mSection) {\n //去掉头的影响\n if (hasHeaderView() && position != 0) {\n position -= 1;\n }\n\n //根据列表实际位置计算是第几个section\n int relativePos = 0;\n for (Integer sectionSize : mSection.keySet()) {\n if (position < sectionSize) {\n relativePos = sectionSize;\n break;\n }\n }\n int testRes = mSection.get(relativePos);\n return mSection.get(relativePos);\n }\n }\n\n /**\n * 根据列表实际位置计算在section中的相对位置\n *\n * @param position\n * @return\n */\n public int getParagraphPosition(int position) {\n synchronized (mSection) {\n //去掉头的影响\n if (hasHeaderView() && position != 0) {\n position -= 1;\n }\n\n //根据列表实际位置计算在section中的相对位置\n if (position == 0) {\n return position;\n }\n int relativePos = mSection.keyAt(getRealPosition(position) - 1);\n return position - relativePos;\n }\n }\n\n public xcArticleSection.IParagraph getParagraph(int position) {\n xcArticleSection section = getItem(position);\n if (section.getType() == 1) {\n return section.getContentObject();\n }\n int relative = getParagraphPosition(position);\n xcArticleSection.IParagraph qq = (xcArticleSection.IParagraph) section.getContentArray().get(relative);\n\n return (xcArticleSection.IParagraph) section.getContentArray().get(getParagraphPosition(position));\n }\n\n @Override\n public int getItemViewType(int position) {\n if (super.getItemViewType(position) == RENDER_TYPE_HEADER) {\n return super.getItemViewType(position);\n }\n xcArticleSection section = getItem(position);\n switch (section.getType()) {\n case 2:\n return TYPE_TEXT;\n case 3:\n return TYPE_IMAGE;\n default:\n return 4;\n }\n }\n\n @TargetApi(4)\n public AbstractViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n\n //header view 的判断\n AbstractViewHolder holder = super.onCreateViewHolder(viewGroup, viewType);\n if (holder != null) {\n return holder;\n }\n switch (viewType) {\n case TYPE_TEXT:\n xcArticleSectionTextRender text = new xcArticleSectionTextRender(viewGroup, this);\n AbstractViewHolder textholder = text.getReusableComponent();\n textholder.itemView.setTag(android.support.design.R.id.list_item, text);\n return textholder;\n case TYPE_IMAGE:\n xcArticleSectionImageRender image = new xcArticleSectionImageRender(viewGroup, this);\n AbstractViewHolder imgHolder = image.getReusableComponent();\n imgHolder.itemView.setTag(android.support.design.R.id.list_item, image);\n return imgHolder;\n default:\n return null;\n }\n\n }\n\n @TargetApi(4)\n public void onBindViewHolder(AbstractViewHolder holder, int position) {\n AbstractRender render = (AbstractRender) holder.itemView.getTag(android.support.design.R.id.list_item);\n render.bindData(position);\n }\n}", "@JsonAdapter(xcArticleSection.xcSectionJsonAdapter.class)\npublic class xcArticleSection<T extends xcArticleSection.IParagraph> {\n\n private int type;\n private IParagraph contentObject;\n private List<T> contentArray;\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public List<T> getContentArray() {\n return contentArray;\n }\n\n public void setContentArray(List<T> contentArray) {\n this.contentArray = contentArray;\n }\n\n public IParagraph getContentObject() {\n return contentObject;\n }\n\n public void setContentObject(IParagraph contentObject) {\n this.contentObject = contentObject;\n }\n\n public interface IParagraph {\n\n }\n\n public static class xcImage implements IParagraph {\n private String url;\n private String text;\n private int width;\n private int height;\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 getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public int getWidth() {\n return width;\n }\n\n public void setWidth(int width) {\n this.width = width;\n }\n\n public int getHeight() {\n return height;\n }\n\n public void setHeight(int height) {\n this.height = height;\n }\n }\n\n public static class xcText implements IParagraph {\n private String text;\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n }\n\n public static class xcTitle implements IParagraph {\n private String title;\n private String subTitle;\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 getSubTitle() {\n return subTitle;\n }\n\n public void setSubTitle(String subTitle) {\n this.subTitle = subTitle;\n }\n }\n\n\n public class xcSectionJsonAdapter extends TypeAdapter<xcArticleSection> {\n @Override\n public void write(JsonWriter out, xcArticleSection value) {\n\n }\n\n @Override\n public xcArticleSection read(JsonReader in) {\n xcArticleSection data = new xcArticleSection();\n try {\n in.beginObject();\n in.skipValue();\n data.setType(in.nextInt());\n switch (data.getType()) {\n case 1:\n data.setContentObject(readTitle(in));\n break;\n case 2:\n data.setContentArray(readText(in));\n break;\n case 3:\n data.setContentArray(readImages(in));\n break;\n case 4:\n break;\n case 5:\n break;\n default:\n Log.d(\"yese\", \"here is thit\");\n break;\n }\n in.endObject();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n return data;\n }\n }\n\n private xcTitle readTitle(JsonReader in) throws Exception {\n xcTitle data = new xcTitle();\n in.skipValue();\n in.beginObject();\n in.skipValue();\n data.setTitle(in.nextString());\n in.skipValue();\n data.setSubTitle(in.nextString());\n in.endObject();\n return data;\n }\n\n private List<xcText> readText(JsonReader in) throws Exception {\n List<xcText> data = new ArrayList<>();\n in.skipValue();\n in.beginArray();\n while (in.hasNext()) {\n xcText item = new xcText();\n item.setText(in.nextString());\n data.add(item);\n }\n in.endArray();\n return data;\n }\n\n private List<xcImage> readImages(JsonReader in) throws Exception {\n List<xcImage> data = new ArrayList<>();\n in.skipValue();\n in.beginArray();\n while (in.hasNext()) {\n in.beginObject();\n xcImage item = new xcImage();\n in.skipValue();\n item.setUrl(in.nextString());\n in.skipValue();\n item.setText(in.nextString());\n in.skipValue();\n item.setWidth(in.nextInt());\n in.skipValue();\n item.setHeight(in.nextInt());\n data.add(item);\n in.endObject();\n }\n in.endArray();\n return data;\n }\n }\n}" ]
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.huijimuhe.commonlayout.R; import com.huijimuhe.commonlayout.adapter.base.AbstractRender; import com.huijimuhe.commonlayout.adapter.base.AbstractRenderAdapter; import com.huijimuhe.commonlayout.adapter.base.AbstractViewHolder; import com.huijimuhe.commonlayout.adapter.xcArticleSectionAdapter; import com.huijimuhe.commonlayout.data.xc.xcArticleSection;
package com.huijimuhe.commonlayout.adapter.render; /** * Created by Huijimuhe on 2016/6/11. * This is a part of Homedev * enjoy */ public class xcArticleSectionTextRender extends AbstractRender { private ViewHolder mHolder;
private xcArticleSectionAdapter mAdapter;
3
pivotal-cf/spring-cloud-services-connector
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
[ "public class MockCloudConnector implements CloudConnector {\n\n\tpublic static final CloudConnector instance = Mockito.mock(CloudConnector.class);\n\n\tpublic static void reset() {\n\t\tMockito.reset(instance);\n\t}\n\n\tpublic boolean isInMatchingCloud() {\n\t\treturn instance.isInMatchingCloud();\n\t}\n\n\tpublic ApplicationInstanceInfo getApplicationInstanceInfo() {\n\t\treturn instance.getApplicationInstanceInfo();\n\t}\n\n\tpublic List<ServiceInfo> getServiceInfos() {\n\t\treturn instance.getServiceInfos();\n\t}\n}", "public class ConfigServerServiceInfo extends UriBasedServiceInfo {\n\tprivate String clientId;\n\tprivate String clientSecret;\n\tprivate String accessTokenUri;\n\n\tpublic ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {\n\t\tsuper(id, uriString);\n\t\tthis.clientId = clientId;\n\t\tthis.clientSecret = clientSecret;\n\t\tthis.accessTokenUri = accessTokenUri;\n\t}\n\n\tpublic String getClientId() {\n\t\treturn clientId;\n\t}\n\n\tpublic String getClientSecret() {\n\t\treturn clientSecret;\n\t}\n\n\tpublic String getAccessTokenUri() {\n\t\treturn accessTokenUri;\n\t}\n}", "public static final String SPRING_AUTOCONFIGURE_EXCLUDE = \"spring.autoconfigure.exclude\";", "public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = \"spring.cloud.config.client.oauth2.accessTokenUri\";", "public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = \"spring.cloud.config.client.oauth2.clientId\";", "public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = \"spring.cloud.config.client.oauth2.clientSecret\";", "public static final String SPRING_CLOUD_CONFIG_URI = \"spring.cloud.config.uri\";" ]
import java.util.Collections; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import io.pivotal.spring.cloud.MockCloudConnector; import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo; import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE; import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI; import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID; import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET; import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI; import static org.junit.Assert.assertEquals;
/* * Copyright 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 * * https://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.pivotal.spring.cloud.service.config; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest( classes = { ConfigServerServiceConnectorIntegrationTest.TestConfig.class }, properties = "spring.cloud.config.enabled=true") public class ConfigServerServiceConnectorIntegrationTest { private static final String CLIENT_ID = "client-id"; private static final String CLIENT_SECRET = "secret"; private static final String ACCESS_TOKEN_URI = "https://your-identity-zone.uaa.my-cf.com/oauth/token"; private static final String URI = "https://username:password@config-server.mydomain.com"; @Autowired private Environment environment; @Autowired private ApplicationContext context; @BeforeClass public static void beforeClass() { Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true); Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList( new ConfigServerServiceInfo("config-server", URI, CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN_URI))); } @AfterClass public static void afterClass() { MockCloudConnector.reset(); } @TestPropertySource(properties = "spring.rabbitmq.host=some_rabbit_host") public static class WithRabbitBinding extends ConfigServerServiceConnectorIntegrationTest { @Test public void springAutoConfigureExcludeIsNull() { assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE); } } public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest { @Test public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() { assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration", SPRING_AUTOCONFIGURE_EXCLUDE); } } @TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar") public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest { @Test public void springAutoConfigureExcludePreservesExistingExcludes() { assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE); } } @Test public void propertySourceIsAdded() { assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI); assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID); assertPropertyEquals(CLIENT_SECRET, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET);
assertPropertyEquals(ACCESS_TOKEN_URI, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI);
3
Akshansh986/Webkiosk
Webkiosk/src/main/java/com/blackMonster/webkiosk/ui/Dialog/RefreshDbErrorDialogStore.java
[ "public class MainPrefs {\n public static final String PREFS_NAME = \"MyPrefsFile\";\n\n public static final String ENROLL_NO = \"enroll\";\n public static final String PASSWORD = \"pass\";\n public static final String DOB = \"dob\";\n public static final String BATCH = \"batch\";\n public static final String COLG = \"colg\";\n public static final String USER_NAME = \"userName\"; //Name of student.\n public static final String IS_FIRST_TIME = \"isFirstTime\";\n private static final String STARTUP_ACTIVITY_NAME = \"startupActivityName\";\n private static final String ONLINE_TIMETABLE_FILE_NAME = \"onlineTimetableFileName\";\n public static final String IS_TIMETABLE_MODIFIED = \"isTimetableModified\"; //True if user modifies timetable at any time in lifetime.\n\n public static final String SAVE_DIALOG_MSG = \"dialog\";\n public static final String SAVE_DIALOG_DEFAULT_MSG = \"NA\";\n\n\n private static SharedPreferences prefs = null;\n\n private static void initPrefInstance(Context context) {\n if (prefs == null) prefs = context.getSharedPreferences(PREFS_NAME, 0);\n }\n\n public static String getEnroll(Context context) {\n initPrefInstance(context);\n return prefs.getString(ENROLL_NO, \"123\");\n }\n\n public static String getPassword(Context context) {\n initPrefInstance(context);\n return prefs.getString(PASSWORD, \"123\");\n }\n\n public static String getDOB(Context context) {\n initPrefInstance(context);\n return prefs.getString(DOB, \"123\");\n }\n\n public static String getBatch(Context context) {\n initPrefInstance(context);\n return prefs.getString(BATCH, \"123\");\n }\n\n\n public static String getColg(Context context) {\n initPrefInstance(context);\n return prefs.getString(COLG, \"JIIT\");\n }\n\n public static String getUserName(Context context) {\n initPrefInstance(context);\n return prefs.getString(USER_NAME, \"NA\");\n }\n\n /**\n * get message of saved error dialog.\n *\n * @param context\n * @return\n */\n public static String getSavedDialogMsg(Context context) {\n initPrefInstance(context);\n return prefs.getString(SAVE_DIALOG_MSG, SAVE_DIALOG_DEFAULT_MSG);\n }\n\n public static String getStartupActivityName(Context context) {\n initPrefInstance(context);\n return prefs.getString(STARTUP_ACTIVITY_NAME, TimetableActivity.class.getSimpleName());\n }\n\n /**\n * FileName of timetable as stored on server.\n *\n * @param context\n * @return\n */\n public static String getOnlineTimetableFileName(Context context) {\n initPrefInstance(context);\n return prefs.getString(ONLINE_TIMETABLE_FILE_NAME, \"NULL\");\n }\n\n\n /**\n * Used in showing help menu at first login.\n *\n * @param context\n * @return true, if app is viewed first time after logging in.\n */\n public static boolean isFirstTime(Context context) {\n initPrefInstance(context);\n return prefs.getBoolean(IS_FIRST_TIME, true);\n }\n\n public static boolean isTimetableModified(Context context) {\n initPrefInstance(context);\n return prefs.getBoolean(IS_TIMETABLE_MODIFIED, false);\n }\n\n //UserName == StudentName\n public static void setUserName(String userName, Context context) {\n initPrefInstance(context);\n prefs.edit().putString(USER_NAME, userName).commit();\n }\n\n public static void setPassword(String password, Context context) {\n initPrefInstance(context);\n prefs.edit().putString(PASSWORD, password).commit();\n }\n\n public static void setDOB(String dob, Context context) {\n initPrefInstance(context);\n prefs.edit().putString(DOB, dob).commit();\n }\n\n /**\n * set meessage of dialog to be saved.\n * @param msg\n * @param context\n */\n public static void setSaveDialogMsg(String msg, Context context) {\n initPrefInstance(context);\n prefs.edit().putString(SAVE_DIALOG_MSG, msg).commit();\n }\n\n /**\n * set that first refresh of database is over.\n * @param context\n */\n public static void setFirstTimeOver(Context context) {\n initPrefInstance(context);\n prefs.edit().putBoolean(IS_FIRST_TIME, false).commit();\n }\n\n public static void storeStartupActivity(Context context, String name) {\n initPrefInstance(context);\n prefs.edit().putString(STARTUP_ACTIVITY_NAME, name).commit();\n }\n\n /**\n * Filename of timetable on server.\n * @param context\n * @param fileName\n */\n public static void setOnlineTimetableFileName(Context context, String fileName) {\n initPrefInstance(context);\n prefs.edit().putString(ONLINE_TIMETABLE_FILE_NAME, fileName).commit();\n }\n\n /**\n * set if timetable if timetable is manually modified by user or not.\n * @param context\n */\n public static void setTimetableModified(Context context) {\n initPrefInstance(context);\n prefs.edit().putBoolean(IS_TIMETABLE_MODIFIED, true).commit();\n }\n\n public static void close() {\n prefs = null;\n }\n\n}", "public class RefreshBroadcasts {\n public static final String BROADCAST_LOGIN_RESULT = \"BROADCAST_LOGIN_RESULT\";\n public static final String BROADCAST_UPDATE_AVG_ATND_RESULT = \"UPDATE_AVG_ATND_RESULT\";\n public static final String BROADCAST_UPDATE_DETAILED_ATTENDENCE_RESULT = \"UPDATE_DETAILED_ATTENDENCE_RESULT\";\n}", "public class TimetableCreateRefresh {\n public static final String TAG = \"Timetable\";\n\n public static final int ERROR_BATCH_UNAVAILABLE = -5;\n public static final int DONE = -123;\n public static final int TRANSFER_FOUND_DONE = -31;\n public static final int ERROR_DB_UNAVAILABLE = -4;\n public static final int ERROR_UNKNOWN = -3;\n public static final int ERROR_CONNECTION = -2;\n\n\n public static int createDatabase(List<SubjectAttendance> subjectLink,\n String colg, String enroll, String batch, Context context) {\n M.log(\"Timetable\", \"creartedatabse\");\n int result;\n\n try {\n String ttFileName = getTimetableFileName(subjectLink, colg, context);\n\n if (ttFileName == null)\n result = DONE; // TIMETABLE NOT AVAILABLE\n else {\n M.log(\"Timetable\", ttFileName);\n String newFileName = handleTimetableTransfers(ttFileName, colg,\n enroll, batch, context);\n result = createTimetableDatabase(newFileName, colg, enroll, batch,\n context);\n if (result == DONE && transferFound(ttFileName, newFileName))\n result = TRANSFER_FOUND_DONE;\n }\n } catch (Exception e) {\n e.printStackTrace();\n result = ERROR_UNKNOWN;\n }\n\n return result;\n }\n\n public static void refresh(Context context) {\n\n String colg, enroll, batch, fileName;\n colg = MainPrefs.getColg(context);\n enroll = MainPrefs.getEnroll(context);\n batch = MainPrefs.getBatch(context);\n fileName = MainPrefs.getOnlineTimetableFileName(context);\n try {\n if (TimetableDbHelper.databaseExists(colg, enroll, batch,\n fileName, context)) {\n M.log(TAG,\n \"imetableDataHelper.databaseExists(colg, enroll, batch, fileName, context)\");\n String newFilename = handleTimetableTransfers(fileName, colg,\n enroll, batch, context);\n if (transferFound(fileName, newFilename)) {\n M.log(TAG, \"transferFound(fileName, newFilename)\");\n CrawlerDelegate cd = new CrawlerDelegate(context);\n cd.login(MainPrefs.getColg(context),\n MainPrefs.getEnroll(context), MainPrefs.getPassword(context), MainPrefs.getDOB(context));\n CreateDatabase.createFillTempAtndOverviewFromPreregSub(cd, context);\n deleteTimetableDb(context);\n createTimetableDatabase(newFilename, colg, enroll, batch,\n context);\n }\n } else {\n List<SubjectAttendance> tmp = (List<SubjectAttendance>) (List<?>) (new AttendenceOverviewTable(context)).getAllSubjectAttendance();\n createDatabase(tmp, colg, enroll, batch,context);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n\n public static void deleteTimetableDb(Context context) {\n String oldDbName = TimetableDbHelper.getDbNameThroughPrefs(context);\n TimetableDbHelper.shutdown();\n if (context.deleteDatabase(oldDbName)) {\n M.log(TAG, \"database deleted\");\n MainPrefs.setOnlineTimetableFileName(context, \"NULL\");\n }\n\n }\n\n public static boolean isError(int result) {\n return result == ERROR_BATCH_UNAVAILABLE\n || result == ERROR_UNKNOWN\n || result == ERROR_CONNECTION;\n }\n\n\n private static boolean transferFound(String f1, String f2) {\n if (f1 == null || f2 == null)\n return false;\n return !f1.equals(f2);\n }\n\n private static String handleTimetableTransfers(String ttFileName,\n String colg, String enroll, String batch, Context context)\n throws Exception {\n M.log(\"Timetable\", \"handleTimetableTransfers\");\n\n String finalFileName = ttFileName;\n BufferedReader transferList = FetchFromServer.getTransferList(colg,\n context);\n\n String newTtFileName = findTransfers(ttFileName, transferList);\n closeReader(transferList);\n if (newTtFileName != null) {\n finalFileName = newTtFileName;\n // createFillTempAtndOverviewFromPreregSub(context);\n\n }\n // /M.log(\"timetable\", finalFileName);\n return finalFileName;\n\n }\n\n private static int createTimetableDatabase(String fileName, String colg,\n String enroll, String batch, Context context) {\n\n // /M.log(TAG, \"loadTimetable\");\n int result;\n\n if (!TimetableDbHelper.databaseExists(colg, enroll, batch, fileName,\n context)) {\n\n List<String> timetableDataList = new ArrayList<String>();\n result = FetchFromServer.getDataBundle(colg, fileName, batch,\n timetableDataList, context);\n\n if (result == DONE) {\n TimetableTable.createDb(colg, fileName, batch, enroll, timetableDataList,\n context);\n result = DONE;\n }\n\n\n } else {\n MainPrefs.setOnlineTimetableFileName(context, fileName);\n MainPrefs.setTimetableModified(context);\n result = DONE;\n\n }\n // /M.log(TAG, \"load timetable result : \" + result);\n// if (result == FetchFromServer.DONE)\n// result = DONE;\n return result;\n }\n\n private static String getTimetableFileName(List<SubjectAttendance> subjectLink,\n String colg, Context context) throws Exception {\n // /M.log(\"Timetable\", \"getTimetableFileName\");\n BufferedReader subCodeList = FetchFromServer.getSubcodeList(colg,\n context);\n String result = findMatch(subjectLink, subCodeList);\n closeReader(subCodeList);\n return result;\n\n }\n\n private static String findTransfers(String ttFileName,\n BufferedReader transferList) {\n // /M.log(\"Timetable\", \"findTransfers\");\n\n try {\n if (!transferDatabaseExist(transferList))\n return null;\n\n while (true) {\n String line = transferList.readLine();\n if (line == null)\n break;\n if (line.replaceAll(\"\\\\s\", \"\").equals(\"\"))\n continue;\n if (line.substring(0, line.indexOf('$')).contains(ttFileName))\n return line.substring(line.indexOf('$') + 1);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n private static String findMatch(List<SubjectAttendance> subjectLink,\n BufferedReader subCodeList) {\n // /M.log(\"Timetable\", \"findMatch\");\n\n if (subCodeList == null || subjectLink == null)\n return null;\n int size = subjectLink.size();\n\n int i;\n String line;\n try {\n if (!subCodeDatabaseExist(subCodeList))\n return null;\n while (true) {\n line = subCodeList.readLine();\n if (line == null)\n break;\n if (line.replaceAll(\"\\\\s\", \"\").equals(\"\"))\n continue;\n // / M.log(\"Timetable\", line);\n\n int matched = 0;\n for (i = 0; i < size; ++i) {\n if (line.contains(subjectLink.get(i).getSubjectCode().substring(1)))\n ++matched;\n }\n\n if (matched >= (size / 2 + 1)) {\n return line.substring(line.indexOf('$') + 1);\n }\n\n }\n } catch (Exception e) {\n }\n return null;\n }\n\n private static boolean transferDatabaseExist(BufferedReader transferList)\n throws IOException {\n if (transferList == null)\n return false;\n return transferList.readLine().contains(\"transfers\");\n }\n\n private static boolean subCodeDatabaseExist(BufferedReader subCodeList)\n throws IOException {\n return subCodeList.readLine().contains(\"subjectCodes\");\n }\n\n private static void closeReader(BufferedReader reader) {\n try {\n reader.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}", "public class CreateDatabase {\n\tstatic final String TAG = \"createDatabase\";\n\tpublic static final int DONE = 1;\n\tpublic static final int ERROR = -52;\n\n\tprivate static String userName = null;\t\t\t\t//Name of student.\n\tprivate static List<SubjectAttendance> subjectAttendances = null;\n\n\tpublic static int start(String colg, String enroll, String batch,\n\t\t\t\t\t\t\tCrawlerDelegate crawlerDelegate, Context context) {\n\t\tdeleteOldDatabase(context);\n\n\t\tint result;\n\t\ttry {\n\t\t\tscrapStudentAndSubjectInfo(crawlerDelegate, context);\t//Get info from crawler.\n\t\t\tresult = handleTimetable(colg, enroll, batch, context);\n\n\t\t\tif ( ! TimetableCreateRefresh.isError(result)) {\n\t\t\t\tinitDatabase(context);\n\t\t\t\tif (result == TimetableCreateRefresh.TRANSFER_FOUND_DONE)\t\t//U have to read timetable wiki to understand it.\n\t\t\t\t\tcreateFillTempAtndOverviewFromPreregSub(crawlerDelegate, context);\n\t\t\t\tcreateTables(context);\n\t\t\t\tcreatePreferences(context);\n\t\t\t\tresult = DONE;\n\t\t\t}\n\n\t\t} catch (Exception e) {\n\t\t\tresult = ERROR;\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate static void initDatabase(Context context) {\n\t\tDbHelper.getInstance(context);\t\t//It's important.\n\t}\n\n\tprivate static int handleTimetable(String colg, String enroll,\n\t\t\tString batch, Context context) {\n\t\treturn TimetableCreateRefresh.createDatabase(subjectAttendances, colg, enroll, batch,\n\t\t\t\tcontext);\n\t}\n\n\tprivate static void scrapStudentAndSubjectInfo(CrawlerDelegate crawlerDelegate, Context context)\n\t\t\tthrows Exception {\n\t\tuserName = crawlerDelegate.getStudentName();\n\t\tsubjectAttendances = crawlerDelegate.getSubjectAttendanceMain();\n\t}\n\n\tprivate static void deleteOldDatabase(Context context) {\n\t\tcontext.deleteDatabase(DbHelper.DB_NAME);\n\t}\n\n\t//Create detailed attendance table for each subject.\n\tprivate static void createTables(Context context) throws Exception {\n\n\t\tfor (SubjectAttendance row : subjectAttendances) {\n\t\t\tnew DetailedAttendanceTable(row.getSubjectCode(),\n\t\t\t\t\trow.isNotLab(),context).createTable();\n\t\t}\n\t}\n\n\t/*Every time \"MY attendance\" menu in Webkiosk website is updated 3-4 days after college starts.\n\tMeanwhile old sem data is present there.\n\tSo to provide latest timetable at the very fist day of college, subject detail is fetched from \"Pre reg\"\n\tpage and store in TempAtndOverview table.\n\t*/\n\tpublic static void createFillTempAtndOverviewFromPreregSub(CrawlerDelegate crawlerDelegate, Context context) {\n\t\tList<SubjectAttendance> preSubjectAttendance = getSubInfoFromPrereg(crawlerDelegate, context);\n\t\tList<SubjectAttendance> regSubjectAttendance = getSubInfoFromReg(crawlerDelegate, context);\n\t\tList<SubjectAttendance> subjectAttendance = combineSubInfo(preSubjectAttendance, regSubjectAttendance);\n\t\t\n\t\tif (subjectAttendance == null)\n\t\t\treturn;\n\t\tTempAtndOverviewTable tempAtndOTable =new TempAtndOverviewTable(context);\n\t\ttempAtndOTable.dropTableifExist();\n\t\ttempAtndOTable.createTable(DbHelper.getInstance(context)\n\t\t\t\t.getWritableDatabase());\n\t\tfor (SubjectAttendance row : subjectAttendance) {\n\n\t\t\tMySubjectAttendance mySubAtnd =\tnew MySubjectAttendance(row.getName(),row.getSubjectCode(),row.getOverall(),\n\t\t\t\t\trow.getLect(),row.getTute(),row.getPract(),row.isNotLab(),0);\n\t\t\ttempAtndOTable.insert(mySubAtnd);\n\t\t}\n\t}\n\n\tprivate static List<SubjectAttendance> combineSubInfo(List<SubjectAttendance> preSubjectLink,\n\t\t\t\t\t\t\t\t\t\t\t\t\tList<SubjectAttendance> regSubjectLink) {\n\t\t\n\t\tif (preSubjectLink==null && regSubjectLink==null) return null;\n\t\tif (preSubjectLink==null && regSubjectLink!=null) return regSubjectLink;\n\t\tif (preSubjectLink!=null && regSubjectLink==null) return preSubjectLink;\n\t\t\n\t\tfor (SubjectAttendance x : preSubjectLink) {\n\t\t\tif (! regSubjectLink.contains(x)) regSubjectLink.add(x);\n\t\t}\n\t\t\n\t\treturn regSubjectLink;\n\t}\n\n\tprivate static List<SubjectAttendance> getSubInfoFromReg(CrawlerDelegate crawlerDelegate, Context context) {\n\n\t\ttry {\n\t\t\treturn crawlerDelegate.getSubjectAttendanceFromSubRegistered();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate static List<SubjectAttendance> getSubInfoFromPrereg(CrawlerDelegate crawlerDelegate, Context context) {\n\t\ttry {\n\t\t\treturn crawlerDelegate.getSubjectAttendanceFromPreReg();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n private static void createPreferences(Context context) {\n\t\tMainPrefs.setUserName(userName,context);\n\t}\n\n}", "public class UpdateAvgAtnd {\n public static final int ERROR = -100;\n\n /**\n * Updates Avg attendance to local db.\n * @param newSubjectAttendances\n * @param context\n * @return Number of subject whose attendance is modified\n * @throws SubjectChangedException\n */\n public static int update(List<SubjectAttendance> newSubjectAttendances, Context context) throws SubjectChangedException {\n int numOfSubjectModified = 0;\n AttendenceOverviewTable atndO = new AttendenceOverviewTable(context);\n\n try {\n if (atndO.isTableEmpty()) {\n doFirstRefresh(newSubjectAttendances, context); //update is run for first time.\n return numOfSubjectModified;\n }\n\n int isModified; //tracks if attendance of a subject is modified or not.\n for (SubjectAttendance newSubjectAttendance : newSubjectAttendances) {\n\n SubjectAttendance oldSubjectAttendance = atndO.getSubjectAttendance(newSubjectAttendance.getSubjectCode());\n if (oldSubjectAttendance == null) throw new SubjectChangedException();\n\n if (oldSubjectAttendance.getOverall() == newSubjectAttendance.getOverall() && oldSubjectAttendance.getLect() == newSubjectAttendance.getLect() && oldSubjectAttendance.getTute() == newSubjectAttendance.getTute() && oldSubjectAttendance.getPract() == newSubjectAttendance.getPract())\n isModified = 0;\n else {\n isModified = 1;\n ++numOfSubjectModified;\n }\n atndO.update(toMySubAtnd(newSubjectAttendance, isModified));\n }\n return numOfSubjectModified;\n } finally {\n RefreshDBPrefs.setAvgAttendanceRefreshTimestamp(context);\n }\n }\n\n\n\n private static void doFirstRefresh(List<SubjectAttendance> newSubjectAttendances, Context context) {\n AttendenceOverviewTable atndO = new AttendenceOverviewTable(context);\n for (SubjectAttendance newSubjectAttendance : newSubjectAttendances) {\n atndO.insert(toMySubAtnd(newSubjectAttendance,0));\n }\n }\n\n public static int update(CrawlerDelegate crawlerDelegate, Context context) throws SubjectChangedException {\n int result;\n try {\n List<SubjectAttendance> listt = crawlerDelegate.getSubjectAttendanceMain();\n result = update(listt, context);\n } catch (SubjectChangedException e) {\n throw e;\n } catch (Exception e) {\n result = ERROR;\n e.printStackTrace();\n }\n\n return result;\n }\n\n //convrets SubjectAttendance to MySubjectAttendance.\n private static MySubjectAttendance toMySubAtnd(SubjectAttendance subAtnd, int isModified) {\n return new MySubjectAttendance(subAtnd.getName(), subAtnd.getSubjectCode(), subAtnd.getOverall(),\n subAtnd.getLect(), subAtnd.getTute(), subAtnd.getPract(), subAtnd.isNotLab(), isModified);\n }\n\n}", "public class UpdateDetailedAttendance {\n static final String TAG = \"UpdateAttendence\";\n public static final int DONE = 1;\n public static final int ERROR = -1;\n\n\n\n public static int start(CrawlerDelegate crawlerDelegate, Context context) {\n int result;\n\n try {\n fillAllAttendenceTable(crawlerDelegate, context);\n createPreferences(context);\n result = DONE;\n } catch (Exception e) {\n result = ERROR;\n e.printStackTrace();\n }\n return result;\n }\n\n //updates detailed attendance of all subjects\n private static void fillAllAttendenceTable(CrawlerDelegate crawlerDelegate, Context context)\n throws Exception {\n\n List<MySubjectAttendance> subjectAttendanceList = new AttendenceOverviewTable(context).getAllSubjectAttendance();\n\n for (SubjectAttendance subjectAttendance : subjectAttendanceList) {\n List<DetailedAttendance> detailedAttendanceList = crawlerDelegate.getDetailedAttendance(subjectAttendance.getSubjectCode());\n if (detailedAttendanceList != null) {\n fillSingleTable(subjectAttendance.getSubjectCode(), detailedAttendanceList, subjectAttendance.isNotLab(), context);\n }\n\n }\n\n }\n\n //updates detailed attendance of single subject.\n private static void fillSingleTable(String subCode, List<DetailedAttendance> detailedAttendanceList, int isNotLab, Context context) throws Exception {\n DetailedAttendanceTable detailedAttendanceTable = new DetailedAttendanceTable(subCode, isNotLab, context);\n\n detailedAttendanceTable.deleteAllRows();\n detailedAttendanceTable.insert(detailedAttendanceList);\n }\n\n private static void createPreferences(Context context) {\n RefreshDBPrefs.setDetailedAtndRefreshTimestamp(context);\n RefreshDBPrefs.setPasswordUptoDate(context); //TODO Someone should move it to it's appropriate place.\n }\n\n}", "public class LoginStatus {\n public static final int LOGIN_DONE = 1;\n public static final int CONN_ERROR = 2;\n public static final int INVALID_PASS = 3;\n public static final int INVALID_ENROLL = 4;\n public static final int ACCOUNT_LOCKED = 5;\n public static final int UNKNOWN_ERROR = 6;\n\n public static String responseToString(Context context,int response) {\n switch (response) {\n\n case INVALID_PASS:\n return context.getString(R.string.invalid_pass);\n\n case INVALID_ENROLL:\n return context.getString(R.string.invalid_enroll);\n\n case CONN_ERROR:\n return context.getString(R.string.con_error);\n case ACCOUNT_LOCKED :\n return context.getString(R.string.webkiosk_account_locked_at_first_login);\n\n case UNKNOWN_ERROR:\n return context.getString(R.string.unknown_error);\n\n default:\n return null;\n\n }\n }\n}", "public class InitDB {\n\n public static final String BROADCAST_DATEBASE_CREATION_RESULT = \"BROADCAST_DATEBASE_CREATION_RESULT\";\n private static final String TAG = \"InitDB\";\n\n String enroll, pass, batch, colg, dob;\n Context context;\n\n CrawlerDelegate crawlerDelegate;\n\n\n public InitDB(String enroll, String pass, String batch, String colg, String dob, Context context) {\n this.enroll = enroll;\n this.pass = pass;\n this.batch = batch;\n this.colg = colg;\n this.dob = dob;\n this.context = context;\n }\n\n\n /*\n * TEMPLATE:\n *\n * RefreshDBPrefs.setStatus(..);\n * do work....\n * broadcastResult(..);\n * Error handling\n *\n * RefreshDBPrefs.setStatus(..);\n * .\n * .\n */\n\n public boolean start() {\n int result;\n\n try {\n RefreshDBPrefs.setStatus(RefreshStatus.LOGGING_IN, context);\n crawlerDelegate = new CrawlerDelegate(context);\n result = crawlerDelegate.login(colg, enroll, pass, dob);\n broadcastResult(RefreshBroadcasts.BROADCAST_LOGIN_RESULT, result);\n\n if (result != LoginStatus.LOGIN_DONE) return false;\n M.log(TAG, \"login done\");\n\n RefreshDBPrefs.setStatus(RefreshStatus.CREATING_DB, context);\n result = CreateDatabase.start(colg, enroll, batch, crawlerDelegate, context);\n broadcastResult(BROADCAST_DATEBASE_CREATION_RESULT, result);\n\n if (isCreateDatabaseSuccessful(result)) {\n saveFirstTimeloginPreference();\n return true;\n } else return false;\n\n } finally {\n RefreshDBPrefs.setStatus(RefreshStatus.STOPPED,\n context);\n }\n\n }\n\n public CrawlerDelegate getCrawlerDelegate() {\n return crawlerDelegate;\n }\n\n private void saveFirstTimeloginPreference() {\n SharedPreferences settings = context.getSharedPreferences(\n MainPrefs.PREFS_NAME, 0);\n SharedPreferences.Editor editor = settings.edit();\n editor.putString(MainPrefs.ENROLL_NO, enroll);\n editor.putString(MainPrefs.PASSWORD, pass);\n editor.putString(MainPrefs.DOB, dob);\n editor.putString(MainPrefs.BATCH, batch);\n editor.putString(AutoRefreshAlarmService.PREF_AUTO_UPDATE_OVER, \"anyNetwork\");\n editor.putString(MainPrefs.COLG, colg);\n editor.commit();\n }\n\n //Broadcast result of every step of DB initialization, so that UI elements can act accordingly.\n private void broadcastResult(String type, int result) {\n RefreshDbErrorDialogStore.store(type, result, context);\n\n Intent intent = new Intent(type).putExtra(type, result);\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n\n //Returns if attendance and timetable database both are successfully created.\n private boolean isCreateDatabaseSuccessful(int result) {\n return !(result == CreateDatabase.ERROR || TimetableCreateRefresh.isError(result));\n }\n}" ]
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import com.blackMonster.webkiosk.SharedPrefs.MainPrefs; import com.blackMonster.webkiosk.controller.RefreshBroadcasts; import com.blackMonster.webkiosk.controller.Timetable.TimetableCreateRefresh; import com.blackMonster.webkiosk.controller.appLogin.CreateDatabase; import com.blackMonster.webkiosk.controller.updateAtnd.UpdateAvgAtnd; import com.blackMonster.webkiosk.controller.updateAtnd.UpdateDetailedAttendance; import com.blackMonster.webkiosk.crawler.LoginStatus; import com.blackMonster.webkiosk.controller.appLogin.InitDB; import com.blackMonster.webkioskApp.R;
package com.blackMonster.webkiosk.ui.Dialog; /** * Stores error dialogs generated while refreshing database. * * Complete dialog handling is done manually. Ex- what happens when when error happens and app is in background. etc. * Every error dialog to be displayed is first saved here. If activity is in foreground * and receives broadcast regarding error, it just check here for any stored dialog and displays it. * If not, then onResume() of most of activity checks and display if any dialog is present here. * */ public class RefreshDbErrorDialogStore { static AlertDialog myDialog = null; /** * Show stored error dialog if present. * @param context */ public static void showDialogIfPresent(Context context) { String dialogMsg = MainPrefs.getSavedDialogMsg(context); if (!dialogMsg.equals(MainPrefs.SAVE_DIALOG_DEFAULT_MSG)) { myDialog = createAlertDialog(dialogMsg, context); myDialog.show(); } } public static void dismissIfPresent() { if (myDialog != null) { myDialog.dismiss(); myDialog = null; } } private static AlertDialog createAlertDialog(String msg, final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { myDialog = null; MainPrefs.setSaveDialogMsg(MainPrefs.SAVE_DIALOG_DEFAULT_MSG, context); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { myDialog = null; MainPrefs.setSaveDialogMsg(MainPrefs.SAVE_DIALOG_DEFAULT_MSG, context); } }); builder.setMessage(msg); return builder.create(); } /** * Stores message of every error dialog, So that dialog can be retrieved from UI elements. * @param type * @param result * @param context */ public static void store(String type, int result, Context context) {
if (type.equals(RefreshBroadcasts.BROADCAST_LOGIN_RESULT)) {
1
idega/com.idega.block.email
src/java/com/idega/block/email/presentation/NewsLetterArchive.java
[ "public class EmailConstants {\n\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"com.idega.block.email\";\n\t\n\tpublic static final String MAILING_LIST_MESSAGE_RECEIVER = CoreConstants.PROP_SYSTEM_ACCOUNT;\n\t\n\tpublic static final String MULTIPART_MIXED_TYPE = \"multipart/Mixed\";\n\tpublic static final String MULTIPART_ALTERNATIVE_TYPE = \"multipart/alternative\";\n\tpublic static final String MULTIPART_RELATED_TYPE = \"multipart/related\";\n\tpublic static final String MESSAGE_RFC822_TYPE = \"message/rfc822\";\n\tpublic static final String MESSAGE_MULTIPART_SIGNED = \"multipart/signed\";\n\tpublic static final String MESSAGE_MULTIPART_REPORT = \"multipart/report\";\n\t\n\tpublic static final String IW_MAILING_LIST = \"-iwlist\";\n}", "public interface EmailLetter {\n\t/** @todo Description of the Field */\n\tpublic final static int TYPE_RECEIVED = 0;\n\t/** @todo Description of the Field */\n\tpublic final static int TYPE_SENT = 1;\n\t/** @todo Description of the Field */\n\tpublic final static int TYPE_SUBSCRIPTION = 2;\n\t/** @todo Description of the Field */\n\tpublic final static int TYPE_UNSUBSCRIBE = 3;\n\tpublic final static int TYPE_DRAFT = 4;\n\tpublic final static int TYPE_LIST = 5;\n\t/**\n\t * Gets the body of the EmailLetter object\n\t *\n\t * @return The body value\n\t */\n\tpublic String getBody();\n\t/**\n\t * Gets the subject of the EmailLetter object\n\t *\n\t * @return The subject value\n\t */\n\tpublic String getSubject();\n\t/**\n\t * Gets the fromAddress of the EmailLetter object\n\t *\n\t * @return The from address value\n\t */\n\tpublic String getFromAddress();\n\t/**\n\t * Gets the fromName of the EmailLetter object\n\t *\n\t * @return The from name value\n\t */\n\tpublic String getFromName();\n\t/**\n\t * Gets the type of the EmailLetter object\n\t *\n\t * @return The type value\n\t */\n\tpublic int getType();\n\t/**\n\t * Gets the created of the EmailLetter object\n\t *\n\t * @return The created value\n\t */\n\tpublic java.sql.Timestamp getCreated();\n\t\n\tpublic Integer getIdentifier();\n}", "public interface EmailTopic{\n\n\n\n /**\n\n * Gets the name of the EmailList object\n\n *\n\n * @return The name value\n\n */\n\n public String getName();\n\n\n\n\n\n /**\n\n * Gets the description of the EmailList object\n\n *\n\n * @return The description value\n\n */\n\n public String getDescription();\n\n\n\n\n\n /**\n\n * Gets the creation date of the EmailList object\n\n *\n\n * @return The created value\n\n */\n\n public java.sql.Timestamp getCreated();\n\n\n\n\n\n /**\n\n * Gets the groupId of the EmailTopic object\n\n *\n\n * @return The group id value\n\n */\n\n public int getGroupId();\n\n\n\n\n\n /**\n\n * Gets the listId of the EmailTopic object\n\n *\n\n * @return The list id value\n\n */\n\n public int getListId();\n\n public int getCategoryId();\n public String getSenderName();\n public String getSenderEmail();\n public Integer getIdentifier();\n\n}", "public class MailBusiness {\n\n private static MailBusiness letterBusiness;\n\n\n /**\n * Gets the instance of the LetterBusiness class\n *\n * @return The instance value\n */\n public static MailBusiness getInstance() {\n if (letterBusiness == null) {\n letterBusiness = new MailBusiness();\n }\n return letterBusiness;\n }\n\n\n /**\n * @param id Description of the Parameter\n * @param name Description of the Parameter\n * @param info Description of the Parameter\n * @param iCategoryId Description of the Parameter\n * @return Description of the Return Value\n * @todo Description of the Method\n */\n public MailGroup saveLetterGroup(int id, String name, String info, int iCategoryId) {\n try {\n MailGroupHome mHome = (MailGroupHome) IDOLookup.getHome(MailGroup.class);\n MailGroup group = mHome.create();\n boolean update = false;\n if (id > 0) {\n group = mHome.findByPrimaryKey(new Integer(id));\n update = true;\n }\n\n group.setName(name);\n group.setDescription(info);\n group.setCategoryId(iCategoryId);\n\n if (update) {\n group.store();\n } else {\n group.setCreated(com.idega.util.IWTimestamp.getTimestampRightNow());\n group.store();\n }\n\n return group;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * @param id Description of the Parameter\n * @param name Description of the Parameter\n * @param info Description of the Parameter\n * @param iGroupId Description of the Parameter\n * @return Description of the Return Value\n * @todo Description of the Method\n */\n public MailTopic saveTopic(int id, String name, String info, int iCategoryId,String senderName,String senderEmail) {\n try {\n MailTopic topic = ((MailTopicHome) IDOLookup.getHome(MailTopic.class)).create();\n boolean update = false;\n if (id > 0) {\n \ttopic = ((MailTopicHome) IDOLookup.getHome(MailTopic.class)).findByPrimaryKey(new Integer(id));\n update = true;\n }\n\n topic.setName(name);\n topic.setDescription(info);\n topic.setCategoryId(iCategoryId);\n topic.setSenderName(senderName);\n topic.setSenderEmail(senderEmail);\n if (update) {\n topic.store();\n } else {\n MailList list = ((MailListHome)IDOLookup.getHome(MailList.class)).create();\n list.setCreated(com.idega.util.IWTimestamp.getTimestampRightNow());\n list.setName(topic.getName() + \" list\");\n list.setDescription(topic.getDescription());\n list.insert();\n topic.setListId(((Integer)list.getPrimaryKey()).intValue());\n topic.setCreated(com.idega.util.IWTimestamp.getTimestampRightNow());\n topic.store();\n }\n\n return topic;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * @todo Description of the Method\n *\n * @param id Description of the Parameter\n * @param name Description of the Parameter\n * @param host Description of the Parameter\n * @param user Description of the Parameter\n * @param pass Description of the Parameter\n * @param protocol Description of the Parameter\n * @param entityId Description of the Parameter\n * @return Description of the Return Value\n */\n public MailAccount saveTopicAccount(int id, String name, String host, String user, String pass, int protocol, int entityId) {\n return saveAccount(id, name, host, user, pass, protocol, entityId, MailTopic.class);\n }\n\n\n /**\n * @todo Description of the Method\n *\n * @param id Description of the Parameter\n * @param name Description of the Parameter\n * @param host Description of the Parameter\n * @param user Description of the Parameter\n * @param pass Description of the Parameter\n * @param protocol Description of the Parameter\n * @param entityId Description of the Parameter\n * @return Description of the Return Value\n */\n public MailAccount saveGroupAccount(int id, String name, String host, String user, String pass, int protocol, int entityId) {\n return saveAccount(id, name, host, user, pass, protocol, entityId, MailGroup.class);\n }\n\n\n /**\n * @param id Description of the Parameter\n * @param name Description of the Parameter\n * @param host Description of the Parameter\n * @param user Description of the Parameter\n * @param pass Description of the Parameter\n * @param protocol Description of the Parameter\n * @param entityId Description of the Parameter\n * @param entityClass Description of the Parameter\n * @return Description of the Return Value\n * @todo Description of the Method\n */\n public MailAccount saveAccount(int id, String name, String host, String user, String pass, int protocol, int entityId, Class entityClass) {\n try {\n MailAccount account = (MailAccount) GenericEntity.getEntityInstance(MailAccount.class);\n boolean update = false;\n if (id > 0) {\n account.findByPrimaryKey(id);\n update = true;\n }\n\n account.setName(name);\n account.setHost(host);\n account.setUser(user);\n account.setPassword(pass);\n account.setProtocol(protocol);\n\n if (update) {\n account.update();\n } else {\n account.insert();\n }\n\n if(entityClass!=null && entityId > 0) {\n\t\t\t\taccount.addTo(entityClass, entityId);\n\t\t\t}\n\n return account;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * @param id Description of the Parameter\n * @param entityClass Description of the Parameter\n * @todo Description of the Method\n */\n private void deleteAccount(int id, Class entityClass) {\n try {\n MailAccount a = (MailAccount) GenericEntity.getEntityInstance(MailAccount.class, id);\n a.removeFrom(entityClass);\n a.delete();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n\n /**\n * @param id Description of the Parameter\n * @todo Description of the Method\n */\n public void deleteGroupAccount(int id) {\n deleteAccount(id, MailGroup.class);\n }\n\n\n /**\n * @param id Description of the Parameter\n * @todo Description of the Method\n */\n public void deleteTopicAccount(int id) {\n deleteAccount(id, MailTopic.class);\n }\n\n\n /**\n * @param email Description of the Parameter\n * @param ListIds Description of the Parameter\n * @todo Description of the Method\n */\n public void saveEmailToLists(String email, int[] ListIds) {\n try {\n\n Email eEmail =MailFinder.getInstance().lookupEmail(email);\n if(eEmail == null){\n eEmail = ((com.idega.core.contact.data.EmailHome)com.idega.data.IDOLookup.getHomeLegacy(Email.class)).createLegacy();\n eEmail.setEmailAddress(email);\n eEmail.insert();\n }\n\n for (int i = 0; i < ListIds.length; i++) {\n try{\n //System.err.println(\"adding \"+eEmail.getEmailAddress()+\" to \"+ListIds[i]);\n eEmail.addTo(MailList.class, ListIds[i]);\n MailTopic topic =((MailTopicHome) IDOLookup.getHome(MailTopic.class)).findOneByListId(ListIds[i]);\n sendWelcomeLetters(topic,eEmail.getEmailAddress());\n }\n catch(Exception ex){}\n }\n\n } catch (Exception ex) {\n //ex.printStackTrace();\n }\n }\n \n public void removeEmailFromLists(String email, int[] ListIds) {\n try {\n\n Email eEmail =MailFinder.getInstance().lookupEmail(email);\n if(eEmail == null){\n \treturn;\n }\n\n for (int i = 0; i < ListIds.length; i++) {\n try{\n //System.err.println(\"adding \"+eEmail.getEmailAddress()+\" to \"+ListIds[i]);\n eEmail.removeFrom(MailList.class,ListIds[i]);\n //eEmail.addTo(MailList.class, ListIds[i]);\n //MailTopic topic =((MailTopicHome) IDOLookup.getHome(MailTopic.class)).findOneByListId(ListIds[i]);\n //sendWelcomeLetters(topic,eEmail.getEmailAddress());\n }\n catch(Exception ex){}\n }\n\n } catch (Exception ex) {\n \n }\n }\n\n public void sendWelcomeLetters(MailTopic topic,String email)throws RemoteException,FinderException{\n \tCollection letters = MailFinder.getInstance().getEmailLetters(((Integer)topic.getPrimaryKey()).intValue(),EmailLetter.TYPE_SUBSCRIPTION);\n \tif(letters!=null &&!letters.isEmpty()){\n\t\tEmail eEmail =MailFinder.getInstance().lookupEmail(email);\n \t\tthis.sendLetter((EmailLetter)letters.iterator().next(),topic,eEmail);\n \t}\n }\n\n /**\n * @param id Description of the Parameter\n * @todo Description of the Method\n */\n public void deleteTopic(int id) {\n try {\n\n MailTopic topic = ((MailTopicHome)IDOLookup.getHome(MailTopic.class)).findByPrimaryKey(new Integer(id));\n\t topic.removeFrom(MailLetter.class);\n\t topic.removeFrom(MailAccount.class);\n\t topic.remove();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n public void deleteLetter(int id) {\n try {\n\n MailLetter l = ((MailLetterHome)IDOLookup.getHome(MailLetter.class)).findByPrimaryKey(new Integer(id));\n l.removeFrom(MailTopic.class);\n l.remove();\n\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n\n /**\n * @param id Description of the Parameter\n * @todo Description of the Method\n */\n public void deleteGroup(int id) {\n try {\n\n ((MailGroupHome)IDOLookup.getHome(MailGroup.class)).findByPrimaryKey(new Integer(id)).remove();\n\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n\n }\n\n\n /**\n * @todo Description of the Method\n *\n * @param id Description of the Parameter\n * @param fromName Description of the Parameter\n * @param fromAddress Description of the Parameter\n * @param subject Description of the Parameter\n * @param body Description of the Parameter\n * @param type Description of the Parameter\n * @param topicId Description of the Parameter\n * @return Description of the Return Value\n */\n public MailLetter saveTopicLetter(int id, String fromName, String fromAddress, String subject, String body, int type, int topicId) {\n return saveMailLetter(id, fromName, fromAddress, subject, body, type, topicId, MailTopic.class);\n }\n\n\n /**\n * @todo Description of the Method\n *\n * @param id Description of the Parameter\n * @param fromName Description of the Parameter\n * @param fromAddress Description of the Parameter\n * @param subject Description of the Parameter\n * @param body Description of the Parameter\n * @param type Description of the Parameter\n * @param entityId Description of the Parameter\n * @param entityClass Description of the Parameter\n * @return Description of the Return Value\n */\n public MailLetter saveMailLetter(int id, String fromName, String fromAddress, String subject, String body, int type, int entityId, Class entityClass) {\n try {\n MailLetter letter = (MailLetter) GenericEntity.getEntityInstance(MailLetter.class);\n boolean update = false;\n if (id > 0) {\n letter.findByPrimaryKey(id);\n update = true;\n }\n\n letter.setFromName(fromName);\n letter.setFromAddress(fromAddress);\n letter.setSubject(subject);\n letter.setBody(body);\n letter.setType(type);\n letter.setCreated(IWTimestamp.getTimestampRightNow());\n\n if (update) {\n letter.update();\n } else {\n letter.insert();\n }\n\n if (entityId > 0) {\n letter.addTo(entityClass, entityId);\n }\n\n return letter;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * @todo Description of the Method\n *\n * @param letter Description of the Parameter\n * @param topic Description of the Parameter\n */\n public void sendLetter(EmailLetter letter, MailTopic topic) throws RemoteException{\n Collection accounts = MailFinder.getInstance().getTopicAccounts(((Integer)topic.getPrimaryKey()).intValue(), MailProtocol.SMTP);\n if (accounts != null && accounts.size() > 0) {\n Collection emails = MailFinder.getInstance().getListEmails(topic.getListId());\n Iterator iter = accounts.iterator();\n EmailAccount account = iter.hasNext() ? ((EmailAccount) iter.next()) : null;\n if (account != null) {\n sendMailLetter(letter, account, emails);\n }\n } else {\n System.err.println(\"unable to send mail: no account\");\n }\n }\n\n public void sendLetter(EmailLetter letter, MailTopic topic, Email email)throws RemoteException{\n\t Collection accounts = MailFinder.getInstance().getTopicAccounts(((Integer)topic.getPrimaryKey()).intValue(), MailProtocol.SMTP);\n\t if (accounts != null && accounts.size() > 0) {\n\t Collection emails = new java.util.ArrayList(1);\n\t emails.add(email);\n\t Iterator iter = accounts.iterator();\n\t EmailAccount account = iter.hasNext() ? ((EmailAccount) iter.next()) : null;\n\t if (account != null) {\n\t \t sendMailLetter(letter, account, emails);\n\t }\n\t } else {\n\t System.err.println(\"unable to send mail: no account\");\n }\n }\n\n public void sendMailLetter(EmailLetter letter,EmailAccount account,Collection emails){\n \tListServer server = new ListServer();\n server.sendMailLetter(letter, account, emails);\n }\n\n}", "public class MailFinder {\n\n private static MailFinder letterFinder;\n\n\n /**\n * Gets a static instance of the LetterFinder class\n *\n * @return The instance value\n */\n public static MailFinder getInstance() {\n if (letterFinder == null) {\n letterFinder = new MailFinder();\n }\n return letterFinder;\n }\n\n\n /**\n * Returns a Collection of Email objects bound to a specified EmailList\n *\n * @param l - the EmailList object bound\n * @return a collection of emails in the specified emaillist\n */\n public Collection getEmails(MailList l) {\n try {\n return EntityFinder.getInstance().findRelatedOrdered(l, Email.class, com.idega.core.contact.data.EmailBMPBean.getColumnNameAddress(), true);\n } catch (IDOFinderException ex) {\n\n }\n return null;\n }\n\n\n /**\n * Returns a Collection of Letter objects bound to a specified Topic\n *\n * @param t - the letter topic\n * @return a collection of the letters contained in specified topic.\n */\n public Collection getEmailLetters(MailTopic t) {\n try {\n return EntityFinder.getInstance().findRelatedOrdered(t, MailLetter.class, com.idega.block.email.data.MailLetterBMPBean.CREATED, true);\n } catch (IDOFinderException ex) {}\n return null;\n }\n\n public Collection getEmailLetters(int topicId) {\n try {\n MailTopic t = ((MailTopicHome)IDOLookup.getHomeLegacy(MailTopic.class)).findByPrimaryKey(new Integer(topicId));\n return EntityFinder.getInstance().findRelatedOrdered(t, MailLetter.class, com.idega.block.email.data.MailLetterBMPBean.CREATED, true);\n } catch (IDOFinderException ex) {}\n catch(Exception ex){}\n return null;\n }\n \n public Collection getEmailLetters(int topicId,int type){\n \ttry {\n \tStringBuffer sql = new StringBuffer(\"select l.* from \");\n \tsql.append(\" em_letter l,em_topic t,em_letter_em_topic m \");\n \tsql.append(\" where l.em_letter_id = m.em_letter_id \");\n \tsql.append(\" and t.em_topic_id = m.em_topic_id \");\n \tsql.append(\" and t.em_topic_id = \");\n \tsql.append(topicId);\n \tsql.append(\" and l.letter_type=\");\n \tsql.append(type);\n \t//System.err.println(sql.toString());\n \treturn EntityFinder.getInstance().findAll(MailLetter.class,sql.toString());\n \t} catch (IDOFinderException ex) {}\n catch(Exception ex){}\n return null;\n }\n \n\n\n /**\n * Gets the letterGroups\n *\n * @param ICObjectInstanceId Description of the Parameter\n * @return The letter groups value\n */\n public Collection getEmailGroups(int ICObjectInstanceId) {\n return CategoryFinder.getInstance().listOfCategoryEntityByInstanceId(MailGroup.class, ICObjectInstanceId);\n }\n\n\n /**\n * @param ICObjectInstanceId Description of the Parameter\n * @return Description of the Return Value\n * @todo Description of the Method\n */\n public Map mapOfEmailGroups(int ICObjectInstanceId) {\n return EntityFinder.getInstance().getMapOfEntity(getEmailGroups(ICObjectInstanceId), ((MailGroup) GenericEntity.getEntityInstance(MailGroup.class)).getIDColumnName());\n }\n\n\n /**\n * Gets the instanceTopics\n *\n * @param ICObjectInstanceId Description of the Parameter\n * @return The instance topics value\n */\n public Collection getInstanceTopics(int ICObjectInstanceId) {\n //return CategoryFinder.getInstance().getCategoryRelatedEntityFromInstanceId(MailGroup.class, MailTopic.class, com.idega.block.email.data.MailTopicBMPBean.GROUP, ICObjectInstanceId);\n return getTopics(ICObjectInstanceId);\n }\n\n\n /**\n * Gets the groupAccounts of the LetterFinder object\n *\n * @param GroupId Description of the Parameter\n * @return The group accounts value\n */\n public Collection getGroupAccounts(int GroupId) {\n try {\n Collection c = EntityFinder.getInstance().findRelated(GenericEntity.getEntityInstance(MailGroup.class, GroupId), MailAccount.class);\n return c;\n } catch (IDOFinderException ex) {\n\n }\n return null;\n }\n\n\n /**\n * Gets the topicAccounts of the LetterFinder object\n *\n * @param TopicId Description of the Parameter\n * @return The topic accounts value\n */\n public Collection getTopicAccounts(int TopicId) {\n try {\n Collection c = EntityFinder.getInstance().findRelated(GenericEntity.getEntityInstance(MailTopic.class, TopicId), MailAccount.class);\n return c;\n } catch (IDOFinderException ex) {\n\n }\n return null;\n }\n\n\n /**\n * Gets the topicAccounts of the MailFinder object\n *\n * @param TopicId Description of the Parameter\n * @param protocol Description of the Parameter\n * @return The topic accounts value\n */\n public Collection getTopicAccounts(int TopicId, int protocol) {\n Collection accounts = getTopicAccounts(TopicId);\n if (accounts != null && accounts.size() > 0) {\n Iterator iter = accounts.iterator();\n MailAccount ma;\n while (iter.hasNext()) {\n ma = (MailAccount) iter.next();\n if (ma.getProtocol() != protocol) {\n iter.remove();\n }\n }\n return accounts;\n }\n\t\telse {\n\t\t\tSystem.err.println(\"topic accounts empty\");\n\t\t}\n return null;\n }\n\n\n /**\n * Gets the groupAccounts of the MailFinder object\n *\n * @param GroupId Description of the Parameter\n * @param protocol Description of the Parameter\n * @return The group accounts value\n */\n public Collection getGroupAccounts(int GroupId, int protocol) {\n Collection accounts = getGroupAccounts(GroupId);\n if (accounts != null && accounts.size() > 0) {\n Iterator iter = accounts.iterator();\n MailAccount ma;\n while (iter.hasNext()) {\n ma = (MailAccount) iter.next();\n if (ma.getProtocol() != protocol) {\n iter.remove();\n }\n }\n return accounts;\n }\n\t\telse {\n\t\t\tSystem.err.println(\"group accounts empty\");\n\t\t}\n return null;\n }\n\n\n /**\n * Gets the topics of the LetterFinder object\n *\n * @param InstanceId Description of the Parameter\n * @return The topics value\n */\n public List getTopics(int instanceId) {\n try {\n List L = CategoryFinder.getInstance().listOfCategoryEntityByInstanceId(MailTopicBMPBean.class,instanceId);\n //Collection L = EntityFinder.getInstance().findAllByColumn(MailTopic.class, com.idega.block.email.data.MailTopicBMPBean.getColumnCategoryId(), CategoryId);\n return L;\n } catch (Exception ex) {\n\n }\n return null;\n }\n\n public MailTopic getTopic(int id){\n try {\n return (MailTopic) GenericEntity.getEntityInstance(MailTopic.class,id);\n }\n catch (Exception ex) {\n\n }\n return null;\n }\n\n\n /**\n * Gets the Email objects bound to a specifiedList\n *\n * @param listId Description of the Parameter\n * @return The list emails value\n */\n public Collection getListEmails(int listId) {\n try {\n return EntityFinder.getInstance().findRelated(GenericEntity.getEntityInstance(MailList.class, listId), Email.class);\n } catch (Exception ex) {\n\n }\n return null;\n }\n \n public int getListEmailsCount(int listId){\n \ttry{\n \treturn GenericEntity.getEntityInstance(MailList.class, listId).getNumberOfRecordsRelated((IDOLegacyEntity)GenericEntity.getEntityInstance(Email.class));\n \t}catch(Exception ex){ex.printStackTrace();}\n \treturn 0;\n }\n\n\n /**\n * @param InstanceId Description of the Parameter\n * @return Description of the Return Value\n * @todo Description of the Method\n */\n public Map mapOfTopics(int InstanceId) {\n return EntityFinder.getInstance().getMapOfEntity(getTopics(InstanceId), MailTopicBMPBean.TABLE_NAME+\"_ID\");\n }\n\n public Email lookupEmail(String EmailAddress){\n try {\n EntityFinder.debug = true;\n java.util.List c = EntityFinder.getInstance().findAllByColumn(Email.class,com.idega.core.contact.data.EmailBMPBean.getColumnNameAddress(),EmailAddress);\n EntityFinder.debug = false;\n if(c!=null && c.size() > 0) {\n\t\t\t\treturn (Email) c.get(0);\n\t\t\t}\n }\n catch (Exception ex) {\n\n }\n return null;\n }\n\n public String getProtocolName(int protocol){\n String p = \"pop3\";\n switch (protocol) {\n case MailProtocol.POP3: p=\"pop3\";break;\n case MailProtocol.SMTP: p=\"smtp\";break;\n case MailProtocol.IMAP4: p=\"imap\";break;\n }\n return p;\n }\n}" ]
import java.text.DateFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.idega.block.category.presentation.CategoryBlock; import com.idega.block.email.EmailConstants; import com.idega.block.email.business.EmailLetter; import com.idega.block.email.business.EmailTopic; import com.idega.block.email.business.MailBusiness; import com.idega.block.email.business.MailFinder; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.SubmitButton; import com.idega.util.text.TextSoap;
package com.idega.block.email.presentation; /** * Title: * Description: * Copyright: Copyright (c) 2001 * Company: * @author <br><a href="mailto:aron@idega.is">Aron Birkir</a><br> * @version 1.0 */ public class NewsLetterArchive extends CategoryBlock { private int topic = -1; private int letter = -1; private String prmLetter = "em_nla_let"; private String prmTopic = "em_nla_tpc"; private String prmLetterDelete = "em_nla_ldel"; private IWBundle core; private IWResourceBundle iwrb; private Collection topics; private Collection letters;
private EmailLetter theLetter;
1
callistaenterprise/blog-microservices
microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/service/ProductCompositeService.java
[ "public class ProductAggregated {\n private int productId;\n private String name;\n private int weight;\n private List<RecommendationSummary> recommendations;\n private List<ReviewSummary> reviews;\n private ServiceAddresses serviceAddresses;\n\n public ProductAggregated(Product product, List<Recommendation> recommendations, List<Review> reviews, String serviceAddress) {\n\n // 1. Setup product info\n this.productId = product.getProductId();\n this.name = product.getName();\n this.weight = product.getWeight();\n\n // 2. Copy summary recommendation info, if available\n if (recommendations != null)\n this.recommendations = recommendations.stream()\n .map(r -> new RecommendationSummary(r.getRecommendationId(), r.getAuthor(), r.getRate()))\n .collect(Collectors.toList());\n\n // 3. Copy summary review info, if available\n if (reviews != null)\n this.reviews = reviews.stream()\n .map(r -> new ReviewSummary(r.getReviewId(), r.getAuthor(), r.getSubject()))\n .collect(Collectors.toList());\n\n // 4. Create info regarding the involved microservices addresses\n String productAddress = product.getServiceAddress();\n String reviewAddress = (reviews != null && reviews.size() > 0) ? reviews.get(0).getServiceAddress() : \"\";\n String recommendationAddress = (recommendations != null && recommendations.size() > 0) ? recommendations.get(0).getServiceAddress() : \"\";\n serviceAddresses = new ServiceAddresses(serviceAddress, productAddress, reviewAddress, recommendationAddress);\n }\n\n public int getProductId() {\n return productId;\n }\n\n public String getName() {\n return name;\n }\n\n public int getWeight() {\n return weight;\n }\n\n public List<RecommendationSummary> getRecommendations() {\n return recommendations;\n }\n\n public List<ReviewSummary> getReviews() {\n return reviews;\n }\n\n public ServiceAddresses getServiceAddresses() {\n return serviceAddresses;\n }\n}", "public class Product {\n private int productId;\n private String name;\n private int weight;\n private String serviceAddress;\n\n public Product() {\n }\n\n public Product(int productId, String name, int weight, String serviceAddress) {\n this.productId = productId;\n this.name = name;\n this.weight = weight;\n this.serviceAddress = serviceAddress;\n }\n\n public int getProductId() {\n return productId;\n }\n\n public void setProductId(int productId) {\n this.productId = productId;\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 getWeight() {\n return weight;\n }\n\n public void setWeight(int weight) {\n this.weight = weight;\n }\n\n public String getServiceAddress() {\n return serviceAddress;\n }\n}", "public class Recommendation {\n private int productId;\n private int recommendationId;\n private String author;\n private int rate;\n private String content;\n private String serviceAddress;\n\n public Recommendation() {\n }\n\n public Recommendation(int productId, int recommendationId, String author, int rate, String content, String serviceAddress) {\n this.productId = productId;\n this.recommendationId = recommendationId;\n this.author = author;\n this.rate = rate;\n this.content = content;\n this.serviceAddress = serviceAddress;\n }\n\n public int getProductId() {\n return productId;\n }\n\n public void setProductId(int productId) {\n this.productId = productId;\n }\n\n public int getRecommendationId() {\n return recommendationId;\n }\n\n public void setRecommendationId(int recommendationId) {\n this.recommendationId = recommendationId;\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 int getRate() {\n return rate;\n }\n\n public void setRate(int rate) {\n this.rate = rate;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getServiceAddress() {\n return serviceAddress;\n }\n}", "public class Review {\n private int productId;\n private int reviewId;\n private String author;\n private String subject;\n private String content;\n private String serviceAddress;\n\n public Review() {\n }\n\n public Review(int productId, int reviewId, String author, String subject, String content, String serviceAddress) {\n this.productId = productId;\n this.reviewId = reviewId;\n this.author = author;\n this.subject = subject;\n this.content = content;\n this.serviceAddress = serviceAddress;\n }\n\n public int getProductId() {\n return productId;\n }\n\n public void setProductId(int productId) {\n this.productId = productId;\n }\n\n public int getReviewId() {\n return reviewId;\n }\n\n public void setReviewId(int reviewId) {\n this.reviewId = reviewId;\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 getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getServiceAddress() {\n return serviceAddress;\n }\n}", "@Component\npublic class ServiceUtils {\n private static final Logger LOG = LoggerFactory.getLogger(ServiceUtils.class);\n\n private final LoadBalancerClient loadBalancer;\n private final String port;\n\n private String serviceAddress = null;\n\n @Autowired\n public ServiceUtils(\n @Value(\"${server.port}\") String port,\n LoadBalancerClient loadBalancer) {\n\n this.port = port;\n this.loadBalancer = loadBalancer;\n }\n\n /**\n *\n * @param serviceId\n * @return\n */\n public URI getServiceUrl(String serviceId) {\n return getServiceUrl(serviceId, null);\n }\n\n /**\n *\n * @param serviceId\n * @param fallbackUri\n * @return\n */\n protected URI getServiceUrl(String serviceId, String fallbackUri) {\n URI uri = null;\n try {\n ServiceInstance instance = loadBalancer.choose(serviceId);\n\n if (instance == null) {\n throw new RuntimeException(\"Can't find a service with serviceId = \" + serviceId);\n }\n\n uri = instance.getUri();\n LOG.debug(\"Resolved serviceId '{}' to URL '{}'.\", serviceId, uri);\n\n } catch (RuntimeException e) {\n // Eureka not available, use fallback if specified otherwise rethrow the error\n if (fallbackUri == null) {\n throw e;\n\n } else {\n uri = URI.create(fallbackUri);\n LOG.warn(\"Failed to resolve serviceId '{}'. Fallback to URL '{}'.\", serviceId, uri);\n }\n }\n\n return uri;\n }\n\n public <T> ResponseEntity<T> createOkResponse(T body) {\n return createResponse(body, HttpStatus.OK);\n }\n\n /**\n * Clone an existing result as a new one, filtering out http headers that not should be moved on and so on...\n *\n * @param result\n * @param <T>\n * @return\n */\n public <T> ResponseEntity<T> createResponse(ResponseEntity<T> result) {\n\n // TODO: How to relay the transfer encoding??? The code below makes the fallback method to kick in...\n ResponseEntity<T> response = createResponse(result.getBody(), result.getStatusCode());\n// LOG.info(\"NEW HEADERS:\");\n// response.getHeaders().entrySet().stream().forEach(e -> LOG.info(\"{} = {}\", e.getKey(), e.getValue()));\n// String ct = result.getHeaders().getFirst(HTTP.CONTENT_TYPE);\n// if (ct != null) {\n// LOG.info(\"Add without remove {}: {}\", HTTP.CONTENT_TYPE, ct);\n//// response.getHeaders().remove(HTTP.CONTENT_TYPE);\n// response.getHeaders().add(HTTP.CONTENT_TYPE, ct);\n// }\n return response;\n }\n\n public <T> ResponseEntity<T> createResponse(T body, HttpStatus httpStatus) {\n return new ResponseEntity<>(body, httpStatus);\n }\n\n public String getServiceAddress() {\n if (serviceAddress == null) {\n serviceAddress = findMyHostname() + \"/\" + findMyIpAddress() + \":\" + port;\n }\n return serviceAddress;\n }\n\n public String findMyHostname() {\n try {\n return InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n return \"unknown host name\";\n }\n }\n\n public String findMyIpAddress() {\n try {\n return InetAddress.getLocalHost().getHostAddress();\n } catch (UnknownHostException e) {\n return \"unknown IP address\";\n }\n }\n\n}" ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import se.callista.microservices.composite.product.model.ProductAggregated; import se.callista.microservices.model.Product; import se.callista.microservices.model.Recommendation; import se.callista.microservices.model.Review; import se.callista.microservices.util.ServiceUtils; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import java.util.Date; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static java.util.concurrent.CompletableFuture.supplyAsync; import static java.util.concurrent.CompletableFuture.allOf; import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
package se.callista.microservices.composite.product.service; /** * Created by magnus on 04/03/15. */ @Produces(APPLICATION_JSON) @Consumes(APPLICATION_JSON) @RestController public class ProductCompositeService { private static final Logger LOG = LoggerFactory.getLogger(ProductCompositeService.class); private final ProductCompositeIntegration integration; private final ServiceUtils util; @Inject public ProductCompositeService(ProductCompositeIntegration integration, ServiceUtils util) { this.integration = integration; this.util = util; } @RequestMapping("/") public String getProduct() { return "{\"timestamp\":\"" + new Date() + "\",\"content\":\"Hello from ProductAPi\"}"; } @RequestMapping("/{productId}") public ResponseEntity<ProductAggregated> getProduct(@PathVariable int productId) { // 1. First get mandatory product information Product product = getBasicProductInfo(productId); // 2. Get optional recommendations List<Recommendation> recommendations = getRecommendations(productId); // 3. Get optional reviews
List<Review> reviews = getReviews(productId);
3
3pillarlabs/socialauth
socialauth/src/main/java/org/brickred/socialauth/provider/OpenIdImpl.java
[ "public abstract class AbstractProvider implements AuthProvider, Serializable {\n\n\tprivate static final long serialVersionUID = -7827145708317886744L;\n\n\tprivate Map<Class<? extends Plugin>, Class<? extends Plugin>> pluginsMap;\n\n\tprivate final Log LOG = LogFactory.getLog(this.getClass());\n\n\tpublic AbstractProvider() throws Exception {\n\t\tpluginsMap = new HashMap<Class<? extends Plugin>, Class<? extends Plugin>>();\n\t}\n\n\t@Override\n\tpublic <T> T getPlugin(final Class<T> clazz) throws Exception {\n\t\tClass<? extends Plugin> plugin = pluginsMap.get(clazz);\n\t\tConstructor<? extends Plugin> cons = plugin\n\t\t\t\t.getConstructor(ProviderSupport.class);\n\t\tProviderSupport support = new ProviderSupport(getOauthStrategy());\n\t\tPlugin obj = cons.newInstance(support);\n\t\treturn (T) obj;\n\t}\n\n\t@Override\n\tpublic boolean isSupportedPlugin(final Class<? extends Plugin> clazz) {\n\t\tif (pluginsMap.containsKey(clazz)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic final void registerPlugins() throws Exception {\n\t\tLOG.info(\"Loading plugins\");\n\t\tList<String> pluginsList = getPluginsList();\n\t\tif (pluginsList != null && !pluginsList.isEmpty()) {\n\t\t\tfor (String s : pluginsList) {\n\t\t\t\tLOG.info(\"Loading plugin :: \" + s);\n\t\t\t\tClass<? extends Plugin> clazz = Class.forName(s).asSubclass(\n\t\t\t\t\t\tPlugin.class);\n\t\t\t\t// getting constructor only for checking\n\t\t\t\tConstructor<? extends Plugin> cons = clazz\n\t\t\t\t\t\t.getConstructor(ProviderSupport.class);\n\t\t\t\tClass<?> interfaces[] = clazz.getInterfaces();\n\t\t\t\tfor (Class<?> c : interfaces) {\n\t\t\t\t\tif (Plugin.class.isAssignableFrom(c)) {\n\t\t\t\t\t\tpluginsMap.put(c.asSubclass(Plugin.class), clazz);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void refreshToken(AccessGrant accessGrant)\n\t\t\tthrows SocialAuthException {\n\t\tthrow new SocialAuthException(\"Not implemented for given provider\");\n\n\t}\n\n\t/**\n\t * Returns the scopes of custom plugins of a provider those are configured\n\t * in properties file\n\t * \n\t * @param oauthConfig\n\t * OAuthConfig object of that provider\n\t * @return String of comma separated scopes of all register plugins of a\n\t * provider those are configured in properties file\n\t */\n\tpublic String getPluginsScope(final OAuthConfig oauthConfig) {\n\t\tList<String> scopes = oauthConfig.getPluginsScopes();\n\t\tif (scopes != null && !scopes.isEmpty()) {\n\t\t\tString scopesStr = scopes.get(0);\n\t\t\tfor (int i = 1; i < scopes.size(); i++) {\n\t\t\t\tscopesStr += \",\" + scopes.get(i);\n\t\t\t}\n\t\t\treturn scopesStr;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the list of plugins of a provider.\n\t * \n\t * @return List of plugins of a provider\n\t */\n\tprotected abstract List<String> getPluginsList();\n\n\t/**\n\t * Returns the OAuthStrategyBase of a provider.\n\t * \n\t * @return OAuthStrategyBase of a provider.\n\t */\n\tprotected abstract OAuthStrategyBase getOauthStrategy();\n}", "public class Contact implements Serializable {\n\tprivate static final long serialVersionUID = 7983770896851139223L;\n\n\t/**\n\t * Email\n\t */\n\tString email;\n\n\t/**\n\t * First Name\n\t */\n\tString firstName;\n\n\t/**\n\t * Last Name\n\t */\n\tString lastName;\n\n\t/**\n\t * Display Name\n\t */\n\tString displayName;\n\n\t/**\n\t * Other emails array.\n\t */\n\tString otherEmails[];\n\n\t/**\n\t * Profile URL\n\t */\n\tString profileUrl;\n\n\t/**\n\t * Id of person\n\t */\n\tString id;\n\n\t/**\n\t * Email hash\n\t */\n\tString emailHash;\n\n\t/**\n\t * profile image URL\n\t */\n\tprivate String profileImageURL;\n\n\t/**\n\t * raw response xml/json as string\n\t */\n\tprivate String rawResponse;\n\n\t/**\n\t * Retrieves the first name\n\t * \n\t * @return String the first name\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * Updates the first name\n\t * \n\t * @param firstName\n\t * the first name of user\n\t */\n\tpublic void setFirstName(final String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * Retrieves the last name\n\t * \n\t * @return String the last name\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * Updates the last name\n\t * \n\t * @param lastName\n\t * the last name of user\n\t */\n\tpublic void setLastName(final String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * Returns the email address.\n\t * \n\t * @return email address of the user\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Updates the email\n\t * \n\t * @param email\n\t * the email of user\n\t */\n\tpublic void setEmail(final String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Retrieves the display name\n\t * \n\t * @return String the display name\n\t */\n\tpublic String getDisplayName() {\n\t\treturn displayName;\n\t}\n\n\t/**\n\t * Updates the display name\n\t * \n\t * @param displayName\n\t * the display name of user\n\t */\n\tpublic void setDisplayName(final String displayName) {\n\t\tthis.displayName = displayName;\n\t}\n\n\t/**\n\t * Retrieves the contact person emails\n\t * \n\t * @return String Array of emails\n\t */\n\tpublic String[] getOtherEmails() {\n\t\treturn otherEmails;\n\t}\n\n\t/**\n\t * \n\t * @param otherEmails\n\t * array of emails, if contact person has more than one email\n\t * then it contains rest of the emails except first one\n\t */\n\tpublic void setOtherEmails(final String[] otherEmails) {\n\t\tthis.otherEmails = otherEmails;\n\t}\n\n\t/**\n\t * Retrieves the contact person Public profile URL\n\t * \n\t * @return String contact person Public profile URL\n\t */\n\tpublic String getProfileUrl() {\n\t\treturn profileUrl;\n\t}\n\n\t/**\n\t * Updates the contact person Public profile URL\n\t * \n\t * @param profileUrl\n\t * contact person Public profile URL\n\t */\n\tpublic void setProfileUrl(final String profileUrl) {\n\t\tthis.profileUrl = profileUrl;\n\t}\n\n\t/**\n\t * Retrieves the contact person id\n\t * \n\t * @return String contact person id\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Updates the contact person id\n\t * \n\t * @param id\n\t * contact person id\n\t */\n\tpublic void setId(final String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Retrieves the email hash\n\t * \n\t * @return String contact person email hash\n\t */\n\tpublic String getEmailHash() {\n\t\treturn emailHash;\n\t}\n\n\t/**\n\t * Updates the contact person email hash\n\t * \n\t * @param emailHash\n\t * contact person email hash\n\t */\n\tpublic void setEmailHash(final String emailHash) {\n\t\tthis.emailHash = emailHash;\n\t}\n\n\t/**\n\t * Retrieves the profile image URL\n\t * \n\t * @return String the profileImageURL\n\t */\n\tpublic String getProfileImageURL() {\n\t\treturn profileImageURL;\n\t}\n\n\t/**\n\t * Updates the profile image URL\n\t * \n\t * @param profileImageURL\n\t * profile image URL of user\n\t */\n\tpublic void setProfileImageURL(final String profileImageURL) {\n\t\tthis.profileImageURL = profileImageURL;\n\t}\n\n\t/**\n\t * Retrieves the raw response xml/json in string which is returned by the\n\t * provider for this object call. Set\n\t * {@link SocialAuthConfig#setRawResponse(boolean)} to true to save the\n\t * response in object.\n\t * \n\t * @return raw response xml/json in string\n\t */\n\tpublic String getRawResponse() {\n\t\treturn rawResponse;\n\t}\n\n\t/**\n\t * Updates raw response xml/json returned by the provider for this object\n\t * call. Set {@link SocialAuthConfig#setRawResponse(boolean)} to true to\n\t * save the response in object.\n\t * \n\t * @param rawResponse\n\t * raw response xml/json in string\n\t */\n\tpublic void setRawResponse(String rawResponse) {\n\t\tthis.rawResponse = rawResponse;\n\t}\n\n\t/**\n\t * Retrieves the profile info as a string\n\t * \n\t * @return String\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" email: \" + email + NEW_LINE);\n\t\tresult.append(\" firstName: \" + firstName + NEW_LINE);\n\t\tresult.append(\" lastName: \" + lastName + NEW_LINE);\n\t\tresult.append(\" displayName: \" + displayName + NEW_LINE);\n\t\tresult.append(\" id: \" + id + NEW_LINE);\n\t\tresult.append(\" profileUrl: \" + profileUrl + NEW_LINE);\n\t\tresult.append(\" profileImageURL: \" + profileImageURL + NEW_LINE);\n\t\tresult.append(\"emailHash: \" + emailHash + NEW_LINE);\n\t\tresult.append(\" otherEmails: \");\n\t\tif (otherEmails != null) {\n\t\t\tStringBuilder estr = new StringBuilder();\n\t\t\tfor (String str : otherEmails) {\n\t\t\t\tif (estr.length() > 0) {\n\t\t\t\t\testr.append(\" , \");\n\t\t\t\t}\n\t\t\t\testr.append(str);\n\t\t\t}\n\t\t\tresult.append(estr.toString());\n\t\t}\n\t\tresult.append(NEW_LINE);\n\t\tresult.append(\"}\");\n\t\treturn result.toString();\n\t}\n\n}", "public class Profile implements Serializable {\n\n\tprivate static final long serialVersionUID = 6082073969740796991L;\n\n\t/**\n\t * Email\n\t */\n\tprivate String email;\n\n\t/**\n\t * First Name\n\t */\n\tprivate String firstName;\n\n\t/**\n\t * Last Name\n\t */\n\tprivate String lastName;\n\n\t/**\n\t * Country\n\t */\n\tprivate String country;\n\n\t/**\n\t * Language\n\t */\n\tprivate String language;\n\n\t/**\n\t * Full Name\n\t */\n\tprivate String fullName;\n\n\t/**\n\t * Display Name\n\t */\n\tprivate String displayName;\n\n\t/**\n\t * Date of Birth\n\t */\n\tprivate BirthDate dob;\n\n\t/**\n\t * Gender\n\t */\n\tprivate String gender;\n\n\t/**\n\t * Location\n\t */\n\tprivate String location;\n\n\t/**\n\t * Validated Id\n\t */\n\tprivate String validatedId;\n\n\t/**\n\t * profile image URL\n\t */\n\tprivate String profileImageURL;\n\n\t/**\n\t * provider id with this profile associates\n\t */\n\tprivate String providerId;\n\n\t/**\n\t * contact info\n\t */\n\tprivate Map<String, String> contactInfo;\n\n\t/**\n\t * raw response xml/json as string\n\t */\n\tprivate String rawResponse;\n\n\t/**\n\t * Retrieves the first name\n\t * \n\t * @return String the first name\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * Updates the first name\n\t * \n\t * @param firstName\n\t * the first name of user\n\t */\n\tpublic void setFirstName(final String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * Retrieves the last name\n\t * \n\t * @return String the last name\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * Updates the last name\n\t * \n\t * @param lastName\n\t * the last name of user\n\t */\n\tpublic void setLastName(final String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * Returns the email address.\n\t * \n\t * @return email address of the user\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Updates the email\n\t * \n\t * @param email\n\t * the email of user\n\t */\n\tpublic void setEmail(final String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Retrieves the validated id\n\t * \n\t * @return String the validated id\n\t */\n\tpublic String getValidatedId() {\n\t\treturn validatedId;\n\t}\n\n\t/**\n\t * Updates the validated id\n\t * \n\t * @param validatedId\n\t * the validated id of user\n\t */\n\tpublic void setValidatedId(final String validatedId) {\n\t\tthis.validatedId = validatedId;\n\t}\n\n\t/**\n\t * Retrieves the display name\n\t * \n\t * @return String the display name\n\t */\n\tpublic String getDisplayName() {\n\t\treturn displayName;\n\t}\n\n\t/**\n\t * Updates the display name\n\t * \n\t * @param displayName\n\t * the display name of user\n\t */\n\tpublic void setDisplayName(final String displayName) {\n\t\tthis.displayName = displayName;\n\t}\n\n\t/**\n\t * Retrieves the country\n\t * \n\t * @return String the country\n\t */\n\tpublic String getCountry() {\n\t\treturn country;\n\t}\n\n\t/**\n\t * Updates the country\n\t * \n\t * @param country\n\t * the country of user\n\t */\n\tpublic void setCountry(final String country) {\n\t\tthis.country = country;\n\t}\n\n\t/**\n\t * Retrieves the language\n\t * \n\t * @return String the language\n\t */\n\tpublic String getLanguage() {\n\t\treturn language;\n\t}\n\n\t/**\n\t * Updates the language\n\t * \n\t * @param language\n\t * the language of user\n\t */\n\tpublic void setLanguage(final String language) {\n\t\tthis.language = language;\n\t}\n\n\t/**\n\t * Retrieves the full name\n\t * \n\t * @return String the full name\n\t */\n\tpublic String getFullName() {\n\t\treturn fullName;\n\t}\n\n\t/**\n\t * Updates the full name\n\t * \n\t * @param fullName\n\t * the full name of user\n\t */\n\tpublic void setFullName(final String fullName) {\n\t\tthis.fullName = fullName;\n\t}\n\n\t/**\n\t * Retrieves the date of birth\n\t * \n\t * @return the date of birth different providers may use different formats\n\t */\n\tpublic BirthDate getDob() {\n\t\treturn dob;\n\t}\n\n\t/**\n\t * Updates the date of birth\n\t * \n\t * @param dob\n\t * the date of birth of user\n\t */\n\tpublic void setDob(final BirthDate dob) {\n\t\tthis.dob = dob;\n\t}\n\n\t/**\n\t * Retrieves the gender\n\t * \n\t * @return String the gender - could be \"Male\", \"M\" or \"male\"\n\t */\n\tpublic String getGender() {\n\t\treturn gender;\n\t}\n\n\t/**\n\t * Updates the gender\n\t * \n\t * @param gender\n\t * the gender of user\n\t */\n\tpublic void setGender(final String gender) {\n\t\tthis.gender = gender;\n\t}\n\n\t/**\n\t * Retrieves the location\n\t * \n\t * @return String the location\n\t */\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\t/**\n\t * Updates the location\n\t * \n\t * @param location\n\t * the location of user\n\t */\n\tpublic void setLocation(final String location) {\n\t\tthis.location = location;\n\t}\n\n\t/**\n\t * Retrieves the profile image URL\n\t * \n\t * @return String the profileImageURL\n\t */\n\tpublic String getProfileImageURL() {\n\t\treturn profileImageURL;\n\t}\n\n\t/**\n\t * Updates the profile image URL\n\t * \n\t * @param profileImageURL\n\t * profile image URL of user\n\t */\n\tpublic void setProfileImageURL(final String profileImageURL) {\n\t\tthis.profileImageURL = profileImageURL;\n\t}\n\n\t/**\n\t * Retrieves the provider id with this profile associates\n\t * \n\t * @return the provider id\n\t */\n\tpublic String getProviderId() {\n\t\treturn providerId;\n\t}\n\n\t/**\n\t * Updates the provider id\n\t * \n\t * @param providerId\n\t * the provider id\n\t */\n\tpublic void setProviderId(final String providerId) {\n\t\tthis.providerId = providerId;\n\t}\n\n\t/**\n\t * Retrieves the contact information. It contains address and phone numbers.\n\t * Key may contain values like mainAddress, home, work where home and work\n\t * value will be phone numbers.\n\t * \n\t * @return contact information.\n\t */\n\tpublic Map<String, String> getContactInfo() {\n\t\treturn contactInfo;\n\t}\n\n\t/**\n\t * Updates the contact info.\n\t * \n\t * @param contactInfo\n\t * the map which contains the contact information\n\t */\n\tpublic void setContactInfo(final Map<String, String> contactInfo) {\n\t\tthis.contactInfo = contactInfo;\n\t}\n\n\t/**\n\t * Retrieves the raw response xml/json in string which is returned by the\n\t * provider for this object. Set\n\t * {@link SocialAuthConfig#setRawResponse(boolean)} to true to save this\n\t * response in object.\n\t * \n\t * @return raw response xml/json in string\n\t */\n\tpublic String getRawResponse() {\n\t\treturn rawResponse;\n\t}\n\n\t/**\n\t * Updates raw response xml/json return by the provider for this object\n\t * call. Set {@link SocialAuthConfig#setRawResponse(boolean)} to true to\n\t * save this response in object.\n\t * \n\t * @param rawResponse\n\t */\n\tpublic void setRawResponse(String rawResponse) {\n\t\tthis.rawResponse = rawResponse;\n\t}\n\n\t/**\n\t * Retrieves the profile info as a string\n\t * \n\t * @return String\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" email: \" + email + NEW_LINE);\n\t\tresult.append(\" firstName: \" + firstName + NEW_LINE);\n\t\tresult.append(\" lastName: \" + lastName + NEW_LINE);\n\t\tresult.append(\" country: \" + country + NEW_LINE);\n\t\tresult.append(\" language: \" + language + NEW_LINE);\n\t\tresult.append(\" fullName: \" + fullName + NEW_LINE);\n\t\tresult.append(\" displayName: \" + displayName + NEW_LINE);\n\t\tresult.append(\" dob: \" + dob + NEW_LINE);\n\t\tresult.append(\" gender: \" + gender + NEW_LINE);\n\t\tresult.append(\" location: \" + location + NEW_LINE);\n\t\tresult.append(\" validatedId: \" + validatedId + NEW_LINE);\n\t\tresult.append(\" profileImageURL: \" + profileImageURL + NEW_LINE);\n\t\tresult.append(\" providerId: \" + providerId + NEW_LINE);\n\t\tresult.append(\" contactInfo { \" + NEW_LINE);\n\t\tif (contactInfo != null && !contactInfo.isEmpty()) {\n\t\t\tfor (Map.Entry<String, String> entry : contactInfo.entrySet()) {\n\t\t\t\tresult.append(entry.getKey() + \" = \" + entry.getValue()\n\t\t\t\t\t\t+ NEW_LINE);\n\t\t\t}\n\t\t}\n\t\tresult.append(\" } \" + NEW_LINE);\n\t\tresult.append(\"}\");\n\n\t\treturn result.toString();\n\n\t}\n\n}", "public interface OAuthStrategyBase extends Serializable {\n\n\t/**\n\t * It provides the URL which will be used for authentication with the\n\t * provider\n\t * \n\t * @param successUrl\n\t * the call back url on which user will be redirected after\n\t * authentication\n\t * @return the authentication url\n\t * @throws Exception\n\t */\n\tpublic String getLoginRedirectURL(String successUrl) throws Exception;\n\t\n\t/**\n\t * It provides the URL which will be used for authentication with the\n\t * provider\n\t * \n\t * @param successUrl\n\t * the call back url on which user will be redirected after\n\t * authentication\n\t * @param requestParams \n\t * \t\t\t parameters need to pass in request \n\t * @return the authentication url\n\t * @throws Exception\n\t */\n\tpublic String getLoginRedirectURL(String successUrl,Map<String, String> requestParams) throws Exception;\n\n\t/**\n\t * Verifies the user and get access token\n\t * \n\t * @param requestParams\n\t * request parameters, received from the provider\n\t * @return AccessGrant which contains access token and other information\n\t * @throws Exception\n\t */\n\tpublic AccessGrant verifyResponse(Map<String, String> requestParams)\n\t\t\tthrows Exception;\n\n\t/**\n\t * Verifies the user and get access token\n\t * \n\t * @param requestParams\n\t * @param methodType\n\t * @return AccessGrant which contains access token and other attributes\n\t * @throws Exception\n\t */\n\tpublic AccessGrant verifyResponse(Map<String, String> requestParams,\n\t\t\tString methodType) throws Exception;\n\n\t/**\n\t * Makes HTTP GET request to a given URL.It attaches access token in URL if\n\t * required.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @return Response object\n\t * @throws Exception\n\t */\n\tpublic Response executeFeed(String url) throws Exception;\n\n\t/**\n\t * Makes HTTP request to a given URL.It attaches access token in URL if\n\t * required.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @param methodType\n\t * Method type can be GET, POST or PUT\n\t * @param params\n\t * Not using this parameter in Google API function\n\t * @param headerParams\n\t * Parameters need to pass as Header Parameters\n\t * @param body\n\t * Request Body\n\t * @throws Exception\n\t */\n\tpublic Response executeFeed(String url, String methodType,\n\t\t\tMap<String, String> params, Map<String, String> headerParams,\n\t\t\tString body) throws Exception;\n\n\t/**\n\t * Sets the permission\n\t * \n\t * @param permission\n\t * Permission object which can be Permission.AUHTHENTICATE_ONLY,\n\t * Permission.ALL, Permission.DEFAULT\n\t */\n\tpublic void setPermission(final Permission permission);\n\n\t/**\n\t * Sets the scope string\n\t * \n\t * @param scope\n\t * scope string\n\t */\n\tpublic void setScope(final String scope);\n\n\t/**\n\t * Stores access grant for the provider\n\t * \n\t * @param accessGrant\n\t * It contains the access token and other information\n\t * @throws Exception\n\t */\n\tpublic void setAccessGrant(AccessGrant accessGrant);\n\n\t/**\n\t * Sets the name of access token parameter which will returns by the\n\t * provider. By default it is \"access_token\"\n\t * \n\t * @param accessTokenParameterName\n\t */\n\tpublic void setAccessTokenParameterName(String accessTokenParameterName);\n\n\t/**\n\t * Logout\n\t */\n\tpublic void logout();\n\n\t/**\n\t * Makes HTTP request to upload image and status.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @param methodType\n\t * Method type can be GET, POST or PUT\n\t * @param params\n\t * Parameters need to pass in request\n\t * @param headerParams\n\t * Parameters need to pass as Header Parameters\n\t * @param fileName\n\t * Image file name\n\t * @param inputStream\n\t * Input stream of image\n\t * @param fileParamName\n\t * Image Filename parameter. It requires in some provider.\n\t * @return Response object\n\t * @throws Exception\n\t */\n\tpublic Response uploadImage(final String url, final String methodType,\n\t\t\tfinal Map<String, String> params,\n\t\t\tfinal Map<String, String> headerParams, final String fileName,\n\t\t\tfinal InputStream inputStream, final String fileParamName)\n\t\t\tthrows Exception;\n\n\t/**\n\t * Retrieves the AccessGrant object.\n\t * \n\t * @return AccessGrant object.\n\t */\n\tpublic AccessGrant getAccessGrant();\n}", "public class OAuthConfig implements Serializable {\n\n\tprivate static final long serialVersionUID = 7574560869168900919L;\n\tprivate final String _consumerKey;\n\tprivate final String _consumerSecret;\n\tprivate final String _signatureMethod;\n\tprivate final String _transportName;\n\tprivate String id;\n\tprivate Class<?> providerImplClass;\n\tprivate String customPermissions;\n\tprivate String requestTokenUrl;\n\tprivate String authenticationUrl;\n\tprivate String accessTokenUrl;\n\tprivate String[] registeredPlugins;\n\tprivate List<String> pluginsScopes;\n\tprivate boolean saveRawResponse;\n\tprivate Map<String, String> customProperties;\n\n\t/**\n\t * \n\t * @param consumerKey\n\t * Application consumer key\n\t * @param consumerSecret\n\t * Application consumer secret\n\t * @param signatureMethod\n\t * Signature Method type\n\t * @param transportName\n\t * Transport name\n\t */\n\tpublic OAuthConfig(final String consumerKey, final String consumerSecret,\n\t\t\tfinal String signatureMethod, final String transportName) {\n\t\t_consumerKey = consumerKey;\n\t\t_consumerSecret = consumerSecret;\n\t\tif (signatureMethod == null || signatureMethod.length() == 0) {\n\t\t\t_signatureMethod = Constants.HMACSHA1_SIGNATURE;\n\t\t} else {\n\t\t\t_signatureMethod = signatureMethod;\n\t\t}\n\t\tif (transportName == null || transportName.length() == 0) {\n\t\t\t_transportName = MethodType.GET.toString();\n\t\t} else {\n\t\t\t_transportName = transportName;\n\t\t}\n\t}\n\n\tpublic OAuthConfig(final String consumerKey, final String consumerSecret) {\n\t\t_consumerKey = consumerKey;\n\t\t_consumerSecret = consumerSecret;\n\t\t_transportName = MethodType.GET.toString();\n\t\t_signatureMethod = Constants.HMACSHA1_SIGNATURE;\n\t}\n\n\t/**\n\t * Retrieves the consumer key\n\t * \n\t * @return the consumer key\n\t */\n\tpublic String get_consumerKey() {\n\t\treturn _consumerKey;\n\t}\n\n\t/**\n\t * Retrieves the consumer secret\n\t * \n\t * @return the consumer secret\n\t */\n\tpublic String get_consumerSecret() {\n\t\treturn _consumerSecret;\n\t}\n\n\t/**\n\t * Retrieves the signature method\n\t * \n\t * @return the signature method\n\t */\n\tpublic String get_signatureMethod() {\n\t\treturn _signatureMethod;\n\t}\n\n\t/**\n\t * Retrieves the transport name\n\t * \n\t * @return the transport name\n\t */\n\tpublic String get_transportName() {\n\t\treturn _transportName;\n\t}\n\n\t/**\n\t * Retrieves the provider id\n\t * \n\t * @return the provider id\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Updates the provider id\n\t * \n\t * @param id\n\t * the provider id\n\t */\n\tpublic void setId(final String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Retrieves the provider implementation class\n\t * \n\t * @return the provider implementation class\n\t */\n\tpublic Class<?> getProviderImplClass() {\n\t\treturn providerImplClass;\n\t}\n\n\t/**\n\t * Updates the provider implementation class\n\t * \n\t * @param providerImplClass\n\t * the provider implementation class\n\t */\n\tpublic void setProviderImplClass(final Class<?> providerImplClass) {\n\t\tthis.providerImplClass = providerImplClass;\n\t}\n\n\t/**\n\t * Retrieves custom permissions configured in properties file\n\t * \n\t * @return String of custom permissions\n\t */\n\tpublic String getCustomPermissions() {\n\t\treturn customPermissions;\n\t}\n\n\t/**\n\t * Updates custom permissions configured in properties file\n\t * \n\t * @param customPermissions\n\t * String of comma seperated custom permissions\n\t */\n\tpublic void setCustomPermissions(final String customPermissions) {\n\t\tthis.customPermissions = customPermissions;\n\t}\n\n\t/**\n\t * Retrieves the authentication url\n\t * \n\t * @return the authentication url string\n\t */\n\tpublic String getAuthenticationUrl() {\n\t\treturn authenticationUrl;\n\t}\n\n\t/**\n\t * Updates the authentication url\n\t * \n\t * @param authenticationUrl\n\t * the authentication url string\n\t */\n\tpublic void setAuthenticationUrl(final String authenticationUrl) {\n\t\tthis.authenticationUrl = authenticationUrl;\n\t}\n\n\t/**\n\t * Retrieves the access token url\n\t * \n\t * @return the access token url string\n\t */\n\tpublic String getAccessTokenUrl() {\n\t\treturn accessTokenUrl;\n\t}\n\n\t/**\n\t * Updates the access token url\n\t * \n\t * @param accessTokenUrl\n\t * the access token url string\n\t */\n\tpublic void setAccessTokenUrl(final String accessTokenUrl) {\n\t\tthis.accessTokenUrl = accessTokenUrl;\n\t}\n\n\t/**\n\t * Retrieves the request token url\n\t * \n\t * @return the request token url string\n\t */\n\tpublic String getRequestTokenUrl() {\n\t\treturn requestTokenUrl;\n\t}\n\n\t/**\n\t * Updates the request token url\n\t * \n\t * @param requestTokenUrl\n\t * the request token url string\n\t */\n\tpublic void setRequestTokenUrl(final String requestTokenUrl) {\n\t\tthis.requestTokenUrl = requestTokenUrl;\n\t}\n\n\t/**\n\t * Retrieves the registered plugins of a provider configured in properties\n\t * file. String contains the fully qualified plugin class name\n\t * \n\t * @return String array of registered plugins\n\t */\n\tpublic String[] getRegisteredPlugins() {\n\t\treturn registeredPlugins;\n\t}\n\n\t/**\n\t * Updates the registered plugins configured in properties file\n\t * \n\t * @param registeredPlugins\n\t * String array of plugins. String should contain fully qualified\n\t * plugin class name\n\t */\n\tpublic void setRegisteredPlugins(final String[] registeredPlugins) {\n\t\tthis.registeredPlugins = registeredPlugins;\n\t}\n\n\t/**\n\t * Retrieves the list of plugins scopes\n\t * \n\t * @return list of plugins scope\n\t */\n\tpublic List<String> getPluginsScopes() {\n\t\treturn pluginsScopes;\n\t}\n\n\t/**\n\t * Updates the plugins scopes\n\t * \n\t * @param pluginsScopes\n\t * list of plugins scopes\n\t */\n\tpublic void setPluginsScopes(final List<String> pluginsScopes) {\n\t\tthis.pluginsScopes = pluginsScopes;\n\t}\n\n\t/**\n\t * Returns status to save the raw response for profile and contacts. Default\n\t * value is False.\n\t * \n\t * @return True/False to check whether raw response should save or not.\n\t */\n\tpublic boolean isSaveRawResponse() {\n\t\treturn saveRawResponse;\n\t}\n\n\t/**\n\t * Set this flag to True if raw response should be save for profile and\n\t * contacts. Default it is False.\n\t * \n\t * @param saveRawResponse\n\t * flag to config whether raw response should be saved or not.\n\t */\n\tpublic void setSaveRawResponse(boolean saveRawResponse) {\n\t\tthis.saveRawResponse = saveRawResponse;\n\t}\n\n\t/**\n\t * Returns custom properties for the provider\n\t * \n\t * @return map which contains custom properties\n\t */\n\tpublic Map<String, String> getCustomProperties() {\n\t\treturn customProperties;\n\t}\n\n\t/**\n\t * Updates the custom properties\n\t * \n\t * @param customProperties\n\t * map which store the custom properties required for the\n\t * provider except conumer key, secret and scopes\n\t */\n\tpublic void setCustomProperties(Map<String, String> customProperties) {\n\t\tthis.customProperties = customProperties;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" consumerKey: \" + _consumerKey + NEW_LINE);\n\t\tresult.append(\" consumerSecret: \" + _consumerSecret + NEW_LINE);\n\t\tresult.append(\" signatureMethod: \" + _signatureMethod + NEW_LINE);\n\t\tresult.append(\" transportName: \" + _transportName + NEW_LINE);\n\t\tresult.append(\" id: \" + id + NEW_LINE);\n\t\tresult.append(\" providerImplClass: \" + providerImplClass + NEW_LINE);\n\t\tresult.append(\" customPermissions: \" + customPermissions + NEW_LINE);\n\t\tresult.append(\" requestTokenUrl: \" + requestTokenUrl + NEW_LINE);\n\t\tresult.append(\" authenticationUrl: \" + authenticationUrl + NEW_LINE);\n\t\tresult.append(\" accessTokenUrl: \" + accessTokenUrl + NEW_LINE);\n\t\tresult.append(\" registeredPlugins: \" + registeredPlugins + NEW_LINE);\n\t\tresult.append(\" pluginsScopes: \" + pluginsScopes + NEW_LINE);\n\t\tresult.append(\" saveRawResponse: \" + saveRawResponse + NEW_LINE);\n\t\tif (customProperties != null) {\n\t\t\tresult.append(\" customProperties: \" + customProperties.toString()\n\t\t\t\t\t+ NEW_LINE);\n\t\t} else {\n\t\t\tresult.append(\" customProperties: null\" + NEW_LINE);\n\t\t}\n\t\tresult.append(\"}\");\n\t\treturn result.toString();\n\t}\n}" ]
import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.brickred.socialauth.AbstractProvider; import org.brickred.socialauth.AuthProvider; import org.brickred.socialauth.Contact; import org.brickred.socialauth.Permission; import org.brickred.socialauth.Profile; import org.brickred.socialauth.exception.AccessTokenExpireException; import org.brickred.socialauth.exception.ProviderStateException; import org.brickred.socialauth.exception.SocialAuthException; import org.brickred.socialauth.oauthstrategy.OAuthStrategyBase; import org.brickred.socialauth.util.AccessGrant; import org.brickred.socialauth.util.OAuthConfig; import org.brickred.socialauth.util.Response; import org.openid4java.OpenIDException; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.AuthSuccess; import org.openid4java.message.ParameterList; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchRequest; import org.openid4java.message.ax.FetchResponse;
fetch.addAttribute("lastname", "http://schema.openid.net/namePerson/last", true); fetch.addAttribute("fullname", "http://schema.openid.net/namePerson", true); // attach the extension to the authentication request authReq.addExtension(fetch); return authReq.getDestinationUrl(true); } catch (OpenIDException e) { e.printStackTrace(); } return null; } /** * Verifies the user when the external provider redirects back to our * application. * * * @param requestParams * request parameters, received from the provider * @return Profile object containing the profile information * @throws Exception */ @Override public Profile verifyResponse(final Map<String, String> requestParams) throws Exception { if (!providerState) { throw new ProviderStateException(); } try { // extract the parameters from the authentication response // (which comes in as a HTTP request from the OpenID provider) ParameterList response = new ParameterList(requestParams); // extract the receiving URL from the HTTP request StringBuffer receivingURL = new StringBuffer(); receivingURL.append(successUrl); StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : requestParams.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (sb.length() > 0) { sb.append("&"); } sb.append(key).append("=").append(value); } receivingURL.append("?").append(sb.toString()); // verify the response; ConsumerManager needs to be the same // (static) instance used to place the authentication request VerificationResult verification = manager.verify( receivingURL.toString(), response, discovered); // examine the verification result and extract the verified // identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { LOG.debug("Verified Id : " + verified.getIdentifier()); Profile p = new Profile(); p.setValidatedId(verified.getIdentifier()); AuthSuccess authSuccess = (AuthSuccess) verification .getAuthResponse(); if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { FetchResponse fetchResp = (FetchResponse) authSuccess .getExtension(AxMessage.OPENID_NS_AX); p.setEmail(fetchResp.getAttributeValue("email")); p.setFirstName(fetchResp.getAttributeValue("firstname")); p.setLastName(fetchResp.getAttributeValue("lastname")); p.setFullName(fetchResp.getAttributeValue("fullname")); // also use the ax namespace for compatibility if (p.getEmail() == null) { p.setEmail(fetchResp.getAttributeValue("emailax")); } if (p.getFirstName() == null) { p.setFirstName(fetchResp .getAttributeValue("firstnameax")); } if (p.getLastName() == null) { p.setLastName(fetchResp.getAttributeValue("lastnameax")); } if (p.getFullName() == null) { p.setFullName(fetchResp.getAttributeValue("fullnameax")); } } userProfile = p; return p; } } catch (OpenIDException e) { throw e; } return null; } /** * Updating status is not available for generic Open ID providers. */ @Override public Response updateStatus(final String msg) throws Exception { LOG.warn("WARNING: Not implemented for OpenId"); throw new SocialAuthException( "Update Status is not implemented for OpenId"); } /** * Contact list is not available for generic Open ID providers. * * @return null */ @Override
public List<Contact> getContactList() {
1
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/activity/ZhDetailActivity.java
[ "public class NewsItem implements Serializable {\n\n private String title;//标题\n private String imageurl;//图片\n private String date;//日期\n private String url;//新闻地址\n private boolean isReaded;\n private boolean isCollected;\n\n public boolean isCollected() {\n return isCollected;\n }\n\n public void setCollected(boolean collected) {\n isCollected = collected;\n }\n\n public boolean isReaded() {\n return isReaded;\n }\n\n public void setReaded(boolean readed) {\n isReaded = readed;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getUrl() {\n return url;\n }\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 getImageurl() {\n return imageurl;\n }\n\n public void setImageurl(String imageurl) {\n this.imageurl = imageurl;\n }\n\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n\n public JSONObject toJSONObj() {\n JSONObject jsonObject = new JSONObject();\n try {\n jsonObject.put(\"title\", title);\n jsonObject.put(\"url\", url);\n jsonObject.put(\"imageurl\", imageurl);\n jsonObject.put(\"date\", date);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return jsonObject;\n }\n\n public static NewsItem parse(JSONObject jsonObject) {\n if(jsonObject == null) {\n return null;\n }\n NewsItem newsItem = new NewsItem();\n newsItem.setTitle(jsonObject.optString(\"title\"));\n newsItem.setUrl(jsonObject.optString(\"url\"));\n newsItem.setImageurl(jsonObject.optString(\"imageurl\"));\n newsItem.setDate(jsonObject.optString(\"date\"));\n return newsItem;\n }\n}", "public class ZhihuPresenter extends BasePresenter {\n\n\n\n public ZhihuPresenter(Context context) {\n super(context);\n }\n\n private Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(Constant.BASE_ZHIHU_URL)\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .build();\n\n public ZhihuApi createZhihuService() {\n return retrofit.create(ZhihuApi.class);\n }\n\n}", "public interface ZhihuApi {\n\n @GET(\"api/4/news/latest\")\n Observable<NewsEntity> getLastestNews();\n\n @GET(\"api/4/news/before/{id}\")\n Observable<NewsEntity> getBeforeNews(@Path(\"id\") String id);\n\n @GET(\"api/4/news/{id}\")\n Observable<StoryDetailsEntity> getNewsDetails(@Path(\"id\") int id);\n}", "public class Constant {\n public static final String TITLE = \"title\";\n public static final String TECHNOLOGICAL_URL = \"http://www.jiemian.com/lists/6.html\";\n public static final String ENTERTAINMENT_URL = \"http://www.jiemian.com/lists/25.html\";\n public static final String NEWS_ITEM = \"news_item\";\n public static final String NEWS_TITLE = \"news_title\";\n public static final String Bmob_App_ID = \"2cb3bdc19bf6e2240dbb8ae06a80cc24\";\n public static final String BASE_ZHIHU_URL = \"http://news-at.zhihu.com/\";\n public static final String ITEM_ID = \"item_id\";\n public static final String DB_NAME = \"news_db\";\n public static final String NEWS_URL = \"new_url\";\n public static final String POPULAR_NEWS_URL = \"http://apis.baidu.com/3023/weixin/channel\";\n public static final String POPULAR_API_KEY = \"891eeffe6f1b4652128542bb8c9971a2\";\n public static final String TRC_ROBOT_REC = \"嗨,我是智能聊天机器人小er,聊两块钱的\";\n public static final String TRC_ROBOT_REST = \"小er已经休息,请明天再聊。\";\n public static final String TRC_ROBOT_FAILED = \"暂时无法回应\";\n public static final String TRC_KEY = \"ae536b38aa743f17ecb5f0e65a8dfea9\";\n public static final String TRC_USER_ID = \"diffey\";\n public static final String SEARCH_URL = \"http://apis.baidu.com/songshuxiansheng/real_time/search_news\";\n public static final String SEARCH_ITEM = \"search_item\";\n}", "public class HtmlUtils {\n public static String structHtml(String oriStr, List<String> cssList) {\n StringBuilder htmlString = new StringBuilder(\"<html><head>\");\n for (String css : cssList) {\n htmlString.append(structCssLink(css));\n }\n htmlString.append(\"</head><body>\");\n htmlString.append(\"<style>img{max-width:340px !important;}</style>\");\n htmlString.append(oriStr);\n htmlString.append(\"</body></html>\");\n return htmlString.toString();\n }\n\n public static String structCssLink(String css) {\n return \"<link type=\\\\\\\"text/css\\\\\\\" rel=\\\\\\\"stylesheet\\\\\\\" href=\\\\\\\"\" + css + \"\\\">\";\n }\n}" ]
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ProgressBar; import com.tyq.jiemian.R; import com.tyq.jiemian.bean.NewsItem; import com.tyq.jiemian.databinding.ActivityDetailBinding; import com.tyq.jiemian.presenter.ZhihuPresenter; import com.tyq.jiemian.ui.callback.ZhihuApi; import com.tyq.jiemian.utils.Constant; import com.tyq.jiemian.utils.HtmlUtils; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.tyq.jiemian.ui.activity; /** * Created by tyq on 2016/5/16. */ public class ZhDetailActivity extends AppCompatActivity { private int item_id; private String item_title; private ZhihuPresenter presenter; private ActivityDetailBinding dataBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dataBinding = DataBindingUtil.setContentView(this,R.layout.activity_detail); presenter = new ZhihuPresenter(this); setUpToolbar(); initView(); loadData(); } private void initView() { Bundle bundle = getIntent().getExtras(); item_id = bundle.getInt(Constant.ITEM_ID); item_title = bundle.getString(Constant.NEWS_TITLE); if (null!=getSupportActionBar() && null!=item_title) getSupportActionBar().setTitle(item_title); dataBinding.webView.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { if(newProgress == 100){ dataBinding.progressBar.setVisibility(View.INVISIBLE); }else{ if(dataBinding.progressBar.getVisibility()==View.INVISIBLE){ dataBinding.progressBar.setVisibility(View.VISIBLE); } dataBinding.progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); } public void setUpToolbar(){ setSupportActionBar(dataBinding.toolbar); } private void loadData() {
ZhihuApi service = presenter.createZhihuService();
2
hawkular/wildfly-monitor
src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java
[ "@MessageLogger(projectCode = \"<<none>>\")\npublic interface MonitorLogger extends BasicLogger {\n /**\n * A logger with the category {@code org.rhq.wfly.monitor}.\n */\n MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, \"org.rhq.wfly.monitor\");\n\n}", "public interface ModelControllerClientFactory {\n ModelControllerClient createClient();\n}", "@MessageLogger(projectCode = \"<<none>>\")\npublic interface SchedulerLogger extends BasicLogger {\n /**\n * A logger with the category {@code org.wildfly.metrics.scheduler}.\n */\n SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, \"org.wildfly.metrics.scheduler\");\n\n}", "public interface Diagnostics {\n Timer getRequestTimer();\n Meter getErrorRate();\n Meter getDelayedRate();\n\n Meter getStorageErrorRate();\n Counter getStorageBufferSize();\n}", "public final class DataPoint {\n private Task task;\n private long timestamp;\n private double value;\n\n public DataPoint(Task task, double value) {\n this.task = task;\n this.timestamp = System.currentTimeMillis();\n this.value = value;\n }\n\n public Task getTask() {\n return task;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public double getValue() {\n return value;\n }\n}" ]
import com.codahale.metrics.Timer; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.rhq.wfly.monitor.extension.MonitorLogger; import org.wildfly.metrics.scheduler.ModelControllerClientFactory; import org.wildfly.metrics.scheduler.SchedulerLogger; import org.wildfly.metrics.scheduler.diagnose.Diagnostics; import org.wildfly.metrics.scheduler.storage.DataPoint; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING; import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED;
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.metrics.scheduler.polling; /** * @author Harald Pehl * @author Heiko Braun */ public class IntervalBasedScheduler extends AbstractScheduler { private final ScheduledExecutorService executorService; private final List<ScheduledFuture> jobs; private final int poolSize;
private final ModelControllerClientFactory clientFactory;
1
superzanti/ServerSync
src/main/java/com/superzanti/serversync/config/SyncConfig.java
[ "@Command(name = \"ServerSync\", mixinStandardHelpOptions = true, version = RefStrings.VERSION, description = \"A utility for synchronizing a server<->client style game.\")\npublic class ServerSync implements Callable<Integer> {\n\n /* AWT EVENT DISPATCHER THREAD */\n\n public static final String APPLICATION_TITLE = \"Serversync\";\n public static final String GET_SERVER_INFO = \"SERVER_INFO\";\n public static EServerMode MODE;\n\n public static ResourceBundle strings;\n\n public static Path rootDir = Paths.get(System.getProperty(\"user.dir\"));\n\n @SuppressWarnings(\"FieldMayBeFinal\") // These have special behavior, final breaks it\n @Option(names = {\"-r\", \"--root\"}, description = \"The root directory of the game, defaults to the current working directory.\")\n private String rootDirectory = System.getProperty(\"user.dir\");\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-o\", \"--progress\", \"progress-only\"}, description = \"Only show progress indication. Ignored if '-s', '--server' is specified.\")\n private boolean modeProgressOnly = false;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-q\", \"--quiet\", \"silent\"}, description = \"Remove all GUI interaction. Ignored if '-s', '--server' is specified.\")\n private boolean modeQuiet = false;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-s\", \"--server\", \"server\"}, description = \"Run the program in server mode.\")\n private boolean modeServer = false;\n @Option(names = {\"-a\", \"--address\"}, description = \"The address of the server you wish to connect to.\")\n private String serverAddress;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-p\", \"--port\"}, description = \"The port the server is running on.\")\n private int serverPort = -1;\n @Option(names = {\"-i\", \"--ignore\"}, arity = \"1..*\", description = \"A glob pattern or series of patterns for files to ignore\")\n private String[] ignorePatterns;\n @Option(names = {\"-l\", \"--lang\"}, description = \"A language code to set the UI language e.g. zh_CN or en_US\")\n private String languageCode;\n\n public static void main(String[] args) {\n int exitCode = new CommandLine(new ServerSync()).execute(args);\n if (exitCode != 0) {\n System.exit(exitCode);\n }\n }\n\n @Override\n public Integer call() {\n ServerSync.rootDir = Paths.get(rootDirectory);\n if (modeServer) {\n runInServerMode();\n } else {\n runInClientMode();\n }\n return 0;\n }\n\n private void commonInit() {\n Logger.log(String.format(\"Root dir: %s\", ServerSync.rootDir.toAbsolutePath()));\n Logger.log(String.format(\"Running version: %s\", RefStrings.VERSION));\n Locale locale = SyncConfig.getConfig().LOCALE;\n if (languageCode != null) {\n String[] lParts = languageCode.split(\"[_-]\");\n locale = new Locale(lParts[0], lParts[1]);\n SyncConfig.getConfig().LOCALE = locale;\n }\n if (serverAddress != null) {\n SyncConfig.getConfig().SERVER_IP = serverAddress;\n }\n if (serverPort > 0) {\n SyncConfig.getConfig().SERVER_PORT = serverPort;\n }\n if (ignorePatterns != null) {\n SyncConfig.getConfig().FILE_IGNORE_LIST = Arrays.stream(ignorePatterns).map(s -> s.replace(\"/\", File.separator).replace(\"\\\\\", File.separator)).collect(Collectors.toList());\n }\n\n try {\n Logger.log(\"Loading language file: \" + locale);\n strings = ResourceBundle.getBundle(\"assets.serversync.lang.MessagesBundle\", locale);\n } catch (MissingResourceException e) {\n Logger.log(\"No language file available for: \" + locale + \", defaulting to en_US\");\n strings = ResourceBundle.getBundle(\"assets.serversync.lang.MessagesBundle\", new Locale(\"en\", \"US\"));\n }\n }\n\n private Thread runInServerMode() {\n ServerSync.MODE = EServerMode.SERVER;\n try {\n ConfigLoader.load(EConfigType.SERVER);\n } catch (IOException e) {\n Logger.error(\"Failed to load server config\");\n Logger.debug(e);\n }\n commonInit();\n\n Thread serverThread = new ServerSetup();\n serverThread.start();\n return serverThread;\n }\n\n private void runInClientMode() {\n ServerSync.MODE = EServerMode.CLIENT;\n if(modeQuiet||modeProgressOnly){\n //Disable the consoleHandler to fix automation hanging\n Logger.setSystemOutput(false);\n }\n SyncConfig config = SyncConfig.getConfig();\n try {\n ConfigLoader.load(EConfigType.CLIENT);\n } catch (IOException e) {\n Logger.error(\"Failed to load client config\");\n e.printStackTrace();\n }\n commonInit();\n\n ClientWorker worker = new ClientWorker();\n if (modeQuiet) {\n try {\n worker.setAddress(SyncConfig.getConfig().SERVER_IP);\n worker.setPort(SyncConfig.getConfig().SERVER_PORT);\n worker.connect();\n Then.onComplete(worker.fetchActions(), actionEntries -> Then.onComplete(worker.executeActions(actionEntries, unused -> {\n }), unused -> {\n worker.close();\n System.exit(0);\n }));\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n } else if (modeProgressOnly) {\n // TODO setup a progress only version of the GUI?\n try {\n worker.setAddress(SyncConfig.getConfig().SERVER_IP);\n worker.setPort(SyncConfig.getConfig().SERVER_PORT);\n worker.connect();\n Then.onComplete(worker.fetchActions(), actionEntries -> Then.onComplete(worker.executeActions(actionEntries, actionProgress -> {\n if (actionProgress.isComplete()) {\n System.out.printf(\"Updated: %s%n\", actionProgress.entry);\n }\n }), unused -> {\n worker.close();\n System.exit(0);\n }));\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n } else {\n new GUI_Launcher().start();\n }\n }\n}", "public class DirectoryEntry implements Serializable {\n public final String path;\n public final EDirectoryMode mode;\n\n public DirectoryEntry(String path, EDirectoryMode mode) {\n this.path = path;\n this.mode = mode;\n }\n\n public String getLocalPath() {\n return path.replace(\"/\", File.separator).replace(\"\\\\\", File.separator);\n }\n\n public JsonObject toJson() {\n return Json.object().add(\"path\", path).add(\"mode\", mode.toString());\n }\n\n @Override\n public String toString() {\n return \"DirectoryEntry{\" +\n \"path='\" + path + '\\'' +\n \", mode=\" + mode +\n '}';\n }\n}", "public enum EDirectoryMode {\n // A bit magical to be using string values that match the enum name\n mirror(\"mirror\"),\n push(\"push\");\n\n private final String value;\n EDirectoryMode(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n}", "public class FileRedirect {\n public final String pattern;\n public final String redirectTo;\n\n public FileRedirect(String pattern, String redirectTo) {\n this.pattern = pattern;\n this.redirectTo = redirectTo;\n }\n\n public static FileRedirect from(JsonObject o) {\n return new FileRedirect(o.get(\"pattern\").asString(), o.get(\"redirectTo\").asString());\n }\n\n public JsonObject toJson() {\n return Json.object().add(\"pattern\", pattern).add(\"redirectTo\", redirectTo);\n }\n}", "public enum EConfigType {\n\tSERVER,\n\tCLIENT,\n\tCOMMON\n}", "public enum EServerMode {\n SERVER,\n CLIENT\n}", "public enum ETheme {\n /*\n -fx-primary -> Color background\n -fx-secondary -> Color button/border/progressbar\n -fx-sidebar-primary -> Color background for the sidebar\n */\n BLUE_YELLOW (\"-fx-primary : #232834; -fx-secondary : #edbe60; -fx-sidebar-primary: #1f2430; -fx-primarytext : #B2B2B2; -fx-secondarytext: #b6b6b6; -fx-background-color: -fx-primary;\"),\n DARK_CYAN (\"-fx-primary : #2A2E37; -fx-secondary : #4DB3B3; -fx-sidebar-primary: #23232e; -fx-primarytext : #B2B2B2; -fx-secondarytext: #b6b6b6; -fx-background-color: -fx-primary;\"),\n DARK_GREEN (\"-fx-primary : #262626; -fx-secondary : #86d291; -fx-sidebar-primary: #1c1c1c; -fx-primarytext : #B2B2B2; -fx-secondarytext: #b6b6b6; -fx-background-color: -fx-primary;\"),\n DARK_PURPLE (\"-fx-primary : #1c1c1c; -fx-secondary : #b883f9; -fx-sidebar-primary: #111111; -fx-primarytext : #B2B2B2; -fx-secondarytext: #b6b6b6; -fx-background-color: -fx-primary;\"),\n GREY_BLUE (\"-fx-primary : #3b4252; -fx-secondary : #95c5c3; -fx-sidebar-primary: #2e3440; -fx-primarytext : #B2B2B2; -fx-secondarytext: #b6b6b6; -fx-background-color: -fx-primary;\");\n\n private final String theme;\n\n ETheme(String theme) {\n this.theme = theme;\n }\n\n public String toString() {\n return this.theme;\n }\n}" ]
import com.superzanti.serversync.ServerSync; import com.superzanti.serversync.files.DirectoryEntry; import com.superzanti.serversync.files.EDirectoryMode; import com.superzanti.serversync.files.FileRedirect; import com.superzanti.serversync.util.enums.EConfigType; import com.superzanti.serversync.util.enums.EServerMode; import com.superzanti.serversync.util.enums.ETheme; import java.io.IOException; import java.util.*;
package com.superzanti.serversync.config; /** * Handles all functionality to do with serversyncs config file and * other configuration properties * * @author Rheimus */ public class SyncConfig { public final EConfigType configType; // COMMON ////////////////////////////// public String SERVER_IP = "127.0.0.1"; public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); public Locale LOCALE = Locale.getDefault(); public ETheme THEME = ETheme.BLUE_YELLOW; public int BUFFER_SIZE = 1024 * 64; //////////////////////////////////////// // SERVER ////////////////////////////// public int SERVER_PORT = 38067; public Boolean PUSH_CLIENT_MODS = false; public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( "mods", EDirectoryMode.mirror )); public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); public int SYNC_MODE = 2; //////////////////////////////////////// // CLIENT ////////////////////////////// public Boolean REFUSE_CLIENT_MODS = false; //////////////////////////////////////// private static SyncConfig singleton; public SyncConfig() { this.configType = EConfigType.COMMON; } public SyncConfig(EConfigType type) { configType = type; } public static SyncConfig getConfig() { if (SyncConfig.singleton == null) {
if (ServerSync.MODE == EServerMode.SERVER) {
0
zegerhoogeboom/flysystem-java
src/main/java/com/flysystem/core/adapter/local/Local.java
[ "public class Config\n{\n\tprotected Map<String, Object> settings = new HashMap<String, Object>();\n\tprotected Config fallback;\n\n\tpublic Config(Map<String, Object> settings)\n\t{\n\t\tthis.settings = settings;\n\t}\n\n\tpublic Config()\n\t{\n\t\tthis.settings = new HashMap<>();\n\t}\n\n\tpublic static Config withVisibility(final Visibility visibility)\n\t{\n\t\treturn new Config(new HashMap<String, Object>() {{\n\t\t\tput(\"visibility\", visibility);\n\t\t}});\n\t}\n\n\tpublic Object get(String key)\n\t{\n\t\treturn get(key, null);\n\t}\n\n\tpublic Object get(String key, Object defaultValue)\n\t{\n\t\tif (! this.settings.containsKey(key)) {\n\t\t\treturn getDefault(key, defaultValue);\n\t\t}\n\t\treturn this.settings.get(key);\n\t}\n\n\tpublic boolean has(String key)\n\t{\n\t\treturn this.settings.containsKey(key);\n\t}\n\n\tprotected Object getDefault(String key, Object defaultValue)\n\t{\n\t\tif (this.fallback == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\treturn this.fallback.get(key, defaultValue);\n\t}\n\n\tpublic Config set(String key, Object value)\n\t{\n\t\tthis.settings.put(key, value);\n\t\treturn this;\n\t}\n\n\tpublic Config setFallback(Config fallback)\n\t{\n\t\tthis.fallback = fallback;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o)\n\t{\n\t\tif (this == o) return true;\n\t\tif (! (o instanceof Config)) return false;\n\n\t\tConfig config = (Config) o;\n\n\t\tif (settings != null ? ! settings.equals(config.settings) : config.settings != null) return false;\n\t\treturn ! (fallback != null ? ! fallback.equals(config.fallback) : config.fallback != null);\n\n\t}\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\tint result = settings != null ? settings.hashCode() : 0;\n\t\tresult = 31 * result + (fallback != null ? fallback.hashCode() : 0);\n\t\treturn result;\n\t}\n}", "public class FileMetadata\n{\n\tString path;\n\tLong size;\n\tVisibility visibility;\n\tString mimetype;\n\tLong timestamp;\n\tString type;\n\n\tpublic FileMetadata(String path)\n\t{\n\t\tthis.path = path;\n\t}\n\n\tpublic FileMetadata(String path, Long size, Visibility visibility, String mimetype, Long timestamp, String type)\n\t{\n\t\tthis.path = path;\n\t\tthis.size = size;\n\t\tthis.visibility = visibility;\n\t\tthis.mimetype = mimetype;\n\t\tthis.timestamp = timestamp;\n\t\tthis.type = type;\n\t}\n\n\tpublic String getPath()\n\t{\n\t\treturn path;\n\t}\n\n\tpublic void setPath(String path)\n\t{\n\t\tthis.path = path;\n\t}\n\n\tpublic Long getSize()\n\t{\n\t\treturn size;\n\t}\n\n\tpublic void setSize(Long size)\n\t{\n\t\tthis.size = size;\n\t}\n\n\tpublic Visibility getVisibility()\n\t{\n\t\treturn visibility;\n\t}\n\n\tpublic void setVisibility(Visibility visibility)\n\t{\n\t\tthis.visibility = visibility;\n\t}\n\n\tpublic String getMimetype()\n\t{\n\t\treturn mimetype;\n\t}\n\n\tpublic void setMimetype(String mimetype)\n\t{\n\t\tthis.mimetype = mimetype;\n\t}\n\n\tpublic Long getTimestamp()\n\t{\n\t\treturn timestamp;\n\t}\n\n\tpublic void setTimestamp(Long timestamp)\n\t{\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic String getType()\n\t{\n\t\treturn type;\n\t}\n\n\tpublic void setType(String type)\n\t{\n\t\tthis.type = type;\n\t}\n\n\tpublic File getFile()\n\t{\n\t\treturn new File(path);\n\t}\n\n\tpublic boolean isFile()\n\t{\n\t\treturn \"file\".equals(getType());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o)\n\t{\n\t\tif (this == o) return true;\n\t\tif (! (o instanceof FileMetadata)) return false;\n\n\t\tFileMetadata that = (FileMetadata) o;\n\n\t\treturn ! (path != null ? ! path.equals(that.path) : that.path != null);\n\n\t}\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn path != null ? path.hashCode() : 0;\n\t}\n}", "public enum Visibility\n{\n\tPUBLIC, PRIVATE\n}", "public abstract class AbstractAdapter implements Adapter\n{\n\tprotected String pathPrefix;\n\n\tpublic void setPathPrefix(String prefix)\n\t{\n\t\tboolean isEmpty = Strings.isNullOrEmpty(prefix);\n\t\tif (! isEmpty) {\n\t\t\tprefix = StringUtils.stripEnd(prefix, File.separator) + File.separator;\n\t\t}\n\t\tthis.pathPrefix = isEmpty ? null : prefix;\n\t}\n\n\tpublic String getPathPrefix()\n\t{\n\t\treturn pathPrefix;\n\t}\n\n\tpublic String applyPathPrefix(String path)\n\t{\n\t\tpath = StringUtils.stripStart(path, \"\\\\/\");\n\t\tif (path.length() == 0) {\n\t\t\treturn getPathPrefix() != null ? getPathPrefix() : \"\";\n\t\t}\n\t\treturn getPathPrefix() + path;\n\t}\n\n\t/**\n\t * Remove a path prefix.\n\t *\n\t * @return string path without the prefix\n\t */\n\tpublic String removePathPrefix(String path)\n\t{\n\t\tif (getPathPrefix() == null) {\n\t\t\treturn path;\n\t\t}\n\n\t\treturn path.substring(pathPrefix.length());\n\t}\n}", "public class DirectoryNotFoundException extends FlysystemGenericException\n{\n\tpublic DirectoryNotFoundException(String path)\n\t{\n\t\tsuper(\"Directory not found at path: \" + path);\n\t}\n}", "public class FileNotFoundException extends FlysystemGenericException\n{\n\tpublic FileNotFoundException(String path)\n\t{\n\t\tsuper(\"File not found at path: \" + path);\n\t}\n}", "public class FlysystemGenericException extends RuntimeException\n{\n\tpublic FlysystemGenericException(String message)\n\t{\n\t\tsuper(message);\n\t}\n\n\tpublic FlysystemGenericException(Throwable cause)\n\t{\n\t\tsuper(cause);\n\t}\n}" ]
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import com.flysystem.core.Config; import com.flysystem.core.FileMetadata; import com.flysystem.core.Visibility; import com.flysystem.core.adapter.AbstractAdapter; import com.flysystem.core.exception.DirectoryNotFoundException; import com.flysystem.core.exception.FileNotFoundException; import com.flysystem.core.exception.FlysystemGenericException; import com.google.common.io.Files;
/* * Copyright (c) 2013-2015 Frank de Jonge * * 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 com.flysystem.core.adapter.local; /** * @author Zeger Hoogeboom */ public class Local extends AbstractAdapter { private static int SKIP_LINKS = 0001; private static int DISALLOW_LINKS = 0002; protected String pathSeparator = "/"; protected int writeFlags; private int linkHandling; public Local(String root, int writeFlags, int linkHandling) { File realRoot = this.ensureDirectory(root); if (! realRoot.isDirectory() || ! realRoot.canRead()) { throw new FlysystemGenericException(String.format("The root path %s is not readable.", realRoot.getAbsolutePath())); } try { this.setPathPrefix(realRoot.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } this.writeFlags = writeFlags; this.linkHandling = linkHandling; } public Local(String root) { this(root, 2, 2); } /** * Ensure the root directory exists. * * @return string real path to root */ protected File ensureDirectory(String root) { File file = new File(root); return ensureDirectory(file); } protected File ensureDirectory(File file) { if (!file.isDirectory()) { new File(file.getParent()).mkdirs(); } return file; } public boolean has(String path) { return new File(applyPathPrefix(path)).exists(); } public String read(String path) throws FileNotFoundException { try { return Files.toString(getExistingFile(path), Charset.defaultCharset()); } catch (IOException e) { throw new FlysystemGenericException(e); } }
public List<FileMetadata> listContents(String directory, boolean recursive)
1
iGoodie/TwitchSpawn
src/main/java/net/programmer/igoodie/twitchspawn/tslanguage/action/ReflectAction.java
[ "@Mod(TwitchSpawn.MOD_ID)\npublic class TwitchSpawn {\n\n public static final String MOD_ID = \"twitchspawn\";\n public static final Logger LOGGER = LogManager.getLogger(TwitchSpawn.class);\n\n public static MinecraftServer SERVER;\n public static TraceManager TRACE_MANAGER;\n\n public TwitchSpawn() {\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientSetup);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::dedicatedServerSetup);\n\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n private void commonSetup(final FMLCommonSetupEvent event) {\n try {\n ConfigManager.loadConfigs();\n NetworkManager.initialize();\n\n ArgumentTypes.register(\"twitchspawn:streamer\", StreamerArgumentType.class,\n new StreamerArgumentSerializer());\n ArgumentTypes.register(\"twitchspawn:ruleset\", RulesetNameArgumentType.class,\n new RulesetNameArgumentSerializer());\n\n } catch (TwitchSpawnLoadingErrors e) {\n e.bindFMLWarnings(ModLoadingStage.COMMON_SETUP);\n throw new RuntimeException(\"TwitchSpawn loading errors occurred\");\n }\n }\n\n private void clientSetup(final FMLClientSetupEvent event) {\n NotepadUDLUpdater.attemptUpdate();\n MinecraftForge.EVENT_BUS.register(StatusIndicatorOverlay.class);\n MinecraftForge.EVENT_BUS.register(GlobalChatCooldownOverlay.class);\n }\n\n private void dedicatedServerSetup(final FMLDedicatedServerSetupEvent event) {}\n\n @SubscribeEvent\n public void registerSounds(RegistryEvent.Register<SoundEvent> event) {\n event.getRegistry().register(new SoundEvent(new ResourceLocation(TwitchSpawn.MOD_ID, \"pop_in\")));\n event.getRegistry().register(new SoundEvent(new ResourceLocation(TwitchSpawn.MOD_ID, \"pop_out\")));\n }\n\n @SubscribeEvent\n public void onRegisterCommands(RegisterCommandsEvent event) {\n TwitchSpawnCommand.register(event.getDispatcher());\n }\n\n @SubscribeEvent\n public void onServerAboutToStart(FMLServerAboutToStartEvent event) {\n SERVER = event.getServer();\n TRACE_MANAGER = new TraceManager();\n }\n\n @SubscribeEvent\n public void onServerStarting(FMLServerStartingEvent event) {\n if (ConfigManager.PREFERENCES.autoStart == PreferencesConfig.AutoStartEnum.ENABLED) {\n LOGGER.info(\"Auto-start is enabled. Attempting to start tracers.\");\n TRACE_MANAGER.start();\n }\n }\n\n @SubscribeEvent\n public void onServerStopping(FMLServerStoppingEvent event) {\n SERVER = null;\n\n if (TRACE_MANAGER.isRunning())\n TRACE_MANAGER.stop(null, \"Server stopping\");\n\n ConfigManager.RULESET_COLLECTION.clearQueue();\n }\n\n @SubscribeEvent\n public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {\n ServerPlayer entity = (ServerPlayer) event.getPlayer();\n\n String translationKey = TRACE_MANAGER.isRunning() ?\n \"commands.twitchspawn.status.on\" : \"commands.twitchspawn.status.off\";\n\n entity.sendMessage(new TranslatableComponent(translationKey), entity.getUUID());\n\n if (TRACE_MANAGER.isRunning())\n TRACE_MANAGER.connectStreamer(entity.getName().getString());\n\n NetworkManager.CHANNEL.sendTo(new StatusChangedPacket(TRACE_MANAGER.isRunning()),\n entity.connection.connection,\n NetworkDirection.PLAY_TO_CLIENT);\n }\n\n @SubscribeEvent\n public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {\n ServerPlayer entity = (ServerPlayer) event.getPlayer();\n\n if (TRACE_MANAGER.isRunning())\n TRACE_MANAGER.disconnectStreamer(entity.getName().getString());\n }\n\n}", "public class ConfigManager {\n\n public static final String CONFIG_DIR_PATH = FMLPaths.CONFIGDIR.get().toString() + File.separator + \"TwitchSpawn\";\n\n public static CredentialsConfig CREDENTIALS;\n public static TSLRulesetCollection RULESET_COLLECTION;\n public static TitlesConfig TITLES;\n public static SubtitlesConfig SUBTITLES;\n public static PreferencesConfig PREFERENCES;\n\n public static void loadConfigs() throws TwitchSpawnLoadingErrors {\n TwitchSpawn.LOGGER.info(\"Loading configs...\");\n TwitchSpawnLoadingErrors errors = new TwitchSpawnLoadingErrors();\n\n File configDirectory = new File(CONFIG_DIR_PATH);\n\n if (!configDirectory.exists())\n configDirectory.mkdirs();\n\n accumulateExceptions(errors,\n () -> CREDENTIALS = CredentialsConfig.create(getPath(\"credentials.toml\")));\n accumulateExceptions(errors,\n () -> RULESET_COLLECTION = RulesConfig.createRules(CONFIG_DIR_PATH));\n accumulateExceptions(errors,\n () -> TITLES = TitlesConfig.create(new File(getPath(\"messages.title.json\"))));\n accumulateExceptions(errors,\n () -> SUBTITLES = SubtitlesConfig.create(new File(getPath(\"messages.subtitle.json\"))));\n accumulateExceptions(errors,\n () -> PREFERENCES = PreferencesConfig.create(new File(getPath(\"preferences.toml\"))));\n\n if(!errors.isEmpty())\n throw errors;\n\n TwitchSpawn.LOGGER.info(\"Configs loaded successfully!\");\n }\n\n public static String getPath(String relativePath) {\n return CONFIG_DIR_PATH + File.separator + relativePath;\n }\n\n private static void accumulateExceptions(TwitchSpawnLoadingErrors container, ExceptionAccumulator task) {\n try {\n task.execute();\n } catch (Exception e) {\n container.addException(e);\n }\n }\n\n @FunctionalInterface\n private interface ExceptionAccumulator {\n void execute() throws Exception;\n }\n\n}", "public class EventQueue {\n\n private final Thread innerThread;\n private volatile EventQueueState state;\n private volatile Deque<EventQueueTask> tasks;\n private volatile boolean waitingForServer;\n private long cooldown; // milliseconds\n private int succeededEvents;\n private int discardedEvents;\n\n public EventQueue(long cooldownDuration) {\n this.innerThread = new Thread(() -> {\n while (true) stepThread();\n }, \"TwitchSpawn Event Queue\");\n this.state = EventQueueState.PAUSED;\n this.tasks = new LinkedList<>();\n this.cooldown = cooldownDuration;\n\n this.innerThread.start();\n }\n\n private void stepThread() {\n try {\n if (hasUnhandledEvent()) {\n if (waitingForServer) {\n // TODO: Sleep?\n return;\n }\n\n EventQueueTask task = tasks.remove();\n\n if (task.getType() == EventQueueTask.Type.SLEEP)\n state = EventQueueState.COOLDOWN;\n\n task.run();\n\n if (task.getType() == EventQueueTask.Type.SLEEP)\n state = EventQueueState.WORKING;\n\n } else {\n pause();\n }\n\n } catch (Throwable e) {\n discardedEvents++;\n e.printStackTrace(); // TODO:\n }\n }\n\n private void unpause() {\n synchronized (innerThread) {\n state = EventQueueState.WORKING;\n innerThread.notifyAll();\n }\n }\n\n private void pause() {\n synchronized (innerThread) {\n try {\n state = EventQueueState.PAUSED;\n innerThread.wait();\n\n } catch (InterruptedException e) {\n e.printStackTrace(); // TODO\n }\n }\n }\n\n public void updateThread() {\n if (state == EventQueueState.PAUSED) unpause();\n }\n\n public void cancelUpcomingSleep() {\n assert this.tasks instanceof LinkedList;\n List<EventQueueTask> tasks = (LinkedList<EventQueueTask>) this.tasks;\n for (int i = 0; i < tasks.size(); i++) {\n EventQueueTask task = tasks.get(i);\n if (task.getType() == EventQueueTask.Type.SLEEP) {\n tasks.remove(i);\n return;\n }\n }\n }\n\n public void queueSleepFirst() {\n queueSleepFirst(cooldown);\n }\n\n public void queueSleepFirst(long millis) {\n tasks.addFirst(new EventQueueTask(\"Sleep\", millis));\n }\n\n public void queueSleep() {\n queueSleep(cooldown);\n }\n\n public void queueSleep(long millis) {\n tasks.add(new EventQueueTask(\"Sleep\", millis));\n }\n\n public void queueFirst(String name, Runnable task) {\n tasks.addFirst(new EventQueueTask(name, task));\n\n }\n\n public void queue(Runnable task) {\n queue(\"Runnable task\", task);\n }\n\n public void queue(String name, Runnable task) {\n tasks.add(new EventQueueTask(name, task));\n }\n\n public void queue(TSLEvent eventNode, EventArguments args, CooldownBucket cooldownBucket) {\n if (eventNode.willPerform(args)) {\n if (cooldownBucket != null) {\n cooldownBucket.consume(args.actorNickname);\n\n ServerPlayer playerEntity = TwitchSpawn.SERVER\n .getPlayerList()\n .getPlayerByName(args.streamerNickname);\n\n if (playerEntity != null) {\n NetworkManager.CHANNEL.sendTo(\n new GlobalChatCooldownPacket(cooldownBucket.getGlobalCooldownTimestamp()),\n playerEntity.connection.connection,\n NetworkDirection.PLAY_TO_CLIENT\n );\n }\n }\n }\n\n tasks.add(new EventQueueTask(\"TSL Event task\", () -> {\n waitingForServer = true;\n TwitchSpawn.SERVER.execute(() -> {\n try {\n boolean performed = eventNode.process(args);\n\n if (performed) succeededEvents++;\n else discardedEvents++;\n\n } catch (Throwable e) {\n discardedEvents++;\n // TODO: \"Event failed HUD\" maybe?\n\n } finally {\n waitingForServer = false;\n }\n });\n }));\n }\n\n public synchronized int succeededEventCount() {\n return succeededEvents;\n }\n\n public synchronized int discardedEventCount() {\n return discardedEvents;\n }\n\n public synchronized int unhandledEventCount() {\n return tasks.size();\n }\n\n public synchronized boolean hasUnhandledEvent() {\n return !tasks.isEmpty();\n }\n\n public void reset() {\n tasks.clear();\n succeededEvents = 0;\n discardedEvents = 0;\n }\n\n}", "public class EventArguments {\n\n public static EventArguments createRandom(String streamerNickname) {\n EventArguments eventArguments = new EventArguments(TSLEventKeyword.randomPair());\n\n eventArguments.streamerNickname = streamerNickname;\n eventArguments.randomize();\n\n return eventArguments;\n }\n\n /* ------------------------------ */\n\n public final String eventType;\n public final String eventAccount;\n public final String eventName;\n\n public String streamerNickname;\n public String actorNickname;\n public String message;\n\n public double donationAmount;\n public String donationCurrency;\n\n public int subscriptionMonths;\n public int subscriptionTier = -1; // 0=Prime, 1=T1, 2=T2, 3=T3\n public boolean gifted;\n\n public int viewerCount;\n public int raiderCount;\n\n public String rewardTitle;\n public Set<String> chatBadges;\n\n public EventArguments(String eventType, String eventAccount) {\n this.eventType = eventType;\n this.eventAccount = eventAccount;\n this.eventName = TSLEventKeyword.ofPair(eventType, eventAccount);\n this.chatBadges = new HashSet<>();\n }\n\n public EventArguments(TSLEventPair eventPair) {\n this(eventPair.getEventType(), eventPair.getEventAccount());\n }\n\n public void randomize() {\n randomize(\"RandomDude\", \"Random event message\");\n }\n\n public void randomize(String actorNickname, String message) {\n Random random = new Random();\n\n this.actorNickname = actorNickname;\n this.message = message;\n this.donationAmount = random.nextDouble() * 1000;\n this.donationCurrency = new String[]{\"USD\", \"TRY\", \"EUR\"}[random.nextInt(3)];\n this.subscriptionMonths = random.nextInt(100 - 1) + 1;\n this.subscriptionTier = random.nextInt(3 + 1);\n this.gifted = random.nextBoolean();\n this.viewerCount = random.nextInt(100 - 1) + 1;\n this.raiderCount = random.nextInt(100 - 1) + 1;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"{\");\n String delimiter = \"\";\n\n try {\n for (Field field : getClass().getFields()) {\n Object value = field.get(this);\n Object defaultValue = Defaults.defaultValue(field.getType());\n\n if (value == null)\n continue;\n\n if (!value.equals(defaultValue)) {\n sb.append(delimiter);\n sb.append(field.getName()).append(\"=\").append(value);\n delimiter = \", \";\n }\n\n // Exception for tier field. (where default 0=Prime)\n else if (field.getName().equalsIgnoreCase(\"tier\") && value.equals(0)) {\n sb.append(delimiter);\n sb.append(field.getName()).append(\"=\").append(value);\n delimiter = \", \";\n }\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n\n sb.append(\"}\");\n\n return sb.toString();\n }\n\n}", "public enum TSLActionKeyword {\n\n DROP(true, DropAction.class),\n SUMMON(true, SummonAction.class),\n THROW(true, ThrowAction.class),\n CLEAR(true, ClearAction.class),\n EXECUTE(true, ExecuteAction.class),\n SHUFFLE(true, ShuffleAction.class),\n CHANGE(true, ChangeAction.class),\n NOTHING(true, NothingAction.class),\n\n EITHER(false, EitherAction.class),\n BOTH(false, BothAction.class),\n FOR(false, ForAction.class),\n WAIT(true, WaitAction.class),\n REFLECT(false, ReflectAction.class),\n\n OS_RUN(true, OsRunAction.class),\n ;\n\n public static boolean exists(String actionName) {\n try {\n valueOf(actionName.toUpperCase());\n return true;\n } catch (IllegalArgumentException e) {\n return false;\n }\n }\n\n public static Class<? extends TSLAction> toClass(String actionName) {\n if (!exists(actionName))\n return null;\n\n return valueOf(actionName.toUpperCase()).actionClass;\n }\n\n public static String ofClass(Class<? extends TSLAction> actionClass) {\n for (TSLActionKeyword keyword : values()) {\n if (keyword.actionClass.equals(actionClass))\n return keyword.name();\n }\n return null;\n }\n\n /* --------------------------- */\n\n public final boolean displayable;\n public final Class<? extends TSLAction> actionClass;\n\n TSLActionKeyword(boolean displayable, Class<? extends TSLAction> actionClass) {\n this.displayable = displayable;\n this.actionClass = actionClass;\n }\n}", "public class TSLParser {\n\n private static Pattern PERCENTAGE_PATTERN = Pattern.compile(\"(?<decimal>\\\\d{1,3})(\\\\.(?<fraction>\\\\d{1,2}))?\");\n\n public static int parsePercentage(String percentageString) {\n Matcher matcher = PERCENTAGE_PATTERN.matcher(percentageString);\n\n if (!matcher.matches())\n throw new IllegalArgumentException(\"Unexpected percentage format -> \" + percentageString);\n\n try {\n String decimalGroup = matcher.group(\"decimal\");\n String fractionGroup = matcher.group(\"fraction\");\n\n int decimal = Integer.parseInt(decimalGroup);\n int fraction = fractionGroup == null ? 0 : Integer.parseInt(String.format(\"%-2s\", fractionGroup).replace(' ', '0'));\n\n return decimal * 100 + fraction;\n\n } catch (NumberFormatException e) {\n throw new IllegalArgumentException(\"Unexpected percentage format -> \" + percentageString);\n }\n }\n\n public static JsonArray parseMessage(List<String> words) throws TSLSyntaxError {\n long messageKeywordCount = words.stream()\n .filter(word -> word.equalsIgnoreCase(TSLRuleTokenizer.DISPLAY_KEYWORD))\n .count();\n\n if (messageKeywordCount == 0)\n return null; // Nothing to parse\n\n if (messageKeywordCount != 1)\n throw new TSLSyntaxError(\"Expected AT MOST one %s, found %d instead\",\n TSLRuleTokenizer.DISPLAY_KEYWORD, messageKeywordCount);\n\n for (int i = 0; i < words.size(); i++) {\n String word = words.get(i);\n\n // Found the displaying keyword\n if (word.equalsIgnoreCase(TSLRuleTokenizer.DISPLAY_KEYWORD)) {\n\n // Range check\n if (i + 1 >= words.size())\n throw new TSLSyntaxError(\"Expected word after %s\", TSLRuleTokenizer.DISPLAY_KEYWORD);\n\n String jsonString = words.get(i + 1);\n\n // Yet another hack for backwards compatibility\n if (jsonString.equalsIgnoreCase(\"NOTHING\")) {\n JsonArray displayNothing = new JsonArray();\n displayNothing.add(\"NOTHING_0xDEADC0DE_0xDEADBEEF\"); // <-- Super hyper mega hacker move\n return displayNothing;\n }\n\n try {\n JsonArray parsedMessage = new JsonParser().parse(jsonString).getAsJsonArray();\n GsonUtils.removeInvalidTextComponent(parsedMessage); // <-- Will also remove null elements created by trailing comma chars\n return parsedMessage;\n\n } catch (JsonParseException e) {\n throw new TSLSyntaxError(\"Malformed JSON array -> %s\", jsonString);\n\n } catch (IllegalStateException e) {\n throw new TSLSyntaxError(\"Expected JSON array, found instead -> %s\", jsonString);\n }\n }\n }\n\n return null;\n }\n\n public static TSLAction parseAction(String actionName, List<String> actionParameters) throws TSLSyntaxError {\n Class<? extends TSLAction> actionClass = TSLActionKeyword.toClass(actionName);\n\n if (actionClass == null)\n throw new TSLSyntaxError(\"Unknown action name -> %s\", actionName);\n\n try {\n return (TSLAction) actionClass.getConstructors()[0].newInstance(actionParameters);\n\n } catch (InstantiationException e) {\n throw new InternalError(\"Tried to instantiate an abstract class -> \" + actionClass.getName());\n\n } catch (IllegalAccessException e) {\n throw new InternalError(\"Tried to instantiate an inaccessible class -> \" + actionClass.getName());\n\n } catch (InvocationTargetException e) {\n if (e.getCause() instanceof TSLSyntaxError)\n throw (TSLSyntaxError) e.getCause();\n e.getCause().printStackTrace();\n throw new InternalError(\"Constructor threw unexpected Throwable: \" + e.getClass().getSimpleName()\n , e.getCause());\n\n } catch (ClassCastException e) {\n throw new InternalError(\"Cannot cast \" + actionClass.getSimpleName() + \" to \" + TSLAction.class.getSimpleName());\n }\n }\n\n public static TSLEvent parseEvent(String eventName) throws TSLSyntaxError {\n if (!TSLEventKeyword.exists(eventName))\n throw new TSLSyntaxError(\"Unknown event name -> %s\", eventName);\n\n return new TSLEvent(eventName);\n }\n\n public static List<TSLPredicate> parsePredicates(List<List<String>> predicateParameters) throws TSLSyntaxError {\n List<TSLPredicate> predicates = new LinkedList<>();\n\n // For each word sequence\n for (List<String> predicateWords : predicateParameters) {\n if (predicateWords.size() < 3)\n throw new TSLSyntaxError(\"Expected at least 3 words after %s, found instead -> %s\",\n TSLRuleTokenizer.PREDICATE_KEYWORD, predicateWords);\n\n // Copy predicate words, will consume them\n List<String> remainingWords = new LinkedList<>(predicateWords);\n\n // Consume rightmost and leftmost words, join remaining\n String propertyName = remainingWords.remove(0);\n String rightHand = remainingWords.remove(remainingWords.size() - 1);\n String symbol = String.join(\" \", remainingWords);\n\n // Create predicate and accumulate\n predicates.add(new TSLPredicate(propertyName, parseComparator(symbol, rightHand)));\n }\n\n return predicates;\n }\n\n public static TSLComparator parseComparator(String symbol, String rightHand) throws TSLSyntaxError {\n Class<? extends TSLComparator> comparatorClass = TSLComparatorSymbol.toClass(symbol);\n\n if (comparatorClass == null)\n throw new TSLSyntaxError(\"Unknown comparator -> %s\", symbol);\n\n try {\n return (TSLComparator) comparatorClass.getConstructors()[0].newInstance(rightHand);\n\n } catch (InstantiationException e) {\n throw new InternalError(\"Tried to instantiate an abstract class -> \" + comparatorClass.getName());\n\n } catch (IllegalAccessException e) {\n throw new InternalError(\"Tried to instantiate an inaccessible class -> \" + comparatorClass.getName());\n\n } catch (InvocationTargetException e) {\n if (e.getCause() instanceof TSLSyntaxError)\n throw (TSLSyntaxError) e.getCause();\n throw new InternalError(\"Constructor threw unexpected Throwable: \" + e.getCause().getClass().getSimpleName());\n\n } catch (ClassCastException e) {\n throw new InternalError(\"Cannot cast \" + comparatorClass.getSimpleName() + \" to \" + TSLComparator.class.getSimpleName());\n }\n }\n\n /* ------------------------------------ */\n\n private TSLTokenizer tokenizer;\n private Map<String, TSLEvent> events; // E.g \"twitch follow\" -> { TSLEvent }\n\n public TSLParser(String script) {\n this.tokenizer = new TSLTokenizer(script);\n this.events = new HashMap<>();\n }\n\n public Map<String, TSLEvent> parse() throws TSLSyntaxErrors {\n // tokenize into rules first\n try { tokenizer.intoRules(); } catch (TSLSyntaxError e) { throw new TSLSyntaxErrors(e); }\n\n List<TSLSyntaxError> syntaxErrors = new LinkedList<>();\n\n // Traverse every rule\n for (int i = 0; i < tokenizer.ruleCount(); i++) {\n try {\n List<String> words = tokenizer.intoWords(i);\n\n TSLRuleTokenizer ruleParts = new TSLRuleTokenizer(words).intoParts();\n\n // Fetch event, or create one\n TSLEvent event = events.containsKey(ruleParts.getEventName().toLowerCase())\n ? events.get(ruleParts.getEventName().toLowerCase())\n : parseEvent(ruleParts.getEventName());\n\n // Parse action and predicates\n TSLAction action = parseAction(ruleParts.getActionName(), ruleParts.getActionParameters());\n List<TSLPredicate> predicates = parsePredicates(ruleParts.getPredicateParameters());\n\n // Chain all the nodes on event node\n chainAll(event, predicates, action);\n\n // Put event to where it belongs\n events.put(event.getName().toLowerCase(), event);\n\n } catch (TSLSyntaxError e) {\n e.setAssociatedRule(tokenizer.getRule(i));\n syntaxErrors.add(e);\n }\n }\n\n if (!syntaxErrors.isEmpty())\n throw new TSLSyntaxErrors(syntaxErrors);\n\n return events;\n }\n\n private void chainAll(TSLEvent event, List<TSLPredicate> predicates, TSLAction action) {\n TSLFlowNode current = event;\n\n for (TSLPredicate predicate : predicates) {\n current = current.chain(predicate);\n }\n\n current.chain(action);\n }\n\n}", "public class TSLSyntaxError extends Exception {\n\n public static final int RULE_LENGTH_LIMIT = 50;\n\n private String associatedRule;\n\n public TSLSyntaxError(String messageFormat, Object... args) {\n super(args.length == 0 ? messageFormat : String.format(messageFormat, args));\n }\n\n public void setAssociatedRule(String associatedRule) {\n this.associatedRule = associatedRule;\n }\n\n public void setAssociatedRule(List<String> associatedWords) {\n this.associatedRule = TSLTokenizer.buildRule(associatedWords);\n }\n\n @Override\n public String getMessage() {\n if (associatedRule != null) {\n return super.getMessage()\n + \" \\non rule \\u00A7c\\u00A7o\"\n + associatedRule();\n }\n\n return super.getMessage();\n }\n\n private String associatedRule() {\n if (associatedRule.length() <= RULE_LENGTH_LIMIT)\n return associatedRule;\n\n return associatedRule.substring(0, RULE_LENGTH_LIMIT / 2).trim() + \"......\"\n + associatedRule.substring(associatedRule.length() - RULE_LENGTH_LIMIT / 2).trim();\n }\n\n}" ]
import net.minecraft.server.level.ServerPlayer; import net.programmer.igoodie.twitchspawn.TwitchSpawn; import net.programmer.igoodie.twitchspawn.configuration.ConfigManager; import net.programmer.igoodie.twitchspawn.eventqueue.EventQueue; import net.programmer.igoodie.twitchspawn.tslanguage.event.EventArguments; import net.programmer.igoodie.twitchspawn.tslanguage.keyword.TSLActionKeyword; import net.programmer.igoodie.twitchspawn.tslanguage.parser.TSLParser; import net.programmer.igoodie.twitchspawn.tslanguage.parser.TSLSyntaxError; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List;
package net.programmer.igoodie.twitchspawn.tslanguage.action; public class ReflectAction extends TSLAction { private boolean onlyReflectedPlayers; private boolean reflectEveryone; private int reflectRandomN; private List<String> reflectedUsers; private TSLAction action;
public ReflectAction(List<String> words) throws TSLSyntaxError {
6
bonigarcia/dualsub
src/main/java/io/github/bonigarcia/dualsub/srt/Worker.java
[ "public class Alert {\n\n\tprivate static Alert singleton = null;\n\n\tprivate JFrame frame;\n\n\tpublic static Alert getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Alert();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic static void error(String message) {\n\t\tJOptionPane.showMessageDialog(Alert.getSingleton().getFrame(), message,\n\t\t\t\tI18N.getText(\"Window.name.text\"), JOptionPane.ERROR_MESSAGE);\n\t}\n\n\tpublic static void info(String message) {\n\t\tJOptionPane.showMessageDialog(Alert.getSingleton().getFrame(), message,\n\t\t\t\tI18N.getText(\"Window.name.text\"),\n\t\t\t\tJOptionPane.INFORMATION_MESSAGE);\n\t}\n\n\tpublic JFrame getFrame() {\n\t\treturn frame;\n\t}\n\n\tpublic static void setFrame(JFrame frame) {\n\t\tAlert.getSingleton().frame = frame;\n\t}\n}", "public class CharsetItem implements Comparable<Object> {\n\tprivate String id;\n\tprivate String description;\n\n\tpublic CharsetItem(String id, String description) {\n\t\tthis.id = id;\n\t\tthis.description = description;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic String toString() {\n\t\tString output = id;\n\t\tif (!description.isEmpty()) {\n\t\t\toutput += \" - \" + description;\n\t\t}\n\t\treturn I18N.HTML_INIT_TAG + output + I18N.HTML_END_TAG;\n\t}\n\n\t@Override\n\tpublic int compareTo(Object arg) {\n\t\treturn -((CharsetItem) arg).getDescription().compareTo(\n\t\t\t\tthis.getDescription());\n\t}\n}", "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 ExceptionDialog extends JDialog {\n\n\tprivate static final Logger log = LoggerFactory\n\t\t\t.getLogger(ExceptionDialog.class);\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate DualSub parent;\n\tprivate Throwable exception;\n\n\tpublic ExceptionDialog(DualSub parent, boolean modal, Throwable exception) {\n\t\tsuper(parent.getFrame(), modal);\n\t\tthis.parent = parent;\n\t\tthis.exception = exception;\n\t\tinitComponents();\n\t\tparent.setException(this);\n\t}\n\n\tpublic void setVisible() {\n\t\tfinal int width = 500;\n\t\tfinal int height = 430;\n\t\tthis.setBounds(100, 100, width, height);\n\t\tPoint point = parent.getFrame().getLocationOnScreen();\n\t\tDimension size = parent.getFrame().getSize();\n\t\tthis.setLocation(\n\t\t\t\t(int) (point.getX() + ((size.getWidth() - width) / 2)),\n\t\t\t\t(int) (point.getY() + ((size.getHeight() - height) / 2)));\n\t\tsetVisible(true);\n\t}\n\n\tprivate void initComponents() {\n\t\tsetDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n\t\tsetTitle(I18N.getText(\"Window.name.text\"));\n\n\t\t// Features\n\t\tthis.setResizable(false);\n\t\tgetContentPane().setLayout(null);\n\t\tthis.getContentPane().setBackground(parent.getBackground());\n\n\t\tJLabel lblTitle = new JLabel(I18N.getText(\"ExceptionDialog.text.01\"));\n\t\tlblTitle.setFont(new Font(\"Lucida\", Font.BOLD, 20));\n\t\tlblTitle.setBounds(29, 21, 435, 25);\n\t\tgetContentPane().add(lblTitle);\n\n\t\tJLabel lblContent01 = new JLabel(\n\t\t\t\tI18N.getHtmlText(\"ExceptionDialog.text.02\"));\n\t\tlblContent01.setBounds(29, 69, 435, 50);\n\t\tgetContentPane().add(lblContent01);\n\n\t\tJScrollPane scrollPane = new JScrollPane();\n\t\tscrollPane.setBounds(28, 130, 435, 150);\n\t\tgetContentPane().add(scrollPane);\n\n\t\tJTextArea textArea = new JTextArea();\n\t\tscrollPane.setViewportView(textArea);\n\t\ttextArea.append(exception.getClass() + \":\" + exception.getMessage()\n\t\t\t\t+ \"\\n\");\n\t\tStackTraceElement[] stack = exception.getStackTrace();\n\t\tfor (StackTraceElement s : stack) {\n\t\t\ttextArea.append(\" \" + s.toString() + \"\\n\");\n\t\t}\n\n\t\tJLabel lblContent02 = new JLabel(\n\t\t\t\tI18N.getHtmlText(\"ExceptionDialog.text.03\"));\n\t\tlblContent02.setBounds(29, 290, 435, 90);\n\t\tgetContentPane().add(lblContent02);\n\n\t\t// Borders (for debug purposes)\n\t\tif (log.isTraceEnabled()) {\n\t\t\tBorder border = BorderFactory.createLineBorder(Color.black);\n\t\t\tlblTitle.setBorder(border);\n\t\t\tlblContent01.setBorder(border);\n\t\t\tlblContent02.setBorder(border);\n\t\t}\n\t}\n}", "public class LangItem implements Comparable<Object> {\n\tprivate String id;\n\tprivate String description;\n\n\tpublic LangItem(String id, String description) {\n\t\tthis.id = id;\n\t\tthis.description = description;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic String toString() {\n\t\treturn description;\n\t}\n\n\t@Override\n\tpublic int compareTo(Object arg) {\n\t\treturn -((LangItem) arg).getDescription().compareTo(this.getDescription());\n\t}\n}", "public class TranslationCanceled extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -7331490683070646382L;\n\n\tpublic TranslationCanceled() {\n\t\tsuper(\"Translation canceled by user\");\n\t}\n\n}", "public class I18N {\n\n\tpublic static final String MESSAGES = \"lang/messages\";\n\n\tpublic static final String HTML_INIT_TAG = \"<html><font face='Lucid'>\";\n\n\tpublic static final String HTML_END_TAG = \"</font></html>\";\n\n\tpublic enum Html {\n\t\tLINK, BOLD, MONOSPACE\n\t}\n\n\tprivate static I18N singleton = null;\n\n\tprivate Locale locale;\n\n\tpublic I18N() {\n\t\tthis.locale = Locale.getDefault();\n\t}\n\n\tpublic static I18N getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new I18N();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic static String getHtmlText(String key, Html html) {\n\t\tString out = HTML_INIT_TAG;\n\t\tswitch (html) {\n\t\tcase LINK:\n\t\t\tout += \"<a href='#'>\" + getText(key) + \"</a>\";\n\t\t\tbreak;\n\t\tcase BOLD:\n\t\t\tout += \"<b><u>\" + getText(key) + \"</u></b>\";\n\t\t\tbreak;\n\t\tcase MONOSPACE:\n\t\t\tout += \"<pre>\" + getText(key) + \"</pre>\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tout += getText(key);\n\t\t\tbreak;\n\t\t}\n\t\tout += HTML_END_TAG;\n\t\treturn out;\n\t}\n\n\tpublic static String getHtmlText(String key) {\n\t\treturn HTML_INIT_TAG + getText(key) + HTML_END_TAG;\n\t}\n\n\tpublic static String getText(String key) {\n\t\treturn ResourceBundle.getBundle(MESSAGES, getLocale()).getString(key);\n\t}\n\n\tpublic static Locale getLocale() {\n\t\treturn I18N.getSingleton().locale;\n\t}\n\n\tpublic static void setLocale(String locale) {\n\t\tI18N.getSingleton().locale = new Locale(locale);\n\t}\n\n\tpublic static void setLocale(Locale locale) {\n\t\tI18N.getSingleton().locale = locale;\n\t}\n\n}" ]
import io.github.bonigarcia.dualsub.gui.Alert; import io.github.bonigarcia.dualsub.gui.CharsetItem; import io.github.bonigarcia.dualsub.gui.DualSub; import io.github.bonigarcia.dualsub.gui.ExceptionDialog; import io.github.bonigarcia.dualsub.gui.LangItem; import io.github.bonigarcia.dualsub.translate.TranslationCanceled; import io.github.bonigarcia.dualsub.util.I18N; import java.io.File; import javax.swing.ListModel; import javax.swing.SwingWorker;
/* * (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.srt; /** * Worker. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public class Worker extends SwingWorker<Integer, String> { // Parent private DualSub parent; public Worker(DualSub parent) { this.parent = parent; } @Override protected Integer doInBackground() { ListModel<File> leftSrtModel = parent.getLeftSubtitles().getModel(); ListModel<File> rightSrtModel = parent.getRightSubtitles().getModel(); boolean translate = parent.getPanelTranslation().getEnableTranslation() .isSelected(); boolean merge = parent.getPanelTranslation().getRdbtnMerged() .isSelected(); // Input validations (left and right list, output folder) if (leftSrtModel.getSize() == 0 && rightSrtModel.getSize() == 0) {
Alert.error(I18N.getHtmlText("MergeButton.selectFile.error"));
0