自定义provider

自定义provider

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hipeak.demo0804">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Demo0804">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <provider
            android:authorities="com.hipeak.demo0804.stuprovider"
            android:name=".StuProvider"
            android:exported="true"
            android:enabled="true"/>
    </application>

</manifest>

MainActivity

package com.hipeak.demo0804;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class StuProvider extends ContentProvider {
    private SchoolDBHelper helper;
    /**
     * 匹配URi的容器
     *  构造的code:匹配不上的时候,code是多少,默认是NO_MATCH -1
     */
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    private static final int CODE_STU=1;
    private static final int CODE_STU_ID=2;
    static{
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu",CODE_STU);
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu/#",CODE_STU_ID);
    }

    //当应用启动的时候创建StuProvider对象,当创建对象的时候onCreate()
    //初始化helper
//    private
    @Override
    public boolean onCreate() {
        Log.d("", "===onCteate");
        helper=new SchoolDBHelper(getContext(),1);
        return false;
    }

    /**
     *
     * @param uri  一个资源的唯一标识
     * @param projection 多个字段
     * @param selection where条件 如:id=?and name=?
     * @param selectionArgs  where条件需要的值
     * @param sortOrder 排序规则
     * @return
     *
     * content://com.hipeak.demo0804.stuprovider/stu    不根据id查询
     * content://com.hipeak.demo0804.stuprovider/stu/1  根据id查询
     */
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri,
                        @Nullable String[] projection,
                        @Nullable String selection,
                        @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = helper.getReadableDatabase();
        int code = matcher.match(uri);
        switch(code){
            case CODE_STU:
                return db.query("stu",projection,selection,selectionArgs,null,null,sortOrder);
            case CODE_STU_ID:
                //TODO uri中的id获取
                long id=ContentUris.parseId(uri);//uri中的id
                return db.query("stu",projection,"_id=?",new String[]{id+""},null,null,sortOrder);
            default:
                Log.e("","Uri不符合规则");
                throw new RuntimeException("Uri不符合规则");
        }
    }


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    //* * content://com.hipeak.demo0804.stuprovider/stu    不根据插入
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code =matcher.match(uri);
        if(code==CODE_STU){
            long id = db.insert("stu", null, values);
            Log.d("","id==="+id);
            db.close();
            return ContentUris.withAppendedId(uri,id);
        }else{
            Log.e("","Uri不符合规则");
            db.close();
            throw new RuntimeException("Uri不符合规则");
        }

    }

    /**
     *  content://com.hipeak.demo0804.stuprovider/stu    不根据id删除
     *  content://com.hipeak.demo0804.stuprovider/stu/1  根据id删除
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code=matcher.match(uri);
        int count=0;
        switch(code){
            case CODE_STU:
                count = db.delete("stu", selection, selectionArgs);//删掉了几行
                db.close();
                break;
            case CODE_STU_ID:
                long id=ContentUris.parseId(uri);
                count=db.delete("stu","_id=?",new String[]{id+""});
                db.close();
                break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}

SchoolDBHelper

package com.hipeak.demo0804;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class SchoolDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME="school.db";

    public SchoolDBHelper(@Nullable Context context, int version) {
        super(context, DB_NAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //
        String sql="create table stu(" +
                "_id integer primary key autoincrement" +
                ",name text" +
                ",age integer );";

        sqLiteDatabase.execSQL(sql);

        String sql2="insert into stu(name,age) values('张三',21),('李四',21),('王五',26)" ;

        sqLiteDatabase.execSQL(sql2);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

StuProvider

package com.hipeak.demo0804;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class StuProvider extends ContentProvider {
    private SchoolDBHelper helper;
    /**
     * 匹配URi的容器
     *  构造的code:匹配不上的时候,code是多少,默认是NO_MATCH -1
     */
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    private static final int CODE_STU=1;
    private static final int CODE_STU_ID=2;
    static{
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu",CODE_STU);
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu/#",CODE_STU_ID);
    }

    //当应用启动的时候创建StuProvider对象,当创建对象的时候onCreate()
    //初始化helper
//    private
    @Override
    public boolean onCreate() {
        Log.d("", "===onCteate");
        helper=new SchoolDBHelper(getContext(),1);
        return false;
    }

    /**
     *
     * @param uri  一个资源的唯一标识
     * @param projection 多个字段
     * @param selection where条件 如:id=?and name=?
     * @param selectionArgs  where条件需要的值
     * @param sortOrder 排序规则
     * @return
     *
     * content://com.hipeak.demo0804.stuprovider/stu    不根据id查询
     * content://com.hipeak.demo0804.stuprovider/stu/1  根据id查询
     */
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri,
                        @Nullable String[] projection,
                        @Nullable String selection,
                        @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = helper.getReadableDatabase();
        int code = matcher.match(uri);
        switch(code){
            case CODE_STU:
                return db.query("stu",projection,selection,selectionArgs,null,null,sortOrder);
            case CODE_STU_ID:
                //TODO uri中的id获取
                long id=ContentUris.parseId(uri);//uri中的id
                return db.query("stu",projection,"_id=?",new String[]{id+""},null,null,sortOrder);
            default:
                Log.e("","Uri不符合规则");
                throw new RuntimeException("Uri不符合规则");
        }
    }


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    //* * content://com.hipeak.demo0804.stuprovider/stu    不根据插入
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code =matcher.match(uri);
        if(code==CODE_STU){
            long id = db.insert("stu", null, values);
            Log.d("","id==="+id);
            db.close();
            return ContentUris.withAppendedId(uri,id);
        }else{
            Log.e("","Uri不符合规则");
            db.close();
            throw new RuntimeException("Uri不符合规则");
        }

    }

    /**
     *  content://com.hipeak.demo0804.stuprovider/stu    不根据id删除
     *  content://com.hipeak.demo0804.stuprovider/stu/1  根据id删除
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code=matcher.match(uri);
        int count=0;
        switch(code){
            case CODE_STU:
                count = db.delete("stu", selection, selectionArgs);//删掉了几行
                db.close();
                break;
            case CODE_STU_ID:
                long id=ContentUris.parseId(uri);
                count=db.delete("stu","_id=?",new String[]{id+""});
                db.close();
                break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}
  break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}
在Spring Security中,我们可以通过实现`AuthenticationProvider`接口来自定义身份验证提供程序,并在`AuthenticationManager`中注册它。下面是一个简单的示例: 1. 创建一个自定义的身份验证提供程序 ```java @Component public class MyAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); // 进行自定义的身份验证逻辑 if ("admin".equals(username) && "123456".equals(password)) { return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>()); } else { throw new BadCredentialsException("Authentication failed"); } } @Override public boolean supports(Class<?> authenticationType) { return authenticationType.equals(UsernamePasswordAuthenticationToken.class); } } ``` 2. 注入自定义的身份验证提供程序到`AuthenticationManager` ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationProvider myAuthenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(myAuthenticationProvider); } // ... 省略其他配置 ... } ``` 在以上示例中,我们通过实现`AuthenticationProvider`接口,自定义了一个名为`MyAuthenticationProvider`的身份验证提供程序。在`configure(AuthenticationManagerBuilder auth)`方法中,我们通过调用`auth.authenticationProvider(myAuthenticationProvider)`方法将该提供程序注册到`AuthenticationManager`中。这样,当用户在登录时,`AuthenticationManager`就会自动调用`MyAuthenticationProvider`中的`authenticate`方法进行身份验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值