Project Name
stringclasses
422 values
Package Name
stringlengths
1
89
Type Name
stringlengths
1
112
NOF
int64
0
1.33k
NOPF
int64
0
1.33k
NOM
int64
0
778
NOPM
int64
0
656
LOC
int64
0
9.42k
WMC
int64
0
2.05k
NC
int64
0
203
DIT
int64
0
9
LCOM
float64
-1
1
FANIN
int64
0
350
FANOUT
int64
0
139
Line no
int64
1
94.8k
code
stringlengths
12
4.03M
ThemeDemo
com.dim.baselibrary
ApplicationTest
0
0
1
1
8
1
0
0
-1
0
0
6
package com.dim.baselibrary; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
ThemeDemo
android.support.v7.app
SkinHelper
1
0
2
2
34
2
0
0
1
1
0
16
package android.support.v7.app; import android.content.Context; import android.os.Build; import android.support.v7.widget.VectorEnabledTintResources; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; /** * Created by dim on 16/5/24. */ public class SkinHelper { private static final String TAG = "SkinHelper"; public static void init(Object ob) { try { Class cls = Class.forName("android.app.SystemServiceRegistry"); Class serviceFetcher = Class.forName("android.app.SystemServiceRegistry$ServiceFetcher"); Field system_service_fetchers = cls.getDeclaredField("SYSTEM_SERVICE_FETCHERS"); system_service_fetchers.setAccessible(true); HashMap o = (HashMap) system_service_fetchers.get(null); final Object layoutInflaterFetcher = o.get(Context.LAYOUT_INFLATER_SERVICE); Object HockLayoutInflaterFetcher = Proxy.newProxyInstance(ob.getClass().getClassLoader(), new Class[]{serviceFetcher}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { LayoutInflater inflater = (LayoutInflater) method.invoke(layoutInflaterFetcher, args); inflater.setFactory2(new LayoutInflaterFactory2()); return inflater; } }); o.put(Context.LAYOUT_INFLATER_SERVICE, HockLayoutInflaterFetcher); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
ThemeDemo
android.support.v7.app
LayoutInflaterFactory2
9
0
7
3
219
39
0
0
0
0
2
45
package android.support.v7.app; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.support.v4.view.ViewCompat; import android.support.v7.view.ContextThemeWrapper; import android.support.v7.widget.AppCompatSeekBar; import android.support.v7.widget.TintContextWrapper; import android.support.v7.widget.VectorEnabledTintResources; import android.util.AttributeSet; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import com.dim.widget.Button; import com.dim.widget.CheckBox; import com.dim.widget.CheckedTextView; import com.dim.widget.CompleteTextView; import com.dim.widget.EditText; import com.dim.widget.FrameLayout; import com.dim.widget.ImageButton; import com.dim.widget.ImageView; import com.dim.widget.LinearLayout; import com.dim.widget.ListView; import com.dim.widget.MultiAutoCompleteTextView; import com.dim.widget.RadioButton; import com.dim.widget.RatingBar; import com.dim.widget.RelativeLayout; import com.dim.widget.Spinner; import com.dim.widget.TextView; import com.dim.widget.WidgetFactor; import com.mingle.baselibrary.R; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** * Created by dim on 15/8/26. */ public class LayoutInflaterFactory2 implements LayoutInflater.Factory2 { static final Class<?>[] sConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; private static final String LOG_TAG = "AppCompatViewInflater"; private static final Map<String, Constructor<? extends View>> sConstructorMap = new ArrayMap<>(); private static final int[] sOnClickAttrs = new int[]{android.R.attr.onClick}; private final Object[] mConstructorArgs = new Object[2]; public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { final boolean isPre21 = Build.VERSION.SDK_INT < 21; return createView(parent, name, context, attrs, false, false, isPre21, VectorEnabledTintResources.shouldBeUsed()); } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { final boolean isPre21 = Build.VERSION.SDK_INT < 21; return createView(null, name, context, attrs, false, false, isPre21, VectorEnabledTintResources.shouldBeUsed()); } public View createView(View parent, final String name, @NonNull Context context, @NonNull AttributeSet attrs, boolean inheritContext, boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) { final Context originalContext = context; // We can emulate Lollipop's android:theme attribute propagating down the view hierarchy // by using the parent's context if (inheritContext && parent != null) { context = parent.getContext(); } if (readAndroidTheme || readAppTheme) { // We then apply the theme on the context, if specified context = themifyContext(context, attrs, readAndroidTheme, readAppTheme); } if (wrapContext) { context = TintContextWrapper.wrap(context); } android.view.View view = WidgetFactor.getInstant().parseWidget(name,context,attrs); // We need to 'inject' our tint aware Views in place of the standard framework versions switch (name) { case "EditText": view = new EditText(context, attrs); break; case "View": view = new com.dim.widget.View(context, attrs); break; case "Spinner": view = new Spinner(context, attrs); break; case "CheckBox": view = new CheckBox(context, attrs); break; case "ListView": view = new ListView(context, attrs); break; case "RadioButton": view = new RadioButton(context, attrs); break; case "ImageView": view = new ImageView(context, attrs); break; case "ImageButton": view = new ImageButton(context, attrs); break; case "CheckedTextView": view = new CheckedTextView(context, attrs); break; case "AutoCompleteTextView": view = new CompleteTextView(context, attrs); break; case "MultiAutoCompleteTextView": view = new MultiAutoCompleteTextView(context, attrs); break; case "RatingBar": view = new RatingBar(context, attrs); break; case "Button": view = new Button(context, attrs); break; case "TextView": view = new TextView(context, attrs); break; case "RelativeLayout": view = new RelativeLayout(context, attrs); break; case "FrameLayout": view = new FrameLayout(context, attrs); break; case "LinearLayout": view = new LinearLayout(context, attrs); break; case "SeekBar": view = new AppCompatSeekBar(context, attrs); break; } if (view == null && originalContext != context) { // If the original context does not equal our themed context, then we need to manually // inflate it using the name so that android:theme takes effect. return createViewFromTag(context, name, attrs); } if (view != null) { // If we have created a view, check it's android:onClick checkOnClickListener(view, attrs); } return view; } private View createViewFromTag(Context context, String name, AttributeSet attrs) { if (name.equals("view")) { name = attrs.getAttributeValue(null, "class"); } try { mConstructorArgs[0] = context; mConstructorArgs[1] = attrs; if (-1 == name.indexOf('.')) { // try the android.widget prefix first... return createView(context, name, "android.widget."); } else { return createView(context, name, null); } } catch (Exception e) { // We do not want to catch these, lets return null and let the actual LayoutInflater // try return null; } finally { // Don't retain references on context. mConstructorArgs[0] = null; mConstructorArgs[1] = null; } } private View createView(Context context, String name, String prefix) throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = sConstructorMap.get(name); try { if (constructor == null) { // Class not found in the cache, see if it's real, and try to add it Class<? extends View> clazz = context.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); constructor = clazz.getConstructor(sConstructorSignature); sConstructorMap.put(name, constructor); } constructor.setAccessible(true); return constructor.newInstance(mConstructorArgs); } catch (Exception e) { // We do not want to catch these, lets return null and let the actual LayoutInflater // try return null; } } /** * Allows us to emulate the {@code android:theme} attribute for devices before L. */ private static Context themifyContext(Context context, AttributeSet attrs, boolean useAndroidTheme, boolean useAppTheme) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0); int themeId = 0; if (useAndroidTheme) { // First try reading android:theme if enabled themeId = a.getResourceId(R.styleable.View_android_theme, 0); } if (useAppTheme && themeId == 0) { // ...if that didn't work, try reading app:theme (for legacy reasons) if enabled themeId = a.getResourceId(R.styleable.View_theme, 0); if (themeId != 0) { Log.i(LOG_TAG, "app:theme is now deprecated. " + "Please move to using android:theme instead."); } } a.recycle(); if (themeId != 0 && (!(context instanceof ContextThemeWrapper) || ((ContextThemeWrapper) context).getThemeResId() != themeId)) { // If the context isn't a ContextThemeWrapper, or it is but does not have // the same theme as we need, wrap it in a new wrapper context = new ContextThemeWrapper(context, themeId); } return context; } /** * android:onClick doesn't handle views with a ContextWrapper context. This method * backports new framework functionality to traverse the Context wrappers to find a * suitable target. */ private void checkOnClickListener(View view, AttributeSet attrs) { final Context context = view.getContext(); if (!(context instanceof ContextWrapper) || (Build.VERSION.SDK_INT >= 15 && !ViewCompat.hasOnClickListeners(view))) { // Skip our compat functionality if: the Context isn't a ContextWrapper, or // the view doesn't have an OnClickListener (we can only rely on this on API 15+ so // always use our compat code on older devices) return; } final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs); final String handlerName = a.getString(0); if (handlerName != null) { view.setOnClickListener(new DeclaredOnClickListener(view, handlerName)); } a.recycle(); } /** * An implementation of OnClickListener that attempts to lazily load a * named click handling method from a parent or ancestor context. */ private static class DeclaredOnClickListener implements View.OnClickListener { private final View mHostView; private final String mMethodName; private Method mResolvedMethod; private Context mResolvedContext; public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { mHostView = hostView; mMethodName = methodName; } @Override public void onClick(@NonNull View v) { if (mResolvedMethod == null) { resolveMethod(mHostView.getContext(), mMethodName); } try { mResolvedMethod.invoke(mResolvedContext, v); } catch (IllegalAccessException e) { throw new IllegalStateException( "Could not execute non-public method for android:onClick", e); } catch (InvocationTargetException e) { throw new IllegalStateException( "Could not execute method for android:onClick", e); } } @NonNull private void resolveMethod(@Nullable Context context, @NonNull String name) { while (context != null) { try { if (!context.isRestricted()) { final Method method = context.getClass().getMethod(mMethodName, View.class); if (method != null) { mResolvedMethod = method; mResolvedContext = context; return; } } } catch (NoSuchMethodException e) { // Failed to find method, keep searching up the hierarchy. } if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { // Can't search up the hierarchy, null out and fail. context = null; } } final int id = mHostView.getId(); final String idText = id == View.NO_ID ? "" : " with id '" + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; throw new IllegalStateException("Could not find method " + mMethodName + "(View) in a parent or ancestor Context for android:onClick " + "attribute defined on view " + mHostView.getClass() + idText); } } }
ThemeDemo
android.support.v7.app
LayoutInflaterFactory2.DeclaredOnClickListener
4
0
0
0
52
0
0
0
-1
0
1
274
package android.support.v7.app; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.support.v4.view.ViewCompat; import android.support.v7.view.ContextThemeWrapper; import android.support.v7.widget.AppCompatSeekBar; import android.support.v7.widget.TintContextWrapper; import android.support.v7.widget.VectorEnabledTintResources; import android.util.AttributeSet; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import com.dim.widget.Button; import com.dim.widget.CheckBox; import com.dim.widget.CheckedTextView; import com.dim.widget.CompleteTextView; import com.dim.widget.EditText; import com.dim.widget.FrameLayout; import com.dim.widget.ImageButton; import com.dim.widget.ImageView; import com.dim.widget.LinearLayout; import com.dim.widget.ListView; import com.dim.widget.MultiAutoCompleteTextView; import com.dim.widget.RadioButton; import com.dim.widget.RatingBar; import com.dim.widget.RelativeLayout; import com.dim.widget.Spinner; import com.dim.widget.TextView; import com.dim.widget.WidgetFactor; import com.mingle.baselibrary.R; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** * Created by dim on 15/8/26. */ public class LayoutInflaterFactory2 implements LayoutInflater.Factory2 { static final Class<?>[] sConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; private static final String LOG_TAG = "AppCompatViewInflater"; private static final Map<String, Constructor<? extends View>> sConstructorMap = new ArrayMap<>(); private static final int[] sOnClickAttrs = new int[]{android.R.attr.onClick}; private final Object[] mConstructorArgs = new Object[2]; public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { final boolean isPre21 = Build.VERSION.SDK_INT < 21; return createView(parent, name, context, attrs, false, false, isPre21, VectorEnabledTintResources.shouldBeUsed()); } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { final boolean isPre21 = Build.VERSION.SDK_INT < 21; return createView(null, name, context, attrs, false, false, isPre21, VectorEnabledTintResources.shouldBeUsed()); } public View createView(View parent, final String name, @NonNull Context context, @NonNull AttributeSet attrs, boolean inheritContext, boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) { final Context originalContext = context; // We can emulate Lollipop's android:theme attribute propagating down the view hierarchy // by using the parent's context if (inheritContext && parent != null) { context = parent.getContext(); } if (readAndroidTheme || readAppTheme) { // We then apply the theme on the context, if specified context = themifyContext(context, attrs, readAndroidTheme, readAppTheme); } if (wrapContext) { context = TintContextWrapper.wrap(context); } android.view.View view = WidgetFactor.getInstant().parseWidget(name,context,attrs); // We need to 'inject' our tint aware Views in place of the standard framework versions switch (name) { case "EditText": view = new EditText(context, attrs); break; case "View": view = new com.dim.widget.View(context, attrs); break; case "Spinner": view = new Spinner(context, attrs); break; case "CheckBox": view = new CheckBox(context, attrs); break; case "ListView": view = new ListView(context, attrs); break; case "RadioButton": view = new RadioButton(context, attrs); break; case "ImageView": view = new ImageView(context, attrs); break; case "ImageButton": view = new ImageButton(context, attrs); break; case "CheckedTextView": view = new CheckedTextView(context, attrs); break; case "AutoCompleteTextView": view = new CompleteTextView(context, attrs); break; case "MultiAutoCompleteTextView": view = new MultiAutoCompleteTextView(context, attrs); break; case "RatingBar": view = new RatingBar(context, attrs); break; case "Button": view = new Button(context, attrs); break; case "TextView": view = new TextView(context, attrs); break; case "RelativeLayout": view = new RelativeLayout(context, attrs); break; case "FrameLayout": view = new FrameLayout(context, attrs); break; case "LinearLayout": view = new LinearLayout(context, attrs); break; case "SeekBar": view = new AppCompatSeekBar(context, attrs); break; } if (view == null && originalContext != context) { // If the original context does not equal our themed context, then we need to manually // inflate it using the name so that android:theme takes effect. return createViewFromTag(context, name, attrs); } if (view != null) { // If we have created a view, check it's android:onClick checkOnClickListener(view, attrs); } return view; } private View createViewFromTag(Context context, String name, AttributeSet attrs) { if (name.equals("view")) { name = attrs.getAttributeValue(null, "class"); } try { mConstructorArgs[0] = context; mConstructorArgs[1] = attrs; if (-1 == name.indexOf('.')) { // try the android.widget prefix first... return createView(context, name, "android.widget."); } else { return createView(context, name, null); } } catch (Exception e) { // We do not want to catch these, lets return null and let the actual LayoutInflater // try return null; } finally { // Don't retain references on context. mConstructorArgs[0] = null; mConstructorArgs[1] = null; } } private View createView(Context context, String name, String prefix) throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = sConstructorMap.get(name); try { if (constructor == null) { // Class not found in the cache, see if it's real, and try to add it Class<? extends View> clazz = context.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); constructor = clazz.getConstructor(sConstructorSignature); sConstructorMap.put(name, constructor); } constructor.setAccessible(true); return constructor.newInstance(mConstructorArgs); } catch (Exception e) { // We do not want to catch these, lets return null and let the actual LayoutInflater // try return null; } } /** * Allows us to emulate the {@code android:theme} attribute for devices before L. */ private static Context themifyContext(Context context, AttributeSet attrs, boolean useAndroidTheme, boolean useAppTheme) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0); int themeId = 0; if (useAndroidTheme) { // First try reading android:theme if enabled themeId = a.getResourceId(R.styleable.View_android_theme, 0); } if (useAppTheme && themeId == 0) { // ...if that didn't work, try reading app:theme (for legacy reasons) if enabled themeId = a.getResourceId(R.styleable.View_theme, 0); if (themeId != 0) { Log.i(LOG_TAG, "app:theme is now deprecated. " + "Please move to using android:theme instead."); } } a.recycle(); if (themeId != 0 && (!(context instanceof ContextThemeWrapper) || ((ContextThemeWrapper) context).getThemeResId() != themeId)) { // If the context isn't a ContextThemeWrapper, or it is but does not have // the same theme as we need, wrap it in a new wrapper context = new ContextThemeWrapper(context, themeId); } return context; } /** * android:onClick doesn't handle views with a ContextWrapper context. This method * backports new framework functionality to traverse the Context wrappers to find a * suitable target. */ private void checkOnClickListener(View view, AttributeSet attrs) { final Context context = view.getContext(); if (!(context instanceof ContextWrapper) || (Build.VERSION.SDK_INT >= 15 && !ViewCompat.hasOnClickListeners(view))) { // Skip our compat functionality if: the Context isn't a ContextWrapper, or // the view doesn't have an OnClickListener (we can only rely on this on API 15+ so // always use our compat code on older devices) return; } final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs); final String handlerName = a.getString(0); if (handlerName != null) { view.setOnClickListener(new DeclaredOnClickListener(view, handlerName)); } a.recycle(); } /** * An implementation of OnClickListener that attempts to lazily load a * named click handling method from a parent or ancestor context. */ private static class DeclaredOnClickListener implements View.OnClickListener { private final View mHostView; private final String mMethodName; private Method mResolvedMethod; private Context mResolvedContext; public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { mHostView = hostView; mMethodName = methodName; } @Override public void onClick(@NonNull View v) { if (mResolvedMethod == null) { resolveMethod(mHostView.getContext(), mMethodName); } try { mResolvedMethod.invoke(mResolvedContext, v); } catch (IllegalAccessException e) { throw new IllegalStateException( "Could not execute non-public method for android:onClick", e); } catch (InvocationTargetException e) { throw new IllegalStateException( "Could not execute method for android:onClick", e); } } @NonNull private void resolveMethod(@Nullable Context context, @NonNull String name) { while (context != null) { try { if (!context.isRestricted()) { final Method method = context.getClass().getMethod(mMethodName, View.class); if (method != null) { mResolvedMethod = method; mResolvedContext = context; return; } } } catch (NoSuchMethodException e) { // Failed to find method, keep searching up the hierarchy. } if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { // Can't search up the hierarchy, null out and fail. context = null; } } final int id = mHostView.getId(); final String idText = id == View.NO_ID ? "" : " with id '" + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; throw new IllegalStateException("Could not find method " + mMethodName + "(View) in a parent or ancestor Context for android:onClick " + "attribute defined on view " + mHostView.getClass() + idText); } } }
ThemeDemo
com.dim.skin
SkinStyle
0
0
0
0
4
0
0
0
-1
29
0
3
package com.dim.skin; /** * Created by dim on 15/8/27. */ public enum SkinStyle { Dark, Light//默认Light }
ThemeDemo
com.dim.skin
SkinConfig
0
0
2
2
14
2
0
0
-1
6
1
7
package com.dim.skin; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; /** * Created by zzz40500 on 15/8/27. */ public class SkinConfig { public static SkinStyle getSkinStyle(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", Activity.MODE_PRIVATE); boolean nightMode = sharedPreferences.getBoolean("nightMode", false); return nightMode ? SkinStyle.Dark : SkinStyle.Light; } public static void setSkinStyle(Context context, SkinStyle skinStyle) { SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", Activity.MODE_PRIVATE).edit(); editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); } }
ThemeDemo
com.dim.skin
SkinEnable
0
0
1
0
6
1
0
0
-1
0
1
3
package com.dim.skin; /** * Created by zzz40500 on 15/8/27. */ public interface SkinEnable { void setSkinStyle(SkinStyle skinStyle); }
ThemeDemo
com.dim.skin.hepler
SkinHelper
2
0
8
8
46
12
2
0
0.625
17
5
13
package com.dim.skin.hepler; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.LinearLayout; /** * /** * * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by dim on 15/8/27. */ public abstract class SkinHelper { private SkinStyle mSkinStyle; private Context mContext; public SkinHelper(Context context) { mSkinStyle = SkinConfig.getSkinStyle(context); mContext = context; } public abstract void init(View view, AttributeSet attrs); public void setSkinStyle(SkinStyle skinStyle) { mSkinStyle = skinStyle; } public static SkinHelper create(View v) { if (v instanceof TextView) { return new TextViewSkinHelper(v.getContext()); } else if (v instanceof ListView) { return new ListViewSkinHelper(v.getContext()); } else if (v instanceof LinearLayout) { return new LinearLayoutSkinHelper(v.getContext()); } return new ViewSkinHelper(v.getContext()); } public SkinStyle getSkinStyle() { return mSkinStyle; } public static DefaultViewSkinHelper createDeFault(Context context) { return new DefaultViewSkinHelper(context); } public abstract void setCurrentTheme(); public void preDraw(View view) { if (!getSkinStyle().equals(SkinConfig.getSkinStyle(view.getContext()))) { SkinCompat.changeSkinView(view,SkinConfig.getSkinStyle(view.getContext())); } } }
ThemeDemo
com.dim.skin.hepler
ViewSkinHelper
9
1
4
4
62
14
3
1
0.5
0
2
11
package com.dim.skin.hepler; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class ViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView; protected SkinStyle mSkinStyle = SkinStyle.Light; private int mLightBackgroundRes = -1; private int mLightBackgroundColor = -1; private int mDarkBackgroundRes = -1; private int mDarkBackgroundColor = -1; public boolean mEnable = true; public ViewSkinHelper(Context context) { super(context); } /** * 设置背景色 * Set background Color */ public void init(View view, AttributeSet attrs) { mView = view; if (attrs == null) { mEnable = false; return; } mLightBackgroundRes = attrs.getAttributeResourceValue(ANDROIDXML, "background", -1); mDarkBackgroundRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightBackground", -1); if (mLightBackgroundRes == -1) { mLightBackgroundColor = attrs.getAttributeIntValue(ANDROIDXML, "background", -1); } if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if (!mEnable) { return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } } } @Override public void setCurrentTheme() { if (SkinConfig.getSkinStyle(mView.getContext()) == SkinStyle.Dark) { setSkinStyle(SkinStyle.Dark); } } }
ThemeDemo
com.dim.skin.hepler
LinearLayoutSkinHelper
2
0
3
3
52
10
0
2
0.666667
0
1
12
package com.dim.skin.hepler; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.dim.skin.SkinStyle; /** * Created by zzz40500 on 15/9/4. */ public class LinearLayoutSkinHelper extends ViewSkinHelper { private int mDividerRes; private int mDarkDividerRes; public LinearLayoutSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); mDarkDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightDivider", -1); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if (!mEnable) { return; } super.setSkinStyle(skinStyle); if (skinStyle == SkinStyle.Light) { if (mDividerRes != -1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { LinearLayout linearLayout = (LinearLayout) mView; try { linearLayout.setDividerDrawable(mView.getResources().getDrawable(mDividerRes)); } catch (Exception e) { e.printStackTrace(); } } } } else { if (mDarkDividerRes != -1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { LinearLayout linearLayout = (LinearLayout) mView; try { linearLayout.setDividerDrawable(mView.getResources().getDrawable(mDarkDividerRes)); } catch (Exception e) { e.printStackTrace(); } } } } } }
ThemeDemo
com.dim.skin.hepler
SkinCompat
0
0
5
5
51
15
0
0
-1
4
3
12
package com.dim.skin.hepler; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */ public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); changeSkinStyle(view, skinStyle); SkinConfig.setSkinStyle(activity, skinStyle); // } if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(View v, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) { if (view instanceof SkinEnable) { ((SkinEnable) view).setSkinStyle(skinStyle); } else { ViewGroup.LayoutParams params = view.getLayoutParams(); if (params instanceof SLayoutParamsI) { ((SLayoutParamsI) params).setSkinStyle(skinStyle); } } } }
ThemeDemo
com.dim.skin.hepler
SkinCompat.SkinStyleChangeListener
0
0
0
0
4
0
0
0
-1
0
0
17
package com.dim.skin.hepler; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */ public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); changeSkinStyle(view, skinStyle); SkinConfig.setSkinStyle(activity, skinStyle); // } if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(View v, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) { if (view instanceof SkinEnable) { ((SkinEnable) view).setSkinStyle(skinStyle); } else { ViewGroup.LayoutParams params = view.getLayoutParams(); if (params instanceof SLayoutParamsI) { ((SLayoutParamsI) params).setSkinStyle(skinStyle); } } } }
ThemeDemo
com.dim.skin.hepler
DefaultViewSkinHelper
13
1
5
5
95
23
0
1
0.4
7
3
12
package com.dim.skin.hepler; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class DefaultViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView; protected SkinStyle mSkinStyle = SkinStyle.Light; private int mLightBackgroundRes = -1; private int mLightBackgroundColor = -1; private int mDarkBackgroundRes = -1; private int mDarkBackgroundColor = -1; private int nightTextColor; private int mNightTextColorRes; private int mLightTextColor; private int mLightTextColorRes; public boolean mEnable =true; public DefaultViewSkinHelper(Context context) { super(context); } /** * 设置背景色 * Set background Color */ public void init(View view, AttributeSet attrs) { mView = view; if (attrs == null) { mEnable = false; return; } mLightBackgroundRes = attrs.getAttributeResourceValue(ANDROIDXML, "background", -1); mDarkBackgroundRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightBackground", -1); if (mLightBackgroundRes == -1) { mLightBackgroundColor = attrs.getAttributeIntValue(ANDROIDXML, "background", -1); } if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } mLightTextColorRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColor", -1); if (mLightTextColorRes == -1) { mLightTextColor = attrs.getAttributeIntValue(ANDROIDXML, "textColor", -1); } mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { nightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } } public void setView(View view){ this.mView=view; } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if(!mEnable){ return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); } if(mView instanceof TextView) { android.widget.TextView tv = (android.widget.TextView) mView; if (mNightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mNightTextColorRes)); } else if (nightTextColor != -1) { tv.setTextColor(nightTextColor); } } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } if(mView instanceof TextView) { android.widget.TextView tv= (android.widget.TextView) mView; if (mLightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mLightTextColorRes)); } else if (mLightTextColor != -1) { tv.setTextColor(mLightTextColor); } } } } @Override public void setCurrentTheme() { if(SkinConfig.getSkinStyle(mView.getContext())== SkinStyle.Dark){ setSkinStyle(SkinStyle.Dark); } } }
ThemeDemo
com.dim.skin.hepler
TextViewSkinHelper
16
0
3
3
132
30
0
2
0.666667
0
1
10
package com.dim.skin.hepler; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.dim.skin.SkinStyle; /** * <attr name="nightTextColor" format="color"/> * <attr name="nightTextColorHighlight" format="color"/> * <attr name="nightTextColorAppearance" format="reference"/> * <attr name="nightTextColorLink" format="reference"/> * textColorHint * Created by dim on 15/9/4. */ public class TextViewSkinHelper extends ViewSkinHelper { private int mNightTextColor; private int mNightTextColorRes; private int mNightTextColorHighlight; private int mNightTextColorAppearance; private int mNightTextColorLinkRes; private int mNightTextColorLink; private int mNightTextColorHintRes; private int mNightTextColorHint; private int mLightTextColor; private int mLightTextColorRes; private int mLightTextColorHighlight; private int mLightTextAppearance; private int mLightTextColorLinkRes; private int mLightTextColorLink; private int mLightTextColorHintRes; private int mLightTextColorHint; public TextViewSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mLightTextColorRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColor", -1); if (mLightTextColorRes == -1) { mLightTextColor = attrs.getAttributeIntValue(ANDROIDXML, "textColor", -1); } int mLightTextColorHighlightRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColorHighlight", -1); if (mLightTextColorHighlightRes == -1) { mLightTextColorHighlight = attrs.getAttributeIntValue(ANDROIDXML, "textColorHighlight", -1); } else { mLightTextColorHighlight = view.getContext().getResources().getColor(mLightTextColorHighlightRes); } mLightTextColorLinkRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColorLink", -1); if (mLightTextColorLinkRes == -1) { mLightTextColorLink = attrs.getAttributeIntValue(ANDROIDXML, "textColorLink", -1); } mLightTextColorHintRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColorHint", -1); if (mLightTextColorHintRes == -1) { mLightTextColorHint = attrs.getAttributeIntValue(ANDROIDXML, "textColorHint", -1); } mLightTextAppearance = attrs.getAttributeResourceValue(ANDROIDXML, "textAppearance", -1); mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { mNightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } int mNightTextColorHighlightRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); if (mNightTextColorHighlightRes != -1) { mNightTextColorHighlight = view.getContext().getResources().getColor(mNightTextColorHighlightRes); } else { mNightTextColorHighlight = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); } mNightTextColorLinkRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorLink", -1); if (mNightTextColorLinkRes == -1) { mNightTextColorLink = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorLink", -1); } mNightTextColorHintRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHint", -1); if (mNightTextColorHintRes == -1) { mNightTextColorHint = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHint", -1); } mNightTextColorAppearance = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorAppearance", -1); } @Override public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if(!mEnable){ return; } super.setSkinStyle(skinStyle); if (skinStyle == SkinStyle.Dark) { TextView tv = (TextView) mView; if (mNightTextColorAppearance != -1) { tv.setTextAppearance(tv.getContext(), mNightTextColorAppearance); } if (mNightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mNightTextColorRes)); } else if (mNightTextColor != -1) { tv.setTextColor(mNightTextColor); } if (mNightTextColorHighlight != -1) { tv.setHighlightColor(mNightTextColorHighlight); } if (mNightTextColorLinkRes != -1) { tv.setLinkTextColor(mView.getResources().getColorStateList(mNightTextColorLinkRes)); } else if (mNightTextColorLink != -1) { tv.setLinkTextColor(mNightTextColorLink); } if (mNightTextColorHintRes != -1) { tv.setHintTextColor(mView.getResources().getColorStateList(mNightTextColorHintRes)); } else if (mNightTextColorHint != -1) { tv.setHintTextColor(mNightTextColorHint); } }else{ TextView tv = (TextView) mView; if (mLightTextAppearance != -1) { tv.setTextAppearance(tv.getContext(), mLightTextAppearance); } if (mLightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mLightTextColorRes)); } else if (mLightTextColor != -1) { tv.setTextColor(mLightTextColor); } if (mLightTextColorHighlight != -1) { tv.setHighlightColor(mLightTextColorHighlight); } if (mLightTextColorLinkRes != -1) { tv.setLinkTextColor(mView.getResources().getColorStateList(mLightTextColorLinkRes)); } else if (mLightTextColorLink != -1) { tv.setLinkTextColor(mLightTextColorLink); } if (mLightTextColorHintRes != -1) { tv.setHintTextColor(mView.getResources().getColorStateList(mLightTextColorHintRes)); } else if (mLightTextColorHint != -1) { tv.setHintTextColor(mLightTextColorHint); } } } }
ThemeDemo
com.dim.skin.hepler
ListViewSkinHelper
4
0
3
3
87
13
0
2
0.666667
0
1
11
package com.dim.skin.hepler; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import com.dim.skin.SkinStyle; /** * Created by zzz40500 on 15/9/4. */ public class ListViewSkinHelper extends ViewSkinHelper { private int mNightLVDivider = -1; private int mNightLVDividerRes = -1; private int mDivider = -1; private int mDividerRes = -1; public ListViewSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); if (mDividerRes == -1) { mDivider = attrs.getAttributeIntValue(ANDROIDXML, "divider", -1); } mNightLVDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightLVDivider", -1); if (mNightLVDividerRes != -1) { mNightLVDivider = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightLVDivider", -1); } } @Override public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if(!mEnable){ return; } super.setSkinStyle(skinStyle); ListView listView = (ListView) mView; int dividerHeight = listView.getDividerHeight(); if (dividerHeight == -1) { return; } if (skinStyle == SkinStyle.Dark) { if (mNightLVDividerRes != -1) { try { listView.setDivider(new ColorDrawable(mView.getContext().getResources().getColor(mNightLVDividerRes))); } catch (Exception e) { try { listView.setDivider(mView.getContext().getResources().getDrawable(mNightLVDividerRes)); } catch (Exception e2) { e2.printStackTrace(); } } listView.setDividerHeight(dividerHeight); } else if (mNightLVDivider != -1) { listView.setDivider(new ColorDrawable(mNightLVDivider)); listView.setDividerHeight(dividerHeight); } else { listView.setDivider(null); listView.setDividerHeight(dividerHeight); } } else { if (mDividerRes != -1) { try { listView.setDivider(new ColorDrawable(mView.getContext().getResources().getColor(mDividerRes))); } catch (Exception e) { try { listView.setDivider(mView.getContext().getResources().getDrawable(mDividerRes)); } catch (Exception e2) { e2.printStackTrace(); } } listView.setDividerHeight(dividerHeight); } else if (mDivider != -1) { listView.setDivider(new ColorDrawable(mDivider)); listView.setDividerHeight(dividerHeight); } else { listView.setDivider(null); listView.setDividerHeight(dividerHeight); } } } }
ThemeDemo
com.dim.listener
SingleClickHelper
2
0
1
1
15
2
0
0
0
2
0
4
package com.dim.listener; import android.os.SystemClock; /** * Created by zzz40500 on 15/8/26. */ public class SingleClickHelper { private static long L_CLICK_INTERVAL = 1200; private long preClickTime; public boolean clickEnable(){ long clickTime= SystemClock.elapsedRealtime(); if ( clickTime - preClickTime > L_CLICK_INTERVAL){ preClickTime=clickTime; return true; } return false; } }
ThemeDemo
com.dim.listener
SingleItemClickListener
2
0
2
2
15
3
0
0
0
0
1
5
package com.dim.listener; import android.view.View; import android.widget.AdapterView; /** * Created by zzz40500 on 15/8/26. */ public class SingleItemClickListener implements AdapterView.OnItemClickListener { private AdapterView.OnItemClickListener singleItemClickListener; private SingleClickHelper singleClickhelper =new SingleClickHelper(); public SingleItemClickListener(AdapterView.OnItemClickListener singleItemClickListener) { this.singleItemClickListener = singleItemClickListener; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(singleItemClickListener != null && singleClickhelper.clickEnable()){ singleItemClickListener.onItemClick(parent, view, position, id); } } }
ThemeDemo
com.dim.listener
SingleClickListener
2
0
2
2
15
3
0
0
0
0
1
6
package com.dim.listener; import android.view.View; /** * Created by zzz40500 on 15/8/26. */ public class SingleClickListener implements View.OnClickListener { private View.OnClickListener mListener; private SingleClickHelper singleClickhelper =new SingleClickHelper(); public SingleClickListener(View.OnClickListener mListener) { this.mListener = mListener; } @Override public void onClick(View v) { if (singleClickhelper.clickEnable()&& mListener != null) { mListener.onClick(v); } } }
ThemeDemo
com.dim.widget
ListView
2
0
10
9
44
10
0
0
0.4
0
3
17
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.skin.SkinStyle; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.listener.SingleItemClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class ListView extends android.widget.ListView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public ListView(Context context) { super(context); init(null); } public ListView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public ListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void setOnItemClickListener(OnItemClickListener listener) { super.setOnItemClickListener(new SingleItemClickListener(listener)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
MultiAutoCompleteTextView
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatMultiAutoCompleteTextView; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class MultiAutoCompleteTextView extends AppCompatMultiAutoCompleteTextView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public MultiAutoCompleteTextView(Context context) { super(context); init(null); } public MultiAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public MultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
LinearLayout
3
0
13
11
85
14
0
0
0.538462
0
5
21
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.*; import android.view.View; import com.dim.circletreveal.CircleRevealHelper; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public LinearLayout(Context context) { super(context); init(null); } public LinearLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setDividerDrawable(Drawable divider) { super.setDividerDrawable(divider); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override protected LayoutParams generateDefaultLayoutParams() { return super.generateDefaultLayoutParams(); } public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(int width, int height, float weight) { super(width, height, weight); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget
LinearLayout.SLayoutParams
1
0
0
0
29
0
0
1
-1
0
1
112
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.*; import android.view.View; import com.dim.circletreveal.CircleRevealHelper; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public LinearLayout(Context context) { super(context); init(null); } public LinearLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setDividerDrawable(Drawable divider) { super.setDividerDrawable(divider); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override protected LayoutParams generateDefaultLayoutParams() { return super.generateDefaultLayoutParams(); } public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(int width, int height, float weight) { super(width, height, weight); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget
EditText
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealEnable; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class EditText extends AppCompatEditText implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public EditText(Context context) { super(context); init(null); } public EditText(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public EditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
SLayoutParamsI
0
0
1
0
6
1
3
0
-1
0
1
5
package com.dim.widget; import com.dim.skin.SkinStyle; /** * Created by zzz40500 on 15/9/5. */ public interface SLayoutParamsI { void setSkinStyle(SkinStyle skinStyle); }
ThemeDemo
com.dim.widget
RatingBar
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatRatingBar; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class RatingBar extends AppCompatRatingBar implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public RatingBar(Context context) { super(context); init(null); } public RatingBar(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public RatingBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
ImageView
2
0
9
8
45
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * @author zwm * @version 2.0 * @ClassName ImageView * @Description TODO(这里用一句话描述这个类的作用) * @date 2015/7/9. */ public class ImageView extends android.widget.ImageView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public ImageView(Context context) { super(context); init(null); } public ImageView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public ImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
RelativeLayout
3
0
11
10
76
12
0
0
0.454545
0
5
21
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.*; import android.view.View; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class RelativeLayout extends android.widget.RelativeLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public RelativeLayout(Context context) { super(context); init(null); } public RelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public RelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } public class SLayoutParams extends android.widget.RelativeLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(android.view.View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(android.widget.RelativeLayout.LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget
RelativeLayout.SLayoutParams
1
0
0
0
26
0
0
1
-1
0
1
99
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.*; import android.view.View; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class RelativeLayout extends android.widget.RelativeLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public RelativeLayout(Context context) { super(context); init(null); } public RelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public RelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } public class SLayoutParams extends android.widget.RelativeLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(android.view.View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(android.widget.RelativeLayout.LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget
Button
2
0
9
8
41
9
0
0
0.333333
0
3
17
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatButton; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class Button extends AppCompatButton implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public Button(Context context) { super(context); init(null); } public Button(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public Button(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
TextView
2
0
9
8
46
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.skin.SkinStyle; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * @attr ref android.R.styleable#TextView_shadowColor * Created by zzz40500 on 15/8/26. */ public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public TextView(Context context) { super(context); init(null); } public TextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public TextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
CheckBox
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class CheckBox extends AppCompatCheckBox implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public CheckBox(Context context) { super(context); init(null); } public CheckBox(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public CheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
View
2
0
9
8
47
9
0
0
0.333333
7
3
18
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinCompat; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#View_scrollbarStyle * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by zzz40500 on 15/8/27. */ public class View extends android.view.View implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public View(Context context) { super(context); init(null); } public View(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public View(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
CompleteTextView
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatAutoCompleteTextView; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealEnable; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class CompleteTextView extends AppCompatAutoCompleteTextView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public CompleteTextView(Context context) { super(context); init(null); } public CompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public CompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
Spinner
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatSpinner; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealEnable; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class Spinner extends AppCompatSpinner implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public Spinner(Context context) { super(context); init(null); } public Spinner(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public Spinner(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
WidgetFactor
2
0
3
3
25
5
0
0
0.666667
1
0
6
package com.dim.widget; import android.content.Context; import android.util.AttributeSet; /** * Created by zzz40500 on 15/9/5. */ public class WidgetFactor { private static WidgetFactor instant; public static WidgetFactor getInstant() { if(instant == null){ instant=new WidgetFactor(); } return instant; } private WidgetParser mWidgetParser; public android.view.View parseWidget(String name, Context context, AttributeSet attrs){ if(mWidgetParser != null){ return mWidgetParser.parseWidget(name,context,attrs); } return null; } public void setWidgetParser(WidgetParser widgetParser) { mWidgetParser = widgetParser; } public interface WidgetParser { android.view.View parseWidget(String name, Context context, AttributeSet attrs); } }
ThemeDemo
com.dim.widget
WidgetFactor.WidgetParser
0
0
0
0
3
0
0
0
-1
0
0
38
package com.dim.widget; import android.content.Context; import android.util.AttributeSet; /** * Created by zzz40500 on 15/9/5. */ public class WidgetFactor { private static WidgetFactor instant; public static WidgetFactor getInstant() { if(instant == null){ instant=new WidgetFactor(); } return instant; } private WidgetParser mWidgetParser; public android.view.View parseWidget(String name, Context context, AttributeSet attrs){ if(mWidgetParser != null){ return mWidgetParser.parseWidget(name,context,attrs); } return null; } public void setWidgetParser(WidgetParser widgetParser) { mWidgetParser = widgetParser; } public interface WidgetParser { android.view.View parseWidget(String name, Context context, AttributeSet attrs); } }
ThemeDemo
com.dim.widget
ImageButton
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class ImageButton extends android.widget.ImageButton implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public ImageButton(Context context) { super(context); init(null); } public ImageButton(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public ImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
RadioButton
2
0
9
8
41
9
0
0
0.333333
0
3
16
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatRadioButton; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class RadioButton extends AppCompatRadioButton implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public RadioButton(Context context) { super(context); init(null); } public RadioButton(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public RadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
CheckedTextView
2
0
9
8
41
9
0
0
0.333333
0
3
17
package com.dim.widget; import android.content.Context; import android.graphics.Canvas; import android.support.v7.widget.AppCompatCheckedTextView; import android.util.AttributeSet; import com.dim.circletreveal.CircleRevealEnable; import com.dim.circletreveal.CircleRevealHelper; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinHelper; import com.dim.skin.SkinEnable; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class CheckedTextView extends AppCompatCheckedTextView implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public CheckedTextView(Context context) { super(context); init(null); } public CheckedTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public CheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } }
ThemeDemo
com.dim.widget
FrameLayout
3
0
11
10
76
12
0
0
0.454545
0
4
20
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.*; import com.dim.circletreveal.CircleRevealHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class FrameLayout extends android.widget.FrameLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public FrameLayout(Context context) { super(context); init(null); } public FrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public FrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public void addView(android.view.View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override public FrameLayout.LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } public class SLayoutParams extends android.widget.FrameLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(android.view.View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(android.widget.FrameLayout.LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget
FrameLayout.SLayoutParams
1
0
0
0
26
0
0
1
-1
0
1
100
package com.dim.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.*; import com.dim.circletreveal.CircleRevealHelper; import com.dim.circletreveal.CircleRevealEnable; import com.dim.listener.SingleClickListener; import com.dim.skin.SkinEnable; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.DefaultViewSkinHelper; import com.dim.skin.hepler.SkinHelper; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class FrameLayout extends android.widget.FrameLayout implements CircleRevealEnable,SkinEnable { private CircleRevealHelper mCircleRevealHelper ; private SkinHelper mSkinHelper; public FrameLayout(Context context) { super(context); init(null); } public FrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mSkinHelper=SkinHelper.create(this); mSkinHelper.init(this, attrs); mSkinHelper.setCurrentTheme(); mCircleRevealHelper=new CircleRevealHelper(this); } public FrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @Override public void setOnClickListener(OnClickListener l) { super.setOnClickListener(new SingleClickListener(l)); } @Override public void draw(Canvas canvas) { mSkinHelper.preDraw(this); mCircleRevealHelper.draw(canvas); } @Override public void superDraw(Canvas canvas) { super.draw(canvas); } @Override public void addView(android.view.View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if(params instanceof SLayoutParams){ ((SLayoutParams) params).setSkinHelper(child); } } @Override public FrameLayout.LayoutParams generateLayoutParams(AttributeSet attrs) { return new SLayoutParams(getContext(),attrs); } @Override public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); } @Override public void setSkinStyle(SkinStyle skinStyle) { mSkinHelper.setSkinStyle(skinStyle); } public class SLayoutParams extends android.widget.FrameLayout.LayoutParams implements SLayoutParamsI { private DefaultViewSkinHelper mSkinHelper; public SLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); mSkinHelper=SkinHelper.createDeFault(c); mSkinHelper.init(null,attrs); } public void setSkinHelper(android.view.View view){ mSkinHelper.setView(view); } public void setSkinStyle(SkinStyle skinStyle){ mSkinHelper.setSkinStyle(skinStyle); } public SLayoutParams(int width, int height) { super(width, height); } public SLayoutParams(ViewGroup.LayoutParams p) { super(p); } public SLayoutParams(MarginLayoutParams source) { super(source); } @TargetApi(Build.VERSION_CODES.KITKAT) public SLayoutParams(android.widget.FrameLayout.LayoutParams source) { super(source); } } }
ThemeDemo
com.dim.widget.animation
SimpleAnimListener
0
0
4
4
13
4
0
0
-1
1
1
3
package com.dim.widget.animation; /** * Created by zzz40500 on 15/9/3. */ public class SimpleAnimListener { public void onAnimationStart(CRAnimation animation) { } public void onAnimationEnd(CRAnimation animation) { } public void onAnimationCancel(CRAnimation animation) { } public void onAnimationRepeat(CRAnimation animation) { } }
ThemeDemo
com.dim.widget.animation
CRAnimation
2
0
17
17
97
31
0
0
0.529412
3
1
10
package com.dim.widget.animation; import android.animation.Animator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.os.Build; import android.view.animation.Interpolator; /** * Created by zzz40500 on 15/9/3. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class CRAnimation { private ValueAnimator mNAnimator; private android.animation.Animator mAAnimator; public CRAnimation(ValueAnimator NAnimator) { mNAnimator = NAnimator; } public CRAnimation(Animator AAnimator) { mAAnimator = AAnimator; } public void setInterpolator(Interpolator interpolator) { if (mAAnimator != null) { mAAnimator.setInterpolator(interpolator); } else if (mNAnimator != null) { mNAnimator.setInterpolator(interpolator); } } public void setStartDelay(long startDelay) { if (mAAnimator != null) { mAAnimator.setStartDelay(startDelay); } else if (mNAnimator != null) { mNAnimator.setStartDelay(startDelay); } } public void addListener(final SimpleAnimListener simpleAnimListener) { if (mAAnimator != null) { mAAnimator.addListener(new android.animation.Animator.AnimatorListener() { @Override public void onAnimationStart(android.animation.Animator animation) { simpleAnimListener.onAnimationStart(CRAnimation.this); } @Override public void onAnimationEnd(android.animation.Animator animation) { simpleAnimListener.onAnimationEnd(CRAnimation.this); } @Override public void onAnimationCancel(android.animation.Animator animation) { simpleAnimListener.onAnimationCancel(CRAnimation.this); } @Override public void onAnimationRepeat(android.animation.Animator animation) { simpleAnimListener.onAnimationRepeat(CRAnimation.this); } }); } else if (mNAnimator != null) { mNAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { simpleAnimListener.onAnimationStart(CRAnimation.this); } @Override public void onAnimationEnd(Animator animation) { simpleAnimListener.onAnimationEnd(CRAnimation.this); } @Override public void onAnimationCancel(Animator animation) { simpleAnimListener.onAnimationCancel(CRAnimation.this); } @Override public void onAnimationRepeat(Animator animation) { simpleAnimListener.onAnimationRepeat(CRAnimation.this); } }); } } public void end() { if (mAAnimator != null) { mAAnimator.end(); } else if (mNAnimator != null) { mNAnimator.end(); } } public void cancel() { if (mAAnimator != null) { mAAnimator.cancel(); } else if (mNAnimator != null) { mNAnimator.cancel(); } } public void setDuration(long duration) { if (mAAnimator != null) { mAAnimator.setDuration(duration); } else if (mNAnimator != null) { mNAnimator.setDuration(duration); } } public void start() { if (mAAnimator != null) { mAAnimator.start(); } else if (mNAnimator != null) { mNAnimator.start(); } } }
ThemeDemo
com.dim.circletreveal
CircleRevealHelper
7
0
4
4
55
7
0
0
0
17
1
15
package com.dim.circletreveal; import android.animation.Animator; import android.animation.ValueAnimator; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Region; import android.os.Build; import android.view.View; import android.view.ViewAnimationUtils; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/26. */ public class CircleRevealHelper { private ValueAnimator mValueAnimator; public CircleRevealHelper(View view) { mView = view; if (view instanceof CircleRevealEnable) { mCircleRevealEnable = (CircleRevealEnable) view; } else { throw new RuntimeException("the View must implements CircleRevealEnable "); } } private Path mPath = new Path(); private View mView; private int mAnchorX, mAnchorY; private float mRadius; private CircleRevealEnable mCircleRevealEnable; public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { mAnchorX = centerX; mAnchorY = centerY; if (Build.VERSION.SDK_INT >= 21) { Animator animator = ViewAnimationUtils.createCircularReveal( mView, mAnchorX, mAnchorY, startRadius, endRadius); animator.setDuration(1200); return new CRAnimation(animator); } else { mValueAnimator = ValueAnimator.ofFloat(startRadius, endRadius); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mRadius = (float) animation.getAnimatedValue(); mView.postInvalidate(); } }); mValueAnimator.setDuration(300); return new CRAnimation(mValueAnimator); } } public void draw(Canvas canvas) { if (mValueAnimator != null && mValueAnimator.isRunning()) { canvas.save(); canvas.translate(0, 0); mPath.reset(); mPath.addCircle(mAnchorX, mAnchorY, mRadius, Path.Direction.CCW); canvas.clipPath(mPath, Region.Op.REPLACE); mCircleRevealEnable.superDraw(canvas); canvas.restore(); } else { mCircleRevealEnable.superDraw(canvas); } } }
ThemeDemo
com.dim.circletreveal
CircleRevealEnable
0
0
2
0
7
2
0
0
-1
1
0
7
package com.dim.circletreveal; import android.graphics.Canvas; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/27. */ public interface CircleRevealEnable { CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius); void superDraw(Canvas canvas); }
ThemeDemo
com.dim.circletreveal
CircularRevealCompat
1
1
2
2
15
3
0
0
0
0
0
8
package com.dim.circletreveal; import android.support.annotation.Nullable; import android.view.View; import com.dim.widget.animation.CRAnimation; /** * Created by zzz40500 on 15/8/27. */ public class CircularRevealCompat { public View mView; public CircularRevealCompat(View view) { mView = view; } @Nullable public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { if (mView instanceof CircleRevealEnable) { return ((CircleRevealEnable) mView).circularReveal(centerX, centerY, startRadius, endRadius); } return null; } }
ThemeDemo
com.dim.themedemo
ApplicationTest
0
0
1
1
8
1
0
0
-1
0
0
6
package com.dim.themedemo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
ThemeDemo
com.dim.themedemo
MainActivity
3
0
6
5
66
10
0
0
0.666667
0
4
20
package com.dim.themedemo; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; import com.dim.circletreveal.CircularRevealCompat; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinCompat; import com.dim.widget.animation.CRAnimation; import com.dim.widget.animation.SimpleAnimListener; import com.mingle.themedemo.R; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RelativeLayout mRl; private FloatingActionButton mFloatingActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar); mRl = (RelativeLayout) findViewById(R.id.rl); setSupportActionBar(toolbar); mFloatingActionButton = (FloatingActionButton) findViewById(R.id.fb); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.this.startActivity(new Intent(MainActivity.this, ListViewDemoActivity.class)); } }); mFloatingActionButton.setOnClickListener(this); } @Override public void onClick(View v) { CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(v.getLeft() + v.getWidth() / 2, v.getTop() + v.getHeight() / 2, mRl.getHeight(), 0); if (crA != null) { crA.addListener(new SimpleAnimListener() { @Override public void onAnimationEnd(CRAnimation animation) { super.onAnimationEnd(animation); mRl.setVisibility(View.GONE); SkinStyle skinStyle = null; if (SkinConfig.getSkinStyle(MainActivity.this) == SkinStyle.Dark) { skinStyle = SkinStyle.Light; } else { skinStyle = SkinStyle.Dark; } SkinCompat.setSkinStyle(MainActivity.this, skinStyle, mSkinStyleChangeListenerImp) ; } }); crA.start(); } } private SkinStyleChangeListenerImp mSkinStyleChangeListenerImp=new SkinStyleChangeListenerImp(); class SkinStyleChangeListenerImp implements SkinCompat.SkinStyleChangeListener { @Override public void beforeChange() { } @Override public void afterChange() { mRl.postDelayed(new Runnable() { @Override public void run() { mRl.setVisibility(View.VISIBLE); CRAnimation crA = new CircularRevealCompat(mRl).circularReveal( mFloatingActionButton.getLeft() + mFloatingActionButton.getWidth() / 2, mFloatingActionButton.getTop() + mFloatingActionButton.getHeight() / 2, 0, mRl.getHeight()); if (crA != null) crA.start(); } },600); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
ThemeDemo
com.dim.themedemo
MainActivity.SkinStyleChangeListenerImp
0
0
0
0
14
0
0
0
-1
0
0
76
package com.dim.themedemo; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; import com.dim.circletreveal.CircularRevealCompat; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinCompat; import com.dim.widget.animation.CRAnimation; import com.dim.widget.animation.SimpleAnimListener; import com.mingle.themedemo.R; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RelativeLayout mRl; private FloatingActionButton mFloatingActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar); mRl = (RelativeLayout) findViewById(R.id.rl); setSupportActionBar(toolbar); mFloatingActionButton = (FloatingActionButton) findViewById(R.id.fb); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.this.startActivity(new Intent(MainActivity.this, ListViewDemoActivity.class)); } }); mFloatingActionButton.setOnClickListener(this); } @Override public void onClick(View v) { CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(v.getLeft() + v.getWidth() / 2, v.getTop() + v.getHeight() / 2, mRl.getHeight(), 0); if (crA != null) { crA.addListener(new SimpleAnimListener() { @Override public void onAnimationEnd(CRAnimation animation) { super.onAnimationEnd(animation); mRl.setVisibility(View.GONE); SkinStyle skinStyle = null; if (SkinConfig.getSkinStyle(MainActivity.this) == SkinStyle.Dark) { skinStyle = SkinStyle.Light; } else { skinStyle = SkinStyle.Dark; } SkinCompat.setSkinStyle(MainActivity.this, skinStyle, mSkinStyleChangeListenerImp) ; } }); crA.start(); } } private SkinStyleChangeListenerImp mSkinStyleChangeListenerImp=new SkinStyleChangeListenerImp(); class SkinStyleChangeListenerImp implements SkinCompat.SkinStyleChangeListener { @Override public void beforeChange() { } @Override public void afterChange() { mRl.postDelayed(new Runnable() { @Override public void run() { mRl.setVisibility(View.VISIBLE); CRAnimation crA = new CircularRevealCompat(mRl).circularReveal( mFloatingActionButton.getLeft() + mFloatingActionButton.getWidth() / 2, mFloatingActionButton.getTop() + mFloatingActionButton.getHeight() / 2, 0, mRl.getHeight()); if (crA != null) crA.start(); } },600); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
ThemeDemo
com.dim.themedemo
ListViewDemoActivity
4
0
5
2
63
9
0
0
0.4
0
4
24
package com.dim.themedemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ListView; import com.dim.circletreveal.CircularRevealCompat; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinCompat; import com.dim.themedemo.adapter.itemhandler.TestItemHandler; import com.dim.widget.animation.CRAnimation; import com.dim.widget.animation.SimpleAnimListener; import com.mingle.themedemo.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import kale.adapter.adapter.AutoAdapter; import kale.adapter.handler.ItemHandler; public class ListViewDemoActivity extends AppCompatActivity implements View.OnClickListener { private View mRl; private List<String> mData=new ArrayList<>(); private int i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view_demo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar); mRl = findViewById(R.id.rl); ListView listView = (ListView) findViewById(R.id.listView); setSupportActionBar(toolbar); for (int i = 0; i < 20; i++) { mData.add(""); } listView.setAdapter(new AutoAdapter(this, mData) { @Override protected void initHandlers(HashMap<Integer, ItemHandler> hashMap) { addHandler(0, new TestItemHandler()); } @Override protected int getViewType(int i) { return 0; } }); findViewById(R.id.button).setOnClickListener(this); } @Override public void onClick(View v) { CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(mRl.getWidth() / 2, mRl.getHeight() / 2, mRl.getWidth(), 0); if (crA != null) { crA.addListener(new SimpleAnimListener() { @Override public void onAnimationEnd(CRAnimation animation) { super.onAnimationEnd(animation); mRl.setVisibility(View.GONE); SkinStyle skinStyle = null; if (SkinConfig.getSkinStyle(ListViewDemoActivity.this) == SkinStyle.Dark) { skinStyle = SkinStyle.Light; } else { skinStyle = SkinStyle.Dark; } SkinCompat.setSkinStyle(ListViewDemoActivity.this, skinStyle, mSkinStyleChangeListenerImp) ; } }); crA.start(); } } private SkinStyleChangeListenerImp mSkinStyleChangeListenerImp=new SkinStyleChangeListenerImp(); class SkinStyleChangeListenerImp implements SkinCompat.SkinStyleChangeListener { @Override public void beforeChange() { } @Override public void afterChange() { mRl.postDelayed(new Runnable() { @Override public void run() { mRl.setVisibility(View.VISIBLE); mRl.setVisibility(View.VISIBLE); CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(mRl.getWidth() / 2, mRl.getHeight() / 2, 0, mRl.getWidth()); if (crA != null) crA.start(); } },600); } } }
ThemeDemo
com.dim.themedemo
ListViewDemoActivity.SkinStyleChangeListenerImp
0
0
0
0
15
0
0
0
-1
0
0
85
package com.dim.themedemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ListView; import com.dim.circletreveal.CircularRevealCompat; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.skin.hepler.SkinCompat; import com.dim.themedemo.adapter.itemhandler.TestItemHandler; import com.dim.widget.animation.CRAnimation; import com.dim.widget.animation.SimpleAnimListener; import com.mingle.themedemo.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import kale.adapter.adapter.AutoAdapter; import kale.adapter.handler.ItemHandler; public class ListViewDemoActivity extends AppCompatActivity implements View.OnClickListener { private View mRl; private List<String> mData=new ArrayList<>(); private int i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view_demo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar); mRl = findViewById(R.id.rl); ListView listView = (ListView) findViewById(R.id.listView); setSupportActionBar(toolbar); for (int i = 0; i < 20; i++) { mData.add(""); } listView.setAdapter(new AutoAdapter(this, mData) { @Override protected void initHandlers(HashMap<Integer, ItemHandler> hashMap) { addHandler(0, new TestItemHandler()); } @Override protected int getViewType(int i) { return 0; } }); findViewById(R.id.button).setOnClickListener(this); } @Override public void onClick(View v) { CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(mRl.getWidth() / 2, mRl.getHeight() / 2, mRl.getWidth(), 0); if (crA != null) { crA.addListener(new SimpleAnimListener() { @Override public void onAnimationEnd(CRAnimation animation) { super.onAnimationEnd(animation); mRl.setVisibility(View.GONE); SkinStyle skinStyle = null; if (SkinConfig.getSkinStyle(ListViewDemoActivity.this) == SkinStyle.Dark) { skinStyle = SkinStyle.Light; } else { skinStyle = SkinStyle.Dark; } SkinCompat.setSkinStyle(ListViewDemoActivity.this, skinStyle, mSkinStyleChangeListenerImp) ; } }); crA.start(); } } private SkinStyleChangeListenerImp mSkinStyleChangeListenerImp=new SkinStyleChangeListenerImp(); class SkinStyleChangeListenerImp implements SkinCompat.SkinStyleChangeListener { @Override public void beforeChange() { } @Override public void afterChange() { mRl.postDelayed(new Runnable() { @Override public void run() { mRl.setVisibility(View.VISIBLE); mRl.setVisibility(View.VISIBLE); CRAnimation crA = new CircularRevealCompat(mRl).circularReveal(mRl.getWidth() / 2, mRl.getHeight() / 2, 0, mRl.getWidth()); if (crA != null) crA.start(); } },600); } } }
ThemeDemo
com.dim.themedemo
APP
0
0
1
1
9
1
0
0
-1
0
1
6
package com.dim.themedemo; import android.app.Application; import android.support.v7.app.SkinHelper; /** * Created by zzz40500 on 16/5/24. */ public class APP extends Application { @Override public void onCreate() { super.onCreate(); SkinHelper.init(this); } }
ThemeDemo
com.dim.themedemo.adapter.itemhandler
TestItemHandler
0
0
3
3
13
3
0
0
-1
0
1
11
package com.dim.themedemo.adapter.itemhandler; import android.view.View; import com.dim.skin.hepler.SkinCompat; import com.mingle.themedemo.R; import kale.adapter.handler.SimpleItemHandler; import kale.adapter.util.ViewHolder; /** * Created by zzz40500 on 15/9/5. */ public class TestItemHandler extends SimpleItemHandler<String> { @Override public void onBindView33(ViewHolder viewHolder, String s, int i) { SkinCompat.setCurrentTheme(viewHolder.getConvertView(),null); } @Override public void onClick(View view, String s, int i) { } @Override public int getLayoutResId() { return R.layout.item_test; } }
diamond
com.taobao.diamond.server.listener
AuthorizationFilter
0
0
3
3
23
4
0
0
-1
0
1
27
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.listener; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.taobao.diamond.server.utils.SessionHolder; /** * 授权验证 * * @author boyan * @date 2010-5-5 */ public class AuthorizationFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(); SessionHolder.setSession(session); try { // 判断是否登录,没有就跳转到登录页面 if (session.getAttribute("user") == null) ((HttpServletResponse) response).sendRedirect(httpRequest.getContextPath() + "/jsp/login.jsp"); else chain.doFilter(httpRequest, response); } finally { SessionHolder.invalidate(); } } public void init(FilterConfig filterConfig) throws ServletException { } }
diamond
com.taobao.diamond.server.utils
GlobalCounter
2
0
4
4
25
5
0
0
0.5
2
0
12
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.utils; /** * 全局计数器 * * @author boyan * @date 2010-5-31 */ public class GlobalCounter { private static GlobalCounter instance = new GlobalCounter(); private long count = 0; public static GlobalCounter getCounter() { return instance; } public synchronized long decrementAndGet() { if (count == Long.MIN_VALUE) { count = 0; } else count--; return count; } public synchronized long get() { return this.count; } public synchronized void set(long value) { this.count = value; } }
diamond
com.taobao.diamond.server.utils
SystemConfig
3
1
3
2
54
6
0
0
1
2
0
25
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.utils; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.taobao.diamond.utils.ResourceUtils; public class SystemConfig { private static final Log log = LogFactory.getLog(SystemConfig.class); /** * Dump配置信息的时间间隔,默认10分钟 */ private static int dumpConfigInterval = 600; public static final String LOCAL_IP = getHostAddress(); static { InputStream in = null; try { in = ResourceUtils.getResourceAsStream("system.properties"); Properties props = new Properties(); props.load(in); dumpConfigInterval = Integer.parseInt(props.getProperty("dump_config_interval", "600")); } catch (IOException e) { log.error("加载system.properties出错", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("关闭system.properties出错", e); } } } } public SystemConfig() { } public static int getDumpConfigInterval() { return dumpConfigInterval; } private static String getHostAddress() { String address = "127.0.0.1"; try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = en.nextElement(); Enumeration<InetAddress> ads = ni.getInetAddresses(); while (ads.hasMoreElements()) { InetAddress ip = ads.nextElement(); if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) { return ip.getHostAddress(); } } } } catch (Exception e) { } return address; } }
diamond
com.taobao.diamond.server.utils
PaginationHelper
0
0
2
2
48
7
0
0
-1
1
1
24
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.utils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import com.taobao.diamond.domain.Page; /** * 分页辅助类 * * @author boyan * @date 2010-5-6 * @param <E> */ public class PaginationHelper<E> { /** * 取分页 * * @param jt * jdbcTemplate * @param sqlCountRows * 查询总数的SQL * @param sqlFetchRows * 查询数据的sql * @param args * 查询参数 * @param pageNo * 页数 * @param pageSize * 每页大小 * @param rowMapper * @return */ public Page<E> fetchPage(final JdbcTemplate jt, final String sqlCountRows, final String sqlFetchRows, final Object args[], final int pageNo, final int pageSize, final ParameterizedRowMapper<E> rowMapper) { if (pageSize == 0) { return null; } // 查询当前记录总数 final int rowCount = jt.queryForInt(sqlCountRows, args); // 计算页数 int pageCount = rowCount / pageSize; if (rowCount > pageSize * pageCount) { pageCount++; } // 创建Page对象 final Page<E> page = new Page<E>(); page.setPageNumber(pageNo); page.setPagesAvailable(pageCount); page.setTotalCount(rowCount); if (pageNo > pageCount) return null; // 取单页数据,计算起始位置 final int startRow = (pageNo - 1) * pageSize; // TODO 在数据量很大时, limit效率很低 final String selectSQL = sqlFetchRows + " limit " + startRow + "," + pageSize; jt.query(selectSQL, args, new ResultSetExtractor() { public Object extractData(ResultSet rs) throws SQLException, DataAccessException { final List<E> pageItems = page.getPageItems(); int currentRow = 0; while (rs.next()) { pageItems.add(rowMapper.mapRow(rs, currentRow++)); } return page; } }); return page; } }
diamond
com.taobao.diamond.server.utils
SessionHolder
1
0
4
3
22
4
0
0
0.5
1
0
15
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.utils; import javax.servlet.http.HttpSession; /** * 通过ThreadLocal传递HttpSession * * @author boyan * @date 2010-5-26 */ public class SessionHolder { private static ThreadLocal<HttpSession> sessionThreadLocal = new ThreadLocal<HttpSession>() { @Override protected HttpSession initialValue() { return null; } }; public static void invalidate() { sessionThreadLocal.remove(); } public static void setSession(HttpSession session) { sessionThreadLocal.set(session); } public static HttpSession getSession() { return sessionThreadLocal.get(); } }
diamond
com.taobao.diamond.server.utils
DiamondUtils
1
0
3
3
29
8
0
0
0.666667
1
0
16
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.utils; import java.sql.Timestamp; import java.util.Date; public class DiamondUtils { static final char[] INVALID_CHAR = { ';', '&', '%', '#', '$', '@', ',', '*', '^', '~', '(', ')', '/', '\\', '|', '+' }; /** * 判断字符串是否有空格 * * @param str * @return */ public static boolean hasInvalidChar(String str) { if (str == null || str.length() == 0) return true; int strLen = str.length(); for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch) || isInvalidChar(ch)) { return true; } } return false; } public static boolean isInvalidChar(char ch) { for (char c : INVALID_CHAR) { if (c == ch) return true; } return false; } public static Timestamp getCurrentTime() { Date date = new Date(); return new Timestamp(date.getTime()); } }
diamond
com.taobao.diamond.server.controller
AdminController
3
0
22
21
370
61
0
0
0.136364
0
9
42
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.controller; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.taobao.diamond.common.Constants; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.ConfigInfoEx; import com.taobao.diamond.domain.Page; import com.taobao.diamond.server.exception.ConfigServiceException; import com.taobao.diamond.server.service.AdminService; import com.taobao.diamond.server.service.ConfigService; import com.taobao.diamond.server.utils.DiamondUtils; import com.taobao.diamond.server.utils.GlobalCounter; import com.taobao.diamond.utils.JSONUtils; /** * 管理控制器 * * @author boyan * @date 2010-5-6 */ @Controller @RequestMapping("/admin.do") public class AdminController { private static final Log log = LogFactory.getLog(AdminController.class); @Autowired private AdminService adminService; @Autowired private ConfigService configService; @RequestMapping(params = "method=postConfig", method = RequestMethod.POST) public String postConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content, ModelMap modelMap) { response.setCharacterEncoding("GBK"); boolean checkSuccess = true; String errorMessage = "参数错误"; if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "无效的DataId"; } if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = "无效的分组"; } if (StringUtils.isBlank(content)) { checkSuccess = false; errorMessage = "无效的内容"; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); return "/admin/config/new"; } dataId = dataId.trim(); group = group.trim(); this.configService.addConfigInfo(dataId, group, content); modelMap.addAttribute("message", "提交成功!"); return listConfig(request, response, dataId, group, 1, 20, modelMap); } @RequestMapping(params = "method=deleteConfig", method = RequestMethod.GET) public String deleteConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") long id, ModelMap modelMap) { // 删除数据 this.configService.removeConfigInfo(id); modelMap.addAttribute("message", "删除成功!"); return "/admin/config/list"; } @RequestMapping(params = "method=upload", method = RequestMethod.POST) public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) { response.setCharacterEncoding("GBK"); boolean checkSuccess = true; String errorMessage = "参数错误"; if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "无效的DataId"; } if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = "无效的分组"; } String content = getContentFromFile(contentFile); if (StringUtils.isBlank(content)) { checkSuccess = false; errorMessage = "无效的内容"; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); return "/admin/config/upload"; } this.configService.addConfigInfo(dataId, group, content); modelMap.addAttribute("message", "提交成功!"); return listConfig(request, response, dataId, group, 1, 20, modelMap); } @RequestMapping(params = "method=reupload", method = RequestMethod.POST) public String reupload(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) { response.setCharacterEncoding("GBK"); boolean checkSuccess = true; String errorMessage = "参数错误"; String content = getContentFromFile(contentFile); ConfigInfo configInfo = new ConfigInfo(dataId, group, content); if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "无效的DataId"; } if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = "无效的分组"; } if (StringUtils.isBlank(content)) { checkSuccess = false; errorMessage = "无效的内容"; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); modelMap.addAttribute("configInfo", configInfo); return "/admin/config/edit"; } this.configService.updateConfigInfo(dataId, group, content); modelMap.addAttribute("message", "更新成功!"); return listConfig(request, response, dataId, group, 1, 20, modelMap); } private String getContentFromFile(MultipartFile contentFile) { try { String charset = Constants.ENCODE; final String content = new String(contentFile.getBytes(), charset); return content; } catch (Exception e) { throw new ConfigServiceException(e); } } @RequestMapping(params = "method=updateConfig", method = RequestMethod.POST) public String updateConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content, ModelMap modelMap) { response.setCharacterEncoding("GBK"); ConfigInfo configInfo = new ConfigInfo(dataId, group, content); boolean checkSuccess = true; String errorMessage = "参数错误"; if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "无效的DataId"; } if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = "无效的分组"; } if (StringUtils.isBlank(content)) { checkSuccess = false; errorMessage = "无效的内容"; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); modelMap.addAttribute("configInfo", configInfo); return "/admin/config/edit"; } this.configService.updateConfigInfo(dataId, group, content); modelMap.addAttribute("message", "提交成功!"); return listConfig(request, response, dataId, group, 1, 20, modelMap); } @RequestMapping(params = "method=listConfig", method = RequestMethod.GET) public String listConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) { Page<ConfigInfo> page = this.configService.findConfigInfo(pageNo, pageSize, group, dataId); String accept = request.getHeader("Accept"); if (accept != null && accept.indexOf("application/json") >= 0) { try { String json = JSONUtils.serializeObject(page); modelMap.addAttribute("pageJson", json); } catch (Exception e) { log.error("序列化page对象出错", e); } return "/admin/config/list_json"; } else { modelMap.addAttribute("dataId", dataId); modelMap.addAttribute("group", group); modelMap.addAttribute("page", page); return "/admin/config/list"; } } @RequestMapping(params = "method=listConfigLike", method = RequestMethod.GET) public String listConfigLike(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) { if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) { modelMap.addAttribute("message", "模糊查询请至少设置一个查询参数"); return "/admin/config/list"; } Page<ConfigInfo> page = this.configService.findConfigInfoLike(pageNo, pageSize, group, dataId); String accept = request.getHeader("Accept"); if (accept != null && accept.indexOf("application/json") >= 0) { try { String json = JSONUtils.serializeObject(page); modelMap.addAttribute("pageJson", json); } catch (Exception e) { log.error("序列化page对象出错", e); } return "/admin/config/list_json"; } else { modelMap.addAttribute("page", page); modelMap.addAttribute("dataId", dataId); modelMap.addAttribute("group", group); modelMap.addAttribute("method", "listConfigLike"); return "/admin/config/list"; } } @RequestMapping(params = "method=detailConfig", method = RequestMethod.GET) public String getConfigInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, ModelMap modelMap) { dataId = dataId.trim(); group = group.trim(); ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group); modelMap.addAttribute("configInfo", configInfo); return "/admin/config/edit"; } // =========================== 批量处理 ============================== // @RequestMapping(params = "method=batchQuery", method = RequestMethod.POST) public String batchQuery(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataIds") String dataIds, @RequestParam("group") String group, ModelMap modelMap) { response.setCharacterEncoding("GBK"); // 这里抛出的异常, 会产生一个500错误, 返回给sdk, sdk会将500错误记录到日志中 if (StringUtils.isBlank(dataIds)) { throw new IllegalArgumentException("批量查询, dataIds不能为空"); } // group对批量操作的每一条数据都相同, 不需要在for循环里面进行判断 if (StringUtils.isBlank(group)) { throw new IllegalArgumentException("批量查询, group不能为空或者包含非法字符"); } // 分解dataId String[] dataIdArray = dataIds.split(Constants.WORD_SEPARATOR); group = group.trim(); List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>(); for (String dataId : dataIdArray) { ConfigInfoEx configInfoEx = new ConfigInfoEx(); configInfoEx.setDataId(dataId); configInfoEx.setGroup(group); configInfoExList.add(configInfoEx); try { if (StringUtils.isBlank(dataId)) { configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS); configInfoEx.setMessage("dataId is blank"); continue; } // 查询数据库 ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group); if (configInfo == null) { // 没有异常, 说明查询成功, 但数据不存在, 设置不存在的状态码 configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS); configInfoEx.setMessage("query data does not exist"); } else { // 没有异常, 说明查询成功, 而且数据存在, 设置存在的状态码 String content = configInfo.getContent(); configInfoEx.setContent(content); configInfoEx.setStatus(Constants.BATCH_QUERY_EXISTS); configInfoEx.setMessage("query success"); } } catch (Exception e) { log.error("批量查询, 在查询这个dataId时出错, dataId=" + dataId + ",group=" + group, e); // 出现异常, 设置异常状态码 configInfoEx.setStatus(Constants.BATCH_OP_ERROR); configInfoEx.setMessage("query error: " + e.getMessage()); } } String json = null; try { json = JSONUtils.serializeObject(configInfoExList); } catch (Exception e) { log.error("批量查询结果序列化出错, json=" + json, e); } modelMap.addAttribute("json", json); return "/admin/config/batch_result"; } @RequestMapping(params = "method=batchAddOrUpdate", method = RequestMethod.POST) public String batchAddOrUpdate(HttpServletRequest request, HttpServletResponse response, @RequestParam("allDataIdAndContent") String allDataIdAndContent, @RequestParam("group") String group, ModelMap modelMap) { response.setCharacterEncoding("GBK"); // 这里抛出的异常, 会产生一个500错误, 返回给sdk, sdk会将500错误记录到日志中 if (StringUtils.isBlank(allDataIdAndContent)) { throw new IllegalArgumentException("批量写, allDataIdAndContent不能为空"); } // group对批量操作的每一条数据都相同, 不需要在for循环里面进行判断 if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group)) { throw new IllegalArgumentException("批量写, group不能为空或者包含非法字符"); } String[] dataIdAndContentArray = allDataIdAndContent.split(Constants.LINE_SEPARATOR); group = group.trim(); List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>(); for (String dataIdAndContent : dataIdAndContentArray) { String dataId = dataIdAndContent.substring(0, dataIdAndContent.indexOf(Constants.WORD_SEPARATOR)); String content = dataIdAndContent.substring(dataIdAndContent.indexOf(Constants.WORD_SEPARATOR) + 1); ConfigInfoEx configInfoEx = new ConfigInfoEx(); configInfoEx.setDataId(dataId); configInfoEx.setGroup(group); configInfoEx.setContent(content); try { // 判断dataId是否包含非法字符 if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId)) { // 这里抛出的异常, 会在下面catch, 然后设置状态, 保证一个dataId的异常不会影响其他dataId throw new IllegalArgumentException("批量写, dataId不能包含非法字符"); } // 判断内容是否为空 if (StringUtils.isBlank(content)) { throw new IllegalArgumentException("批量写, 内容不能为空"); } // 查询数据库 ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group); if (configInfo == null) { // 数据不存在, 新增 this.configService.addConfigInfo(dataId, group, content); // 新增成功, 设置状态码 configInfoEx.setStatus(Constants.BATCH_ADD_SUCCESS); configInfoEx.setMessage("add success"); } else { // 数据存在, 更新 this.configService.updateConfigInfo(dataId, group, content); // 更新成功, 设置状态码 configInfoEx.setStatus(Constants.BATCH_UPDATE_SUCCESS); configInfoEx.setMessage("update success"); } } catch (Exception e) { log.error("批量写这条数据时出错, dataId=" + dataId + ",group=" + group + ",content=" + content, e); // 出现异常, 设置异常状态码 configInfoEx.setStatus(Constants.BATCH_OP_ERROR); configInfoEx.setMessage("batch write error: " + e.getMessage()); } configInfoExList.add(configInfoEx); } String json = null; try { json = JSONUtils.serializeObject(configInfoExList); } catch (Exception e) { log.error("批量写, 结果序列化出错, json=" + json, e); } modelMap.addAttribute("json", json); return "/admin/config/batch_result"; } @RequestMapping(params = "method=listUser", method = RequestMethod.GET) public String listUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) { Map<String, String> userMap = this.adminService.getAllUsers(); modelMap.addAttribute("userMap", userMap); return "/admin/user/list"; } @RequestMapping(params = "method=addUser", method = RequestMethod.POST) public String addUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap modelMap) { if (StringUtils.isBlank(userName) || DiamondUtils.hasInvalidChar(userName.trim())) { modelMap.addAttribute("message", "无效的用户名"); return listUser(request, response, modelMap); } if (StringUtils.isBlank(password) || DiamondUtils.hasInvalidChar(password.trim())) { modelMap.addAttribute("message", "无效的密码"); return "/admin/user/new"; } if (this.adminService.addUser(userName, password)) modelMap.addAttribute("message", "添加成功!"); else modelMap.addAttribute("message", "添加失败!"); return listUser(request, response, modelMap); } @RequestMapping(params = "method=deleteUser", method = RequestMethod.GET) public String deleteUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, ModelMap modelMap) { if (StringUtils.isBlank(userName) || DiamondUtils.hasInvalidChar(userName.trim())) { modelMap.addAttribute("message", "无效的用户名"); return listUser(request, response, modelMap); } if (this.adminService.removeUser(userName)) { modelMap.addAttribute("message", "删除成功!"); } else { modelMap.addAttribute("message", "删除失败!"); } return listUser(request, response, modelMap); } @RequestMapping(params = "method=changePassword", method = RequestMethod.GET) public String changePassword(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap modelMap) { userName = userName.trim(); password = password.trim(); if (StringUtils.isBlank(userName) || DiamondUtils.hasInvalidChar(userName.trim())) { modelMap.addAttribute("message", "无效的用户名"); return listUser(request, response, modelMap); } if (StringUtils.isBlank(password) || DiamondUtils.hasInvalidChar(password.trim())) { modelMap.addAttribute("message", "无效的新密码"); return listUser(request, response, modelMap); } if (this.adminService.updatePassword(userName, password)) { modelMap.addAttribute("message", "更改成功,下次登录请用新密码!"); } else { modelMap.addAttribute("message", "更改失败!"); } return listUser(request, response, modelMap); } @RequestMapping(params = "method=setRefuseRequestCount", method = RequestMethod.POST) public String setRefuseRequestCount(@RequestParam("count") long count, ModelMap modelMap) { if (count <= 0) { modelMap.addAttribute("message", "非法的计数"); return "/admin/count"; } GlobalCounter.getCounter().set(count); modelMap.addAttribute("message", "设置成功!"); return getRefuseRequestCount(modelMap); } @RequestMapping(params = "method=getRefuseRequestCount", method = RequestMethod.GET) public String getRefuseRequestCount(ModelMap modelMap) { modelMap.addAttribute("count", GlobalCounter.getCounter().get()); return "/admin/count"; } /** * 重新文件加载用户信息 * * @param modelMap * @return */ @RequestMapping(params = "method=reloadUser", method = RequestMethod.GET) public String reloadUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) { this.adminService.loadUsers(); modelMap.addAttribute("message", "加载成功!"); return listUser(request, response, modelMap); } public AdminService getAdminService() { return adminService; } public void setAdminService(AdminService adminService) { this.adminService = adminService; } public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } }
diamond
com.taobao.diamond.server.controller
ConfigController
5
0
8
8
149
24
0
0
0
1
4
32
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.controller; import static com.taobao.diamond.common.Constants.LINE_SEPARATOR; import static com.taobao.diamond.common.Constants.WORD_SEPARATOR; import java.net.URLEncoder; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.taobao.diamond.common.Constants; import com.taobao.diamond.server.service.ConfigService; import com.taobao.diamond.server.service.DiskService; import com.taobao.diamond.server.utils.GlobalCounter; /** * 处理配置信息获取和提交的controller * * @author boyan * @date 2010-5-4 */ @Controller public class ConfigController { @Autowired private ConfigService configService; @Autowired private DiskService diskService; public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) { response.setHeader("Content-Type", "text/html;charset=GBK"); final String address = getRemortIP(request); if (address == null) { // 未找到远端地址,返回400错误 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } String md5 = this.configService.getContentMD5(dataId, group); if (md5 == null) { return "404"; } response.setHeader(Constants.CONTENT_MD5, md5); // 正在被修改,返回304,这里的检查并没有办法保证一致性,因此做double-check尽力保证 if (diskService.isModified(dataId, group)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return "304"; } String path = configService.getConfigInfoPath(dataId, group); // 再次检查 if (diskService.isModified(dataId, group)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return "304"; } // 禁用缓存 response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "forward:" + path; } public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response, String probeModify) { response.setHeader("Content-Type", "text/html;charset=GBK"); final String address = getRemortIP(request); if (address == null) { // 未找到远端地址,返回400错误 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } final List<ConfigKey> configKeyList = getConfigKeyList(probeModify); StringBuilder resultBuilder = new StringBuilder(); for (ConfigKey key : configKeyList) { String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup()); if (!StringUtils.equals(md5, key.getMd5())) { resultBuilder.append(key.getDataId()).append(WORD_SEPARATOR).append(key.getGroup()) .append(LINE_SEPARATOR); } } String returnHeader = resultBuilder.toString(); try { returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8"); } catch (Exception e) { // ignore } request.setAttribute("content", returnHeader); // 禁用缓存 response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "200"; } public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } public DiskService getDiskService() { return diskService; } public void setDiskService(DiskService diskService) { this.diskService = diskService; } /** * 查找真实的IP地址 * * @param request * @return */ public String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } public static List<ConfigKey> getConfigKeyList(String configKeysString) { List<ConfigKey> configKeyList = new LinkedList<ConfigKey>(); if (null == configKeysString || "".equals(configKeysString)) { return configKeyList; } String[] configKeyStrings = configKeysString.split(LINE_SEPARATOR); for (String configKeyString : configKeyStrings) { String[] configKey = configKeyString.split(WORD_SEPARATOR); if (configKey.length > 3) { continue; } ConfigKey key = new ConfigKey(); if ("".equals(configKey[0])) { continue; } key.setDataId(configKey[0]); if (configKey.length >= 2 && !"".equals(configKey[1])) { key.setGroup(configKey[1]); } if (configKey.length == 3 && !"".equals(configKey[2])) { key.setMd5(configKey[2]); } configKeyList.add(key); } return configKeyList; } public static class ConfigKey { private String dataId; private String group; private String md5; public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DataID: ").append(dataId).append("\r\n"); sb.append("Group: ").append((null == group ? "" : group)).append("\r\n"); sb.append("MD5: ").append((null == md5 ? "" : md5)).append("\r\n"); return sb.toString(); } } }
diamond
com.taobao.diamond.server.controller
ConfigController.ConfigKey
3
0
0
0
30
0
0
0
-1
0
0
192
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.controller; import static com.taobao.diamond.common.Constants.LINE_SEPARATOR; import static com.taobao.diamond.common.Constants.WORD_SEPARATOR; import java.net.URLEncoder; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.taobao.diamond.common.Constants; import com.taobao.diamond.server.service.ConfigService; import com.taobao.diamond.server.service.DiskService; import com.taobao.diamond.server.utils.GlobalCounter; /** * 处理配置信息获取和提交的controller * * @author boyan * @date 2010-5-4 */ @Controller public class ConfigController { @Autowired private ConfigService configService; @Autowired private DiskService diskService; public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) { response.setHeader("Content-Type", "text/html;charset=GBK"); final String address = getRemortIP(request); if (address == null) { // 未找到远端地址,返回400错误 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } String md5 = this.configService.getContentMD5(dataId, group); if (md5 == null) { return "404"; } response.setHeader(Constants.CONTENT_MD5, md5); // 正在被修改,返回304,这里的检查并没有办法保证一致性,因此做double-check尽力保证 if (diskService.isModified(dataId, group)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return "304"; } String path = configService.getConfigInfoPath(dataId, group); // 再次检查 if (diskService.isModified(dataId, group)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return "304"; } // 禁用缓存 response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "forward:" + path; } public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response, String probeModify) { response.setHeader("Content-Type", "text/html;charset=GBK"); final String address = getRemortIP(request); if (address == null) { // 未找到远端地址,返回400错误 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } final List<ConfigKey> configKeyList = getConfigKeyList(probeModify); StringBuilder resultBuilder = new StringBuilder(); for (ConfigKey key : configKeyList) { String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup()); if (!StringUtils.equals(md5, key.getMd5())) { resultBuilder.append(key.getDataId()).append(WORD_SEPARATOR).append(key.getGroup()) .append(LINE_SEPARATOR); } } String returnHeader = resultBuilder.toString(); try { returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8"); } catch (Exception e) { // ignore } request.setAttribute("content", returnHeader); // 禁用缓存 response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "200"; } public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } public DiskService getDiskService() { return diskService; } public void setDiskService(DiskService diskService) { this.diskService = diskService; } /** * 查找真实的IP地址 * * @param request * @return */ public String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } public static List<ConfigKey> getConfigKeyList(String configKeysString) { List<ConfigKey> configKeyList = new LinkedList<ConfigKey>(); if (null == configKeysString || "".equals(configKeysString)) { return configKeyList; } String[] configKeyStrings = configKeysString.split(LINE_SEPARATOR); for (String configKeyString : configKeyStrings) { String[] configKey = configKeyString.split(WORD_SEPARATOR); if (configKey.length > 3) { continue; } ConfigKey key = new ConfigKey(); if ("".equals(configKey[0])) { continue; } key.setDataId(configKey[0]); if (configKey.length >= 2 && !"".equals(configKey[1])) { key.setGroup(configKey[1]); } if (configKey.length == 3 && !"".equals(configKey[2])) { key.setMd5(configKey[2]); } configKeyList.add(key); } return configKeyList; } public static class ConfigKey { private String dataId; private String group; private String md5; public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DataID: ").append(dataId).append("\r\n"); sb.append("Group: ").append((null == group ? "" : group)).append("\r\n"); sb.append("MD5: ").append((null == md5 ? "" : md5)).append("\r\n"); return sb.toString(); } } }
diamond
com.taobao.diamond.server.controller
NotifyController
1
0
3
3
25
3
0
0
0
0
1
21
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.taobao.diamond.server.service.ConfigService; /** * 用于其他节点通知的控制器 * * @author boyan * @date 2010-5-7 */ @Controller @RequestMapping("/notify.do") public class NotifyController { @Autowired private ConfigService configService; public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } /** * 通知配置信息改变 * * @param id * @return */ @RequestMapping(method = RequestMethod.GET, params = "method=notifyConfigInfo") public String notifyConfigInfo(@RequestParam("dataId") String dataId, @RequestParam("group") String group) { dataId = dataId.trim(); group = group.trim(); this.configService.loadConfigInfoToDisk(dataId, group); return "200"; } }
diamond
com.taobao.diamond.server.controller
LoginController
1
0
4
4
28
5
0
0
0.5
0
1
24
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.taobao.diamond.server.service.AdminService; /** * 登录登出控制器 * * @author boyan * @date 2010-5-6 */ @Controller @RequestMapping("/login.do") public class LoginController { @Autowired private AdminService adminService; @RequestMapping(params = "method=login", method = RequestMethod.POST) public String login(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password, ModelMap modelMap) { if (adminService.login(username, password)) { request.getSession().setAttribute("user", username); return "admin/admin"; } else { modelMap.addAttribute("message", "登录失败,用户名密码不匹配"); return "login"; } } public AdminService getAdminService() { return adminService; } public void setAdminService(AdminService adminService) { this.adminService = adminService; } @RequestMapping(params = "method=logout", method = RequestMethod.GET) public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "login"; } }
diamond
com.taobao.diamond.server.controller
ConfigServlet
4
0
5
3
51
9
0
0
0.4
0
4
20
package com.taobao.diamond.server.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.taobao.diamond.common.Constants; import com.taobao.diamond.server.service.ConfigService; import com.taobao.diamond.server.service.DiskService; public class ConfigServlet extends HttpServlet { private static final long serialVersionUID = 4339468526746635388L; private ConfigController configController; @Override public void init() throws ServletException { super.init(); WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); configService = (ConfigService) webApplicationContext.getBean("configService"); this.diskService = (DiskService) webApplicationContext.getBean("diskService"); configController = new ConfigController(); this.configController.setConfigService(configService); this.configController.setDiskService(diskService); } private ConfigService configService; private DiskService diskService; /** * 查找真实的IP地址 * * @param request * @return */ public String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } public void forward(HttpServletRequest request, HttpServletResponse response, String page, String basePath, String postfix) throws IOException, ServletException { RequestDispatcher requestDispatcher = request.getRequestDispatcher(basePath + page + postfix); requestDispatcher.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String probeModify = request.getParameter(Constants.PROBE_MODIFY_REQUEST); if (!StringUtils.hasLength(probeModify)) throw new IOException("无效的probeModify"); String page = this.configController.getProbeModifyResult(request, response, probeModify); forward(request, response, page, "/jsp/", ".jsp"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String group = request.getParameter("group"); String dataId = request.getParameter("dataId"); if (!StringUtils.hasLength(dataId)) { throw new IOException("无效的dataId: " + dataId); } String page = this.configController.getConfig(request, response, dataId, group); if (page.startsWith("forward:")) { page = page.substring(8); forward(request, response, page, "", ""); } else { forward(request, response, page, "/jsp/", ".jsp"); } } }
diamond
com.taobao.diamond.server.service
AdminService
3
0
9
8
96
17
0
0
0
2
1
29
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.service; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; import com.taobao.diamond.utils.ResourceUtils; /** * 管理服务 * * @author boyan * @date 2010-5-5 */ @Service public class AdminService { private static final Log log = LogFactory.getLog(AdminService.class); private volatile Properties properties = new Properties(); /** * user.properties的路径url */ private URL url; public URL getUrl() { return url; } public AdminService() { loadUsers(); } public void loadUsers() { Properties tempProperties = new Properties(); InputStream in = null; try { url = ResourceUtils.getResourceURL("user.properties"); in = new FileInputStream(url.getPath()); tempProperties.load(in); } catch (IOException e) { log.error("加载user.properties文件失败", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("关闭user.properties文件失败", e); } } } this.properties = tempProperties; } public synchronized boolean login(String userName, String password) { String passwordInFile = this.properties.getProperty(userName); if (passwordInFile != null) return passwordInFile.equals(password); else return false; } public synchronized boolean addUser(String userName, String password) { if (this.properties.containsKey(userName)) return false; this.properties.put(userName, password); return saveToDisk(); } private boolean saveToDisk() { FileOutputStream out = null; try { out = new FileOutputStream(url.getPath()); this.properties.store(out, "add user"); out.flush(); return true; } catch (IOException e) { log.error("保存user.properties文件失败", e); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error("关闭user.properties文件失败", e); } } } } public synchronized Map<String, String> getAllUsers() { Map<String, String> result = new HashMap<String, String>(); Enumeration<?> enu = this.properties.keys(); while (enu.hasMoreElements()) { String address = (String) enu.nextElement(); String group = this.properties.getProperty(address); result.put(address, group); } return result; } public synchronized boolean updatePassword(String userName, String newPassword) { if (!this.properties.containsKey(userName)) return false; this.properties.put(userName, newPassword); return saveToDisk(); } public synchronized boolean removeUser(String userName) { if (this.properties.size() == 1) return false; if (!this.properties.containsKey(userName)) return false; this.properties.remove(userName); return saveToDisk(); } }
diamond
com.taobao.diamond.server.service
DumpConfigInfoTask
3
0
3
2
47
9
0
0
0
1
2
12
package com.taobao.diamond.server.service; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.Page; /** * Dump配置信息任务 * * @author boyan * @date 2010-5-10 */ public final class DumpConfigInfoTask implements Runnable { private static final Log log = LogFactory.getLog(DumpConfigInfoTask.class); private static final int PAGE_SIZE = 1000; private final TimerTaskService timerTaskService; public DumpConfigInfoTask(TimerTaskService timerTaskService) { this.timerTaskService = timerTaskService; } public void run() { try { Page<ConfigInfo> page = this.timerTaskService.getPersistService().findAllConfigInfo(1, PAGE_SIZE); if (page != null) { // 总页数 int totalPages = page.getPagesAvailable(); updateConfigInfo(page); if (totalPages > 1) { for (int pageNo = 2; pageNo <= totalPages; pageNo++) { page = this.timerTaskService.getPersistService().findAllConfigInfo(pageNo, PAGE_SIZE); if (page != null) { updateConfigInfo(page); } } } } } catch (Throwable t) { log.error("dump task run error", t); } } private void updateConfigInfo(Page<ConfigInfo> page) throws IOException { for (ConfigInfo configInfo : page.getPageItems()) { if (configInfo == null) { continue; } try { // 写入磁盘,更新缓存 this.timerTaskService.getConfigService().updateMD5Cache(configInfo); this.timerTaskService.getDiskService().saveToDisk(configInfo); } catch (Throwable t) { log.error( "dump config info error, dataId=" + configInfo.getDataId() + ", group=" + configInfo.getGroup(), t); } } } }
diamond
com.taobao.diamond.server.service
NotifyService
5
0
5
2
99
12
0
0
0
1
2
32
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.taobao.diamond.server.utils.SystemConfig; import com.taobao.diamond.utils.ResourceUtils; /** * 通知服务,用于通知其他节点 * * @author boyan * @date 2010-5-6 */ @Service public class NotifyService { private static final int TIMEOUT = 5000; private final String URL_PREFIX = "/diamond-server/notify.do"; private final String PROTOCOL = "http://"; private final Properties nodeProperties = new Properties(); static final Log log = LogFactory.getLog(NotifyService.class); Properties getNodeProperties() { return this.nodeProperties; } @PostConstruct public void loadNodes() { InputStream in = null; try { in = ResourceUtils.getResourceAsStream("node.properties"); nodeProperties.load(in); } catch (IOException e) { log.error("加载节点配置文件失败"); } finally { try { if (in != null) in.close(); } catch (IOException e) { log.error("关闭node.properties失败", e); } } log.info("节点列表:" + nodeProperties); } /** * 通知配置信息改变 * * @param id */ public void notifyConfigInfoChange(String dataId, String group) { Enumeration<?> enu = nodeProperties.propertyNames(); while (enu.hasMoreElements()) { String address = (String) enu.nextElement(); if (address.contains(SystemConfig.LOCAL_IP)) { continue; } String urlString = generateNotifyConfigInfoPath(dataId, group, address); final String result = invokeURL(urlString); log.info("通知节点" + address + "分组信息改变:" + result); } } String generateNotifyConfigInfoPath(String dataId, String group, String address) { String specialUrl = this.nodeProperties.getProperty(address); String urlString = PROTOCOL + address + URL_PREFIX; // 如果有指定url,使用指定的url if (specialUrl != null && StringUtils.hasLength(specialUrl.trim())) { urlString = specialUrl; } urlString += "?method=notifyConfigInfo&dataId=" + dataId + "&group=" + group; return urlString; } /** * http get调用 * * @param urlString * @return */ private String invokeURL(String urlString) { HttpURLConnection conn = null; URL url = null; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); conn.connect(); InputStream urlStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(urlStream)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) reader.close(); } return sb.toString(); } catch (Exception e) { log.error("http调用失败,url=" + urlString, e); } finally { if (conn != null) { conn.disconnect(); } } return "error"; } }
diamond
com.taobao.diamond.server.service
ConfigService
5
0
20
16
181
29
0
0
0.15
5
7
27
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.service; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.taobao.diamond.common.Constants; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.Page; import com.taobao.diamond.md5.MD5; import com.taobao.diamond.server.exception.ConfigServiceException; @Service public class ConfigService { private static final Log log = LogFactory.getLog(ConfigService.class); @Autowired private PersistService persistService; @Autowired private DiskService diskService; @Autowired private NotifyService notifyService; /** * content的MD5的缓存,key为group/dataId,value为md5值 */ private final ConcurrentHashMap<String, String> contentMD5Cache = new ConcurrentHashMap<String, String>(); public String getConfigInfoPath(String dataId, String group) { StringBuilder sb = new StringBuilder("/"); sb.append(Constants.BASE_DIR).append("/"); sb.append(group).append("/"); sb.append(dataId); return sb.toString(); } public void updateMD5Cache(ConfigInfo configInfo) { this.contentMD5Cache.put(generateMD5CacheKey(configInfo.getDataId(), configInfo.getGroup()), MD5.getInstance() .getMD5String(configInfo.getContent())); } public String getContentMD5(String dataId, String group) { String key = generateMD5CacheKey(dataId, group); String md5 = this.contentMD5Cache.get(key); if (md5 == null) { synchronized (this) { // 二重检查 return this.contentMD5Cache.get(key); } } else { return md5; } } String generateMD5CacheKey(String dataId, String group) { String key = group + "/" + dataId; return key; } String generatePath(String dataId, final String group) { StringBuilder sb = new StringBuilder("/"); sb.append(Constants.BASE_DIR).append("/"); sb.append(group).append("/"); sb.append(dataId); return sb.toString(); } public void removeConfigInfo(long id) { try { ConfigInfo configInfo = this.persistService.findConfigInfo(id); this.diskService.removeConfigInfo(configInfo.getDataId(), configInfo.getGroup()); this.contentMD5Cache.remove(generateMD5CacheKey(configInfo.getDataId(), configInfo.getGroup())); this.persistService.removeConfigInfo(configInfo); // 通知其他节点 this.notifyOtherNodes(configInfo.getDataId(), configInfo.getGroup()); } catch (Exception e) { log.error("删除配置信息错误", e); throw new ConfigServiceException(e); } } public void addConfigInfo(String dataId, String group, String content) { checkParameter(dataId, group, content); ConfigInfo configInfo = new ConfigInfo(dataId, group, content); // 保存顺序:先数据库,再磁盘 try { persistService.addConfigInfo(configInfo); // 切记更新缓存 this.contentMD5Cache.put(generateMD5CacheKey(dataId, group), configInfo.getMd5()); diskService.saveToDisk(configInfo); // 通知其他节点 this.notifyOtherNodes(dataId, group); } catch (Exception e) { log.error("保存ConfigInfo失败", e); throw new ConfigServiceException(e); } } /** * 更新配置信息 * * @param dataId * @param group * @param content */ public void updateConfigInfo(String dataId, String group, String content) { checkParameter(dataId, group, content); ConfigInfo configInfo = new ConfigInfo(dataId, group, content); // 先更新数据库,再更新磁盘 try { persistService.updateConfigInfo(configInfo); // 切记更新缓存 this.contentMD5Cache.put(generateMD5CacheKey(dataId, group), configInfo.getMd5()); diskService.saveToDisk(configInfo); // 通知其他节点 this.notifyOtherNodes(dataId, group); } catch (Exception e) { log.error("保存ConfigInfo失败", e); throw new ConfigServiceException(e); } } /** * 将配置信息从数据库加载到磁盘 * * @param id */ public void loadConfigInfoToDisk(String dataId, String group) { try { ConfigInfo configInfo = this.persistService.findConfigInfo(dataId, group); if (configInfo != null) { this.contentMD5Cache.put(generateMD5CacheKey(dataId, group), configInfo.getMd5()); this.diskService.saveToDisk(configInfo); } else { // 删除文件 this.contentMD5Cache.remove(generateMD5CacheKey(dataId, group)); this.diskService.removeConfigInfo(dataId, group); } } catch (Exception e) { log.error("保存ConfigInfo到磁盘失败", e); throw new ConfigServiceException(e); } } public ConfigInfo findConfigInfo(String dataId, String group) { return persistService.findConfigInfo(dataId, group); } /** * 分页查找配置信息 * * @param pageNo * @param pageSize * @param group * @param dataId * @return */ public Page<ConfigInfo> findConfigInfo(final int pageNo, final int pageSize, final String group, final String dataId) { if (StringUtils.hasLength(dataId) && StringUtils.hasLength(group)) { ConfigInfo ConfigInfo = this.persistService.findConfigInfo(dataId, group); Page<ConfigInfo> page = new Page<ConfigInfo>(); if (ConfigInfo != null) { page.setPageNumber(1); page.setTotalCount(1); page.setPagesAvailable(1); page.getPageItems().add(ConfigInfo); } return page; } else if (StringUtils.hasLength(dataId) && !StringUtils.hasLength(group)) { return this.persistService.findConfigInfoByDataId(pageNo, pageSize, dataId); } else if (!StringUtils.hasLength(dataId) && StringUtils.hasLength(group)) { return this.persistService.findConfigInfoByGroup(pageNo, pageSize, group); } else { return this.persistService.findAllConfigInfo(pageNo, pageSize); } } /** * 分页模糊查找配置信息 * * @param pageNo * @param pageSize * @param group * @param dataId * @return */ public Page<ConfigInfo> findConfigInfoLike(final int pageNo, final int pageSize, final String group, final String dataId) { return this.persistService.findConfigInfoLike(pageNo, pageSize, dataId, group); } private void checkParameter(String dataId, String group, String content) { if (!StringUtils.hasLength(dataId) || StringUtils.containsWhitespace(dataId)) throw new ConfigServiceException("无效的dataId"); if (!StringUtils.hasLength(group) || StringUtils.containsWhitespace(group)) throw new ConfigServiceException("无效的group"); if (!StringUtils.hasLength(content)) throw new ConfigServiceException("无效的content"); } private void notifyOtherNodes(String dataId, String group) { this.notifyService.notifyConfigInfoChange(dataId, group); } public DiskService getDiskService() { return diskService; } public void setDiskService(DiskService diskService) { this.diskService = diskService; } public PersistService getPersistService() { return persistService; } public void setPersistService(PersistService persistService) { this.persistService = persistService; } public NotifyService getNotifyService() { return notifyService; } public void setNotifyService(NotifyService notifyService) { this.notifyService = notifyService; } }
diamond
com.taobao.diamond.server.service
PersistService
5
0
16
14
162
25
0
0
0.25
2
4
26
package com.taobao.diamond.server.service; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Properties; import javax.annotation.PostConstruct; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.lang.StringUtils; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.stereotype.Service; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.Page; import com.taobao.diamond.server.utils.PaginationHelper; import com.taobao.diamond.utils.ResourceUtils; import com.taobao.diamond.utils.TimeUtils; /** * 数据库服务,提供ConfigInfo在数据库的存取<br> * * @author boyan * @author leiwen.zh * @since 1.0 */ @Service public class PersistService { private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver"; // 最大记录条数 private static final int MAX_ROWS = 10000; // JDBC执行超时时间, 单位秒 private static final int QUERY_TIMEOUT = 2; private static final ConfigInfoRowMapper CONFIG_INFO_ROW_MAPPER = new ConfigInfoRowMapper(); private static final class ConfigInfoRowMapper implements ParameterizedRowMapper<ConfigInfo> { public ConfigInfo mapRow(ResultSet rs, int rowNum) throws SQLException { ConfigInfo info = new ConfigInfo(); info.setId(rs.getLong("id")); info.setDataId(rs.getString("data_id")); info.setGroup(rs.getString("group_id")); info.setContent(rs.getString("content")); info.setMd5(rs.getString("md5")); return info; } } private static String ensurePropValueNotNull(String srcValue) { if (srcValue == null) { throw new IllegalArgumentException("property is illegal:" + srcValue); } return srcValue; } private JdbcTemplate jt; /** * 单元测试用 * * @return */ public JdbcTemplate getJdbcTemplate() { return this.jt; } @PostConstruct public void initDataSource() throws Exception { // 读取jdbc.properties配置, 加载数据源 Properties props = ResourceUtils.getResourceAsProperties("jdbc.properties"); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(JDBC_DRIVER_NAME); ds.setUrl(ensurePropValueNotNull(props.getProperty("db.url"))); ds.setUsername(ensurePropValueNotNull(props.getProperty("db.user"))); ds.setPassword(ensurePropValueNotNull(props.getProperty("db.password"))); ds.setInitialSize(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.initialSize")))); ds.setMaxActive(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxActive")))); ds.setMaxIdle(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxIdle")))); ds.setMaxWait(Long.parseLong(ensurePropValueNotNull(props.getProperty("db.maxWait")))); ds.setPoolPreparedStatements(Boolean.parseBoolean(ensurePropValueNotNull(props .getProperty("db.poolPreparedStatements")))); this.jt = new JdbcTemplate(); this.jt.setDataSource(ds); // 设置最大记录数,防止内存膨胀 this.jt.setMaxRows(MAX_ROWS); // 设置JDBC执行超时时间 this.jt.setQueryTimeout(QUERY_TIMEOUT); } public void addConfigInfo(final ConfigInfo configInfo) { final Timestamp time = TimeUtils.getCurrentTime(); this.jt.update( "insert into config_info (data_id,group_id,content,md5,gmt_create,gmt_modified) values(?,?,?,?,?,?)", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); ps.setString(index++, configInfo.getContent()); ps.setString(index++, configInfo.getMd5()); ps.setTimestamp(index++, time); ps.setTimestamp(index++, time); } }); } public void removeConfigInfo(final ConfigInfo configInfo) { this.jt.update("delete from config_info where data_id=? and group_id=?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); } }); } public void updateConfigInfo(final ConfigInfo configInfo) { final Timestamp time = TimeUtils.getCurrentTime(); this.jt.update("update config_info set content=?,md5=?,gmt_modified=? where data_id=? and group_id=?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getContent()); ps.setString(index++, configInfo.getMd5()); ps.setTimestamp(index++, time); ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); } }); } public ConfigInfo findConfigInfo(final String dataId, final String group) { try { return this.jt.queryForObject( "select id,data_id,group_id,content,md5 from config_info where data_id=? and group_id=?", new Object[] { dataId, group }, CONFIG_INFO_ROW_MAPPER); } catch (EmptyResultDataAccessException e) { // 是EmptyResultDataAccessException, 表明数据不存在, 返回null return null; } } public ConfigInfo findConfigInfo(long id) { try { return this.jt.queryForObject("select id,data_id,group_id,content,md5 from config_info where id=?", new Object[] { id }, CONFIG_INFO_ROW_MAPPER); } catch (EmptyResultDataAccessException e) { return null; } } public Page<ConfigInfo> findConfigInfoByDataId(final int pageNo, final int pageSize, final String dataId) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info where data_id=?", "select id,data_id,group_id,content,md5 from config_info where data_id=?", new Object[] { dataId }, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findConfigInfoByGroup(final int pageNo, final int pageSize, final String group) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info where group_id=?", "select id,data_id,group_id,content,md5 from config_info where group_id=?", new Object[] { group }, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findAllConfigInfo(final int pageNo, final int pageSize) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info order by id", "select id,data_id,group_id,content,md5 from config_info order by id ", new Object[] {}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findConfigInfoLike(final int pageNo, final int pageSize, final String dataId, final String group) { if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) { return this.findAllConfigInfo(pageNo, pageSize); } PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); String sqlCountRows = "select count(id) from config_info where "; String sqlFetchRows = "select id,data_id,group_id,content,md5 from config_info where "; boolean wasFirst = true; if (!StringUtils.isBlank(dataId)) { sqlCountRows += "data_id like ? "; sqlFetchRows += "data_id like ? "; wasFirst = false; } if (!StringUtils.isBlank(group)) { if (wasFirst) { sqlCountRows += "group_id like ? "; sqlFetchRows += "group_id like ? "; } else { sqlCountRows += "and group_id like ? "; sqlFetchRows += "and group_id like ? "; } } Object[] args = null; if (!StringUtils.isBlank(dataId) && !StringUtils.isBlank(group)) { args = new Object[] { generateLikeArgument(dataId), generateLikeArgument(group) }; } else if (!StringUtils.isBlank(dataId)) { args = new Object[] { generateLikeArgument(dataId) }; } else if (!StringUtils.isBlank(group)) { args = new Object[] { generateLikeArgument(group) }; } return helper.fetchPage(this.jt, sqlCountRows, sqlFetchRows, args, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } private String generateLikeArgument(String s) { if (s.indexOf("*") >= 0) return s.replaceAll("\\*", "%"); else { return "%" + s + "%"; } } }
diamond
com.taobao.diamond.server.service
PersistService.ConfigInfoRowMapper
0
0
0
0
11
0
0
0
-1
0
0
46
package com.taobao.diamond.server.service; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Properties; import javax.annotation.PostConstruct; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.lang.StringUtils; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.stereotype.Service; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.Page; import com.taobao.diamond.server.utils.PaginationHelper; import com.taobao.diamond.utils.ResourceUtils; import com.taobao.diamond.utils.TimeUtils; /** * 数据库服务,提供ConfigInfo在数据库的存取<br> * * @author boyan * @author leiwen.zh * @since 1.0 */ @Service public class PersistService { private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver"; // 最大记录条数 private static final int MAX_ROWS = 10000; // JDBC执行超时时间, 单位秒 private static final int QUERY_TIMEOUT = 2; private static final ConfigInfoRowMapper CONFIG_INFO_ROW_MAPPER = new ConfigInfoRowMapper(); private static final class ConfigInfoRowMapper implements ParameterizedRowMapper<ConfigInfo> { public ConfigInfo mapRow(ResultSet rs, int rowNum) throws SQLException { ConfigInfo info = new ConfigInfo(); info.setId(rs.getLong("id")); info.setDataId(rs.getString("data_id")); info.setGroup(rs.getString("group_id")); info.setContent(rs.getString("content")); info.setMd5(rs.getString("md5")); return info; } } private static String ensurePropValueNotNull(String srcValue) { if (srcValue == null) { throw new IllegalArgumentException("property is illegal:" + srcValue); } return srcValue; } private JdbcTemplate jt; /** * 单元测试用 * * @return */ public JdbcTemplate getJdbcTemplate() { return this.jt; } @PostConstruct public void initDataSource() throws Exception { // 读取jdbc.properties配置, 加载数据源 Properties props = ResourceUtils.getResourceAsProperties("jdbc.properties"); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(JDBC_DRIVER_NAME); ds.setUrl(ensurePropValueNotNull(props.getProperty("db.url"))); ds.setUsername(ensurePropValueNotNull(props.getProperty("db.user"))); ds.setPassword(ensurePropValueNotNull(props.getProperty("db.password"))); ds.setInitialSize(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.initialSize")))); ds.setMaxActive(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxActive")))); ds.setMaxIdle(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxIdle")))); ds.setMaxWait(Long.parseLong(ensurePropValueNotNull(props.getProperty("db.maxWait")))); ds.setPoolPreparedStatements(Boolean.parseBoolean(ensurePropValueNotNull(props .getProperty("db.poolPreparedStatements")))); this.jt = new JdbcTemplate(); this.jt.setDataSource(ds); // 设置最大记录数,防止内存膨胀 this.jt.setMaxRows(MAX_ROWS); // 设置JDBC执行超时时间 this.jt.setQueryTimeout(QUERY_TIMEOUT); } public void addConfigInfo(final ConfigInfo configInfo) { final Timestamp time = TimeUtils.getCurrentTime(); this.jt.update( "insert into config_info (data_id,group_id,content,md5,gmt_create,gmt_modified) values(?,?,?,?,?,?)", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); ps.setString(index++, configInfo.getContent()); ps.setString(index++, configInfo.getMd5()); ps.setTimestamp(index++, time); ps.setTimestamp(index++, time); } }); } public void removeConfigInfo(final ConfigInfo configInfo) { this.jt.update("delete from config_info where data_id=? and group_id=?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); } }); } public void updateConfigInfo(final ConfigInfo configInfo) { final Timestamp time = TimeUtils.getCurrentTime(); this.jt.update("update config_info set content=?,md5=?,gmt_modified=? where data_id=? and group_id=?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { int index = 1; ps.setString(index++, configInfo.getContent()); ps.setString(index++, configInfo.getMd5()); ps.setTimestamp(index++, time); ps.setString(index++, configInfo.getDataId()); ps.setString(index++, configInfo.getGroup()); } }); } public ConfigInfo findConfigInfo(final String dataId, final String group) { try { return this.jt.queryForObject( "select id,data_id,group_id,content,md5 from config_info where data_id=? and group_id=?", new Object[] { dataId, group }, CONFIG_INFO_ROW_MAPPER); } catch (EmptyResultDataAccessException e) { // 是EmptyResultDataAccessException, 表明数据不存在, 返回null return null; } } public ConfigInfo findConfigInfo(long id) { try { return this.jt.queryForObject("select id,data_id,group_id,content,md5 from config_info where id=?", new Object[] { id }, CONFIG_INFO_ROW_MAPPER); } catch (EmptyResultDataAccessException e) { return null; } } public Page<ConfigInfo> findConfigInfoByDataId(final int pageNo, final int pageSize, final String dataId) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info where data_id=?", "select id,data_id,group_id,content,md5 from config_info where data_id=?", new Object[] { dataId }, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findConfigInfoByGroup(final int pageNo, final int pageSize, final String group) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info where group_id=?", "select id,data_id,group_id,content,md5 from config_info where group_id=?", new Object[] { group }, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findAllConfigInfo(final int pageNo, final int pageSize) { PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); return helper.fetchPage(this.jt, "select count(id) from config_info order by id", "select id,data_id,group_id,content,md5 from config_info order by id ", new Object[] {}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } public Page<ConfigInfo> findConfigInfoLike(final int pageNo, final int pageSize, final String dataId, final String group) { if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) { return this.findAllConfigInfo(pageNo, pageSize); } PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); String sqlCountRows = "select count(id) from config_info where "; String sqlFetchRows = "select id,data_id,group_id,content,md5 from config_info where "; boolean wasFirst = true; if (!StringUtils.isBlank(dataId)) { sqlCountRows += "data_id like ? "; sqlFetchRows += "data_id like ? "; wasFirst = false; } if (!StringUtils.isBlank(group)) { if (wasFirst) { sqlCountRows += "group_id like ? "; sqlFetchRows += "group_id like ? "; } else { sqlCountRows += "and group_id like ? "; sqlFetchRows += "and group_id like ? "; } } Object[] args = null; if (!StringUtils.isBlank(dataId) && !StringUtils.isBlank(group)) { args = new Object[] { generateLikeArgument(dataId), generateLikeArgument(group) }; } else if (!StringUtils.isBlank(dataId)) { args = new Object[] { generateLikeArgument(dataId) }; } else if (!StringUtils.isBlank(group)) { args = new Object[] { generateLikeArgument(group) }; } return helper.fetchPage(this.jt, sqlCountRows, sqlFetchRows, args, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); } private String generateLikeArgument(String s) { if (s.indexOf("*") >= 0) return s.replaceAll("\\*", "%"); else { return "%" + s + "%"; } } }
diamond
com.taobao.diamond.server.service
DiskService
3
0
13
8
138
20
0
0
0
4
2
22
package com.taobao.diamond.server.service; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.WebUtils; import com.taobao.diamond.common.Constants; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.server.exception.ConfigServiceException; /** * 磁盘操作服务 * * @author boyan * @date 2010-5-4 */ @Service public class DiskService { private static final Log log = LogFactory.getLog(DiskService.class); /** * 修改标记缓存 */ private final ConcurrentHashMap<String/* dataId + group */, Boolean/* 是否正在修改 */> modifyMarkCache = new ConcurrentHashMap<String, Boolean>(); @Autowired private ServletContext servletContext; public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public ServletContext getServletContext() { return this.servletContext; } /** * 单元测试用 * * @return */ public ConcurrentHashMap<String, Boolean> getModifyMarkCache() { return this.modifyMarkCache; } /** * 获取配置文件路径, 单元测试用 * * @param dataId * @param group * @return * @throws FileNotFoundException */ public String getFilePath(String dataId, String group) throws FileNotFoundException { return getFilePath(Constants.BASE_DIR + "/" + group + "/" + dataId); } public void saveToDisk(ConfigInfo configInfo) { String group = configInfo.getGroup(); String dataId = configInfo.getDataId(); String content = configInfo.getContent(); String cacheKey = generateCacheKey(group, dataId); // 标记正在写磁盘 if (this.modifyMarkCache.putIfAbsent(cacheKey, true) == null) { File tempFile = null; try { // 目标目录 String groupPath = getFilePath(Constants.BASE_DIR + "/" + group); createDirIfNessary(groupPath); // 目标文件 File targetFile = createFileIfNessary(groupPath, dataId); // 创建临时文件 tempFile = createTempFile(dataId, group); // 写数据至临时文件 FileUtils.writeStringToFile(tempFile, content, Constants.ENCODE); // 用临时文件覆盖目标文件, 完成本次磁盘操作 FileUtils.copyFile(tempFile, targetFile); } catch (Exception e) { String errorMsg = "save disk error, dataId=" + dataId + ",group=" + group; log.error(errorMsg, e); throw new ConfigServiceException(errorMsg, e); } finally { // 删除临时文件 if (tempFile != null && tempFile.exists()) { FileUtils.deleteQuietly(tempFile); } // 清除标记 this.modifyMarkCache.remove(cacheKey); } } else { throw new ConfigServiceException("config info is being motified, dataId=" + dataId + ",group=" + group); } } public boolean isModified(String dataId, String group) { return this.modifyMarkCache.get(generateCacheKey(group, dataId)) != null; } /** * 生成缓存key,用于标记文件是否正在被修改 * * @param group * @param dataId * * @return */ public final String generateCacheKey(String group, String dataId) { return group + "/" + dataId; } public void removeConfigInfo(String dataId, String group) { String cacheKey = generateCacheKey(group, dataId); // 标记正在写磁盘 if (this.modifyMarkCache.putIfAbsent(cacheKey, true) == null) { try { String basePath = getFilePath(Constants.BASE_DIR); createDirIfNessary(basePath); String groupPath = getFilePath(Constants.BASE_DIR + "/" + group); File groupDir = new File(groupPath); if (!groupDir.exists()) { return; } String dataPath = getFilePath(Constants.BASE_DIR + "/" + group + "/" + dataId); File dataFile = new File(dataPath); if (!dataFile.exists()) { return; } FileUtils.deleteQuietly(dataFile); } catch (Exception e) { String errorMsg = "delete config info error, dataId=" + dataId + ",group=" + group; log.error(errorMsg, e); throw new ConfigServiceException(errorMsg, e); } finally { // 清除标记 this.modifyMarkCache.remove(cacheKey); } } else { throw new ConfigServiceException("config info is being motified, dataId=" + dataId + ",group=" + group); } } private String getFilePath(String dir) throws FileNotFoundException { return WebUtils.getRealPath(servletContext, dir); } private void createDirIfNessary(String path) { final File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } } private File createFileIfNessary(String parent, String child) throws IOException { final File file = new File(parent, child); if (!file.exists()) { file.createNewFile(); // 设置文件权限 changeFilePermission(file); } return file; } private void changeFilePermission(File file) { // 文件权限设置为600 file.setExecutable(false, false); file.setWritable(false, false); file.setReadable(false, false); file.setExecutable(false, true); file.setWritable(true, true); file.setReadable(true, true); } private File createTempFile(String dataId, String group) throws IOException { return File.createTempFile(group + "-" + dataId, ".tmp"); } }
diamond
com.taobao.diamond.server.service
TimerTaskService
5
0
9
9
48
10
0
0
0.444444
1
5
17
package com.taobao.diamond.server.service; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.taobao.diamond.server.utils.SystemConfig; /** * 定时任务服务 * * @author boyan */ @Service public class TimerTaskService { private static final String THREAD_NAME = "diamond dump config thread"; @Autowired private PersistService persistService; @Autowired private DiskService diskService; @Autowired private ConfigService configService; private ScheduledExecutorService scheduledExecutorService; @PostConstruct public void init() { this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName(THREAD_NAME); t.setDaemon(true); return t; } }); DumpConfigInfoTask dumpTask = new DumpConfigInfoTask(this); dumpTask.run(); this.scheduledExecutorService.scheduleWithFixedDelay(dumpTask, SystemConfig.getDumpConfigInterval(), SystemConfig.getDumpConfigInterval(), TimeUnit.SECONDS); } @PreDestroy public void dispose() { if (this.scheduledExecutorService != null) { this.scheduledExecutorService.shutdown(); } } public void setPersistService(PersistService persistService) { this.persistService = persistService; } public PersistService getPersistService() { return persistService; } public void setDiskService(DiskService diskService) { this.diskService = diskService; } public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } public DiskService getDiskService() { return diskService; } }
diamond
com.taobao.diamond.server.exception
ConfigServiceException
1
0
4
4
20
4
0
0
1
0
0
12
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.server.exception; /** * Service层的任何异常都包装成这个Runtime异常抛出 * * @author boyan * @date 2010-5-5 */ public class ConfigServiceException extends RuntimeException { static final long serialVersionUID = -1L; public ConfigServiceException() { super(); } public ConfigServiceException(String message, Throwable cause) { super(message, cause); } public ConfigServiceException(String message) { super(message); } public ConfigServiceException(Throwable cause) { super(cause); } }
diamond
com.taobao.diamond.util
PatternUtils
0
0
2
2
38
8
0
0
-1
1
0
12
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.util; /** * 模糊查询时合成 sql的工具类 * * @filename PatternUtils.java * @author libinbin.pt * @datetime 2010-7-23 上午11:42:58 */ public class PatternUtils { /** * 检查参数字符串中是否包含符号 '*' * * @param patternStr * @return 包含返回true, 否则返回false */ public static boolean hasCharPattern(String patternStr) { if (patternStr == null) return false; String pattern = patternStr; for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == '*') return true; } return false; } /** * 替换掉所有的符号'*'为'%' * * @param sourcePattern * @return 返回替换后的字符串 */ public static String generatePattern(String sourcePattern) { if (sourcePattern == null) return ""; StringBuilder sb = new StringBuilder(); String pattern = sourcePattern; for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == '*') sb.append('%'); else sb.append(c); } return sb.toString(); } }
diamond
com.taobao.diamond.util
DiamondUtils
1
1
2
2
25
7
0
0
0
0
0
12
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.util; public class DiamondUtils { public static final char[] INVALID_CHAR = {';', '&', '%', '#', '$', '@', ',', '*', '^', '~', '(', ')', '/', '\\', '|', '+' }; /** * 判断字符串是否有空格 * * @param str * @return */ public static boolean hasInvalidChar(String str) { if (str == null || str.length() == 0) return true; int strLen = str.length(); for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch) || isInvalidChar(ch)) { return true; } } return false; } public static boolean isInvalidChar(char ch) { for (char c : INVALID_CHAR) { if (c == ch) return true; } return false; } }
diamond
com.taobao.diamond.util
ResourceUtils
0
0
10
10
131
22
0
0
-1
0
0
21
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Properties; /** * * @author boyan * @date 2010-5-4 */ public class ResourceUtils extends Object { /** */ /** * Returns the URL of the resource on the classpath * * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static URL getResourceURL(String resource) throws IOException { URL url = null; ClassLoader loader = ResourceUtils.class.getClassLoader(); if (loader != null) url = loader.getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) throw new IOException("Could not find resource " + resource); return url; } /** */ /** * Returns the URL of the resource on the classpath * * @param loader * The classloader used to load the resource * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static URL getResourceURL(ClassLoader loader, String resource) throws IOException { URL url = null; if (loader != null) url = loader.getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) throw new IOException("Could not find resource " + resource); return url; } /** */ /** * Returns a resource on the classpath as a Stream object * * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static InputStream getResourceAsStream(String resource) throws IOException { InputStream in = null; ClassLoader loader = ResourceUtils.class.getClassLoader(); if (loader != null) in = loader.getResourceAsStream(resource); if (in == null) in = ClassLoader.getSystemResourceAsStream(resource); if (in == null) throw new IOException("Could not find resource " + resource); return in; } /** */ /** * Returns a resource on the classpath as a Stream object * * @param loader * The classloader used to load the resource * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { InputStream in = null; if (loader != null) in = loader.getResourceAsStream(resource); if (in == null) in = ClassLoader.getSystemResourceAsStream(resource); if (in == null) throw new IOException("Could not find resource " + resource); return in; } /** */ /** * Returns a resource on the classpath as a Properties object * * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static Properties getResourceAsProperties(String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(propfile); props.load(in); in.close(); return props; } /** */ /** * Returns a resource on the classpath as a Properties object * * @param loader * The classloader used to load the resource * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(loader, propfile); props.load(in); in.close(); return props; } /** */ /** * Returns a resource on the classpath as a Reader object * * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static InputStreamReader getResourceAsReader(String resource) throws IOException { return new InputStreamReader(getResourceAsStream(resource)); } /** */ /** * Returns a resource on the classpath as a Reader object * * @param loader * The classloader used to load the resource * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException { return new InputStreamReader(getResourceAsStream(loader, resource)); } /** */ /** * Returns a resource on the classpath as a File object * * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static File getResourceAsFile(String resource) throws IOException { return new File(getResourceURL(resource).getFile()); } /** */ /** * Returns a resource on the classpath as a File object * * @param loader * The classloader used to load the resource * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException { return new File(getResourceURL(loader, resource).getFile()); } }
diamond
com.taobao.diamond.util
RandomDiamondUtils
5
0
6
6
66
13
0
0
0
1
1
18
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.util; import java.util.List; import java.util.Random; import com.taobao.diamond.domain.DiamondConf; public class RandomDiamondUtils { private List<DiamondConf> allDiamondConfs; private int retry_times; private int max_times; private int[] randomIndexSequence; private int currentIndex; public void init(List<DiamondConf> diamondConfs) { int len=diamondConfs.size(); if(allDiamondConfs==null){ allDiamondConfs=diamondConfs; } //最大访问次数为diamondConfs.size() max_times=len; //设置重试次数为0 retry_times=0; //当前下标设置为0 currentIndex=0; //初始化下标数组 randomIndexSequence=new int[len]; //赋值 for(int i=0;i<len;i++){ randomIndexSequence[i]=i; } // 1.长度为1直接返回 if(len==1) return; // 2.长度为2,50%的概率换一下 Random random=new Random(); if(len==2 && random.nextInt(2)==1) { int temp=randomIndexSequence[0]; randomIndexSequence[0]=randomIndexSequence[1]; randomIndexSequence[1]=temp; return; } // 3.随机产生一个0~n-2的下标,并将此下标的值与数组最后一个元素交换,进行2n次 int times=2 * len; for(int j=0;j<times;j++){ int selectedIndex=random.nextInt(len-1); //将随机产生下标的值与最后一个元素值交换 int temp=randomIndexSequence[selectedIndex]; randomIndexSequence[selectedIndex]=randomIndexSequence[len-1]; randomIndexSequence[len-1]=temp; } } public int getRetry_times() { return retry_times; } public int getMax_times() { return max_times; } /** * 随机取得一个diamondServer配置对象 * * @param diamondConfs * @return DiamondConf diamondServer配置对象 */ public DiamondConf generatorOneDiamondConf(){ DiamondConf diamondConf=null; //访问下标小于最后一个下标 if(retry_times < max_times){ //得到当前访问下标 currentIndex=randomIndexSequence[retry_times]; diamondConf = allDiamondConfs.get(currentIndex); } else{ randomIndexSequence=null; } retry_times++; return diamondConf; } public int[] getRandomIndexSequence() { return randomIndexSequence; } public String getSequenceToString(){ StringBuilder sb=new StringBuilder(); for(int i : this.randomIndexSequence) sb.append(i+""); return sb.toString(); } }
diamond
com.taobao.diamond.domain
ContextResult
5
0
12
12
48
12
0
0
0.166667
1
1
21
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.io.Serializable; /** * 根据dataId,groupName精确查询返回的对象 * * @filename ContextResult.java * @author libinbin.pt * @datetime 2010-7-15 下午06:49:12 */ /** * * @filename ContextResult.java * @author libinbin.pt * @param <T> * @datetime 2010-7-16 下午05:48:54 */ @SuppressWarnings("serial") public class ContextResult implements Serializable { private boolean isSuccess; // 是否成功 private int statusCode; // 状态码 private String statusMsg = ""; // 状态信息 private String receiveResult; // 回传信息 private ConfigInfo configInfo; // 配置对象包括[内容,dataId,groupName] public ContextResult() { } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getStatusMsg() { return statusMsg; } public void setStatusMsg(String statusMsg) { this.statusMsg = statusMsg; } public ConfigInfo getConfigInfo() { return configInfo; } public void setConfigInfo(ConfigInfo configInfo) { this.configInfo = configInfo; } public String getReceiveResult() { return receiveResult; } public void setReceiveResult(String receiveResult) { this.receiveResult = receiveResult; } @Override public String toString() { return "[" + "statusCode=" + statusCode + ",isSuccess=" + isSuccess + ",statusMsg=" + statusMsg + ",receiveResult=" + receiveResult + ",[configInfo=" + configInfo + "]]"; } }
diamond
com.taobao.diamond.domain
DiamondSDKConf
3
0
6
6
23
6
0
0
0.5
1
0
17
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.util.List; import org.apache.commons.lang.builder.ToStringBuilder; public class DiamondSDKConf { private static final long serialVersionUID = 8378550702596810462L; private String serverId; // 多个diamond配置 private List<DiamondConf> diamondConfs; // 构造时需要传入diamondConfs 列表 public DiamondSDKConf(List<DiamondConf> diamondConfs) { this.diamondConfs = diamondConfs; } // setter,getter public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public List<DiamondConf> getDiamondConfs() { return diamondConfs; } public void setDiamondConfs(List<DiamondConf> diamondConfs) { this.diamondConfs = diamondConfs; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
diamond
com.taobao.diamond.domain
DiamondConf
5
0
12
12
51
12
0
0
0.166667
2
0
14
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.text.MessageFormat; /** * 单个diamond基本信息配置类 * * @filename DiamondConf.java * @author libinbin.pt * @datetime 2010-8-24 下午03:52:15 */ public class DiamondConf { // diamondServer web访问地址 private String diamondIp; // diamondServer web访问端口 private String diamondPort; // diamondServer web登录用户名 private String diamondUsername; // diamondServer web登录密码 private String diamondPassword; private static MessageFormat DIAMONDURL_FORMAT = new MessageFormat("http://{0}:{1}"); public DiamondConf(){ } public DiamondConf(String diamondIp, String diamondPort, String diamondUsername, String diamondPassword) { this.diamondIp = diamondIp; this.diamondPort = diamondPort; this.diamondUsername = diamondUsername; this.diamondPassword = diamondPassword; } //合成diamond访问路径 public String getDiamondConUrl(){ return DIAMONDURL_FORMAT.format(new String[]{this.diamondIp,this.diamondPort}); } public String getDiamondIp() { return diamondIp; } public void setDiamondIp(String diamondIp) { this.diamondIp = diamondIp; } public String getDiamondPort() { return diamondPort; } public void setDiamondPort(String diamondPort) { this.diamondPort = diamondPort; } public String getDiamondUsername() { return diamondUsername; } public void setDiamondUsername(String diamondUsername) { this.diamondUsername = diamondUsername; } public String getDiamondPassword() { return diamondPassword; } public void setDiamondPassword(String diamondPassword) { this.diamondPassword = diamondPassword; } @Override public String toString() { return "[diamondIp=" + diamondIp + ",diamondPort=" + diamondPort + ",diamondUsername=" + diamondUsername + ",diamondPassword=" + diamondPassword + "]"; } }
diamond
com.taobao.diamond.domain
PageContextResult
11
0
26
26
105
34
0
0
0.153846
1
0
15
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.util.List; public class PageContextResult<T> { // 总记录数 private long totalCounts = 0; // 总页数 private long totalPages = 1; // 当前是哪页 private long currentPage = 1; // 偏移位置 private long offset = 0; // 偏移长度 private long length = 1; // 每页记录数 private long sizeOfPerPage = 10; // 记录数据集 private List<T> diamondData; // 数据集的大小 private long originalDataSize = 0; private int statusCode; // 状态码 // 是否成功 private boolean isSuccess = false; // 状态信息 private String statusMsg; public PageContextResult() { } public PageContextResult(long totalCounts, long sizeOfPerPage) { this.totalCounts = totalCounts; this.sizeOfPerPage = sizeOfPerPage; } public void operation() { // =========检验sizeOfPerPage合法性 if (totalCounts < 0) { totalCounts = 0; } // =========检验sizeOfPerPage合法性 if (sizeOfPerPage <= 0) sizeOfPerPage = 1; // =========计算总页数 // 如果总记录数能被每页大小整除,则总页数为(总记录数 /每页大小) // 否则总页数为(总记录数 /每页大小+1) if (totalCounts % sizeOfPerPage == 0) { totalPages = totalCounts / sizeOfPerPage; } else totalPages = totalCounts / sizeOfPerPage + 1; // =========纠正总页数 if (totalPages <= 1) totalPages = 1; // =========检验currentPage合法性 if (currentPage <= 1) currentPage = 1; else if (currentPage > totalPages) currentPage = totalPages; // =========计算偏移位置 offset = (currentPage - 1) * sizeOfPerPage; // =========检验offset合法性 if (offset < 0) offset = 0; // =========计算长度 if (currentPage < totalPages) length = sizeOfPerPage; else length = totalCounts - (currentPage - 1) * sizeOfPerPage; } // setter , getter public long getTotalCounts() { return totalCounts; } public void setTotalCounts(long totalCounts) { this.totalCounts = totalCounts; } public long getTotalPages() { return totalPages; } public long getCurrentPage() { return currentPage; } public void setCurrentPage(long currentPage) { this.currentPage = currentPage; } public long getOffset() { return offset; } public long getLength() { return length; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public long getSizeOfPerPage() { return sizeOfPerPage; } public void setTotalPages(long totalPages) { this.totalPages = totalPages; } public void setOffset(long offset) { this.offset = offset; } public void setLength(long length) { this.length = length; } public void setSizeOfPerPage(long sizeOfPerPage) { this.sizeOfPerPage = sizeOfPerPage; } public List<T> getDiamondData() { return diamondData; } public void setDiamondData(List<T> diamondData) { this.diamondData = diamondData; } public long getOriginalDataSize() { return originalDataSize; } public void setOriginalDataSize(long originalDataSize) { this.originalDataSize = originalDataSize; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } public String getStatusMsg() { return statusMsg; } public void setStatusMsg(String statusMsg) { this.statusMsg = statusMsg; } @Override public String toString() { return "[totalCounts=" + totalCounts + ",totalPages=" + totalPages + ",currentPage=" + currentPage + ",offset=" + offset + ",length=" + length + ",sizeOfPerPage=" + sizeOfPerPage + ",diamondData=" + diamondData + ",isSuccess=" + isSuccess + ",statusMsg=" + statusMsg + "]"; } }
diamond
com.taobao.diamond.domain
BatchContextResult
6
0
11
11
45
11
0
0
0.181818
1
0
8
package com.taobao.diamond.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 批处理的返回结果 * * @author leiwen.zh * */ public class BatchContextResult<T> implements Serializable { private static final long serialVersionUID = -5170746311067772091L; // 批处理是否成功 private boolean success = true; // 请求返回的状态码 private int statusCode; // 用户可读的返回信息 private String statusMsg; // response中的元信息 private String responseMsg; // 返回的结果集 private List<T> result; public BatchContextResult() { this.result = new ArrayList<T>(); } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getStatusMsg() { return statusMsg; } public void setStatusMsg(String statusMsg) { this.statusMsg = statusMsg; } public String getResponseMsg() { return responseMsg; } public void setResponseMsg(String responseMsg) { this.responseMsg = responseMsg; } public List<T> getResult() { return result; } @Override public String toString() { return "BatchContextResult [success=" + success + ", statusCode=" + statusCode + ", statusMsg=" + statusMsg + ", result=" + result + "]"; } }
diamond
com.taobao.diamond.domain
Page
5
0
8
8
37
8
0
0
0.5
5
0
17
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 分页对象 * * @author boyan * @date 2010-5-6 * @param <E> */ public class Page<E> implements Serializable { static final long serialVersionUID = -1L; private int totalCount; // 总记录数 private int pageNumber; // 页数 private int pagesAvailable; // 总页数 private List<E> pageItems = new ArrayList<E>(); // 该页内容 public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public void setPagesAvailable(int pagesAvailable) { this.pagesAvailable = pagesAvailable; } public void setPageItems(List<E> pageItems) { this.pageItems = pageItems; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageNumber() { return pageNumber; } public int getPagesAvailable() { return pagesAvailable; } public List<E> getPageItems() { return pageItems; } }
diamond
com.taobao.diamond.domain
ConfigInfo
6
0
17
17
111
40
1
0
0.176471
6
1
18
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.domain; import java.io.PrintWriter; import java.io.Serializable; import com.taobao.diamond.md5.MD5; /** * 配置信息类 * * @author boyan * @date 2010-5-4 */ public class ConfigInfo implements Serializable, Comparable<ConfigInfo> { static final long serialVersionUID = -1L; private String dataId; private String content; private String md5; private String group; private long id; public ConfigInfo() { } public ConfigInfo(String dataId, String group, String content) { super(); this.dataId = dataId; this.content = content; this.group = group; if (this.content != null) { this.md5 = MD5.getInstance().getMD5String(this.content); } } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public void dump(PrintWriter writer) { writer.write(this.content); } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public int compareTo(ConfigInfo o) { if (o == null) return 1; if (this.dataId == null && o.getDataId() != null) return -1; int cmpDataId = this.dataId.compareTo(o.getDataId()); if (cmpDataId != 0) { return cmpDataId; } if (this.group == null && o.getGroup() != null) return -1; int cmpGroup = this.group.compareTo(o.getGroup()); if (cmpGroup != 0) { return cmpGroup; } if (this.content == null && o.getContent() != null) return -1; int cmpContent = this.content.compareTo(o.getContent()); if (cmpContent != 0) { return cmpContent; } return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((dataId == null) ? 0 : dataId.hashCode()); result = prime * result + ((group == null) ? 0 : group.hashCode()); result = prime * result + ((md5 == null) ? 0 : md5.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ConfigInfo other = (ConfigInfo) obj; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (dataId == null) { if (other.dataId != null) return false; } else if (!dataId.equals(other.dataId)) return false; if (group == null) { if (other.group != null) return false; } else if (!group.equals(other.group)) return false; if (md5 == null) { if (other.md5 != null) return false; } else if (!md5.equals(other.md5)) return false; return true; } @Override public String toString() { return "[" + "dataId=" + dataId + "," + "groupName=" + group + "," + "context=" + content + "," + "]"; } }
diamond
com.taobao.diamond.domain
ConfigInfoEx
3
0
7
7
30
7
0
1
0.428571
1
0
3
package com.taobao.diamond.domain; /** * ConfigInfo的扩展类, 解决老版本的SDK与新版本的server由于反序列化字段错误而产生的不兼容问题 * * @author leiwen.zh * */ public class ConfigInfoEx extends ConfigInfo { private static final long serialVersionUID = -1L; // 批量查询时, 单条数据的状态码, 具体的状态码在Constants.java中 private int status; // 批量查询时, 单条数据的信息 private String message; public ConfigInfoEx() { super(); } public ConfigInfoEx(String dataId, String group, String content) { super(dataId, group, content); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "ConfigInfoEx [status=" + status + ", message=" + message + ", getDataId()=" + getDataId() + ", getGroup()=" + getGroup() + ", getContent()=" + getContent() + ", getMd5()=" + getMd5() + "]"; } }
diamond
com.taobao.diamond.sdkapi.impl
DiamondSDKManagerImpl
7
0
19
10
0
80
0
0
0
0
11
58
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.sdkapi.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.type.TypeReference; import com.taobao.diamond.common.Constants; import com.taobao.diamond.domain.BatchContextResult; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.ConfigInfoEx; import com.taobao.diamond.domain.ContextResult; import com.taobao.diamond.domain.DiamondConf; import com.taobao.diamond.domain.DiamondSDKConf; import com.taobao.diamond.domain.Page; import com.taobao.diamond.domain.PageContextResult; import com.taobao.diamond.sdkapi.DiamondSDKManager; import com.taobao.diamond.util.PatternUtils; import com.taobao.diamond.util.RandomDiamondUtils; import com.taobao.diamond.utils.JSONUtils; /** * SDK对外开放的数据接口的功能实现 * * @filename DiamondSDKManagerImpl.java * @author libinbin.pt * @datetime 2010-7-16 下午04:00:19 */ public class DiamondSDKManagerImpl implements DiamondSDKManager { private static final Log log = LogFactory.getLog("diamondSdkLog"); // DiamondSDKConf配置集map private Map<String, DiamondSDKConf> diamondSDKConfMaps; // 连接超时时间 private final int connection_timeout; // 请求超时时间 private final int require_timeout; // 构造时需要传入连接超时时间,请求超时时间 public DiamondSDKManagerImpl(int connection_timeout, int require_timeout) throws IllegalArgumentException { if (connection_timeout < 0) throw new IllegalArgumentException("连接超时时间设置必须大于0[单位(毫秒)]!"); if (require_timeout < 0) throw new IllegalArgumentException("请求超时时间设置必须大于0[单位(毫秒)]!"); this.connection_timeout = connection_timeout; this.require_timeout = require_timeout; int maxHostConnections = 50; MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections); connectionManager.getParams().setStaleCheckingEnabled(true); this.client = new HttpClient(connectionManager); // 设置连接超时时间 client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connection_timeout); // 设置读超时为1分钟 client.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000); client.getParams().setContentCharset("GBK"); log.info("设置连接超时时间为: " + this.connection_timeout + "毫秒"); } /** * 使用指定的diamond来推送数据 * * @param dataId * @param groupName * @param context * @param serverId * @return ContextResult 单个对象 */ public synchronized ContextResult pulish(String dataId, String groupName, String context, String serverId) { ContextResult response = null; // 进行dataId,groupName,context,serverId为空验证 if (validate(dataId, groupName, context)) { response = this.processPulishByDefinedServerId(dataId, groupName, context, serverId); return response; } // 未通过为空验证 response = new ContextResult(); response.setSuccess(false); response.setStatusMsg("请确保dataId,group,content不为空"); return response; } /** * 使用指定的diamond来推送修改后的数据 * * @param dataId * @param groupName * @param context * @param serverId * @return ContextResult 单个对象 */ public synchronized ContextResult pulishAfterModified(String dataId, String groupName, String context, String serverId) { ContextResult response = null; // 进行dataId,groupName,context,serverId为空验证 if (validate(dataId, groupName, context)) { // 向diamondserver发布修改数据 response = this.processPulishAfterModifiedByDefinedServerId(dataId, groupName, context, serverId); return response; } else { response = new ContextResult(); // 未通过为空验证 response.setSuccess(false); response.setStatusMsg("请确保dataId,group,content不为空"); return response; } } // -------------------------模糊查询-------------------------------// /** * 使用指定的diamond来模糊查询数据 * * @param dataIdPattern * @param groupNamePattern * @param serverId * @param currentPage * @param sizeOfPerPage * @return PageContextResult<ConfigInfo> 单个对象 * @throws SQLException */ public synchronized PageContextResult<ConfigInfo> queryBy(String dataIdPattern, String groupNamePattern, String serverId, long currentPage, long sizeOfPerPage) { return processQuery(dataIdPattern, groupNamePattern, null, serverId, currentPage, sizeOfPerPage); } /** * 根据指定的 dataId,组名和content到指定配置的diamond来查询数据列表 如果模式中包含符号'*',则会自动替换为'%'并使用[ * like ]语句 如果模式中不包含符号'*'并且不为空串(包括" "),则使用[ = ]语句 * * @param dataIdPattern * @param groupNamePattern * @param contentPattern * @param serverId * @param currentPage * @param sizeOfPerPage * @return PageContextResult<ConfigInfo> 单个对象 * @throws SQLException */ public synchronized PageContextResult<ConfigInfo> queryBy(String dataIdPattern, String groupNamePattern, String contentPattern, String serverId, long currentPage, long sizeOfPerPage) { return processQuery(dataIdPattern, groupNamePattern, contentPattern, serverId, currentPage, sizeOfPerPage); } // =====================精确查询 ================================== /** * 使用指定的diamond和指定的dataId,groupName来精确查询数据 * * @param dataId * @param groupName * @param serverId * @return ContextResult 单个对象 * @throws SQLException */ public synchronized ContextResult queryByDataIdAndGroupName(String dataId, String groupName, String serverId) { ContextResult result = new ContextResult(); PageContextResult<ConfigInfo> pageContextResult = processQuery(dataId, groupName, null, serverId, 1, 1); result.setStatusMsg(pageContextResult.getStatusMsg()); result.setSuccess(pageContextResult.isSuccess()); result.setStatusCode(pageContextResult.getStatusCode()); if (pageContextResult.isSuccess()) { List<ConfigInfo> list = pageContextResult.getDiamondData(); if (list != null && !list.isEmpty()) { ConfigInfo info = list.iterator().next(); result.setConfigInfo(info); result.setReceiveResult(info.getContent()); result.setStatusCode(pageContextResult.getStatusCode()); } } return result; } // ========================精确查询结束================================== // /////////////////////////私有工具对象定义和工具方法实现//////////////////////////////////////// private final HttpClient client; // =========================== 推送 =============================== private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context, String serverId) { ContextResult response = new ContextResult(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("登录失败,造成错误的原因可能是指定的serverId为空或不存在"); return response; } if (log.isDebugEnabled()) log.debug("使用processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + "," + serverId + ")进行推送"); String postUrl = "/diamond-server/admin.do?method=postConfig"; PostMethod post = new PostMethod(postUrl); // 设置请求超时时间 post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", groupName); NameValuePair content_value = new NameValuePair("content", context); // 设置参数 post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); // 配置对象 ConfigInfo configInfo = new ConfigInfo(); configInfo.setDataId(dataId); configInfo.setGroup(groupName); configInfo.setContent(context); if (log.isDebugEnabled()) log.debug("待推送的ConfigInfo: " + configInfo); // 添加一个配置对象到响应结果中 response.setConfigInfo(configInfo); // 执行方法并返回http状态码 int status = client.executeMethod(post); response.setReceiveResult(post.getResponseBodyAsString()); response.setStatusCode(status); log.info("状态码:" + status + ",响应结果:" + post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { response.setSuccess(true); response.setStatusMsg("推送处理成功"); log.info("推送处理成功, dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg("推送处理超时, 默认超时时间为:" + require_timeout + "毫秒"); log.error("推送处理超时,默认超时时间为:" + require_timeout + "毫秒, dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else { response.setSuccess(false); response.setStatusMsg("推送处理失败, 状态码为:" + status); log.error("推送处理失败:" + response.getReceiveResult() + ",dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } } catch (HttpException e) { response.setStatusMsg("推送处理发生HttpException:" + e.getMessage()); log.error("推送处理发生HttpException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } catch (IOException e) { response.setStatusMsg("推送处理发生IOException:" + e.getMessage()); log.error("推送处理发生IOException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } finally { // 释放连接资源 post.releaseConnection(); } return response; } // =========================== 推送结束 =============================== // =========================== 修改 =============================== private ContextResult processPulishAfterModifiedByDefinedServerId(String dataId, String groupName, String context, String serverId) { ContextResult response = new ContextResult(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("登录失败,造成错误的原因可能是指定的serverId为空"); return response; } if (log.isDebugEnabled()) log.debug("使用processPulishAfterModifiedByDefinedServerId(" + dataId + "," + groupName + "," + context + "," + serverId + ")进行推送修改"); // 是否存在此dataId,groupName的数据记录 ContextResult result = null; result = queryByDataIdAndGroupName(dataId, groupName, serverId); if (null == result || !result.isSuccess()) { response.setSuccess(false); response.setStatusMsg("找不到需要修改的数据记录,记录不存在!"); log.warn("找不到需要修改的数据记录,记录不存在! dataId=" + dataId + ",group=" + groupName + ",serverId=" + serverId); return response; } // 有数据,则修改 else { String postUrl = "/diamond-server/admin.do?method=updateConfig"; PostMethod post = new PostMethod(postUrl); // 设置请求超时时间 post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", groupName); NameValuePair content_value = new NameValuePair("content", context); // 设置参数 post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); // 配置对象 ConfigInfo configInfo = new ConfigInfo(); configInfo.setDataId(dataId); configInfo.setGroup(groupName); configInfo.setContent(context); if (log.isDebugEnabled()) log.debug("待推送的修改ConfigInfo: " + configInfo); // 添加一个配置对象到响应结果中 response.setConfigInfo(configInfo); // 执行方法并返回http状态码 int status = client.executeMethod(post); response.setReceiveResult(post.getResponseBodyAsString()); response.setStatusCode(status); log.info("状态码:" + status + ",响应结果:" + post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { response.setSuccess(true); response.setStatusMsg("推送修改处理成功"); log.info("推送修改处理成功"); } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg("推送修改处理超时,默认超时时间为:" + require_timeout + "毫秒"); log.error("推送修改处理超时,默认超时时间为:" + require_timeout + "毫秒, dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else { response.setSuccess(false); response.setStatusMsg("推送修改处理失败,失败原因请通过ContextResult的getReceiveResult()方法查看"); log.error("推送修改处理失败:" + response.getReceiveResult() + ",dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } } catch (HttpException e) { response.setSuccess(false); response.setStatusMsg("推送修改方法执行过程发生HttpException:" + e.getMessage()); log.error( "在推送修改方法processPulishAfterModifiedByDefinedServerId(String dataId, String groupName, String context,String serverId)执行过程中发生HttpException:dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); return response; } catch (IOException e) { response.setSuccess(false); response.setStatusMsg("推送修改方法执行过程发生IOException:" + e.getMessage()); log.error( "在推送修改方法processPulishAfterModifiedByDefinedServerId(String dataId, String groupName, String context,String serverId)执行过程中发生IOException:dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); return response; } finally { // 释放连接资源 post.releaseConnection(); } return response; } } // =========================== 修改结束 =============================== /** * 利用 httpclient实现页面登录 * * @return 登录结果 true:登录成功,false:登录失败 */ private boolean login(String serverId) { // serverId 为空判断 if (StringUtils.isEmpty(serverId) || StringUtils.isBlank(serverId)) return false; DiamondSDKConf defaultConf = diamondSDKConfMaps.get(serverId); log.info("[login] 登录使用serverId:" + serverId + ",该环境对象属性:" + defaultConf); if (null == defaultConf) return false; RandomDiamondUtils util = new RandomDiamondUtils(); // 初始化随机取值器 util.init(defaultConf.getDiamondConfs()); if (defaultConf.getDiamondConfs().size() == 0) return false; boolean flag = false; log.info("[randomSequence] 此次访问序列为: " + util.getSequenceToString()); // 最多重试次数为:某个环境的所有已配置的diamondConf的长度 while (util.getRetry_times() < util.getMax_times()) { // 得到随机取得的diamondConf DiamondConf diamondConf = util.generatorOneDiamondConf(); log.info("第" + util.getRetry_times() + "次尝试:" + diamondConf); if (diamondConf == null) break; client.getHostConfiguration().setHost(diamondConf.getDiamondIp(), Integer.parseInt(diamondConf.getDiamondPort()), "http"); PostMethod post = new PostMethod("/diamond-server/login.do?method=login"); // 设置请求超时时间 post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); // 填充用户名,密码 NameValuePair username_value = new NameValuePair("username", diamondConf.getDiamondUsername()); NameValuePair password_value = new NameValuePair("password", diamondConf.getDiamondPassword()); // 设置请求内容 post.setRequestBody(new NameValuePair[] { username_value, password_value }); log.info("使用diamondIp: " + diamondConf.getDiamondIp() + ",diamondPort: " + diamondConf.getDiamondPort() + ",diamondUsername: " + diamondConf.getDiamondUsername() + ",diamondPassword: " + diamondConf.getDiamondPassword() + "登录diamondServerUrl: [" + diamondConf.getDiamondConUrl() + "]"); try { int state = client.executeMethod(post); log.info("登录返回状态码:" + state); // 状态码为200,则登录成功,跳出循环并返回true if (state == HttpStatus.SC_OK) { log.info("第" + util.getRetry_times() + "次尝试成功"); flag = true; break; } } catch (HttpException e) { log.error("登录过程发生HttpException", e); } catch (IOException e) { log.error("登录过程发生IOException", e); } finally { post.releaseConnection(); } } if (flag == false) { log.error("造成login失败的原因可能是:所有diamondServer的配置环境目前均不可用.serverId=" + serverId); } return flag; } static final String LIST_FORMAT_URL = "/diamond-server/admin.do?method=listConfig&group=%s&dataId=%s&pageNo=%d&pageSize=%d"; static final String LIST_LIKE_FORMAT_URL = "/diamond-server/admin.do?method=listConfigLike&group=%s&dataId=%s&pageNo=%d&pageSize=%d"; /** * 处理查询 * * @param dataIdPattern * @param groupNamePattern * @param contentPattern * @param serverId * @param currentPage * @param sizeOfPerPage * @return */ @SuppressWarnings("unchecked") private PageContextResult<ConfigInfo> processQuery(String dataIdPattern, String groupNamePattern, String contentPattern, String serverId, long currentPage, long sizeOfPerPage) { PageContextResult<ConfigInfo> response = new PageContextResult<ConfigInfo>(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("登录失败,造成错误的原因可能是指定的serverId为空或不存在"); return response; } if (log.isDebugEnabled()) log.debug("使用processQuery(" + dataIdPattern + "," + groupNamePattern + "," + contentPattern + "," + serverId + ")进行查询"); boolean hasPattern = PatternUtils.hasCharPattern(dataIdPattern) || PatternUtils.hasCharPattern(groupNamePattern) || PatternUtils.hasCharPattern(contentPattern); String url = null; if (hasPattern) { if (!StringUtils.isBlank(contentPattern)) { log.warn("注意, 正在根据内容来进行模糊查询, dataIdPattern=" + dataIdPattern + ",groupNamePattern=" + groupNamePattern + ",contentPattern=" + contentPattern); // 模糊查询内容,全部查出来 url = String.format(LIST_LIKE_FORMAT_URL, groupNamePattern, dataIdPattern, 1, Integer.MAX_VALUE); } else url = String.format(LIST_LIKE_FORMAT_URL, groupNamePattern, dataIdPattern, currentPage, sizeOfPerPage); } else { url = String.format(LIST_FORMAT_URL, groupNamePattern, dataIdPattern, currentPage, sizeOfPerPage); } GetMethod method = new GetMethod(url); configureGetMethod(method); try { int status = client.executeMethod(method); response.setStatusCode(status); switch (status) { case HttpStatus.SC_OK: String json = ""; try { json = getContent(method).trim(); Page<ConfigInfo> page = null; if (!json.equals("null")) { page = (Page<ConfigInfo>) JSONUtils.deserializeObject(json, new TypeReference<Page<ConfigInfo>>() { }); } if (page != null) { List<ConfigInfo> diamondData = page.getPageItems(); if (!StringUtils.isBlank(contentPattern)) { Pattern pattern = Pattern.compile(contentPattern.replaceAll("\\*", ".*")); List<ConfigInfo> newList = new ArrayList<ConfigInfo>(); // 强制排序 Collections.sort(diamondData); int totalCount = 0; long begin = sizeOfPerPage * (currentPage - 1); long end = sizeOfPerPage * currentPage; for (ConfigInfo configInfo : diamondData) { if (configInfo.getContent() != null) { Matcher m = pattern.matcher(configInfo.getContent()); if (m.find()) { // 只添加sizeOfPerPage个 if (totalCount >= begin && totalCount < end) { newList.add(configInfo); } totalCount++; } } } page.setPageItems(newList); page.setTotalCount(totalCount); } response.setOriginalDataSize(diamondData.size()); response.setTotalCounts(page.getTotalCount()); response.setCurrentPage(currentPage); response.setSizeOfPerPage(sizeOfPerPage); } else { response.setOriginalDataSize(0); response.setTotalCounts(0); response.setCurrentPage(currentPage); response.setSizeOfPerPage(sizeOfPerPage); } response.operation(); List<ConfigInfo> pageItems = new ArrayList<ConfigInfo>(); if (page != null) { pageItems = page.getPageItems(); } response.setDiamondData(pageItems); response.setSuccess(true); response.setStatusMsg("指定diamond的查询完成"); log.info("指定diamond的查询完成, url=" + url); } catch (Exception e) { response.setSuccess(false); response.setStatusMsg("反序列化失败,错误信息为:" + e.getLocalizedMessage()); log.error("反序列化page对象失败, dataId=" + dataIdPattern + ",group=" + groupNamePattern + ",serverId=" + serverId + ",json=" + json, e); } break; case HttpStatus.SC_REQUEST_TIMEOUT: response.setSuccess(false); response.setStatusMsg("查询数据超时" + require_timeout + "毫秒"); log.error("查询数据超时,默认超时时间为:" + require_timeout + "毫秒, dataId=" + dataIdPattern + ",group=" + groupNamePattern + ",serverId=" + serverId); break; default: response.setSuccess(false); response.setStatusMsg("查询数据出错,服务器返回状态码为" + status); log.error("查询数据出错,状态码为:" + status + ",dataId=" + dataIdPattern + ",group=" + groupNamePattern + ",serverId=" + serverId); break; } } catch (HttpException e) { response.setSuccess(false); response.setStatusMsg("查询数据出错,错误信息如下:" + e.getMessage()); log.error("查询数据出错, dataId=" + dataIdPattern + ",group=" + groupNamePattern + ",serverId=" + serverId, e); } catch (IOException e) { response.setSuccess(false); response.setStatusMsg("查询数据出错,错误信息如下:" + e.getMessage()); log.error("查询数据出错, dataId=" + dataIdPattern + ",group=" + groupNamePattern + ",serverId=" + serverId, e); } finally { // 释放连接资源 method.releaseConnection(); } return response; } /** * 查看是否为压缩的内容 * * @param httpMethod * @return */ boolean isZipContent(HttpMethod httpMethod) { if (null != httpMethod.getResponseHeader(Constants.CONTENT_ENCODING)) { String acceptEncoding = httpMethod.getResponseHeader(Constants.CONTENT_ENCODING).getValue(); if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) { return true; } } return false; } /** * 获取Response的配置信息 * * @param httpMethod * @return */ String getContent(HttpMethod httpMethod) throws UnsupportedEncodingException { StringBuilder contentBuilder = new StringBuilder(); if (isZipContent(httpMethod)) { // 处理压缩过的配置信息的逻辑 InputStream is = null; GZIPInputStream gzin = null; InputStreamReader isr = null; BufferedReader br = null; try { is = httpMethod.getResponseBodyAsStream(); gzin = new GZIPInputStream(is); isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // 设置读取流的编码格式,自定义编码 br = new BufferedReader(isr); char[] buffer = new char[4096]; int readlen = -1; while ((readlen = br.read(buffer, 0, 4096)) != -1) { contentBuilder.append(buffer, 0, readlen); } } catch (Exception e) { log.error("解压缩失败", e); } finally { try { br.close(); } catch (Exception e1) { // ignore } try { isr.close(); } catch (Exception e1) { // ignore } try { gzin.close(); } catch (Exception e1) { // ignore } try { is.close(); } catch (Exception e1) { // ignore } } } else { // 处理没有被压缩过的配置信息的逻辑 String content = null; try { content = httpMethod.getResponseBodyAsString(); } catch (Exception e) { log.error("获取配置信息失败", e); } if (null == content) { return null; } contentBuilder.append(content); } return StringEscapeUtils.unescapeHtml(contentBuilder.toString()); } private void configureGetMethod(GetMethod method) { method.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate"); method.addRequestHeader("Accept", "application/json"); // 设置请求超时时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); } /** * 字段dataId,groupName,context为空验证,有一个为空立即返回false * * @param dataId * @param groupName * @param context * @return */ private boolean validate(String dataId, String groupName, String context) { if (StringUtils.isEmpty(dataId) || StringUtils.isEmpty(groupName) || StringUtils.isEmpty(context) || StringUtils.isBlank(dataId) || StringUtils.isBlank(groupName) || StringUtils.isBlank(context)) return false; return true; } public synchronized ContextResult unpublish(String serverId, long id) { return processDelete(serverId, id); } /** * 处理删除 * * @param serverId * @param id * @return */ private ContextResult processDelete(String serverId, long id) { ContextResult response = new ContextResult(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("登录失败,造成错误的原因可能是指定的serverId为空或不存在"); return response; } log.info("使用processDelete(" + serverId + "," + id); String url = "/diamond-server/admin.do?method=deleteConfig&id=" + id; GetMethod method = new GetMethod(url); configureGetMethod(method); try { int status = client.executeMethod(method); response.setStatusCode(status); switch (status) { case HttpStatus.SC_OK: response.setSuccess(true); response.setReceiveResult(getContent(method)); response.setStatusMsg("删除成功, url=" + url); log.warn("删除配置数据成功, url=" + url); break; case HttpStatus.SC_REQUEST_TIMEOUT: response.setSuccess(false); response.setStatusMsg("删除数据超时" + require_timeout + "毫秒"); log.error("删除数据超时,默认超时时间为:" + require_timeout + "毫秒, id=" + id + ",serverId=" + serverId); break; default: response.setSuccess(false); response.setStatusMsg("删除数据出错,服务器返回状态码为" + status); log.error("删除数据出错,状态码为:" + status + ", id=" + id + ",serverId=" + serverId); break; } } catch (HttpException e) { response.setSuccess(false); response.setStatusMsg("删除数据出错,错误信息如下:" + e.getMessage()); log.error("删除数据出错, id=" + id + ",serverId=" + serverId, e); } catch (IOException e) { response.setSuccess(false); response.setStatusMsg("删除数据出错,错误信息如下:" + e.getMessage()); log.error("删除数据出错, id=" + id + ",serverId=" + serverId, e); } finally { // 释放连接资源 method.releaseConnection(); } return response; } @Override public Map<String, DiamondSDKConf> getDiamondSDKConfMaps() { return this.diamondSDKConfMaps; } @Override public BatchContextResult<ConfigInfoEx> batchQuery(String serverId, String groupName, List<String> dataIds) { // 创建返回结果 BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>(); // 判断list是否为null if (dataIds == null) { log.error("dataId list cannot be null, serverId=" + serverId + ",group=" + groupName); response.setSuccess(false); response.setStatusMsg("dataId list cannot be null"); return response; } // 将dataId的list处理为用一个不可见字符分隔的字符串 StringBuilder dataIdBuilder = new StringBuilder(); for (String dataId : dataIds) { dataIdBuilder.append(dataId).append(Constants.LINE_SEPARATOR); } String dataIdStr = dataIdBuilder.toString(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("login fail, serverId=" + serverId); return response; } // 构造HTTP method PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchQuery"); // 设置请求超时时间 post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { // 设置参数 NameValuePair dataId_value = new NameValuePair("dataIds", dataIdStr); NameValuePair group_value = new NameValuePair("group", groupName); post.setRequestBody(new NameValuePair[] { dataId_value, group_value }); // 执行方法并返回http状态码 int status = client.executeMethod(post); response.setStatusCode(status); String responseMsg = post.getResponseBodyAsString(); response.setResponseMsg(responseMsg); if (status == HttpStatus.SC_OK) { String json = null; try { json = responseMsg; // 反序列化json字符串, 并将结果处理后放入BatchContextResult中 List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>(); Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() { }); if (!(resultObj instanceof List<?>)) { throw new RuntimeException("batch query deserialize type error, not list, json=" + json); } List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj; for (ConfigInfoEx configInfoEx : resultList) { configInfoExList.add(configInfoEx); } response.getResult().addAll(configInfoExList); // 反序列化成功, 本次批量查询成功 response.setSuccess(true); response.setStatusMsg("batch query success"); log.info("batch query success, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName + ",json=" + json); } catch (Exception e) { response.setSuccess(false); response.setStatusMsg("batch query deserialize error"); log.error("batch query deserialize error, serverId=" + serverId + ",dataIdStr=" + dataIdStr + ",group=" + groupName + ",json=" + json, e); } } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg("batch query timeout, socket timeout(ms):" + require_timeout); log.error("batch query timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName); } else { response.setSuccess(false); response.setStatusMsg("batch query fail, status:" + status); log.error("batch query fail, status:" + status + ", response:" + responseMsg + ",serverId=" + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName); } } catch (HttpException e) { response.setSuccess(false); response.setStatusMsg("batch query http exception:" + e.getMessage()); log.error("batch query http exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName, e); } catch (IOException e) { response.setSuccess(false); response.setStatusMsg("batch query io exception:" + e.getMessage()); log.error("batch query io exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName, e); } finally { // 释放连接资源 post.releaseConnection(); } return response; } @Override public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName, Map<String, String> dataId2ContentMap) { // 创建返回结果 BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>(); // 判断map是否为null if (dataId2ContentMap == null) { log.error("dataId2ContentMap cannot be null, serverId=" + serverId + " ,group=" + groupName); response.setSuccess(false); response.setStatusMsg("dataId2ContentMap cannot be null"); return response; } // 将dataId和content的map处理为用一个不可见字符分隔的字符串 StringBuilder allDataIdAndContentBuilder = new StringBuilder(); for (String dataId : dataId2ContentMap.keySet()) { String content = dataId2ContentMap.get(dataId); allDataIdAndContentBuilder.append(dataId + Constants.WORD_SEPARATOR + content).append( Constants.LINE_SEPARATOR); } String allDataIdAndContent = allDataIdAndContentBuilder.toString(); // 登录 if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg("login fail, serverId=" + serverId); return response; } // 构造HTTP method PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchAddOrUpdate"); // 设置请求超时时间 post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { // 设置参数 NameValuePair dataId_value = new NameValuePair("allDataIdAndContent", allDataIdAndContent); NameValuePair group_value = new NameValuePair("group", groupName); post.setRequestBody(new NameValuePair[] { dataId_value, group_value }); // 执行方法并返回http状态码 int status = client.executeMethod(post); response.setStatusCode(status); String responseMsg = post.getResponseBodyAsString(); response.setResponseMsg(responseMsg); if (status == HttpStatus.SC_OK) { String json = null; try { json = responseMsg; // 反序列化json字符串, 并将结果处理后放入BatchContextResult中 List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>(); Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() { }); if (!(resultObj instanceof List<?>)) { throw new RuntimeException("batch write deserialize type error, not list, json=" + json); } List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj; for (ConfigInfoEx configInfoEx : resultList) { configInfoExList.add(configInfoEx); } response.getResult().addAll(configInfoExList); // 反序列化成功, 本次批量操作成功 response.setStatusMsg("batch write success"); log.info("batch write success,serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName + ",json=" + json); } catch (Exception e) { response.setSuccess(false); response.setStatusMsg("batch write deserialize error"); log.error("batch write deserialize error, serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName + ",json=" + json, e); } } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg("batch write timeout, socket timeout(ms):" + require_timeout); log.error("batch write timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName); } else { response.setSuccess(false); response.setStatusMsg("batch write fail, status:" + status); log.error("batch write fail, status:" + status + ", response:" + responseMsg + ",serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName); } } catch (HttpException e) { response.setSuccess(false); response.setStatusMsg("batch write http exception:" + e.getMessage()); log.error("batch write http exception, serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName, e); } catch (IOException e) { response.setSuccess(false); response.setStatusMsg("batch write io exception:" + e.getMessage()); log.error("batch write io exception, serverId=" + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName, e); } finally { // 释放连接资源 post.releaseConnection(); } return response; } }
diamond
com.taobao.diamond.sdkapi
DiamondSDKManager
0
0
9
9
82
9
0
0
-1
0
0
23
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.sdkapi; import java.sql.SQLException; import java.util.List; import java.util.Map; import com.taobao.diamond.domain.BatchContextResult; import com.taobao.diamond.domain.ConfigInfo; import com.taobao.diamond.domain.ConfigInfoEx; import com.taobao.diamond.domain.ContextResult; import com.taobao.diamond.domain.DiamondSDKConf; import com.taobao.diamond.domain.PageContextResult; /** * 定义SDK对外开放的数据访问接口 * * @filename DiamondSDKManager.java * @author libinbin.pt * @datetime 2010-7-16 下午04:03:28 * * {@link #exists(String, String, String)} */ public interface DiamondSDKManager { public Map<String, DiamondSDKConf> getDiamondSDKConfMaps(); // /////////////////////////////////////////推送数据接口定义//////////////////////////////////////// /** * 使用指定的diamond来推送数据 * * @param dataId * @param groupName * @param context * @param serverId * @return ContextResult 单个对象 */ public ContextResult pulish(String dataId, String groupName, String context, String serverId); // /////////////////////////////////////////推送修改后的数据接口定义//////////////////////////////////////// /** * 使用指定的diamond来推送修改后的数据,修改前先检查数据存在性 * * @param dataId * @param groupName * @param context * @param serverId * @return ContextResult 单个对象 */ public ContextResult pulishAfterModified(String dataId, String groupName, String context, String serverId); // /////////////////////////////////////////模糊查询接口定义//////////////////////////////////////// /** * 根据指定的 dataId和组名到指定的diamond上查询数据列表 如果模式中包含符号'*',则会自动替换为'%'并使用[ like ]语句 * 如果模式中不包含符号'*'并且不为空串(包括" "),则使用[ = ]语句 * * @param dataIdPattern * @param groupNamePattern * @param serverId * @param currentPage * @param sizeOfPerPage * @return PageContextResult<ConfigInfo> 单个对象 * @throws SQLException */ public PageContextResult<ConfigInfo> queryBy(String dataIdPattern, String groupNamePattern, String serverId, long currentPage, long sizeOfPerPage); /** * 根据指定的 dataId,组名和content到指定配置的diamond来查询数据列表 如果模式中包含符号'*',则会自动替换为'%'并使用[ * like ]语句 如果模式中不包含符号'*'并且不为空串(包括" "),则使用[ = ]语句 * * @param dataIdPattern * @param groupNamePattern * @param contentPattern * @param serverId * @param currentPage * @param sizeOfPerPage * @return PageContextResult<ConfigInfo> 单个对象 * @throws SQLException */ public PageContextResult<ConfigInfo> queryBy(String dataIdPattern, String groupNamePattern, String contentPattern, String serverId, long currentPage, long sizeOfPerPage); // /////////////////////////////////////////精确查询接口定义//////////////////////////////////////// /** * 根据指定的dataId和组名到指定的diamond上查询数据列表 * * @param dataId * @param groupName * @param serverId * @return ContextResult 单个对象 * @throws SQLException */ public ContextResult queryByDataIdAndGroupName(String dataId, String groupName, String serverId); // /////////////////////////////////////////移除信息接口定义//////////////////////////////////// /** * 移除特定服务器上id指定的配置信息 * * @param serverId * @param id * @return ContextResult 单个对象 */ public ContextResult unpublish(String serverId, long id); /** * 批量查询 * * @param groupName * @param dataIds * @param serverId * @return */ public BatchContextResult<ConfigInfoEx> batchQuery(String serverId, String groupName, List<String> dataIds); /** * 批量新增或更新 * * @param serverId * @param groupName * @param dataId2ContentMap * key:dataId,value:content * @return */ public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName, Map<String/* dataId */, String/* content */> dataId2ContentMap); }
diamond
com.taobao.diamond.mockserver
MockServer
4
0
10
10
81
20
0
0
0
3
2
19
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.mockserver; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.taobao.diamond.client.impl.DiamondClientFactory; import com.taobao.diamond.common.Constants; public class MockServer { private static class Pair { String configInfo; Boolean checkable; public Pair(String configInfo) { this.configInfo = configInfo; this.checkable = true; } } private static ConcurrentHashMap<String, Map<String, Pair>> staticConfigInfos = new ConcurrentHashMap<String, Map<String, Pair>>(); private static volatile boolean testMode = false; public static void setUpMockServer() { testMode = true; } public static void tearDownMockServer() { staticConfigInfos.clear(); DiamondClientFactory.getSingletonDiamondSubscriber().close(); testMode = false; } public static String getConfigInfo(String dataId) { return getConfigInfo(dataId, null); } public static String getConfigInfo(String dataId, String group) { if (null == group) { group = Constants.DEFAULT_GROUP; } Map<String, Pair> pairs = staticConfigInfos.get(dataId); if (null == pairs) { return null; } Pair pair = pairs.get(group); if (null == pair) { return null; } pair.checkable = false; return pair.configInfo; } public static String getUpdateConfigInfo(String dataId) { return getUpdateConfigInfo(dataId, null); } public static String getUpdateConfigInfo(String dataId, String group) { if (null == group) { group = Constants.DEFAULT_GROUP; } Map<String, Pair> pairs = staticConfigInfos.get(dataId); if (null == pairs) { return null; } Pair pair = pairs.get(group); if (null != pair && pair.checkable) { pair.checkable = false; return pair.configInfo; } return null; } public static void setConfigInfos(Map<String, String> configInfos) { if (null != configInfos) { for (Map.Entry<String, String> entry : configInfos.entrySet()) { setConfigInfo(entry.getKey(), entry.getValue()); } } } public static void setConfigInfo(String dataId, String configInfo) { setConfigInfo(dataId, null, configInfo); } public static void setConfigInfo(String dataId, String group, String configInfo) { if (null == group) { group = Constants.DEFAULT_GROUP; } Pair pair = new Pair(configInfo); Map<String, Pair> newPairs = new ConcurrentHashMap<String, Pair>(); Map<String, Pair> pairs = staticConfigInfos.putIfAbsent(dataId, newPairs); if (null == pairs) { pairs = newPairs; } pairs.put(group, pair); } public static boolean isTestMode() { return testMode; } }
diamond
com.taobao.diamond.mockserver
MockServer.Pair
2
0
0
0
8
0
0
0
-1
0
0
21
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.mockserver; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.taobao.diamond.client.impl.DiamondClientFactory; import com.taobao.diamond.common.Constants; public class MockServer { private static class Pair { String configInfo; Boolean checkable; public Pair(String configInfo) { this.configInfo = configInfo; this.checkable = true; } } private static ConcurrentHashMap<String, Map<String, Pair>> staticConfigInfos = new ConcurrentHashMap<String, Map<String, Pair>>(); private static volatile boolean testMode = false; public static void setUpMockServer() { testMode = true; } public static void tearDownMockServer() { staticConfigInfos.clear(); DiamondClientFactory.getSingletonDiamondSubscriber().close(); testMode = false; } public static String getConfigInfo(String dataId) { return getConfigInfo(dataId, null); } public static String getConfigInfo(String dataId, String group) { if (null == group) { group = Constants.DEFAULT_GROUP; } Map<String, Pair> pairs = staticConfigInfos.get(dataId); if (null == pairs) { return null; } Pair pair = pairs.get(group); if (null == pair) { return null; } pair.checkable = false; return pair.configInfo; } public static String getUpdateConfigInfo(String dataId) { return getUpdateConfigInfo(dataId, null); } public static String getUpdateConfigInfo(String dataId, String group) { if (null == group) { group = Constants.DEFAULT_GROUP; } Map<String, Pair> pairs = staticConfigInfos.get(dataId); if (null == pairs) { return null; } Pair pair = pairs.get(group); if (null != pair && pair.checkable) { pair.checkable = false; return pair.configInfo; } return null; } public static void setConfigInfos(Map<String, String> configInfos) { if (null != configInfos) { for (Map.Entry<String, String> entry : configInfos.entrySet()) { setConfigInfo(entry.getKey(), entry.getValue()); } } } public static void setConfigInfo(String dataId, String configInfo) { setConfigInfo(dataId, null, configInfo); } public static void setConfigInfo(String dataId, String group, String configInfo) { if (null == group) { group = Constants.DEFAULT_GROUP; } Pair pair = new Pair(configInfo); Map<String, Pair> newPairs = new ConcurrentHashMap<String, Pair>(); Map<String, Pair> pairs = staticConfigInfos.putIfAbsent(dataId, newPairs); if (null == pairs) { pairs = newPairs; } pairs.put(group, pair); } public static boolean isTestMode() { return testMode; } }
diamond
com.taobao.diamond.manager.impl
PropertiesListener
1
0
2
2
18
3
0
0
0
0
0
23
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.manager.impl; import java.io.IOException; import java.io.StringReader; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.taobao.diamond.manager.ManagerListenerAdapter; public abstract class PropertiesListener extends ManagerListenerAdapter { private static final Log log = LogFactory.getLog(PropertiesListener.class); public void receiveConfigInfo(String configInfo) { if (StringUtils.isEmpty(configInfo)) { log.warn("收到的配置信息为空"); return; } Properties properties = new Properties(); try { properties.load(new StringReader(configInfo)); innerReceive(properties); } catch (IOException e) { log.warn("装载properties失败:" + configInfo, e); } } public abstract void innerReceive(Properties properties); }
diamond
com.taobao.diamond.manager.impl
DefaultDiamondManager
5
0
16
16
115
17
0
0
0
0
4
29
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.manager.impl; import java.io.IOException; import java.io.StringReader; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.taobao.diamond.client.DiamondConfigure; import com.taobao.diamond.client.DiamondSubscriber; import com.taobao.diamond.client.impl.DefaultSubscriberListener; import com.taobao.diamond.client.impl.DiamondClientFactory; import com.taobao.diamond.manager.DiamondManager; import com.taobao.diamond.manager.ManagerListener; /** * 需要注意的是:一个JVM中一个DataID只能对应一个DiamondManager * * @author aoqiong * */ public class DefaultDiamondManager implements DiamondManager { private static final Log log = LogFactory.getLog(DefaultDiamondManager.class); private DiamondSubscriber diamondSubscriber = null; private final List<ManagerListener> managerListeners = new LinkedList<ManagerListener>(); private final String dataId; private final String group; public DefaultDiamondManager(String dataId, ManagerListener managerListener) { this(null, dataId, managerListener); } public DefaultDiamondManager(String group, String dataId, ManagerListener managerListener) { this.dataId = dataId; this.group = group; diamondSubscriber = DiamondClientFactory.getSingletonDiamondSubscriber(); this.managerListeners.add(managerListener); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).addManagerListeners(this.dataId, this.group, this.managerListeners); diamondSubscriber.addDataId(this.dataId, this.group); diamondSubscriber.start(); } public DefaultDiamondManager(String dataId, List<ManagerListener> managerListenerList) { this(null, dataId, managerListenerList); } /** * 使用指定的集群类型clusterType * * @param group * @param dataId * @param managerListenerList * @param clusterType */ public DefaultDiamondManager(String group, String dataId, List<ManagerListener> managerListenerList) { this.dataId = dataId; this.group = group; diamondSubscriber = DiamondClientFactory.getSingletonDiamondSubscriber(); this.managerListeners.addAll(managerListenerList); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).addManagerListeners(this.dataId, this.group, this.managerListeners); diamondSubscriber.addDataId(this.dataId, this.group); diamondSubscriber.start(); } public void setManagerListener(ManagerListener managerListener) { this.managerListeners.clear(); this.managerListeners.add(managerListener); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).removeManagerListeners(this.dataId, this.group); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).addManagerListeners(this.dataId, this.group, this.managerListeners); } public void close() { /** * 因为同一个DataID只能对应一个MnanagerListener,所以,关闭时一次性关闭所有ManagerListener即可 */ ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).removeManagerListeners(this.dataId, this.group); diamondSubscriber.removeDataId(dataId, group); if (diamondSubscriber.getDataIds().size() == 0) { diamondSubscriber.close(); } } public String getConfigureInfomation(long timeout) { return diamondSubscriber.getConfigureInfomation(this.dataId, this.group, timeout); } public String getAvailableConfigureInfomation(long timeout) { return diamondSubscriber.getAvailableConfigureInfomation(dataId, group, timeout); } public String getAvailableConfigureInfomationFromSnapshot(long timeout) { return diamondSubscriber.getAvailableConfigureInfomationFromSnapshot(dataId, group, timeout); } public Properties getAvailablePropertiesConfigureInfomation(long timeout) { String configInfo = this.getAvailableConfigureInfomation(timeout); Properties properties = new Properties(); try { properties.load(new StringReader(configInfo)); return properties; } catch (IOException e) { log.warn("装载properties失败:" + configInfo, e); throw new RuntimeException("装载properties失败:" + configInfo, e); } } public Properties getAvailablePropertiesConfigureInfomationFromSnapshot(long timeout) { String configInfo = this.getAvailableConfigureInfomationFromSnapshot(timeout); Properties properties = new Properties(); try { properties.load(new StringReader(configInfo)); return properties; } catch (IOException e) { log.warn("装载properties失败:" + configInfo, e); throw new RuntimeException("装载properties失败:" + configInfo, e); } } public void setManagerListeners(List<ManagerListener> managerListenerList) { this.managerListeners.clear(); this.managerListeners.addAll(managerListenerList); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).removeManagerListeners(this.dataId, this.group); ((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).addManagerListeners(this.dataId, this.group, this.managerListeners); } public DiamondConfigure getDiamondConfigure() { return diamondSubscriber.getDiamondConfigure(); } public void setDiamondConfigure(DiamondConfigure diamondConfigure) { diamondSubscriber.setDiamondConfigure(diamondConfigure); } public Properties getPropertiesConfigureInfomation(long timeout) { String configInfo = this.getConfigureInfomation(timeout); Properties properties = new Properties(); try { properties.load(new StringReader(configInfo)); return properties; } catch (IOException e) { log.warn("装载properties失败:" + configInfo, e); throw new RuntimeException("装载properties失败:" + configInfo, e); } } public List<ManagerListener> getManagerListeners() { return this.managerListeners; } }
diamond
com.taobao.diamond.manager
DiamondManager
0
0
12
12
71
12
0
0
-1
1
2
18
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.manager; import java.util.List; import java.util.Properties; import com.taobao.diamond.client.DiamondConfigure; /** * DiamondManager用于订阅一个且仅有一个DataID对应的配置信息 * * @author aoqiong * */ public interface DiamondManager { /** * 设置ManagerListener,每当收到一个DataID对应的配置信息,则客户设置的ManagerListener会接收到这个配置信息 * * @param managerListener */ public void setManagerListener(ManagerListener managerListener); /** * 设置DataID对应的多个ManagerListener,每当收到一个DataID对应的配置信息, * 则客户设置的多个ManagerListener会接收到这个配置信息 * * @param managerListenerList */ public void setManagerListeners(List<ManagerListener> managerListenerList); /** * 返回该DiamondManager设置的listener列表 * * @return */ public List<ManagerListener> getManagerListeners(); /** * 同步获取配置信息,,此方法优先从${user.home * }/diamond/data/config-data/${group}/${dataId}下获取配置文件,如果没有,则从diamond * server获取配置信息 * * @param timeout * 从网络获取配置信息的超时,单位毫秒 * @return */ public String getConfigureInfomation(long timeout); /** * 同步获取一份有效的配置信息,按照<strong>本地文件->diamond服务器->上一次正确配置的snapshot</strong> * 的优先顺序获取, 如果这些途径都无效,则返回null * * @param timeout * 从网络获取配置信息的超时,单位毫秒 * @return */ public String getAvailableConfigureInfomation(long timeout); /** * 同步获取一份有效的配置信息,按照<strong>上一次正确配置的snapshot->本地文件->diamond服务器</strong> * 的优先顺序获取, 如果这些途径都无效,则返回null * * @param timeout * 从网络获取配置信息的超时,单位毫秒 * @return */ public String getAvailableConfigureInfomationFromSnapshot(long timeout); /** * 同步获取Properties格式的配置信息 * * @param timeout * 单位:毫秒 * @return */ public Properties getPropertiesConfigureInfomation(long timeout); /** * 同步获取Properties格式的配置信息,本地snapshot优先 * * @param timeout * @return */ public Properties getAvailablePropertiesConfigureInfomationFromSnapshot(long timeout); /** * 同步获取一份有效的Properties配置信息,按照<strong>本地文件->diamond服务器->上一次正确配置的snapshot</ * strong> 的优先顺序获取, 如果这些途径都无效,则返回null * * @param timeout * 单位:毫秒 * @return */ public Properties getAvailablePropertiesConfigureInfomation(long timeout); /** * 设置DiamondConfigure,一个JVM中所有的DiamondManager对应这一个DiamondConfigure * * @param diamondConfigure */ public void setDiamondConfigure(DiamondConfigure diamondConfigure); /** * 获取DiamondConfigure,一个JVM中所有的DiamondManager对应这一个DiamondConfigure * * @param diamondConfigure */ public DiamondConfigure getDiamondConfigure(); /** * 关闭这个DiamondManager */ public void close(); }
diamond
com.taobao.diamond.manager
ManagerListener
0
0
2
2
12
2
2
0
-1
4
0
15
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.manager; import java.util.concurrent.Executor; /** * 客户如果想接收DataID对应的配置信息,需要自己实现一个监听器 * * @author aoqiong * */ public interface ManagerListener { public Executor getExecutor(); /** * 接收配置信息 * * @param configInfo */ public void receiveConfigInfo(final String configInfo); }
diamond
com.taobao.diamond.manager
SkipInitialCallbackListener
1
0
3
3
17
5
0
1
0
0
0
5
/** Copyright 2013-2023 步步高商城. */ package com.taobao.diamond.manager; /** * * @author <a href="mailto:takeseem@gmail.com">杨浩</a> * @since 0.1.0 */ public abstract class SkipInitialCallbackListener implements ManagerListener { private String first; public SkipInitialCallbackListener(String data) { first = data; } @Override public void receiveConfigInfo(String configInfo) { if (first == configInfo) return; if (first == null || !first.equals(configInfo)) { receiveConfigInfo0(configInfo); } } //FIXME: 必须实现 public abstract void receiveConfigInfo0(String data); }
diamond
com.taobao.diamond.manager
ManagerListenerAdapter
0
0
1
1
5
1
0
1
-1
0
0
15
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.manager; import java.util.concurrent.Executor; public abstract class ManagerListenerAdapter implements ManagerListener { public Executor getExecutor() { return null; } }
diamond
com.taobao.diamond.configinfo
CacheData
9
0
21
21
94
30
0
0
0.380952
2
1
18
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.configinfo; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import com.taobao.diamond.common.Constants; public class CacheData { private String dataId; private String group; private volatile String lastModifiedHeader = Constants.NULL; private volatile String md5 = Constants.NULL; private AtomicInteger domainNamePos = new AtomicInteger(0); private volatile String localConfigInfoFile = null; private volatile long localConfigInfoVersion; private volatile boolean useLocalConfigInfo = false; /** * 统计成功获取配置信息的次数 */ private final AtomicLong fetchCounter = new AtomicLong(0); public CacheData(String dataId, String group) { this.dataId = dataId; this.group = group; } public String getDataId() { return dataId; } public long getFetchCount() { return this.fetchCounter.get(); } public long incrementFetchCountAndGet() { return this.fetchCounter.incrementAndGet(); } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getLocalConfigInfoFile() { return localConfigInfoFile; } public void setLocalConfigInfoFile(String localConfigInfoFile) { this.localConfigInfoFile = localConfigInfoFile; } public long getLocalConfigInfoVersion() { return localConfigInfoVersion; } public void setLocalConfigInfoVersion(long localConfigInfoVersion) { this.localConfigInfoVersion = localConfigInfoVersion; } public boolean isUseLocalConfigInfo() { return useLocalConfigInfo; } public void setUseLocalConfigInfo(boolean useLocalConfigInfo) { this.useLocalConfigInfo = useLocalConfigInfo; } public String getLastModifiedHeader() { return lastModifiedHeader; } public void setLastModifiedHeader(String lastModifiedHeader) { this.lastModifiedHeader = lastModifiedHeader; } public AtomicInteger getDomainNamePos() { return domainNamePos; } public void setDomainNamePos(int domainNamePos) { this.domainNamePos.set(domainNamePos); } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataId == null) ? 0 : dataId.hashCode()); result = prime * result + ((group == null) ? 0 : group.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CacheData other = (CacheData) obj; if (dataId == null) { if (other.dataId != null) return false; } else if (!dataId.equals(other.dataId)) return false; if (group == null) { if (other.group != null) return false; } else if (!group.equals(other.group)) return false; return true; } }
diamond
com.taobao.diamond.configinfo
ConfigureInfomation
4
0
9
9
64
21
0
0
0
3
0
15
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.configinfo; import java.io.Serializable; /** * 配置信息的类 * * @author aoqiong * */ public class ConfigureInfomation implements Serializable { /** * */ private static final long serialVersionUID = 6684264073344815420L; private String dataId; private String group; private String ConfigureInfomation; public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getConfigureInfomation() { return ConfigureInfomation; } public void setConfigureInfomation(String configureInfomation) { ConfigureInfomation = configureInfomation; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ConfigureInfomation == null) ? 0 : ConfigureInfomation.hashCode()); result = prime * result + ((dataId == null) ? 0 : dataId.hashCode()); result = prime * result + ((group == null) ? 0 : group.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ConfigureInfomation other = (ConfigureInfomation) obj; if (ConfigureInfomation == null) { if (other.ConfigureInfomation != null) return false; } else if (!ConfigureInfomation.equals(other.ConfigureInfomation)) return false; if (dataId == null) { if (other.dataId != null) return false; } else if (!dataId.equals(other.dataId)) return false; if (group == null) { if (other.group != null) return false; } else if (!group.equals(other.group)) return false; return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DataId: ").append(dataId); sb.append(", Group: ").append(group); sb.append(", ConfigureInfomation: ").append(ConfigureInfomation); return sb.toString(); } }
diamond
com.taobao.diamond.client
DiamondSubscriber
0
0
15
15
93
15
0
1
-1
2
1
18
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.client; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.taobao.diamond.configinfo.CacheData; /** * DiamondSubscriber用于订阅持久的文本配置信息。<br> * * @author aoqiong * */ public interface DiamondSubscriber extends DiamondClientSub { /** * 设置异步订阅的Listener,可以动态替换 * * @param subscriberListener */ public void setSubscriberListener(SubscriberListener subscriberListener); /** * 获取异步订阅的Listener * * @return */ public SubscriberListener getSubscriberListener(); /** * 获取group组DataID为dataId的ConfigureInfomation,必须在start()方法后调用,,此方法优先从${user. * home}/diamond/data下获取配置文件,如果没有,则从diamond server获取配置信息 * * @param dataId * @param group * @param timeout * @return */ public String getConfigureInfomation(String dataId, String group, long timeout); /** * 获取缺省组的DataID为dataId的ConfigureInfomation,必须在start()方法后调用,此方法优先从${user.home * }/diamond/data下获取配置文件,如果没有,则从diamond server获取配置信息 * * @param dataId * @param timeout * @return */ public String getConfigureInfomation(String dataId, long timeout); /** * 获取一份可用的配置信息,按照<strong>本地文件->diamond服务器->本地上一次保存的snapshot</strong> * 的优先顺序获取一份有效的配置信息,如果所有途径都无法获取一份有效配置信息 , 则返回null * * @param dataId * @param group * @param timeout * @return */ public String getAvailableConfigureInfomation(String dataId, String group, long timeout); /** * 添加一个DataID,如果原来有此DataID和Group,将替换它们 * * @param dataId * @param group * 组名,可为null,代表使用缺省的组名 */ public void addDataId(String dataId, String group); /** * 添加一个DataID,使用缺省的组名。如果原来有此DataID和Group,将替换它们 * * @param dataId */ public void addDataId(String dataId); /** * 目前是否支持对DataID对应的ConfigInfo * * @param dataId * @return */ public boolean containDataId(String dataId); /** * * @param dataId * @param group * @return */ public boolean containDataId(String dataId, String group); /** * * @param dataId */ public void removeDataId(String dataId); /** * * @param dataId * @param group */ public void removeDataId(String dataId, String group); /** * 清空所有的DataID */ public void clearAllDataIds(); /** * 获取支持的所有的DataID * * @return */ public Set<String> getDataIds(); /** * 获取客户端cache * * @return */ public ConcurrentHashMap<String, ConcurrentHashMap<String, CacheData>> getCache(); /** * 获取一份可用的配置信息,按照本地snapshot -> 本地文件 -> server的顺序 * * @param dataId * @param group * @param timeout * @return */ public String getAvailableConfigureInfomationFromSnapshot(String dataId, String group, long timeout); }
diamond
com.taobao.diamond.client
DiamondClientSub
0
0
4
4
10
4
1
0
-1
0
1
12
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.client; /** * Diamond是一个支持持久的可靠的文本配置信息管理中心,用于文本配置信息的订阅。<br> * Diamond目前是使用ops发布持久配置信息。<br> * Diamond由于使用集中的数据库保存持久的配置信息,配置信息十分安全,并且,Diamond能够使客户永远获取最新的订阅信息。<br> * 目前Diamond客户端拥有如下几种方式: <br> * 1.主动获取<br> * 2.定时获取<br> * Diamond客户端还支持相对远程配置信息而言,优先级更高的本地配置配置信息的获取(使用Properties或者xml) * * @author aoqiong * */ public interface DiamondClientSub { public void setDiamondConfigure(DiamondConfigure diamondConfigure); public DiamondConfigure getDiamondConfigure(); public void start(); public void close(); }