repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/adapter/AccentAdapter.java | src/app/src/main/java/com/atul/musicplayer/adapter/AccentAdapter.java | package com.atul.musicplayer.adapter;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import androidx.annotation.NonNull;
import androidx.core.widget.ImageViewCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayer.MPConstants;
import com.atul.musicplayer.MPPreferences;
import com.atul.musicplayer.R;
import com.atul.musicplayer.helper.ThemeHelper;
import java.util.List;
public class AccentAdapter extends RecyclerView.Adapter<AccentAdapter.MyViewHolder> {
private final Activity activity;
public List<Integer> accentList;
public AccentAdapter(Activity activity) {
this.accentList = MPConstants.ACCENT_LIST;
this.activity = activity;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_accent, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
ImageViewCompat.setImageTintList(
holder.accent,
ColorStateList.valueOf(activity.getColor(accentList.get(position)))
);
if (accentList.get(position) == MPPreferences.getTheme(activity.getApplicationContext()))
holder.check.setVisibility(View.VISIBLE);
else
holder.check.setVisibility(View.GONE);
}
@Override
public int getItemCount() {
return accentList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final ImageButton accent;
private final ImageButton check;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
accent = itemView.findViewById(R.id.accent);
check = itemView.findViewById(R.id.check);
accent.setOnClickListener(v -> {
MPPreferences.storeTheme(activity.getApplicationContext(), accentList.get(getAdapterPosition()));
ThemeHelper.applySettings(activity);
});
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/adapter/SleepTimerAdapter.java | src/app/src/main/java/com/atul/musicplayer/adapter/SleepTimerAdapter.java | package com.atul.musicplayer.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayer.MPConstants;
import com.atul.musicplayer.R;
import com.atul.musicplayer.listener.MinuteSelectListener;
import com.google.android.material.button.MaterialButton;
import java.util.List;
public class SleepTimerAdapter extends RecyclerView.Adapter<SleepTimerAdapter.MyViewHolder> {
private final List<Integer> minutes;
private final MinuteSelectListener listener;
public SleepTimerAdapter(MinuteSelectListener listener) {
this.minutes = MPConstants.MINUTES_LIST;
this.listener = listener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_minutes, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.minuteButton.setText(String.valueOf(minutes.get(position)));
}
@Override
public int getItemCount() {
return minutes.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final MaterialButton minuteButton;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
minuteButton = itemView.findViewById(R.id.minutes_item);
minuteButton.setOnClickListener(v -> listener.select(minutes.get(getAdapterPosition())));
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/adapter/SongsAdapter.java | src/app/src/main/java/com/atul/musicplayer/adapter/SongsAdapter.java | package com.atul.musicplayer.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayer.MPPreferences;
import com.atul.musicplayer.R;
import com.atul.musicplayer.helper.MusicLibraryHelper;
import com.atul.musicplayer.listener.MusicSelectListener;
import com.atul.musicplayer.model.Music;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class SongsAdapter extends RecyclerView.Adapter<SongsAdapter.MyViewHolder> {
private final List<Music> musicList;
public final MusicSelectListener listener;
public SongsAdapter(MusicSelectListener listener, List<Music> musics) {
this.listener = listener;
this.musicList = musics;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_songs, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Music music = musicList.get(position);
holder.songName.setText(music.title);
holder.albumName.setText(
String.format(Locale.getDefault(), "%s • %s",
music.artist,
music.album)
);
if (music.dateAdded == -1)
holder.songHistory.setVisibility(View.GONE);
else
holder.songHistory.setText(
String.format(Locale.getDefault(), "%s • %s",
MusicLibraryHelper.formatDuration(music.duration),
MusicLibraryHelper.formatDate(music.dateAdded))
);
if (holder.state && !music.albumArt.equals("")) {
Glide.with(holder.albumArt.getContext())
.load(music.albumArt)
.placeholder(R.drawable.ic_album_art)
.into(holder.albumArt);
} else if (music.albumArt.equals("")) {
holder.albumArt.setImageResource(R.drawable.ic_album_art);
}
}
@Override
public int getItemCount() {
return musicList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView songName;
private final TextView albumName;
private final TextView songHistory;
private final ImageView albumArt;
private final boolean state;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
state = MPPreferences.getAlbumRequest(itemView.getContext());
albumArt = itemView.findViewById(R.id.album_art);
songHistory = itemView.findViewById(R.id.song_history);
songName = itemView.findViewById(R.id.song_name);
albumName = itemView.findViewById(R.id.song_album);
itemView.findViewById(R.id.root_layout).setOnClickListener(v -> {
List<Music> toPlay = new ArrayList<>();
boolean autoPlay = MPPreferences.getAutoPlay(itemView.getContext());
if (autoPlay) {
toPlay.addAll(musicList.subList(getAdapterPosition(), musicList.size()));
} else {
toPlay.add(musicList.get(getAdapterPosition()));
}
listener.playQueue(toPlay, false);
}
);
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/adapter/ArtistAdapter.java | src/app/src/main/java/com/atul/musicplayer/adapter/ArtistAdapter.java | package com.atul.musicplayer.adapter;
import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayer.R;
import com.atul.musicplayer.listener.ArtistSelectListener;
import com.atul.musicplayer.model.Artist;
import java.util.List;
import java.util.Locale;
public class ArtistAdapter extends RecyclerView.Adapter<ArtistAdapter.MyViewHolder> {
private final List<Artist> artistList;
private final ArtistSelectListener selectListener;
public ArtistAdapter(ArtistSelectListener selectListener, List<Artist> artistList) {
this.artistList = artistList;
this.selectListener = selectListener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_artists, parent, false);
return new MyViewHolder(view);
}
@SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.artistName.setText(artistList.get(position).name);
holder.artistHistory.setText(String.format(Locale.getDefault(), "%d Albums • %d Songs",
artistList.get(position).albumCount,
artistList.get(position).songCount));
}
@Override
public int getItemCount() {
return artistList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView artistName;
private final TextView artistHistory;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
artistName = itemView.findViewById(R.id.artist_name);
artistHistory = itemView.findViewById(R.id.artist_history);
itemView.findViewById(R.id.root_layout).setOnClickListener(v ->
selectListener.selectedArtist(artistList.get(getAdapterPosition())));
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/adapter/HorizontalAlbumsAdapter.java | src/app/src/main/java/com/atul/musicplayer/adapter/HorizontalAlbumsAdapter.java | package com.atul.musicplayer.adapter;
import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayer.MPPreferences;
import com.atul.musicplayer.R;
import com.atul.musicplayer.listener.AlbumSelectListener;
import com.atul.musicplayer.model.Album;
import com.bumptech.glide.Glide;
import java.util.List;
public class HorizontalAlbumsAdapter extends RecyclerView.Adapter<HorizontalAlbumsAdapter.MyViewHolder> {
public final List<Album> albumList;
public final AlbumSelectListener listener;
public HorizontalAlbumsAdapter(List<Album> albums, AlbumSelectListener listener) {
this.albumList = albums;
this.listener = listener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_item_albums, parent, false);
return new MyViewHolder(view);
}
@SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.albumTitle.setText(albumList.get(position).title);
if (holder.state)
Glide.with(holder.albumArt.getContext())
.load(albumList.get(position).music.get(0).albumArt)
.placeholder(R.drawable.ic_album_art)
.into(holder.albumArt);
}
@Override
public int getItemCount() {
return albumList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final ImageView albumArt;
private final TextView albumTitle;
private final boolean state;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
state = MPPreferences.getAlbumRequest(itemView.getContext());
albumArt = itemView.findViewById(R.id.album_art);
albumTitle = itemView.findViewById(R.id.album_title);
itemView.findViewById(R.id.album_art_layout).setOnClickListener(v ->
listener.selectedAlbum(albumList.get(getAdapterPosition())));
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/SleepTimerSetListener.java | src/app/src/main/java/com/atul/musicplayer/listener/SleepTimerSetListener.java | package com.atul.musicplayer.listener;
import androidx.lifecycle.MutableLiveData;
public interface SleepTimerSetListener {
void setTimer(int minutes);
void cancelTimer();
MutableLiveData<Long> getTick();
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/MinuteSelectListener.java | src/app/src/main/java/com/atul/musicplayer/listener/MinuteSelectListener.java | package com.atul.musicplayer.listener;
public interface MinuteSelectListener {
void select(int minutes);
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/ArtistSelectListener.java | src/app/src/main/java/com/atul/musicplayer/listener/ArtistSelectListener.java | package com.atul.musicplayer.listener;
import com.atul.musicplayer.model.Artist;
public interface ArtistSelectListener {
void selectedArtist(Artist artist);
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/MusicSelectListener.java | src/app/src/main/java/com/atul/musicplayer/listener/MusicSelectListener.java | package com.atul.musicplayer.listener;
import com.atul.musicplayer.model.Music;
import java.util.List;
public interface MusicSelectListener {
void playQueue(List<Music> musicList, boolean shuffle);
void addToQueue(List<Music> musicList);
void refreshMediaLibrary();
} | java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/PlayerDialogListener.java | src/app/src/main/java/com/atul/musicplayer/listener/PlayerDialogListener.java | package com.atul.musicplayer.listener;
public interface PlayerDialogListener {
void queueOptionSelect();
void sleepTimerOptionSelect();
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/listener/AlbumSelectListener.java | src/app/src/main/java/com/atul/musicplayer/listener/AlbumSelectListener.java | package com.atul.musicplayer.listener;
import com.atul.musicplayer.model.Album;
public interface AlbumSelectListener {
void selectedAlbum(Album album);
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerQueue.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerQueue.java | package com.atul.musicplayer.player;
import com.atul.musicplayer.model.Music;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class PlayerQueue {
private static PlayerQueue instance = null;
private final Random random = new Random();
private List<Music> currentQueue;
private List<Integer> played;
private boolean shuffle = false;
private boolean repeat = false;
private int currentPosition = 0;
public static PlayerQueue getInstance() {
if (instance == null) {
instance = new PlayerQueue();
}
return instance;
}
private boolean isCurrentPositionOutOfBound(int pos) {
return pos >= currentQueue.size() || pos < 0;
}
public boolean isShuffle() {
return shuffle;
}
public void setShuffle(boolean shuffle) {
this.shuffle = shuffle;
}
public boolean isRepeat() {
return repeat;
}
public void setRepeat(boolean repeat) {
this.repeat = repeat;
}
public List<Music> getCurrentQueue() {
return currentQueue;
}
public void setCurrentQueue(List<Music> currentQueue) {
this.played = new ArrayList<>();
this.currentQueue = currentQueue;
this.currentPosition = 0;
if (this.shuffle) {
Collections.shuffle(currentQueue);
}
}
public int getCurrentPosition() {
return currentPosition;
}
public Music getCurrentMusic() {
return currentQueue.get(currentPosition);
}
public void addMusicListToQueue(List<Music> music) {
currentQueue.addAll(music);
this.currentPosition = (shuffle) ? random.nextInt(currentQueue.size()) : 0;
}
public void next() {
played.add(currentPosition);
if (!repeat) {
currentPosition = (shuffle)
? random.nextInt(currentQueue.size())
: isCurrentPositionOutOfBound(currentPosition + 1)
? 0
: ++currentPosition;
}
}
public void prev() {
if (played.size() == 0) {
currentPosition = 0;
} else {
int lastPosition = played.size() - 1;
currentPosition = played.get(lastPosition);
played.remove(lastPosition);
}
}
public void removeMusicFromQueue(int position) {
if (!isCurrentPositionOutOfBound(position)) {
currentQueue.remove(position);
if(currentPosition > position)
currentPosition -= 1;
}
}
public void swap(int one, int two) {
if (!isCurrentPositionOutOfBound(one) && !isCurrentPositionOutOfBound(two)) {
if(one == currentPosition) {
currentPosition = two;
}
else if(two == currentPosition) {
currentPosition = one;
}
Collections.swap(currentQueue, one, two);
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerManager.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerManager.java | package com.atul.musicplayer.player;
import static android.content.Context.RECEIVER_EXPORTED;
import static com.atul.musicplayer.MPConstants.AUDIO_FOCUSED;
import static com.atul.musicplayer.MPConstants.AUDIO_NO_FOCUS_CAN_DUCK;
import static com.atul.musicplayer.MPConstants.AUDIO_NO_FOCUS_NO_DUCK;
import static com.atul.musicplayer.MPConstants.NEXT_ACTION;
import static com.atul.musicplayer.MPConstants.NOTIFICATION_ID;
import static com.atul.musicplayer.MPConstants.PLAY_PAUSE_ACTION;
import static com.atul.musicplayer.MPConstants.PREV_ACTION;
import static com.atul.musicplayer.MPConstants.VOLUME_DUCK;
import static com.atul.musicplayer.MPConstants.VOLUME_NORMAL;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ServiceInfo;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.support.v4.media.session.PlaybackStateCompat;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.atul.musicplayer.model.Music;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import kotlin.Suppress;
public class PlayerManager implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener {
private final Context context;
private final PlayerService playerService;
private final AudioManager audioManager;
private final List<PlayerListener> playerListeners = new ArrayList<>();
private final PlayerQueue playerQueue;
private final MutableLiveData<Integer> progressPercent = new MutableLiveData<>();
private int playerState;
private MediaPlayer mediaPlayer;
private NotificationReceiver notificationReceiver;
private PlayerNotificationManager notificationManager;
private int currentAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
private boolean playOnFocusGain;
private final AudioManager.OnAudioFocusChangeListener audioFocusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(final int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
currentAudioFocus = AUDIO_FOCUSED;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Audio focus was lost, but it's possible to duck (i.e.: play quietly)
currentAudioFocus = AUDIO_NO_FOCUS_CAN_DUCK;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost audio focus, but will gain it back (shortly), so note whether
// playback should resume
currentAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
playOnFocusGain = isMediaPlayer() && playerState == PlaybackStateCompat.STATE_PLAYING || playerState == PlaybackStateCompat.STATE_NONE;
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost audio focus, probably "permanently"
currentAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
break;
}
if (mediaPlayer != null) {
// Update the player state based on the change
configurePlayerState();
}
}
};
private MediaObserver mediaObserver;
public PlayerManager(@NonNull PlayerService playerService) {
this.playerService = playerService;
this.context = playerService.getApplicationContext();
this.playerQueue = PlayerQueue.getInstance();
this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Observer<Integer> progressObserver = percent -> {
for (PlayerListener playerListener : playerListeners)
playerListener.onPositionChanged(percent);
};
progressPercent.observeForever(progressObserver);
}
@SuppressLint("UnspecifiedRegisterReceiverFlag")
public void registerActionsReceiver() {
notificationReceiver = new PlayerManager.NotificationReceiver();
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(PREV_ACTION);
intentFilter.addAction(PLAY_PAUSE_ACTION);
intentFilter.addAction(NEXT_ACTION);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
playerService.registerReceiver(notificationReceiver, intentFilter, RECEIVER_EXPORTED);
} else {
playerService.registerReceiver(notificationReceiver, intentFilter);
}
}
public void unregisterActionsReceiver() {
if (playerService != null && notificationReceiver != null) {
try {
playerService.unregisterReceiver(notificationReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
public void attachListener(PlayerListener playerListener) {
playerListeners.add(playerListener);
}
public void detachListener(PlayerListener playerListener) {
if (playerListeners.size() > 2) {
playerListeners.remove(playerListener);
}
}
private void setPlayerState(@PlayerListener.State int state) {
playerState = state;
for (PlayerListener listener : playerListeners) {
listener.onStateChanged(state);
}
playerService.getNotificationManager().updateNotification();
int playbackState = isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
int currentPosition = mediaPlayer == null ? 0 : mediaPlayer.getCurrentPosition();
playerService.getMediaSessionCompat().setPlaybackState(
new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PAUSE |
PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
PlaybackStateCompat.ACTION_SEEK_TO |
PlaybackStateCompat.ACTION_PLAY_PAUSE)
.setState(playbackState, currentPosition, 0)
.build());
}
public Music getCurrentMusic() {
return playerQueue.getCurrentMusic();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public PlayerQueue getPlayerQueue() {
return playerQueue;
}
public void setPlayerListener(PlayerListener listener) {
playerListeners.add(listener);
listener.onPrepared();
}
public void setMusicList(List<Music> musicList) {
playerQueue.setCurrentQueue(new ArrayList<>(musicList));
initMediaPlayer(); // play now
}
public void setMusic(Music music) {
List<Music> musicList = new ArrayList<>();
musicList.add(music);
playerQueue.setCurrentQueue(musicList);
initMediaPlayer();
}
public void addMusicQueue(List<Music> musicList) {
playerQueue.addMusicListToQueue(new ArrayList<>(musicList));
if (!mediaPlayer.isPlaying())
initMediaPlayer(); // play when ready
}
public int getAudioSessionId() {
return (mediaPlayer != null) ? mediaPlayer.getAudioSessionId() : -1;
}
public void detachService() {
playerService.stopForeground(false);
}
public void attachService() {
if (notificationManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
playerService.startForeground(NOTIFICATION_ID, notificationManager.createNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
} else {
playerService.startForeground(NOTIFICATION_ID, notificationManager.createNotification());
}
}
}
@Override
public void onCompletion(MediaPlayer mp) {
playNext();
for (PlayerListener listener : playerListeners)
listener.onPlaybackCompleted();
}
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
playerService.startForeground(NOTIFICATION_ID, notificationManager.createNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
} else {
playerService.startForeground(NOTIFICATION_ID, notificationManager.createNotification());
}
} catch (Exception e) {
e.printStackTrace();
}
for (PlayerListener listener : playerListeners)
listener.onMusicSet(playerQueue.getCurrentMusic());
if (mediaObserver == null) {
mediaObserver = new MediaObserver();
new Thread(mediaObserver).start();
}
}
public boolean isPlaying() {
return isMediaPlayer() && mediaPlayer.isPlaying();
}
public boolean isMediaPlayer() {
return mediaPlayer != null;
}
public void pauseMediaPlayer() {
setPlayerState(PlayerListener.State.PAUSED);
mediaPlayer.pause();
playerService.stopForeground(false);
notificationManager.getNotificationManager().notify(NOTIFICATION_ID, notificationManager.createNotification());
}
public void resumeMediaPlayer() {
if (!isPlaying()) {
if (mediaPlayer == null) {
initMediaPlayer();
}
mediaPlayer.start();
setPlayerState(PlayerListener.State.RESUMED);
playerService.startForeground(NOTIFICATION_ID, notificationManager.createNotification());
notificationManager.updateNotification();
}
}
public void playPrev() {
playerQueue.prev();
initMediaPlayer();
}
public void playNext() {
playerQueue.next();
initMediaPlayer();
}
public void playPause() {
if (isPlaying()) {
mediaPlayer.pause();
setPlayerState(PlayerListener.State.PAUSED);
} else {
if (mediaPlayer == null) {
initMediaPlayer();
}
mediaPlayer.start();
setPlayerState(PlayerListener.State.PLAYING);
}
}
public void release() {
if (mediaObserver != null) {
mediaObserver.stop();
}
if (playerService != null) {
playerService.stopForeground(true);
playerService.stopSelf();
}
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
for (PlayerListener playerListener : playerListeners)
playerListener.onRelease();
}
public void seekTo(int position) {
mediaPlayer.seekTo(position);
}
private void configurePlayerState() {
if (currentAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
// We don't have audio focus and can't duck, so we have to pause
pauseMediaPlayer();
} else {
if (currentAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
// We're permitted to play, but only if we 'duck', ie: play softly
mediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK);
} else {
mediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL);
}
// If we were playing when we lost focus, we need to resume playing.
if (playOnFocusGain) {
resumeMediaPlayer();
playOnFocusGain = false;
}
}
}
private void tryToGetAudioFocus() {
final int result = audioManager.requestAudioFocus(
audioFocusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
currentAudioFocus = AUDIO_FOCUSED;
} else {
currentAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
}
}
private void initMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.reset();
} else {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
notificationManager = playerService.getNotificationManager();
}
tryToGetAudioFocus();
Music currentMusic = playerQueue.getCurrentMusic();
if (currentMusic != null) {
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currentMusic.id);
try {
mediaPlayer.setDataSource(context, trackUri);
mediaPlayer.prepareAsync();
setPlayerState(PlayerListener.State.PLAYING);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {
final String action = intent.getAction();
Music currentSong = null;
if (playerQueue.getCurrentQueue() != null)
currentSong = playerQueue.getCurrentMusic();
if (action != null && currentSong != null) {
switch (action) {
case PREV_ACTION:
playPrev();
break;
case PLAY_PAUSE_ACTION:
playPause();
break;
case NEXT_ACTION:
playNext();
break;
case BluetoothDevice.ACTION_ACL_DISCONNECTED:
pauseMediaPlayer();
break;
case BluetoothDevice.ACTION_ACL_CONNECTED:
if (!isPlaying()) {
resumeMediaPlayer();
}
break;
case Intent.ACTION_HEADSET_PLUG:
if (intent.hasExtra("state")) {
switch (intent.getIntExtra("state", -1)) {
//0 means disconnected
case 0:
pauseMediaPlayer();
break;
//1 means connected
case 1:
if (!isPlaying()) {
resumeMediaPlayer();
}
break;
}
}
break;
case AudioManager.ACTION_AUDIO_BECOMING_NOISY:
if (isPlaying()) {
pauseMediaPlayer();
}
break;
}
}
}
}
private class MediaObserver implements Runnable {
private final AtomicBoolean stop = new AtomicBoolean(false);
public void stop() {
stop.set(true);
}
@Override
public void run() {
while (!stop.get()) {
try {
if (mediaPlayer != null && isPlaying()) {
int percent = mediaPlayer.getCurrentPosition() * 100 / mediaPlayer.getDuration();
progressPercent.postValue(percent);
}
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerService.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerService.java | package com.atul.musicplayer.player;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.media.session.MediaSessionCompat;
import android.view.KeyEvent;
import com.atul.musicplayer.MPConstants;
public class PlayerService extends Service {
private final IBinder iBinder = new LocalBinder();
private PlayerManager playerManager;
private PlayerNotificationManager notificationManager;
private MediaSessionCompat mediaSessionCompat;
private final MediaSessionCompat.Callback mediaSessionCallback = new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
playerManager.playPause();
}
@Override
public void onPause() {
playerManager.playPause();
}
@Override
public void onSkipToNext() {
playerManager.playNext();
}
@Override
public void onSkipToPrevious() {
playerManager.playPrev();
}
@Override
public void onFastForward() {
super.onFastForward();
}
@Override
public void onRewind() {
playerManager.seekTo(0);
}
@Override
public void onStop() {
playerManager.playPause();
}
@Override
public void onSeekTo(long pos) {
playerManager.seekTo((int) pos);
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
return handleMediaButtonEvent(mediaButtonEvent);
}
};
private PowerManager.WakeLock wakeLock;
public PlayerService() {
}
public PlayerManager getPlayerManager() {
return playerManager;
}
public PlayerNotificationManager getNotificationManager() {
return notificationManager;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// prevents the service from closing, when app started from
// notification click, this will make sure that a foreground
// service exists too.
if (playerManager != null && playerManager.isPlaying())
playerManager.attachService();
return START_NOT_STICKY;
}
private void configureMediaSession() {
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
ComponentName mediaButtonReceiverComponentName = new ComponentName(this, PlayerManager.NotificationReceiver.class);
PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, PendingIntent.FLAG_IMMUTABLE);
mediaSessionCompat = new MediaSessionCompat(this, MPConstants.MEDIA_SESSION_TAG, mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent);
mediaSessionCompat.setActive(true);
mediaSessionCompat.setCallback(mediaSessionCallback);
mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
private boolean handleMediaButtonEvent(Intent mediaButtonEvent) {
boolean isSuccess = false;
if (mediaButtonEvent == null) {
return false;
}
KeyEvent keyEvent = mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_HEADSETHOOK:
playerManager.playPause();
isSuccess = true;
break;
case KeyEvent.KEYCODE_MEDIA_CLOSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
playerManager.pauseMediaPlayer();
isSuccess = true;
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
playerManager.playPrev();
isSuccess = true;
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
playerManager.playNext();
isSuccess = true;
break;
case KeyEvent.KEYCODE_MEDIA_REWIND:
playerManager.seekTo(0);
isSuccess = true;
break;
}
}
return isSuccess;
}
@Override
public IBinder onBind(Intent intent) {
if (playerManager == null) {
playerManager = new PlayerManager(this);
notificationManager = new PlayerNotificationManager(this);
playerManager.registerActionsReceiver();
}
return iBinder;
}
@Override
public void onCreate() {
super.onCreate();
if (wakeLock == null) {
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
wakeLock.setReferenceCounted(false);
}
configureMediaSession();
}
@Override
public void onDestroy() {
if (playerManager != null) {
playerManager.unregisterActionsReceiver();
playerManager.release();
}
notificationManager = null;
playerManager = null;
super.onDestroy();
}
public MediaSessionCompat getMediaSessionCompat() {
return mediaSessionCompat;
}
class LocalBinder extends Binder {
public PlayerService getInstance() {
return PlayerService.this;
}
}
} | java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerBuilder.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerBuilder.java | package com.atul.musicplayer.player;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.annotation.NonNull;
public class PlayerBuilder {
private final Context context;
private final PlayerListener playerListener;
private PlayerService playerService;
private PlayerManager playerManager;
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(@NonNull final ComponentName componentName, @NonNull final IBinder iBinder) {
playerService = ((PlayerService.LocalBinder) iBinder).getInstance();
playerManager = playerService.getPlayerManager();
if (playerListener != null) {
playerManager.setPlayerListener(playerListener);
}
}
@Override
public void onServiceDisconnected(@NonNull final ComponentName componentName) {
playerService = null;
}
};
public PlayerBuilder(Context context, PlayerListener listener) {
this.context = context;
this.playerListener = listener;
bindService();
}
public PlayerManager getPlayerManager() {
return playerManager;
}
public void bindService() {
context.bindService(new Intent(context, PlayerService.class), serviceConnection, Context.BIND_AUTO_CREATE);
context.startService(new Intent(context, PlayerService.class));
}
public void unBindService() {
if (playerManager != null) {
playerManager.detachService();
context.unbindService(serviceConnection);
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerNotificationManager.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerNotificationManager.java | package com.atul.musicplayer.player;
import static com.atul.musicplayer.MPConstants.CHANNEL_ID;
import static com.atul.musicplayer.MPConstants.NEXT_ACTION;
import static com.atul.musicplayer.MPConstants.NOTIFICATION_ID;
import static com.atul.musicplayer.MPConstants.PLAY_PAUSE_ACTION;
import static com.atul.musicplayer.MPConstants.PREV_ACTION;
import static com.atul.musicplayer.MPConstants.REQUEST_CODE;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.atul.musicplayer.MainActivity;
import com.atul.musicplayer.R;
import com.atul.musicplayer.helper.MusicLibraryHelper;
import com.atul.musicplayer.model.Music;
public class PlayerNotificationManager {
private final NotificationManager notificationManager;
private final PlayerService playerService;
private NotificationCompat.Builder notificationBuilder;
private final androidx.media.app.NotificationCompat.MediaStyle notificationStyle;
PlayerNotificationManager(@NonNull final PlayerService playerService) {
this.playerService = playerService;
notificationStyle = new androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2);
notificationManager = (NotificationManager) playerService.getSystemService(Context.NOTIFICATION_SERVICE);
}
public final NotificationManager getNotificationManager() {
return notificationManager;
}
private PendingIntent playerAction(@NonNull final String action) {
final Intent pauseIntent = new Intent();
pauseIntent.setAction(action);
return PendingIntent.getBroadcast(playerService, REQUEST_CODE, pauseIntent, PendingIntent.FLAG_IMMUTABLE);
}
public Notification createNotification() {
final Music song = playerService.getPlayerManager().getCurrentMusic();
final Intent openPlayerIntent = new Intent(playerService, MainActivity.class);
openPlayerIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent contentIntent = PendingIntent.getActivity(playerService, REQUEST_CODE,
openPlayerIntent, PendingIntent.FLAG_IMMUTABLE);
if (notificationBuilder == null) {
notificationBuilder = new NotificationCompat.Builder(playerService, CHANNEL_ID);
notificationBuilder
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_notif_music_note)
.setColorized(true)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel();
}
Bitmap albumArt = MusicLibraryHelper.getThumbnail(playerService.getApplicationContext(), song.albumArt);
notificationBuilder
.setContentTitle(song.title)
.setContentText(song.artist)
.setColor(MusicLibraryHelper.getDominantColorFromThumbnail(albumArt))
.setLargeIcon(albumArt)
.setStyle(notificationStyle);
notificationBuilder.clearActions();
notificationBuilder
.addAction(notificationAction(PREV_ACTION))
.addAction(notificationAction(PLAY_PAUSE_ACTION))
.addAction(notificationAction(NEXT_ACTION));
return notificationBuilder.build();
}
public void updateNotification() {
if (notificationBuilder == null)
return;
notificationBuilder.setOngoing(playerService.getPlayerManager().isPlaying());
PlayerManager playerManager = playerService.getPlayerManager();
Music song = playerManager.getCurrentMusic();
Bitmap albumArt = MusicLibraryHelper.getThumbnail(playerService.getApplicationContext(),
song.albumArt);
notificationBuilder.clearActions();
notificationBuilder
.addAction(notificationAction(PREV_ACTION))
.addAction(notificationAction(PLAY_PAUSE_ACTION))
.addAction(notificationAction(NEXT_ACTION));
notificationBuilder
.setLargeIcon(albumArt)
.setColor(MusicLibraryHelper.getDominantColorFromThumbnail(albumArt))
.setContentTitle(song.title)
.setContentText(song.artist)
.setColorized(true)
.setAutoCancel(true);
NotificationManagerCompat.from(playerService).notify(NOTIFICATION_ID, notificationBuilder.build());
}
@NonNull
private NotificationCompat.Action notificationAction(@NonNull final String action) {
int icon = -1;
if (action.equals(PREV_ACTION)) icon = R.drawable.ic_controls_prev;
else if (action.equals(NEXT_ACTION)) icon = R.drawable.ic_controls_next;
else if (action.equals(PLAY_PAUSE_ACTION)) icon =
playerService.getPlayerManager().isPlaying()
? R.drawable.ic_controls_pause
: R.drawable.ic_controls_play;
return new NotificationCompat.Action.Builder(icon, action, playerAction(action)).build();
}
@RequiresApi(26)
private void createNotificationChannel() {
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
final NotificationChannel notificationChannel =
new NotificationChannel(CHANNEL_ID,
playerService.getString(R.string.app_name),
NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(playerService.getString(R.string.app_name));
notificationChannel.enableLights(false);
notificationChannel.enableVibration(false);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
ap-atul/music_player_lite | https://github.com/ap-atul/music_player_lite/blob/46d714451b83ebad1f810d43df31a679b9ec85b4/src/app/src/main/java/com/atul/musicplayer/player/PlayerListener.java | src/app/src/main/java/com/atul/musicplayer/player/PlayerListener.java | package com.atul.musicplayer.player;
import androidx.annotation.IntDef;
import com.atul.musicplayer.model.Music;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public interface PlayerListener {
void onPrepared();
void onStateChanged(@State int state);
void onPositionChanged(int position);
void onMusicSet(Music music);
void onPlaybackCompleted();
void onRelease();
@IntDef({PlayerListener.State.INVALID,
PlayerListener.State.PLAYING,
PlayerListener.State.PAUSED,
PlayerListener.State.COMPLETED,
PlayerListener.State.RESUMED})
@Retention(RetentionPolicy.SOURCE)
@interface State {
int INVALID = -1;
int PLAYING = 0;
int PAUSED = 1;
int COMPLETED = 2;
int RESUMED = 3;
}
}
| java | Unlicense | 46d714451b83ebad1f810d43df31a679b9ec85b4 | 2026-01-05T02:39:08.858591Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/IMEntranceFragment.java | im/src/main/java/com/xpleemoon/im/IMEntranceFragment.java | package com.xpleemoon.im;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.xpleemoon.common.app.BaseCommonFragment;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
/**
* @author xpleemoon
*/
public class IMEntranceFragment extends BaseCommonFragment {
@InjectXModule(name = ModuleName.IM)
IMModule imModule;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.im_fragment_entrance, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.im_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imModule.getIMService().startIM();
}
});
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/IMActivity.java | im/src/main/java/com/xpleemoon/im/IMActivity.java | package com.xpleemoon.im;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
import com.xpleemoon.im.router.path.PathConstants;
@Route(path = PathConstants.PATH_VIEW_IM)
public class IMActivity extends BaseCommonActivity {
@InjectXModule(name = ModuleName.IM)
IMModule imModule;
private EditText mContractEdt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.im_activity_im);
mContractEdt = (EditText) findViewById(R.id.contract_edt);
mContractEdt.setText(imModule.getIMDaoService().getContact());
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.update_contract) {
imModule.getIMDaoService().updateContact(mContractEdt.getText().toString());
Toast.makeText(getApplication(), "联系人更新成功", Toast.LENGTH_SHORT).show();
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/repo/IMDataRepo.java | im/src/main/java/com/xpleemoon/im/repo/IMDataRepo.java | package com.xpleemoon.im.repo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
public class IMDataRepo {
private static final String NAME = "IMData";
private static final String KEY_CONTRACT = "contract";
private static volatile IMDataRepo sInstance;
private IMDataRepo() {
}
public static IMDataRepo getInstance() {
if (sInstance == null) {
synchronized (IMDataRepo.class) {
if (sInstance == null) {
sInstance = new IMDataRepo();
}
}
}
return sInstance;
}
private SharedPreferences getPreferences(@NonNull Context context) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
}
public void updateContract(@NonNull Context context, String name) {
getPreferences(context).edit().putString(KEY_CONTRACT, name).commit();
}
public String getContract(@NonNull Context context) {
return getPreferences(context).getString(KEY_CONTRACT, "");
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/router/IMModuleImpl.java | im/src/main/java/com/xpleemoon/im/router/IMModuleImpl.java | package com.xpleemoon.im.router;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.common.router.module.im.service.IMDaoService;
import com.xpleemoon.common.router.module.im.service.IMService;
import com.xpleemoon.xmodulable.annotation.XModule;
@XModule(name = ModuleName.IM)
public class IMModuleImpl extends IMModule {
@Autowired
IMService imService;
@Autowired
IMDaoService imDaoService;
@Override
public IMService getIMService() {
return imService;
}
@Override
public IMDaoService getIMDaoService() {
return imDaoService;
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/router/service/IMServiceImpl.java | im/src/main/java/com/xpleemoon/im/router/service/IMServiceImpl.java | package com.xpleemoon.im.router.service;
import android.content.Context;
import android.support.v4.app.Fragment;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.common.router.module.im.service.IMService;
import com.xpleemoon.im.IMEntranceFragment;
import com.xpleemoon.im.router.path.PathConstants;
@Route(path = PathConstants.PATH_SERVICE_IM)
public class IMServiceImpl implements IMService {
@Override
public void init(Context context) {
}
@Override
public Fragment createIMEntranceFragment() {
return new IMEntranceFragment();
}
@Override
public void startIM() {
ARouter.getInstance().build(PathConstants.PATH_VIEW_IM).navigation();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/router/service/IMDaoServiceImpl.java | im/src/main/java/com/xpleemoon/im/router/service/IMDaoServiceImpl.java | package com.xpleemoon.im.router.service;
import android.content.Context;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.xpleemoon.common.router.module.im.service.IMDaoService;
import com.xpleemoon.im.repo.IMDataRepo;
import com.xpleemoon.im.router.path.PathConstants;
@Route(path = PathConstants.PATH_SERVICE_DAO)
public class IMDaoServiceImpl implements IMDaoService {
private Context mCtx;
@Override
public String getContact() {
return IMDataRepo.getInstance().getContract(mCtx);
}
@Override
public void updateContact(String name) {
IMDataRepo.getInstance().updateContract(mCtx, name);
}
@Override
public void init(Context context) {
mCtx = context;
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/main/java/com/xpleemoon/im/router/path/PathConstants.java | im/src/main/java/com/xpleemoon/im/router/path/PathConstants.java | package com.xpleemoon.im.router.path;
public class PathConstants {
private static final String PATH_ROOT = "/im";
private static final String PATH_VIEW = "/view";
private static final String PATH_SERVICE = "/service";
public static final String PATH_VIEW_IM = PATH_ROOT + PATH_VIEW + "/im";
public static final String PATH_SERVICE_IM = PATH_ROOT + PATH_SERVICE + "/im";
public static final String PATH_SERVICE_DAO = PATH_ROOT + PATH_SERVICE + "/dao";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/standalone/java/com/xpleemoon/im/standalone/IMApplication.java | im/src/standalone/java/com/xpleemoon/im/standalone/IMApplication.java | package com.xpleemoon.im.standalone;
import com.xpleemoon.common.app.BaseCommonApplication;
import com.xpleemoon.im.BuildConfig;
public class IMApplication extends BaseCommonApplication {
@Override
public void onCreate() {
super.onCreate();
initRouterAndModule(BuildConfig.DEBUG);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/im/src/standalone/java/com/xpleemoon/im/standalone/IMSplashActivity.java | im/src/standalone/java/com/xpleemoon/im/standalone/IMSplashActivity.java | package com.xpleemoon.im.standalone;
import android.os.Bundle;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.im.R;
public class IMSplashActivity extends BaseCommonActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.im_activity_splash);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/app/src/main/java/com/xpleemoon/sample/modulable/SplashActivity.java | app/src/main/java/com/xpleemoon/sample/modulable/SplashActivity.java | package com.xpleemoon.sample.modulable;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.common.router.module.main.MainModule;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
public class SplashActivity extends BaseCommonActivity {
@InjectXModule(name = ModuleName.MAIN)
MainModule mainModule;
@InjectXModule(name = ModuleName.IM)
IMModule imModule;
@InjectXModule(name = ModuleName.LIVE)
LiveModule liveModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_main:
if (mainModule == null) {
Toast.makeText(getApplicationContext(), "Main组件未知", Toast.LENGTH_SHORT).show();
break;
}
mainModule.getMainService().startMainActivity();
break;
case R.id.start_live:
if (liveModule == null) {
Toast.makeText(getApplicationContext(), "Live组件未知", Toast.LENGTH_SHORT).show();
break;
}
liveModule.getLiveService().startLive();
break;
case R.id.start_IM:
if (imModule == null) {// 组件独立运行,会导致app壳找不到对应的组件,从而引起依赖注入失败
Toast.makeText(getApplicationContext(), "IM组件未知", Toast.LENGTH_SHORT).show();
break;
}
imModule.getIMService().startIM();
break;
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/app/src/main/java/com/xpleemoon/sample/modulable/SampleApplication.java | app/src/main/java/com/xpleemoon/sample/modulable/SampleApplication.java | package com.xpleemoon.sample.modulable;
import com.xpleemoon.common.app.BaseCommonApplication;
public class SampleApplication extends BaseCommonApplication {
@Override
public void onCreate() {
super.onCreate();
initRouterAndModule(BuildConfig.DEBUG);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/basiclib/src/main/java/com/xpleemoon/basiclib/BaseFragment.java | basiclib/src/main/java/com/xpleemoon/basiclib/BaseFragment.java | package com.xpleemoon.basiclib;
import android.support.v4.app.Fragment;
/**
* 基础fragment
*
* @author xpleemoon
*/
public class BaseFragment extends Fragment {
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/basiclib/src/main/java/com/xpleemoon/basiclib/BaseApplication.java | basiclib/src/main/java/com/xpleemoon/basiclib/BaseApplication.java | package com.xpleemoon.basiclib;
import android.app.Application;
/**
* 基础application
*
* @author xpleemoon
*/
public class BaseApplication extends Application {
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/basiclib/src/main/java/com/xpleemoon/basiclib/BaseActivity.java | basiclib/src/main/java/com/xpleemoon/basiclib/BaseActivity.java | package com.xpleemoon.basiclib;
import android.support.v7.app.AppCompatActivity;
/**
* 基础activity
*
* @author xpleemoon
*/
public class BaseActivity extends AppCompatActivity {
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/main/java/com/xpleemoon/live/LiveEntranceFragment.java | live/src/main/java/com/xpleemoon/live/LiveEntranceFragment.java | package com.xpleemoon.live;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.xpleemoon.common.app.BaseCommonFragment;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
/**
* @author xpleemoon
*/
public class LiveEntranceFragment extends BaseCommonFragment {
@InjectXModule(name = ModuleName.LIVE)
LiveModule liveModule;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.live_fragment_entrance, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.live_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
liveModule.getLiveService().startLive();
}
});
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/main/java/com/xpleemoon/live/LiveActivity.java | live/src/main/java/com/xpleemoon/live/LiveActivity.java | package com.xpleemoon.live;
import android.os.Bundle;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.live.router.path.PathConstants;
@Route(path = PathConstants.PATH_VIEW_LIVE)
public class LiveActivity extends BaseCommonActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.live_activity_live);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/main/java/com/xpleemoon/live/router/LiveModuleImpl.java | live/src/main/java/com/xpleemoon/live/router/LiveModuleImpl.java | package com.xpleemoon.live.router;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.common.router.module.live.service.LiveService;
import com.xpleemoon.xmodulable.annotation.XModule;
@XModule(name = ModuleName.LIVE)
public class LiveModuleImpl extends LiveModule {
@Autowired
LiveService liveService;
@Override
public LiveService getLiveService() {
return liveService;
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/main/java/com/xpleemoon/live/router/service/LiveServiceImpl.java | live/src/main/java/com/xpleemoon/live/router/service/LiveServiceImpl.java | package com.xpleemoon.live.router.service;
import android.content.Context;
import android.support.v4.app.Fragment;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.common.router.module.live.service.LiveService;
import com.xpleemoon.live.LiveEntranceFragment;
import com.xpleemoon.live.router.path.PathConstants;
@Route(path = PathConstants.PATH_SERVICE_LIVE)
public class LiveServiceImpl implements LiveService {
@Override
public void init(Context context) {
}
@Override
public Fragment createLiveEntranceFragment() {
return new LiveEntranceFragment();
}
@Override
public void startLive() {
ARouter.getInstance().build(PathConstants.PATH_VIEW_LIVE).navigation();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/main/java/com/xpleemoon/live/router/path/PathConstants.java | live/src/main/java/com/xpleemoon/live/router/path/PathConstants.java | package com.xpleemoon.live.router.path;
public class PathConstants {
private static final String PATH_ROOT = "/live";
private static final String PATH_VIEW = "/view";
private static final String PATH_SERVICE = "/service";
public static final String PATH_VIEW_LIVE = PATH_ROOT + PATH_VIEW + "/live";
public static final String PATH_SERVICE_LIVE = PATH_ROOT + PATH_SERVICE + "/live";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/standalone/java/com/xpleemoon/live/standalone/LiveApplication.java | live/src/standalone/java/com/xpleemoon/live/standalone/LiveApplication.java | package com.xpleemoon.live.standalone;
import com.xpleemoon.common.app.BaseCommonApplication;
import com.xpleemoon.live.BuildConfig;
public class LiveApplication extends BaseCommonApplication {
@Override
public void onCreate() {
super.onCreate();
initRouterAndModule(BuildConfig.DEBUG);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/live/src/standalone/java/com/xpleemoon/live/standalone/LiveSplashActivity.java | live/src/standalone/java/com/xpleemoon/live/standalone/LiveSplashActivity.java | package com.xpleemoon.live.standalone;
import android.os.Bundle;
import android.view.View;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.live.R;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
public class LiveSplashActivity extends BaseCommonActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.live_activity_splash);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/app/BaseCommonActivity.java | common/src/main/java/com/xpleemoon/common/app/BaseCommonActivity.java | package com.xpleemoon.common.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.basiclib.BaseActivity;
import com.xpleemoon.xmodulable.api.XModulable;
/**
* 公共业务基础activity
* <ul>
* <li>{@link #onCreate(Bundle)}内部调用了{@link ARouter#inject(Object)}用于IOC</li>
* </ul>
*
* @author xpleemoon
*/
public class BaseCommonActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ARouter.getInstance().inject(this);
XModulable.inject(this);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/app/BaseCommonApplication.java | common/src/main/java/com/xpleemoon/common/app/BaseCommonApplication.java | package com.xpleemoon.common.app;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.basiclib.BaseApplication;
import com.xpleemoon.xmodulable.api.XModulable;
/**
* 公共业务基础application
*
* @author xpleemoon
*/
public abstract class BaseCommonApplication extends BaseApplication {
/**
* 初始化路由和组件
*
* @param isDebug 是否调试模式
*/
protected final void initRouterAndModule(boolean isDebug) {
if (isDebug) { // 这两行必须写在init之前,否则这些配置在init过程中将无效
ARouter.openLog(); // 打印日志
ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
ARouter.init(this); // 尽可能早,推荐在Application中初始化
if (isDebug) {
XModulable.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
XModulable.init(this); // 必须在ARouter初始化后进行,因为组件对象有可能回包含ARouter对应的IOC
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/app/BaseCommonFragment.java | common/src/main/java/com/xpleemoon/common/app/BaseCommonFragment.java | package com.xpleemoon.common.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.basiclib.BaseFragment;
import com.xpleemoon.xmodulable.api.XModulable;
/**
* 公共业务基础fragment
* <ul>
* <li>{@link #onCreate(Bundle)}内部调用了{@link ARouter#inject(Object)}用于IOC</li>
* </ul>
*
* @author xpleemoon
*/
public class BaseCommonFragment extends BaseFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ARouter.getInstance().inject(this);
XModulable.inject(this);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/ModuleName.java | common/src/main/java/com/xpleemoon/common/router/module/ModuleName.java | package com.xpleemoon.common.router.module;
/**
* Created by xplee on 2017/12/13.
*/
public class ModuleName {
public static final String MAIN = "main";
public static final String IM = "im";
public static final String LIVE = "live";
} | java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/BaseService.java | common/src/main/java/com/xpleemoon/common/router/module/BaseService.java | package com.xpleemoon.common.router.module;
import com.alibaba.android.arouter.facade.template.IProvider;
/**
* 组件基础服务接口,业务组件务必实现该接口暴露服务,从而实现面向该接口编程
*
* @author xpleemoon
*/
public interface BaseService extends IProvider {
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/BaseModule.java | common/src/main/java/com/xpleemoon/common/router/module/BaseModule.java | package com.xpleemoon.common.router.module;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.xmodulable.api.IModule;
/**
* 业务组件基础类,用于承载业务组件暴露的{@link BaseService 服务},
* </br>通俗地说就是{@link BaseService 服务}容器
* <ul>
* <li>{@link #BaseModule()}调用了{@link ARouter#inject(Object)}用于IOC,
* <br/>子类若要重载或者重写构造方法,务必调用super()</li>
* </ul>
*
* @author xpleemoon
*/
public class BaseModule implements IModule {
public BaseModule() {
ARouter.getInstance().inject(this);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/im/IMModule.java | common/src/main/java/com/xpleemoon/common/router/module/im/IMModule.java | package com.xpleemoon.common.router.module.im;
import com.xpleemoon.common.router.module.BaseModule;
import com.xpleemoon.common.router.module.im.service.IMDaoService;
import com.xpleemoon.common.router.module.im.service.IMService;
public abstract class IMModule extends BaseModule {
public abstract IMService getIMService();
public abstract IMDaoService getIMDaoService();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/im/service/IMDaoService.java | common/src/main/java/com/xpleemoon/common/router/module/im/service/IMDaoService.java | package com.xpleemoon.common.router.module.im.service;
import com.xpleemoon.common.router.module.BaseService;
public interface IMDaoService extends BaseService {
String getContact();
void updateContact(String name);
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/im/service/IMService.java | common/src/main/java/com/xpleemoon/common/router/module/im/service/IMService.java | package com.xpleemoon.common.router.module.im.service;
import android.support.v4.app.Fragment;
import com.xpleemoon.common.router.module.BaseService;
public interface IMService extends BaseService {
Fragment createIMEntranceFragment();
void startIM();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/live/LiveModule.java | common/src/main/java/com/xpleemoon/common/router/module/live/LiveModule.java | package com.xpleemoon.common.router.module.live;
import com.xpleemoon.common.router.module.BaseModule;
import com.xpleemoon.common.router.module.live.service.LiveService;
public abstract class LiveModule extends BaseModule {
public abstract LiveService getLiveService();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/live/service/LiveService.java | common/src/main/java/com/xpleemoon/common/router/module/live/service/LiveService.java | package com.xpleemoon.common.router.module.live.service;
import android.support.v4.app.Fragment;
import com.xpleemoon.common.router.module.BaseService;
public interface LiveService extends BaseService {
Fragment createLiveEntranceFragment();
void startLive();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/main/MainModule.java | common/src/main/java/com/xpleemoon/common/router/module/main/MainModule.java | package com.xpleemoon.common.router.module.main;
import com.xpleemoon.common.router.module.BaseModule;
import com.xpleemoon.common.router.module.main.service.MainService;
public abstract class MainModule extends BaseModule {
public abstract MainService getMainService();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/common/src/main/java/com/xpleemoon/common/router/module/main/service/MainService.java | common/src/main/java/com/xpleemoon/common/router/module/main/service/MainService.java | package com.xpleemoon.common.router.module.main.service;
import com.xpleemoon.common.router.module.BaseService;
public interface MainService extends BaseService {
void startMainActivity();
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/main/java/com/xpleemoon/main/MainFragment.java | main/src/main/java/com/xpleemoon/main/MainFragment.java | package com.xpleemoon.main;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.xpleemoon.common.app.BaseCommonFragment;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
/**
* @author xpleemoon
*/
public class MainFragment extends BaseCommonFragment implements View.OnClickListener {
@InjectXModule(name = ModuleName.LIVE)
LiveModule liveModule;
@InjectXModule(name = ModuleName.IM)
IMModule imModule;
private EditText mContractEdt;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment_main, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.start_live).setOnClickListener(this);
view.findViewById(R.id.update_im_contract).setOnClickListener(this);
mContractEdt = (EditText) view.findViewById(R.id.im_contract_edt);
if (imModule != null) {
mContractEdt.setText(imModule.getIMDaoService().getContact());
} else {
Toast.makeText(getContext(), "IM组件未知", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.start_live) {
if (liveModule == null) {
Toast.makeText(getContext(), "Live组件未知", Toast.LENGTH_SHORT).show();
return;
}
liveModule.getLiveService().startLive();
} else if (id == R.id.update_im_contract) {
if (imModule == null) {
Toast.makeText(getContext(), "IM组件未知", Toast.LENGTH_SHORT).show();
return;
}
imModule.getIMDaoService().updateContact(mContractEdt.getText().toString());
Toast.makeText(getContext(), "IM组件中的联系人更新成功", Toast.LENGTH_SHORT).show();
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/main/java/com/xpleemoon/main/MainActivity.java | main/src/main/java/com/xpleemoon/main/MainActivity.java | package com.xpleemoon.main;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.im.IMModule;
import com.xpleemoon.common.router.module.live.LiveModule;
import com.xpleemoon.main.router.path.PathConstants;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
import java.util.LinkedHashMap;
import java.util.Map;
@Route(path = PathConstants.PATH_VIEW_MAIN)
public class MainActivity extends BaseCommonActivity {
@InjectXModule(name = ModuleName.LIVE)
LiveModule liveModule;
@InjectXModule(name = ModuleName.IM)
IMModule imModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_main);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false); // 设置导航按钮无效
getSupportActionBar().setDisplayHomeAsUpEnabled(false); // 不显示导航按钮
getSupportActionBar().setDisplayShowTitleEnabled(true); // 显示标题
TabLayout tabLayout = findViewById(R.id.main_tab_layout);
ViewPager viewPager = findViewById(R.id.main_pager);
LinkedHashMap<String, Fragment> fragments = new LinkedHashMap<>(3);
fragments.put("main", new MainFragment());
if (liveModule != null) {
fragments.put("live", liveModule.getLiveService().createLiveEntranceFragment());
}
if (imModule != null) {
fragments.put("im", imModule.getIMService().createIMEntranceFragment());
}
viewPager.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), fragments));
tabLayout.setupWithViewPager(viewPager);
}
private static class MainPagerAdapter extends FragmentStatePagerAdapter {
private LinkedHashMap<String, Fragment> fragments;
public MainPagerAdapter(FragmentManager fm, LinkedHashMap<String, Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
private Map.Entry<String, Fragment> getEntry(int position) {
int index = 0;
for (Map.Entry<String, Fragment> entry : fragments.entrySet()) {
if (index++ == position) {
return entry;
}
}
return null;
}
@Override
public Fragment getItem(int position) {
Map.Entry<String, Fragment> entry = getEntry(position);
return entry != null ? entry.getValue() : null;
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
Map.Entry<String, Fragment> entry = getEntry(position);
return entry != null ? entry.getKey() : null;
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/main/java/com/xpleemoon/main/router/MainModuleImpl.java | main/src/main/java/com/xpleemoon/main/router/MainModuleImpl.java | package com.xpleemoon.main.router;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.main.MainModule;
import com.xpleemoon.common.router.module.main.service.MainService;
import com.xpleemoon.xmodulable.annotation.XModule;
import com.xpleemoon.main.router.path.PathConstants;
@XModule(name = ModuleName.MAIN)
public class MainModuleImpl extends MainModule {
MainService mainService;
@Override
public MainService getMainService() {
return mainService != null ? mainService : (mainService = (MainService) ARouter.getInstance().build(PathConstants.PATH_SERVICE_MAIN).navigation());
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/main/java/com/xpleemoon/main/router/service/MainServiceImpl.java | main/src/main/java/com/xpleemoon/main/router/service/MainServiceImpl.java | package com.xpleemoon.main.router.service;
import android.content.Context;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xpleemoon.common.router.module.main.service.MainService;
import com.xpleemoon.main.router.path.PathConstants;
@Route(path = PathConstants.PATH_SERVICE_MAIN)
public class MainServiceImpl implements MainService {
@Override
public void init(Context context) {
}
@Override
public void startMainActivity() {
ARouter.getInstance().build(PathConstants.PATH_VIEW_MAIN).navigation();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/main/java/com/xpleemoon/main/router/path/PathConstants.java | main/src/main/java/com/xpleemoon/main/router/path/PathConstants.java | package com.xpleemoon.main.router.path;
public class PathConstants {
private static final String PATH_ROOT = "/main";
private static final String PATH_VIEW = "/view";
private static final String PATH_SERVICE = "/service";
public static final String PATH_VIEW_MAIN = PATH_ROOT + PATH_VIEW + "/main";
public static final String PATH_SERVICE_MAIN = PATH_ROOT + PATH_SERVICE + "/main";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/standalone/java/com/xpleemoon/main/standalone/MainApplication.java | main/src/standalone/java/com/xpleemoon/main/standalone/MainApplication.java | package com.xpleemoon.main.standalone;
import com.xpleemoon.common.app.BaseCommonApplication;
import com.xpleemoon.main.BuildConfig;
public class MainApplication extends BaseCommonApplication {
@Override
public void onCreate() {
super.onCreate();
initRouterAndModule(BuildConfig.DEBUG);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/main/src/standalone/java/com/xpleemoon/main/standalone/MainSplashActivity.java | main/src/standalone/java/com/xpleemoon/main/standalone/MainSplashActivity.java | package com.xpleemoon.main.standalone;
import android.os.Bundle;
import android.view.View;
import com.xpleemoon.common.app.BaseCommonActivity;
import com.xpleemoon.common.router.module.ModuleName;
import com.xpleemoon.common.router.module.main.MainModule;
import com.xpleemoon.main.R;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
public class MainSplashActivity extends BaseCommonActivity {
@InjectXModule(name = ModuleName.MAIN)
MainModule mainModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_splash);
}
public void startEntrance(View view) {
mainModule.getMainService().startMainActivity();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-annotation/src/main/java/com/xpleemoon/xmodulable/annotation/InjectXModule.java | XModulable-annotation/src/main/java/com/xpleemoon/xmodulable/annotation/InjectXModule.java | package com.xpleemoon.xmodulable.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 组件注入
*
* @author xpleemoon
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.CLASS)
public @interface InjectXModule {
/**
* 组件名
*/
String name() default "";
String desc() default "若组件未注册或未知,则会引起依赖注入失败";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-annotation/src/main/java/com/xpleemoon/xmodulable/annotation/XModule.java | XModulable-annotation/src/main/java/com/xpleemoon/xmodulable/annotation/XModule.java | package com.xpleemoon.xmodulable.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 组件声明
*
* @author xpleemoon
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface XModule {
/**
* 组件名
*/
String name() default "";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/XModulableOptions.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/XModulableOptions.java | package com.xpleemoon.xmodulable.api;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 组件配置缓存类,内部通过{@link #mModuleMap map}实现组件的缓存
*
* @author xpleemoon
*/
public class XModulableOptions {
private Map<String, IModule> mModuleMap;
private XModulableOptions(Map<String, IModule> moduleMap) {
this.mModuleMap = moduleMap;
}
/**
* 根据{@code name}获取组件服务管理
*
* @param name 组件服务类型
* @return
*/
public IModule getModule(String name) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("组件名不能为空");
}
return mModuleMap.get(name);
}
/**
* 添加组件
*
* @param name
* @param m
* @param <M>
*/
public <M extends IModule> void addModule(String name, M m) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("组件名不能为空");
}
if (m == null) {
throw new IllegalArgumentException("组件不能为null");
}
mModuleMap.put(name, m);
}
public static final class Builder {
Map<String, IModule> mModuleMap;
public Builder() {
mModuleMap = new HashMap<>();
}
/**
* @see #addModule(String, Class)
*/
public Builder addModule(String name, String moduleClzName) {
if (TextUtils.isEmpty(moduleClzName)) {
return this;
}
Class<? extends IModule> moduleClz = null;
try {
moduleClz = (Class<? extends IModule>) Class.forName(moduleClzName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return addModule(name, moduleClz);
}
/**
* @see #addModule(String, IModule)
*/
public Builder addModule(String name, Class<? extends IModule> moduleClz) {
if (moduleClz == null) {
return this;
}
IModule module = null;
try {
module = moduleClz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return addModule(name, module);
}
/**
* 添加组件
*
* @param name 组件名
* @param m 组件
* @param <M> 组件泛型类型为{@link IModule}子类
* @return
*/
public <M extends IModule> Builder addModule(String name, M m) {
if (TextUtils.isEmpty(name) || m == null) {
return this;
}
mModuleMap.put(name, m);
return this;
}
public XModulableOptions build() {
return new XModulableOptions(mModuleMap);
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/IModule.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/IModule.java | package com.xpleemoon.xmodulable.api;
/**
* 组件
*
* @author xpleemoon
*/
public interface IModule {
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/Constants.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/Constants.java | package com.xpleemoon.xmodulable.api;
public final class Constants {
public static final String SDK_NAME = "XModulable";
public static final String TAG = SDK_NAME + "::";
public static final String PACKAGE_OF_GENERATE = "com.xpleemoon.xmodulable.api.loaders";
/**
* 类名分隔符
*/
public static final String SEPARATOR_OF_CLASS_NAME = "$$";
public static final String CLASS_OF_LOADER = "Loader";
public static final String CLASS_OF_INJECTOR = SDK_NAME + "Injector";
public static final String METHOD_OF_INJECT = "inject";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/XModulable.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/XModulable.java | package com.xpleemoon.xmodulable.api;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.LruCache;
import com.xpleemoon.xmodulable.api.exception.UnknownModuleException;
import com.xpleemoon.xmodulable.api.template.XModuleLoader;
import com.xpleemoon.xmodulable.api.utils.CacheUtils;
import com.xpleemoon.xmodulable.api.utils.ClassUtils;
import com.xpleemoon.xmodulable.api.utils.PackageUtils;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* 业务组件管理类
* <ul>
* <li>上层通过{@link #init(Context)}实现{@link IModule 组件}的注册</li>
* <li>使用前确保先进行{@link #init(Context) 初始化}</li>
* <li>暴露的{@link #getModule(String)}用于获取已注册的{@link IModule 组件}</li>
* </ul>
*
* @author xpleemoon
*/
public class XModulable {
private static boolean sDebuggable = false;
private static Context sCtx;
private static volatile XModulable sInstance;
private static final LruCache<String, Class> sInjectorClzCache = new LruCache<>(20);
private static final List<String> sBlackNames = new ArrayList<>();
private final XModulableOptions mOptions;
private XModulable() {
this.mOptions = new XModulableOptions.Builder().build();
}
public static XModulable getInstance() {
if (sInstance == null) {
synchronized (XModulable.class) {
if (sInstance == null) {
sInstance = new XModulable();
}
}
}
return sInstance;
}
public static boolean debuggable() {
return sDebuggable;
}
public static void openDebug() {
sDebuggable = true;
}
public static void closeDebug() {
sDebuggable = false;
}
/**
* 初始化组件服务管理类,在使用该类时确保先进行初始化
*/
public static synchronized void init(Context context) {
sCtx = context.getApplicationContext();
Set<String> loaderSet = null;
// 调试模式或者是新版本,会有新的类生成,因此需要重新加载,
if (debuggable() || PackageUtils.isNewVersion(context)) {
try {
// 扫面由XModuleProcessor生成的组件加载器
loaderSet = ClassUtils.getFileNameByPackageName(context, Constants.PACKAGE_OF_GENERATE);
CacheUtils.updateModuleLoaderSet(context, loaderSet);
PackageUtils.updateVersion(context);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
loaderSet = CacheUtils.getModuleLoaderSet(context);
}
if (loaderSet != null) {
String prefixOfLoader = new StringBuilder()
.append(Constants.PACKAGE_OF_GENERATE)
.append(".")
.append(Constants.SDK_NAME)
.append(Constants.SEPARATOR_OF_CLASS_NAME)
.append(Constants.CLASS_OF_LOADER)
.toString();
for (String className : loaderSet) {
if (className.startsWith(prefixOfLoader)) {
try {
Class<XModuleLoader> componentLoaderClass = (Class<XModuleLoader>) Class.forName(className);
XModuleLoader componentLoader = componentLoaderClass.getConstructor().newInstance();
componentLoader.loadInto(getInstance().mOptions);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
private static void check() {
if (sCtx == null) {
throw new IllegalStateException("XModulable未初始化");
}
}
/**
* 组件的依赖注入
*
* @param target
*/
public static void inject(Object target) {
check();
String injectorClzName = target.getClass().getName() + Constants.SEPARATOR_OF_CLASS_NAME + Constants.CLASS_OF_INJECTOR;
if (sBlackNames.contains(injectorClzName)) {
return;
}
Class injectorClz = sInjectorClzCache.get(injectorClzName);
try {
if (injectorClz == null) {
injectorClz = Class.forName(injectorClzName);
}
Method bindsMethod = injectorClz.getMethod(Constants.METHOD_OF_INJECT, target.getClass());
bindsMethod.invoke(null, target);
sInjectorClzCache.put(injectorClzName, injectorClz);
} catch (Exception e) {
sBlackNames.add(injectorClzName);
}
}
/**
* @throws UnknownModuleException 组件{@code name}未注册或不存在
* @see XModulableOptions#getModule(String)
*/
public IModule getModule(String name) throws UnknownModuleException {
check();
IModule module = mOptions.getModule(name);
if (module == null) {
throw new UnknownModuleException(name);
}
return module;
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/exception/UnknownModuleException.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/exception/UnknownModuleException.java | package com.xpleemoon.xmodulable.api.exception;
/**
* 组件未知
*
* @author xpleemoon
*/
public class UnknownModuleException extends Exception {
public UnknownModuleException(String name) {
super(String.format("组件%1s未注册或不存在", name));
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/ClassUtils.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/ClassUtils.java | package com.xpleemoon.xmodulable.api.utils;
// Copy from galaxy sdk ${com.alibaba.android.galaxy.utils.ClassUtils}
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import com.xpleemoon.xmodulable.api.XModulable;
import com.xpleemoon.xmodulable.api.Constants;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import dalvik.system.DexFile;
/**
* Scanner, find out class with any conditions, copy from google source code.
*
* @author 正纬 <a href="mailto:zhilong.liu@aliyun.com">Contact me.</a>
* @version 1.0
* @since 16/6/27 下午10:58
*/
public class ClassUtils {
private static final String EXTRACTED_NAME_EXT = ".classes";
private static final String EXTRACTED_SUFFIX = ".zip";
private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes";
private static final String PREFS_FILE = "multidex.version";
private static final String KEY_DEX_NUMBER = "dex.number";
private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2;
private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1;
private static SharedPreferences getMultiDexPreferences(Context context) {
return context.getSharedPreferences(PREFS_FILE, Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
/**
* 通过指定包名,扫描包下面包含的所有的ClassName
*
* @param context U know
* @param packageName 包名
* @return 所有class的集合
*/
public static Set<String> getFileNameByPackageName(Context context, final String packageName) throws PackageManager.NameNotFoundException, IOException, InterruptedException {
final Set<String> classNames = new HashSet<>();
List<String> paths = getSourcePaths(context);
final CountDownLatch parserCtl = new CountDownLatch(paths.size());
Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()/*cpu数量*/ + 1);
for (final String path : paths) {
executor.execute(new Runnable() {
@Override
public void run() {
DexFile dexfile = null;
try {
if (path.endsWith(EXTRACTED_SUFFIX)) {
//NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"
dexfile = DexFile.loadDex(path, path + ".tmp", 0);
} else {
dexfile = new DexFile(path);
}
Enumeration<String> dexEntries = dexfile.entries();
while (dexEntries.hasMoreElements()) {
String className = dexEntries.nextElement();
if (className.startsWith(packageName)) {
classNames.add(className);
}
}
} catch (Throwable ignore) {
Log.e(Constants.TAG, "Scan map file in dex files made error.", ignore);
} finally {
if (null != dexfile) {
try {
dexfile.close();
} catch (Throwable ignore) {
}
}
parserCtl.countDown();
}
}
});
}
parserCtl.await();
Log.d(Constants.TAG, "Filter " + classNames.size() + " classes by packageName <" + packageName + ">");
return classNames;
}
/**
* get all the dex path
*
* @param context the application context
* @return all the dex path
* @throws PackageManager.NameNotFoundException
* @throws IOException
*/
public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
File sourceApk = new File(applicationInfo.sourceDir);
List<String> sourcePaths = new ArrayList<>();
sourcePaths.add(applicationInfo.sourceDir); //add the default apk path
//the prefix of extracted file, ie: test.classes
String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
// 如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了
// 通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的
if (!isVMMultidexCapable()) {
//the total dex numbers
int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);
for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
//for each dex file, ie: test.classes2.zip, test.classes3.zip...
String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
File extractedFile = new File(dexDir, fileName);
if (extractedFile.isFile()) {
sourcePaths.add(extractedFile.getAbsolutePath());
//we ignore the verify zip part
} else {
throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");
}
}
}
if (XModulable.debuggable()) { // Search instant run support only debuggable
sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));
}
return sourcePaths;
}
/**
* Get instant run dex path, used to catch the branch usingApkSplits=false.
*/
private static List<String> tryLoadInstantRunDexFile(ApplicationInfo applicationInfo) {
List<String> instantRunSourcePaths = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && null != applicationInfo.splitSourceDirs) {
// add the split apk, normally for InstantRun, and newest version.
instantRunSourcePaths.addAll(Arrays.asList(applicationInfo.splitSourceDirs));
Log.d(Constants.TAG, "Found InstantRun support");
} else {
try {
// This man is reflection from Google instant run sdk, he will tell me where the dex files go.
Class pathsByInstantRun = Class.forName("com.android.tools.fd.runtime.Paths");
Method getDexFileDirectory = pathsByInstantRun.getMethod("getDexFileDirectory", String.class);
String instantRunDexPath = (String) getDexFileDirectory.invoke(null, applicationInfo.packageName);
File instantRunFilePath = new File(instantRunDexPath);
if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) {
File[] dexFile = instantRunFilePath.listFiles();
for (File file : dexFile) {
if (null != file && file.exists() && file.isFile() && file.getName().endsWith(".dex")) {
instantRunSourcePaths.add(file.getAbsolutePath());
}
}
Log.d(Constants.TAG, "Found InstantRun support");
}
} catch (Exception e) {
Log.e(Constants.TAG, "InstantRun support error, " + e.getMessage());
}
}
return instantRunSourcePaths;
}
/**
* Identifies if the current VM has a native support for multidex, meaning there is no need for
* additional installation by this library.
*
* @return true if the VM handles multidex
*/
private static boolean isVMMultidexCapable() {
boolean isMultidexCapable = false;
String vmName = null;
try {
if (isYunOS()) { // YunOS需要特殊判断
vmName = "'YunOS'";
isMultidexCapable = Integer.valueOf(System.getProperty("ro.build.version.sdk")) >= 21;
} else { // 非YunOS原生Android
vmName = "'Android'";
String versionString = System.getProperty("java.vm.version");
if (versionString != null) {
Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString);
if (matcher.matches()) {
try {
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR)
|| ((major == VM_WITH_MULTIDEX_VERSION_MAJOR)
&& (minor >= VM_WITH_MULTIDEX_VERSION_MINOR));
} catch (NumberFormatException ignore) {
// let isMultidexCapable be false
}
}
}
}
} catch (Exception ignore) {
}
Log.i(Constants.TAG, "VM with name " + vmName + (isMultidexCapable ? " has multidex support" : " does not have multidex support"));
return isMultidexCapable;
}
/**
* 判断系统是否为YunOS系统
*/
private static boolean isYunOS() {
try {
String version = System.getProperty("ro.yunos.version");
String vmName = System.getProperty("java.vm.name");
return (vmName != null && vmName.toLowerCase().contains("lemur"))
|| (version != null && version.trim().length() > 0);
} catch (Exception ignore) {
return false;
}
}
} | java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/CacheUtils.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/CacheUtils.java | package com.xpleemoon.xmodulable.api.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
/**
* 组件相关的缓存工具
*
* @author xpleemoon
*/
public class CacheUtils {
private static final String NAME = "xmodulable_cache";
/**
* 组件加载器集合的缓存key
*/
static final String KEY_MODULE_LOADER_SET = "ModuleLoaderSet";
/**
* 缓存的apk版本名key
*/
static final String KEY_LAST_VERSION_NAME = "lastVersionName";
/**
* apk缓存的版本号key
*/
static final String KEY_LAST_VERSION_CODE = "lastVersionCode";
static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
}
/**
* 获取缓存的组件加载器集合
*
* @param context
* @return
*/
public static Set<String> getModuleLoaderSet(Context context) {
return getPrefs(context).getStringSet(KEY_MODULE_LOADER_SET, null);
}
/**
* 更新缓存的组件加载器集合
*
* @param context
* @param componentLoaderSet
*/
public static void updateModuleLoaderSet(Context context, Set<String> componentLoaderSet) {
getPrefs(context).edit().putStringSet(KEY_MODULE_LOADER_SET, componentLoaderSet).apply();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/PackageUtils.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/utils/PackageUtils.java | package com.xpleemoon.xmodulable.api.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Android package utils
*
* @author zhilong <a href="mailto:zhilong.liu@aliyun.com">Contact me.</a>
* @version 1.0
* @since 2017/8/8 下午8:19
*/
public class PackageUtils {
private static String NEW_VERSION_NAME;
private static int NEW_VERSION_CODE;
public static boolean isNewVersion(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
if (null != packageInfo) {
String versionName = packageInfo.versionName;
int versionCode = packageInfo.versionCode;
SharedPreferences sp = CacheUtils.getPrefs(context);
if (!versionName.equals(sp.getString(CacheUtils.KEY_LAST_VERSION_NAME, null))
|| versionCode != sp.getInt(CacheUtils.KEY_LAST_VERSION_CODE, -1)) {
// new version
NEW_VERSION_NAME = versionName;
NEW_VERSION_CODE = versionCode;
return true;
} else {
return false;
}
} else {
return true;
}
}
public static void updateVersion(Context context) {
if (!android.text.TextUtils.isEmpty(NEW_VERSION_NAME) && NEW_VERSION_CODE != 0) {
SharedPreferences sp = CacheUtils.getPrefs(context);
sp.edit()
.putString(CacheUtils.KEY_LAST_VERSION_NAME, NEW_VERSION_NAME)
.putInt(CacheUtils.KEY_LAST_VERSION_CODE, NEW_VERSION_CODE)
.apply();
}
}
private static PackageInfo getPackageInfo(Context context) {
PackageInfo packageInfo = null;
try {
packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
} catch (Exception e) {
e.printStackTrace();
}
return packageInfo;
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/template/XModuleLoader.java | XModulable-api/src/main/java/com/xpleemoon/xmodulable/api/template/XModuleLoader.java | package com.xpleemoon.xmodulable.api.template;
import com.xpleemoon.xmodulable.api.IModule;
import com.xpleemoon.xmodulable.api.XModulableOptions;
/**
* {@link IModule 组件}加载器
*
* @author xpleemoon
*/
public interface XModuleLoader {
/**
* 主要作用:加载{@link IModule 组件},并添加到{@code XModulableOptions}
*
* @param options {@link IModule 组件}容器wrapper
*/
void loadInto(XModulableOptions options);
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/Constants.java | XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/Constants.java | package com.xpleemoon.xmodulable.compiler;
public final class Constants {
public static final String WARNING_TIPS = "DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY XMODULABLE.";
/**
* 组建模块
*/
public static final String KEY_XMODULE = "XModule";
public static final String PACKAGE_OF_API = "com.xpleemoon.xmodulable.api";
public static final String PACKAGE_OF_GENERATE = "com.xpleemoon.xmodulable.api.loaders";
public static final String PACKAGE_OF_ANNOTATION = "com.xpleemoon.xmodulable.annotation";
public static final String SDK_NAME = "XModulable";
public static final String PREFIX_OF_LOGGER = SDK_NAME + "::Compiler >>> ";
/**
* 类名分隔符
*/
public static final String SEPARATOR_OF_CLASS_NAME = "$$";
public static final String CLASS_OF_LOADER = "Loader";
public static final String CLASS_OF_INJECTOR = SDK_NAME + "Injector";
public static final String METHOD_OF_LOAD_INTO = "loadInto";
public static final String METHOD_OF_INJECT = "inject";
public static final String PARAMETER_OF_XMODULABLE_OPTIONS = "options";
public static final String PARAMETER_OF_TARGET = "target";
public static final String XMODULABLE = PACKAGE_OF_API + ".XModulable";
public static final String XMODULABLE_OPTIONS = PACKAGE_OF_API + ".XModulableOptions";
public static final String XMODULE_LOADER = PACKAGE_OF_API + ".template.XModuleLoader";
public static final String UNKNOWN_MODULE_EXCEPTION = PACKAGE_OF_API + ".exception.UnknownModuleException";
public static final String ANNOTATION_TYPE_XMODULE = PACKAGE_OF_ANNOTATION + ".XModule";
public static final String ANNOTATION_TYPE_INJECT_XMODULE = PACKAGE_OF_ANNOTATION + ".InjectXModule";
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/processor/InjectProcessor.java | XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/processor/InjectProcessor.java | package com.xpleemoon.xmodulable.compiler.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeSpec;
import com.xpleemoon.xmodulable.annotation.InjectXModule;
import com.xpleemoon.xmodulable.compiler.Constants;
import com.xpleemoon.xmodulable.compiler.exception.ProcessException;
import com.xpleemoon.xmodulable.compiler.utils.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
/**
* 依赖注入处理器
*
* @author xpleemoon
*/
@AutoService(Processor.class)
@SupportedOptions(Constants.KEY_XMODULE)
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@SupportedAnnotationTypes(Constants.ANNOTATION_TYPE_INJECT_XMODULE)
public class InjectProcessor extends AbstractProcessor {
/**
* 可用于编译时,信息打印
*/
private Logger mLogger;
/**
* 用于{@link Element}处理的工具类
*/
private Elements mElementUtils;
/**
* 用于文件创建
*/
private Filer mFiler;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
mLogger = new Logger(processingEnvironment.getMessager());
mElementUtils = processingEnvironment.getElementUtils();
mFiler = processingEnvironment.getFiler();
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (set != null && !set.isEmpty()) {
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(InjectXModule.class);
if (elements == null || elements.size() <= 0) {
return true;
}
mLogger.info(String.format("解析注解:%s", InjectXModule.class.getSimpleName()));
try {
// key:依赖注入变量的目标类全限定名;value:目标类中携带@InjectXModule的Element的map集合
Map<String, List<Element>> targetInjectElements = new LinkedHashMap<>();
// 扫描注解InjectXModule
for (Element injectElement : elements) {
verify(injectElement);
String fullClzName = injectElement.getEnclosingElement().toString();
List<Element> injectElements = targetInjectElements.get(fullClzName);
if (injectElements == null) {
injectElements = new ArrayList<>();
targetInjectElements.put(fullClzName, injectElements);
}
injectElements.add(injectElement);
}
// 生成代码
generateCode(targetInjectElements);
} catch (ProcessException e) {
mLogger.error(e.fillInStackTrace());
}
return true;
}
return false;
}
private void verify(Element injectElement) throws ProcessException {
InjectXModule injectXModule = injectElement.getAnnotation(InjectXModule.class);
// 检验InjectXModule注解
if (injectXModule == null) {
throw new ProcessException(
String.format("当前的element(%s)未携带%s注解",
injectElement.toString(),
InjectXModule.class.getSimpleName()));
} else if (injectXModule.name() == null || injectXModule.name().isEmpty()) {
throw new ProcessException(String.format("%s的组件名不能为空", injectElement.toString()));
}
// 检验被InjectXModule注解的是否为成员变量
if (injectElement.getKind() != ElementKind.FIELD) {
throw new ProcessException(
String.format("%s不是类成员变量,只有类才成员变量能使用%s",
injectElement.toString(),
InjectXModule.class.getSimpleName()));
}
}
private void generateCode(Map<String, List<Element>> targetInjectElements) throws ProcessException {
if (targetInjectElements == null || targetInjectElements.isEmpty()) {
return;
}
for (Map.Entry<String, List<Element>> entry : targetInjectElements.entrySet()) {
String targetFullClzName = entry.getKey();
List<Element> injectElements = entry.getValue();
if (injectElements == null || injectElements.isEmpty()) {
continue;
}
// 创建注入方法
TypeElement target = mElementUtils.getTypeElement(targetFullClzName);
ParameterSpec injectParameter = ParameterSpec.builder(ClassName.get(target), Constants.PARAMETER_OF_TARGET).build();
MethodSpec.Builder injectMethod = MethodSpec.methodBuilder(Constants.METHOD_OF_INJECT)
.addJavadoc("向{@code $N}注入组件\n@param $N",
Constants.PARAMETER_OF_TARGET,
Constants.PARAMETER_OF_TARGET)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(injectParameter)
.returns(void.class);
for (Element injectElement : injectElements) {
injectMethod
.beginControlFlow("try")
.addStatement("$N.$N = ($T) $T.getInstance().getModule($S)",
Constants.PARAMETER_OF_TARGET,
injectElement.getSimpleName(),
injectElement.asType(),
mElementUtils.getTypeElement(Constants.XMODULABLE),
injectElement.getAnnotation(InjectXModule.class).name())
.nextControlFlow("catch ($T e)",
ClassName.get(mElementUtils.getTypeElement(Constants.UNKNOWN_MODULE_EXCEPTION)))
.addStatement("e.printStackTrace()")
.endControlFlow();
}
mLogger.info(String.format("创建方法:%s", Constants.METHOD_OF_INJECT));
// 创建类
String injectorClzName = new StringBuilder()
.append(target.getSimpleName())
.append(Constants.SEPARATOR_OF_CLASS_NAME)
.append(Constants.CLASS_OF_INJECTOR)
.toString();
TypeSpec.Builder targetInjector = TypeSpec.classBuilder(injectorClzName)
.addJavadoc(
new StringBuilder()
.append("组件注入器")
.append("\n")
.append("<ul><li>")
.append(Constants.WARNING_TIPS)
.append("</li></ul>")
.append("\n@author $N")
.toString(),
InjectProcessor.class.getSimpleName())
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(injectMethod.build());
mLogger.info(String.format("创建类:%s", injectorClzName));
// 输出源文件
try {
String pkgName = mElementUtils.getPackageOf(injectElements.get(0)).getQualifiedName().toString();
JavaFile.builder(pkgName, targetInjector.build())
.build()
.writeTo(mFiler);
mLogger.info(String.format("输出源文件:%s", pkgName + "." + injectorClzName + ".java"));
} catch (IOException e) {
throw new ProcessException(e.fillInStackTrace());
}
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/processor/XModuleProcessor.java | XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/processor/XModuleProcessor.java | package com.xpleemoon.xmodulable.compiler.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.xpleemoon.xmodulable.annotation.XModule;
import com.xpleemoon.xmodulable.compiler.Constants;
import com.xpleemoon.xmodulable.compiler.exception.ProcessException;
import com.xpleemoon.xmodulable.compiler.utils.Logger;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
/**
* 组件注解处理器
*
* @author xpleemoon
*/
@AutoService(Processor.class)
@SupportedOptions(Constants.KEY_XMODULE)
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@SupportedAnnotationTypes(Constants.ANNOTATION_TYPE_XMODULE)
public class XModuleProcessor extends AbstractProcessor {
/**
* 可用于编译时,信息打印
*/
private Logger mLogger;
/**
* 用于{@link Element}处理的工具类
*/
private Elements mElementUtils;
/**
* 用于文件创建
*/
private Filer mFiler;
/**
* 组件模块名
*/
private String mModuleName;
private TypeElement mXModuleLoader;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
mLogger = new Logger(processingEnvironment.getMessager());
mElementUtils = processingEnvironment.getElementUtils();
mFiler = processingEnvironment.getFiler();
Map<String, String> options = processingEnvironment.getOptions();
if (options != null && !options.isEmpty()) {
mModuleName = options.get(Constants.KEY_XMODULE);
}
if (mModuleName != null && !mModuleName.isEmpty()) {
mModuleName = mModuleName.replaceAll("[^0-9a-zA-Z_]+", "");
mLogger.info("The user has configuration the XModule, it was [" + mModuleName + "]");
} else {
mLogger.error("These no XModule, at 'build.gradle', like :\n" +
"javaCompileOptions {\n" +
" annotationProcessorOptions {\n" +
" arguments = [\n" +
" XModule : moduleName\n" +
" ]\n" +
" }\n" +
" }");
throw new RuntimeException(Constants.PREFIX_OF_LOGGER + "No XModule, for more information, look at gradle log.");
}
mXModuleLoader = mElementUtils.getTypeElement(Constants.XMODULE_LOADER);
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (set != null && !set.isEmpty()) {
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(XModule.class);
if (elements == null || elements.size() <= 0) {
return true;
}
mLogger.info(String.format("解析注解:%s", XModule.class.getSimpleName()));
try {
// key:组件名;value:携带@XModule的Element
Map<String, Element> moduleElements = new LinkedHashMap<>();
// 扫描注解@XModule
for (Element module : elements) {
verify(module);
moduleElements.put(module.getAnnotation(XModule.class).name(), module);
}
// 生成代码
generateCode(moduleElements);
} catch (ProcessException e) {
mLogger.error(e.fillInStackTrace());
}
return true;
}
return false;
}
/**
* 校验{@code moduleElement}的合法性
*
* @param moduleElement 携带@XModule的Element
* @throws ProcessException
*/
private void verify(Element moduleElement) throws ProcessException {
XModule XModule = moduleElement.getAnnotation(XModule.class);
// 检验XModule注解
if (XModule == null) {
throw new ProcessException(
String.format("当前的element(%s)未携带%s注解",
moduleElement.toString(),
XModule.class.getSimpleName()));
} else if (XModule.name() == null || XModule.name().isEmpty()) {
throw new ProcessException(String.format("%s的组件名不能为空", moduleElement.toString()));
}
// 检验被XModule注解的是否为class
if (moduleElement.getKind() != ElementKind.CLASS) {
throw new ProcessException(
String.format("%s不是类,只有类才能使用%s",
moduleElement.toString(),
XModule.class.getSimpleName()));
}
TypeElement classElement = (TypeElement) moduleElement;
// 检验类修饰符
Set<Modifier> modifiers = classElement.getModifiers();
if (!modifiers.contains(Modifier.PUBLIC)) {
throw new ProcessException(
String.format("被%s注解的%s的权限修饰符必须为public",
XModule.class.getSimpleName(),
classElement.getQualifiedName().toString()));
}
if (modifiers.contains(Modifier.ABSTRACT)) {
throw new ProcessException(
String.format("%s是抽象类,不能被%s注解",
classElement.getQualifiedName().toString(),
XModule.class.getSimpleName()));
}
}
/**
* 生成源码,主要由三个步骤
* <ol>
* <li>创建方法</li>
* <li>创建类</li>
* <li>输出源文件</li>
* </ol>
*
* @param moduleElements key:组件名;value:携带@XModule的Element
*/
private void generateCode(Map<String, Element> moduleElements) throws ProcessException {
if (moduleElements == null || moduleElements.isEmpty()) {
return;
}
/*
1、创建方法
public void loadInto(XModulableOptions options) {
if (options == null) {
return;
}
options.addModule(, );
}
*/
MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(Constants.METHOD_OF_LOAD_INTO)
.addJavadoc("向$N添加组件", Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.addParameter(ClassName.get(mElementUtils.getTypeElement(Constants.XMODULABLE_OPTIONS)), Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
.returns(void.class)
.beginControlFlow("if ($N == null)", Constants.PARAMETER_OF_XMODULABLE_OPTIONS)
.addStatement("return")
.endControlFlow();
for (Map.Entry<String, Element> entry : moduleElements.entrySet()) {
String moduleName = entry.getKey();
TypeName moduleTypeName = TypeName.get(entry.getValue().asType()); // 注解的宿主类型名
loadIntoMethod.addStatement("$N.addModule($S, new $T())", Constants.PARAMETER_OF_XMODULABLE_OPTIONS, moduleName, moduleTypeName);
}
mLogger.info(String.format("创建方法:%s", Constants.METHOD_OF_LOAD_INTO));
/*
2、创建类
public final class XModule$$Loader$$组件名 implements XModuleLoader
*/
String className = new StringBuilder()
.append(Constants.SDK_NAME)
.append(Constants.SEPARATOR_OF_CLASS_NAME)
.append(Constants.CLASS_OF_LOADER)
.append(Constants.SEPARATOR_OF_CLASS_NAME)
.append(mModuleName)
.toString();
TypeSpec.Builder componentLoader = TypeSpec.classBuilder(className)
.addJavadoc(
new StringBuilder()
.append("$N组件加载器")
.append("\n")
.append("<ul><li>")
.append(Constants.WARNING_TIPS)
.append("</li></ul>")
.append("\n@author $N")
.toString(),
mModuleName,
XModuleProcessor.class.getSimpleName())
.addSuperinterface(ClassName.get(mXModuleLoader))
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(loadIntoMethod.build());
mLogger.info(String.format("创建类:%s", className));
/*
3、输出源文件
XModule$$Loader$$组件名.java
*/
try {
JavaFile.builder(Constants.PACKAGE_OF_GENERATE, componentLoader.build())
.build().writeTo(mFiler);
mLogger.info(String.format("输出源文件:%s", Constants.PACKAGE_OF_GENERATE + "." + className + ".java"));
} catch (IOException e) {
throw new ProcessException(e.fillInStackTrace());
}
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/exception/ProcessException.java | XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/exception/ProcessException.java | package com.xpleemoon.xmodulable.compiler.exception;
public class ProcessException extends Exception {
public ProcessException(String msg) {
super(msg);
}
public ProcessException(Throwable throwable) {
super(throwable);
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
xpleemoon/XModulable | https://github.com/xpleemoon/XModulable/blob/4c4ffefae9cfe065bdce86baedca3b189676c2f6/XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/utils/Logger.java | XModulable-compiler/src/main/java/com/xpleemoon/xmodulable/compiler/utils/Logger.java | package com.xpleemoon.xmodulable.compiler.utils;
import com.xpleemoon.xmodulable.compiler.Constants;
import javax.annotation.processing.Messager;
import javax.tools.Diagnostic;
/**
* Simplify the messager.
*
* @author Alex <a href="mailto:zhilong.liu@aliyun.com">Contact me.</a>
* @version 1.0
* @since 16/8/22 上午11:48
*/
public class Logger {
private final Messager msg;
public Logger(Messager messager) {
this.msg = messager;
}
public void info(CharSequence info) {
msg.printMessage(Diagnostic.Kind.NOTE, Constants.PREFIX_OF_LOGGER + info);
}
public void error(CharSequence error) {
msg.printMessage(Diagnostic.Kind.ERROR, Constants.PREFIX_OF_LOGGER + "An exception is encountered, [" + error + "]");
}
public void error(Throwable error) {
msg.printMessage(Diagnostic.Kind.ERROR, Constants.PREFIX_OF_LOGGER + "An exception is encountered, [" + error.getMessage() + "]" + "\n" + formatStackTrace(error.getStackTrace()));
}
public void warning(CharSequence warning) {
msg.printMessage(Diagnostic.Kind.WARNING, Constants.PREFIX_OF_LOGGER + warning);
}
private String formatStackTrace(StackTraceElement[] stackTrace) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : stackTrace) {
sb.append(" at ").append(element.toString());
sb.append("\n");
}
return sb.toString();
}
}
| java | Apache-2.0 | 4c4ffefae9cfe065bdce86baedca3b189676c2f6 | 2026-01-05T02:40:24.584665Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/test/java/cn/bixin/sona/gateway/SonaGatewayApplicationTests.java | sona-gateway/src/test/java/cn/bixin/sona/gateway/SonaGatewayApplicationTests.java | package cn.bixin.sona.gateway;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SonaGatewayApplicationTests {
@Test
void contextLoads() {
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/SonaGatewayApplication.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/SonaGatewayApplication.java | package cn.bixin.sona.gateway;
import cn.bixin.sona.gateway.cat.MercuryStatCollector;
import cn.bixin.sona.gateway.netty.NettyServer;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.dianping.cat.status.StatusExtensionRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.Resource;
/**
* @author qinwei
*/
@Slf4j
@EnableApolloConfig
@EnableScheduling
@SpringBootApplication(scanBasePackages = "cn.bixin.*")
public class SonaGatewayApplication implements CommandLineRunner {
public static final long SERVER_START_TIME = System.currentTimeMillis();
@Resource
private NettyServer nettyServer;
public static void main(String[] args) {
SpringApplication.run(SonaGatewayApplication.class, args);
StatusExtensionRegister.getInstance().register(new MercuryStatCollector());
log.info("SonaGatewayApplication start ...");
}
@Override
public void run(String... args) throws Exception {
nettyServer.start();
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/util/ExecuteFunction.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/util/ExecuteFunction.java | package cn.bixin.sona.gateway.util;
/**
* @author qinwei
*/
@FunctionalInterface
public interface ExecuteFunction {
void execute() throws Exception;
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/util/NetUtil.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/util/NetUtil.java | package cn.bixin.sona.gateway.util;
import com.google.common.net.InetAddresses;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.net.*;
import java.util.Enumeration;
/**
* @author qinwei
*/
@Slf4j
public final class NetUtil {
public static final String LOCAL_IP_ADDR = getLocalIpAddress().trim();
private NetUtil() {
}
public static String getLocalIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
} catch (Exception e) {
log.error("IP地址获取失败 {}", e.toString());
}
return "";
}
public static String getIpAddr(SocketAddress socketAddress) {
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress addr = (InetSocketAddress) socketAddress;
return addr.getAddress().getHostAddress();
}
return "UNKNOWN";
}
public static int getPort(SocketAddress socketAddress) {
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress addr = (InetSocketAddress) socketAddress;
return addr.getPort();
}
return -1;
}
public static InetSocketAddress getWsRemoteAddrFromHeader(HttpHeaders requestHeaders, Channel ch) {
InetSocketAddress remoteAddr = (InetSocketAddress) ch.remoteAddress();
try {
String ipForwarded = requestHeaders.get("X-Forwarded-For");
if (StringUtils.isNotBlank(ipForwarded)) {
String[] ipArr = ipForwarded.split(",");
String ip = ipArr[0];
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
remoteAddr = new InetSocketAddress(InetAddresses.forString(ip.trim()), remoteAddr.getPort());
}
} catch (Throwable e) {
log.error("getWsRemoteAddrFromHeader error! requestHeaders={}", requestHeaders, e);
}
return remoteAddr;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/util/EventRecordLog.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/util/EventRecordLog.java | package cn.bixin.sona.gateway.util;
import cn.bixin.sona.common.spring.SpringApplicationContext;
import cn.bixin.sona.gateway.channel.NettyChannel;
import cn.bixin.sona.gateway.channel.support.ChannelAttrs;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.Header;
import cn.bixin.sona.gateway.concurrent.counter.SystemClock;
import cn.bixin.sona.gateway.mq.KafkaSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author qinwei
*/
@Slf4j
public class EventRecordLog {
private static final String TOPIC_MERCURY_EVENT_LOG = "TOPIC-MERCURY_EVENT_LOG";
public static void logEvent(NettyChannel channel, String event, String desc) {
logEvent(channel, event, null, desc);
}
public static void logEvent(NettyChannel channel, String event, AccessMessage message, String desc) {
Map<String, Object> map = new HashMap<>(16);
ChannelAttrs attrs = channel.getAttrs();
map.put("uid", channel.getUid());
map.put("server", NetUtil.LOCAL_IP_ADDR);
map.put("addr", channel.getRemoteAddress().toString());
map.put("type", attrs.getChannelType());
map.put("device", attrs.getDeviceId());
map.put("event", event);
map.put("content", desc);
if (message != null) {
map.put("cmd", message.getCmd());
List<Header> headers = message.getHeaders();
if (!CollectionUtils.isEmpty(headers)) {
map.put("header", headers.toString());
}
}
map.put("sendTime", SystemClock.currentTimeMillis());
// log.info("mercury_event : {}", JSON.toJSONString(map));
SpringApplicationContext.getBean(KafkaSender.class).send(TOPIC_MERCURY_EVENT_LOG, map);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/util/AccessMessageUtils.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/util/AccessMessageUtils.java | package cn.bixin.sona.gateway.util;
import cn.bixin.sona.gateway.cat.MonitorUtils;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.Header;
import cn.bixin.sona.gateway.common.HeaderEnum;
import cn.bixin.sona.gateway.common.Varint;
import org.springframework.util.CollectionUtils;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
/**
* @author qinwei
*/
public final class AccessMessageUtils {
private AccessMessageUtils() {
}
public static AccessMessage createRequest(int cmd, byte[] body) {
return createRequest(cmd, 0, body);
}
public static AccessMessage createRequest(int cmd, int id, byte[] body) {
return createRequest(cmd, id, false, body);
}
public static AccessMessage createRequest(int cmd, int id, boolean twoWay, byte[] body) {
AccessMessage request = new AccessMessage();
request.setReq(true);
request.setTwoWay(twoWay);
request.setId(id);
request.setCmd(cmd);
request.setBody(body);
return request;
}
public static AccessMessage createResponse(int id, int cmd, byte[] body) {
AccessMessage response = new AccessMessage();
response.setId(id);
response.setCmd(cmd);
response.setBody(body);
return response;
}
public static AccessMessage createHeartResponse(int id) {
AccessMessage response = new AccessMessage();
response.setHeartbeat(true);
response.setId(id);
return response;
}
public static AccessMessage createHeartRequest(int id) {
AccessMessage request = new AccessMessage();
request.setReq(true);
request.setTwoWay(true);
request.setHeartbeat(true);
request.setId(id);
return request;
}
public static String extractHeaderData(AccessMessage message, HeaderEnum header) {
return extractHeaderData(message, header.getType());
}
public static String extractHeaderData(AccessMessage message, int headerType) {
List<Header> headers = message.getHeaders();
if (CollectionUtils.isEmpty(headers)) {
return null;
}
return headers.stream().filter(header -> header.getType() == headerType).findFirst().map(header -> new String(header.getData(), StandardCharsets.UTF_8)).orElse(null);
}
public static void logInboundMsgSize(AccessMessage message, String cmd) {
logMsgSize(message, cmd, MonitorUtils.CAT_METRIC_IN_SIZE);
}
public static void logOutboundMsgSize(AccessMessage message) {
logMsgSize(message, message.isHeartbeat() ? "HB" : String.valueOf(message.getCmd()), MonitorUtils.CAT_METRIC_OUT_SIZE);
}
public static void logMsgSize(AccessMessage message, String cmd, String type) {
MonitorUtils.logMetricForCount(type, calcMsgSize(message), Collections.singletonMap("cmd", cmd));
}
public static int calcMsgSize(AccessMessage message) {
int size = 4 + Varint.computeRawVarint32Size(message.getId());
if (!message.isHeartbeat()) {
int length = message.getLength();
if (length <= 0) {
List<Header> headers = message.getHeaders();
int headerCount = headers == null ? 0 : headers.size();
int headerLength = 0;
for (int i = 0; i < headerCount; i++) {
headerLength += headers.get(i).calcTotalLength();
}
int bodyLength = message.getBody() == null ? 0 : message.getBody().length;
length = headerLength + bodyLength;
}
size += 1 + Varint.computeRawVarint32Size(length) + length;
}
return size;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/util/Constants.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/util/Constants.java | package cn.bixin.sona.gateway.util;
/**
* @author qinwei
*/
public class Constants {
public static final String MQ_SEND_KEY_CMD = "cmd";
public static final String MQ_REPORT_KEY_TYPE = "t";
public static final String MQ_REPORT_VAL_TYPE_CONNECT = "connect";
public static final String MQ_REPORT_VAL_TYPE_ROOM = "room";
public static final String MQ_REPORT_KEY_DEVICE_ID = "deviceId";
public static final String MQ_REPORT_KEY_CLIENT_IP = "clientIp";
public static final String MQ_REPORT_KEY_SESSION = "session";
public static final String MQ_REPORT_KEY_CHANNEL_ID = "channelId";
public static final String MQ_REPORT_KEY_SERVER_ID = "serverId";
public static final String MQ_REPORT_KEY_START_TIME = "startTime";
public static final String MQ_REPORT_KEY_TIMESTAMP_SHORT = "tm";
public static final String MQ_REPORT_KEY_AUTH_CONN = "authConn";
public static final String MQ_REPORT_KEY_UNAUTH_CONN = "unAuthConn";
public static final String MQ_REPORT_KEY_UID = "uid";
public static final String MQ_REPORT_KEY_ROOM = "room";
public static final String MQ_REPORT_KEY_ROOMS = "rooms";
public static final String MQ_REPORT_KEY_GLOBAL = "global";
public static final String MQ_REPORT_KEY_GROUP = "group";
public static final String MQ_REPORT_KEY_CMD = "cmd";
public static final String MQ_REPORT_KEY_DATA = "data";
public static final String MQ_REPORT_KEY_MEMBERS = "members";
public static final String MQ_REPORT_KEY_PRIORITY = "highPriority";
public static final String MQ_REPORT_KEY_ACK_UIDS = "ackUids";
public static final int SESSION_ONLINE = 1;
public static final int SESSION_OFFLINE = 0;
public static final String PUSH_MSG_KEY_TYPE = "type";
public static final String PUSH_MSG_KEY_DATA = "data";
public static final String PUSH_MSG_TYPE_APPSTATE = "appstate";
public static final String APPSTATE_KEY_FOREGROUND = "foreground";
public static final String CHATROOM_MSG_KEY_ROOM = "room";
public static final String CHATROOM_MSG_KEY_ACK = "ack";
public static final String CHATROOM_MSG_KEY_SIGNAL = "signal";
public static final String CHATROOM_MSG_KEY_UID = "uid";
public static final String CHATROOM_MSG_KEY_IDENTITY = "identity";
public static final int PROTOCOL_META_LEN = 5;
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/mq/KafkaSender.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/mq/KafkaSender.java | package cn.bixin.sona.gateway.mq;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
/**
* @author qinwei
*/
@Component
@Slf4j
public class KafkaSender {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void send(String topic, String key, Object object) {
String json = JSON.toJSONString(object);
kafkaTemplate.send(topic, key, json)
.addCallback(o -> {
}, throwable -> log.error("kafka消息发送失败: topic = {}, key = {} , json = {}", topic, key, json));
}
public void send(String topic, Object object) {
send(topic, null, object);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/mq/RocketSender.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/mq/RocketSender.java | package cn.bixin.sona.gateway.mq;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
/**
* @author qinwei
*/
@Service
@Slf4j
public class RocketSender {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public SendResult syncSend(String topic, String content) {
return syncSend(topic, null, content);
}
public SendResult syncSend(String topic, String tag, String content) {
return syncSend(topic, tag, null, content);
}
public SendResult syncSend(String topic, String tag, String hashKey, String content) {
String destination = tag == null ? topic : topic + ':' + tag;
Transaction t = Cat.newTransaction("RocketMQ", destination);
try {
MessageBuilder<?> builder = MessageBuilder.withPayload(content);
if (hashKey == null) {
return rocketMQTemplate.syncSendOrderly(destination, builder.build(), hashKey);
} else {
return rocketMQTemplate.syncSend(destination, builder.build());
}
} catch (Exception e) {
log.error("send rocketmq failure, destination : {}, content:{}", destination, content, e);
t.setStatus(e);
} finally {
t.complete();
}
return null;
}
public void asyncSend(String topic, String content) {
asyncSend(topic, content, null);
}
public void asyncSend(String topic, String content, SendCallback callback) {
Transaction t = Cat.newTransaction("RocketMQ", topic);
try {
MessageBuilder<?> builder = MessageBuilder.withPayload(content);
rocketMQTemplate.asyncSend(topic, builder.build(), new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
if (callback != null) {
callback.onSuccess(sendResult);
}
}
@Override
public void onException(Throwable e) {
log.error("send rocketmq failure, topic : {}, content:{}", topic, content, e);
if (callback != null) {
callback.onException(e);
}
}
});
} catch (Exception e) {
t.setStatus(e);
} finally {
t.complete();
}
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/service/SocketNotifyService.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/service/SocketNotifyService.java | package cn.bixin.sona.gateway.service;
import cn.bixin.sona.gateway.SonaGatewayApplication;
import cn.bixin.sona.gateway.channel.NettyChannel;
import cn.bixin.sona.gateway.channel.support.ChannelAttrs;
import cn.bixin.sona.gateway.common.ChannelTypeEnum;
import cn.bixin.sona.gateway.mq.RocketSender;
import cn.bixin.sona.gateway.util.Constants;
import cn.bixin.sona.gateway.util.NetUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
/**
* @author qinwei
*/
@Service
public class SocketNotifyService {
private static final String TOPIC_SOCKET_ROOM_SESSION = "TOPIC_SOCKET_ROOM_SESSION";
private static final String TOPIC_ROOM_MESSAGE = "TOPIC_ROOM_MESSAGE";
private static final String TOPIC_SERVER_STATS = "TOPIC_SERVER_STATS";
@Resource
private RocketSender rocketSender;
public SendResult processConnect(NettyChannel channel) {
ChannelAttrs attrs = channel.getAttrs();
if (ChannelTypeEnum.CHATROOM.getType() != attrs.getChannelType()) {
return null;
}
JSONObject jsonParam = new JSONObject();
jsonParam.put(Constants.MQ_REPORT_KEY_TYPE, Constants.MQ_REPORT_VAL_TYPE_CONNECT);
jsonParam.put(Constants.MQ_REPORT_KEY_CHANNEL_ID, attrs.getChannelId());
jsonParam.put(Constants.MQ_REPORT_KEY_TIMESTAMP_SHORT, System.currentTimeMillis());
jsonParam.put(Constants.MQ_REPORT_KEY_DEVICE_ID, attrs.getDeviceId());
jsonParam.put(Constants.MQ_REPORT_KEY_UID, attrs.getUid());
jsonParam.put(Constants.MQ_REPORT_KEY_SESSION, Constants.SESSION_ONLINE);
return rocketSender.syncSend(TOPIC_SOCKET_ROOM_SESSION, null, attrs.getChannelId(), jsonParam.toJSONString());
}
public SendResult processDisConnect(NettyChannel channel) {
ChannelAttrs attrs = channel.getAttrs();
if (ChannelTypeEnum.CHATROOM.getType() != attrs.getChannelType()) {
return null;
}
String uid = attrs.getUid();
JSONObject jsonParam = new JSONObject();
jsonParam.put(Constants.MQ_REPORT_KEY_TYPE, Constants.MQ_REPORT_VAL_TYPE_CONNECT);
jsonParam.put(Constants.MQ_REPORT_KEY_CHANNEL_ID, attrs.getChannelId());
jsonParam.put(Constants.MQ_REPORT_KEY_TIMESTAMP_SHORT, System.currentTimeMillis());
jsonParam.put(Constants.MQ_REPORT_KEY_SESSION, Constants.SESSION_OFFLINE);
jsonParam.put(Constants.MQ_REPORT_KEY_UID, uid);
String hashKey = StringUtils.hasText(uid) ? uid : attrs.getChannelId();
return rocketSender.syncSend(TOPIC_SOCKET_ROOM_SESSION, null, hashKey, jsonParam.toJSONString());
}
public SendResult notifyChatRoomSession(NettyChannel channel, int cmd, String room, String uid) {
ChannelAttrs attrs = channel.getAttrs();
JSONObject jsonParam = new JSONObject();
jsonParam.put(Constants.MQ_REPORT_KEY_TYPE, Constants.MQ_REPORT_VAL_TYPE_ROOM);
jsonParam.put(Constants.MQ_REPORT_KEY_CHANNEL_ID, attrs.getChannelId());
jsonParam.put(Constants.MQ_REPORT_KEY_TIMESTAMP_SHORT, System.currentTimeMillis());
jsonParam.put(Constants.MQ_REPORT_KEY_ROOM, room);
jsonParam.put(Constants.MQ_REPORT_KEY_UID, ObjectUtils.defaultIfNull(uid, attrs.getUid()));
jsonParam.put(Constants.MQ_REPORT_KEY_CMD, cmd);
return rocketSender.syncSend(TOPIC_SOCKET_ROOM_SESSION, null, uid, jsonParam.toJSONString());
}
public void notifyChatRoomMessage(NettyChannel channel, String uid, String room, String body) {
ChannelAttrs attrs = channel.getAttrs();
JSONObject jsonParam = new JSONObject();
jsonParam.put(Constants.MQ_REPORT_KEY_UID, uid);
jsonParam.put(Constants.MQ_REPORT_KEY_DEVICE_ID, attrs.getDeviceId());
jsonParam.put(Constants.MQ_REPORT_KEY_CLIENT_IP, NetUtil.getIpAddr(channel.getRemoteAddress()));
jsonParam.put(Constants.MQ_REPORT_KEY_ROOM, room);
jsonParam.put(Constants.MQ_REPORT_KEY_DATA, body);
rocketSender.asyncSend(TOPIC_ROOM_MESSAGE, jsonParam.toJSONString());
}
@Scheduled(fixedRate = 5000)
public void reportServerStats() {
String serverId = NetUtil.LOCAL_IP_ADDR;
JSONObject jsonParam = new JSONObject();
jsonParam.put(Constants.MQ_REPORT_KEY_SERVER_ID, serverId);
jsonParam.put(Constants.MQ_REPORT_KEY_START_TIME, SonaGatewayApplication.SERVER_START_TIME);
jsonParam.put(Constants.MQ_REPORT_KEY_TIMESTAMP_SHORT, System.currentTimeMillis());
jsonParam.put(Constants.MQ_REPORT_KEY_AUTH_CONN, NettyChannel.authChannelCount());
jsonParam.put(Constants.MQ_REPORT_KEY_UNAUTH_CONN, NettyChannel.unAuthChannelCount());
rocketSender.syncSend(TOPIC_SERVER_STATS, null, serverId, jsonParam.toJSONString());
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyFactory.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyFactory.java | package cn.bixin.sona.gateway.netty;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.internal.SystemPropertyUtil;
import net.openhft.affinity.AffinityStrategies;
import net.openhft.affinity.AffinityThreadFactory;
import java.util.concurrent.ThreadFactory;
/**
* @author qinwei
*/
public class NettyFactory {
public static EventLoopGroup eventLoopGroup(int threads, String threadName) {
ThreadFactory threadFactory = new AffinityThreadFactory(threadName, AffinityStrategies.DIFFERENT_CORE);
return supportEpoll() ? new EpollEventLoopGroup(threads, threadFactory) : new NioEventLoopGroup(threads, threadFactory);
}
public static Class<? extends SocketChannel> socketChannelClass() {
return supportEpoll() ? EpollSocketChannel.class : NioSocketChannel.class;
}
public static Class<? extends ServerSocketChannel> serverSocketChannelClass() {
return supportEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class;
}
private static boolean supportEpoll() {
return SystemPropertyUtil.get("os.name").toLowerCase().contains("linux") && Epoll.isAvailable();
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServer.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServer.java | package cn.bixin.sona.gateway.netty;
import cn.bixin.sona.gateway.cat.MonitorUtils;
import cn.bixin.sona.gateway.channel.NettyChannel;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.CommandEnum;
import cn.bixin.sona.gateway.config.ApolloConfiguration;
import cn.bixin.sona.gateway.util.AccessMessageUtils;
import com.google.common.util.concurrent.RateLimiter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author qinwei
*/
@Component
@Slf4j
public class NettyServer implements ApplicationListener<ContextClosedEvent> {
public static final Integer PORT = 2180;
public static final Integer PORT_WS = 2190;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private Channel channel;
private Channel channelWs;
@Resource
private ApolloConfiguration apolloConfiguration;
/**
* 启动netty服务
*/
public ChannelFuture start() {
ChannelFuture cf = null;
ChannelFuture cfWs = null;
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bossGroup = NettyFactory.eventLoopGroup(1, "bossLoopGroup");
workerGroup = NettyFactory.eventLoopGroup(4, "workerLoopGroup");
bootstrap.group(bossGroup, workerGroup)
.channel(NettyFactory.serverSocketChannelClass())
.option(ChannelOption.SO_BACKLOG, 2048)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(64 * 1024, 128 * 1024))
.childHandler(new NettyServerInitializer());
cf = bootstrap.bind(PORT).sync();
channel = cf.channel();
cfWs = bootstrap.bind(PORT_WS).sync();
channelWs = cfWs.channel();
} catch (Exception e) {
log.error("Netty server start fail", e);
} finally {
if (cf != null && cf.isSuccess() && cfWs != null && cfWs.isSuccess()) {
log.info("Netty server listening ready for connections...");
} else {
log.error("Netty server start up error!");
}
}
printNettyConfig();
return cf;
}
private static void printNettyConfig() {
log.info("Runtime.getRuntime().availableProcessors() : {}", Runtime.getRuntime().availableProcessors());
log.info("-Dio.netty.allocator.numHeapArenas: {}", PooledByteBufAllocator.defaultNumHeapArena());
log.info("-Dio.netty.allocator.numDirectArenas: {}", PooledByteBufAllocator.defaultNumDirectArena());
log.info("-Dio.netty.allocator.pageSize: {}", PooledByteBufAllocator.defaultPageSize());
log.info("-Dio.netty.allocator.maxOrder: {}", PooledByteBufAllocator.defaultMaxOrder());
log.info("-Dio.netty.allocator.chunkSize: {}", PooledByteBufAllocator.defaultPageSize() << PooledByteBufAllocator.defaultMaxOrder());
log.info("-Dio.netty.allocator.tinyCacheSize: {}", PooledByteBufAllocator.defaultTinyCacheSize());
log.info("-Dio.netty.allocator.smallCacheSize: {}", PooledByteBufAllocator.defaultSmallCacheSize());
log.info("-Dio.netty.allocator.normalCacheSize: {}", PooledByteBufAllocator.defaultNormalCacheSize());
log.info("-Dio.netty.allocator.useCacheForAllThreads: {}", PooledByteBufAllocator.defaultUseCacheForAllThreads());
}
/**
* 停止netty服务
*/
@Override
public void onApplicationEvent(ContextClosedEvent event) {
log.info("Shutdown Netty Server... ");
//关闭 server channel
closeServerChannel();
// server发送close消息,让client主动断开连接
sendReconnectMsg();
//还是不断开的连接,就让server主动断开
forceCloseChannel();
//等待channel被清空
waitClose();
//优雅关闭
shutdown();
log.info("Shutdown Netty Server Success!");
}
private void shutdown() {
try {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
} catch (Throwable e) {
log.error("EventLoopGroup.shutdownGracefully() failed", e);
}
}
private void waitClose() {
long startTime = System.currentTimeMillis();
try {
while (NettyChannel.authChannelCount() > 0) {
Thread.sleep(250L);
if (System.currentTimeMillis() - startTime >= 3000L) {
log.info("wait channel close remainingSize={}, elapsedTime={} seconds, wait no more, just shut down!", NettyChannel.authChannelCount(), (System.currentTimeMillis() - startTime) / 1000.0);
break;
}
}
} catch (Throwable e) {
log.error("wait channel close failed!", e);
}
}
private void forceCloseChannel() {
long startTime = System.currentTimeMillis();
try {
Collection<NettyChannel> channels = NettyChannel.getAllChannels();
RateLimiter rateLimiter = RateLimiter.create(Math.max(apolloConfiguration.getCloseMsgThrottling(), 1));
for (NettyChannel channel : channels) {
if (channel.isAuth()) {
rateLimiter.acquire();
channel.close();
}
}
log.info("server-side close all remaining channels, elapsedTime={} seconds", (System.currentTimeMillis() - startTime) / 1000.0);
} catch (Throwable e) {
log.error("server-side close channels failed!", e);
}
}
private void sendReconnectMsg() {
try {
long startTime = System.currentTimeMillis();
int maxProcessSeconds = Math.max(apolloConfiguration.getCloseMsgMaxWaitSeconds(), 1);
long deadline = startTime + 1000L * maxProcessSeconds;
RateLimiter rateLimiter = RateLimiter.create(Math.max(apolloConfiguration.getCloseMsgThrottling(), 1));
Collection<NettyChannel> channels = NettyChannel.getAllChannels();
if (CollectionUtils.isEmpty(channels)) {
return;
}
AccessMessage message = AccessMessageUtils.createRequest(CommandEnum.CLOSE_CHANNEL.getCommand(), null);
for (NettyChannel ch : channels) {
if (!ch.isAuth()) {
continue;
}
rateLimiter.acquire();
ch.send(message);
if (System.currentTimeMillis() >= deadline) {
log.info("send close message remainingSize={}, elapsedTime={} seconds, wait no more, just kill them!", channels.size(), (System.currentTimeMillis() - startTime) / 1000.0);
break;
}
}
log.info("send close message remainingSize={}, elapsedTime={} seconds", channels.size(), (System.currentTimeMillis() - startTime) / 1000.0);
Thread.sleep(2000L);
} catch (Throwable e) {
log.error("send close message failed !", e);
}
}
private void closeServerChannel() {
try {
if (channel != null) {
channel.close();
}
if (channelWs != null) {
channelWs.close();
}
} catch (Throwable e) {
log.error("server channel close failed !", e);
}
}
@Scheduled(cron = "0 0 7 * * *")
public void closeLongLastingChannels() {
int longLastingCloseHours = apolloConfiguration.getLongLastingCloseHours();
if (longLastingCloseHours <= 0) {
return;
}
long longLastingCloseMs = 1000L * 60 * 60 * longLastingCloseHours;
long startTime = System.currentTimeMillis();
try {
Collection<NettyChannel> channels = NettyChannel.getAllChannels();
List<NettyChannel> longLastingChannels = new ArrayList<>();
for (NettyChannel ch : channels) {
if (!ch.isAuth()) {
continue;
}
long createTime = ch.getAttrs().getCreateTime();
if (System.currentTimeMillis() - createTime >= longLastingCloseMs) {
longLastingChannels.add(ch);
log.info("closeLongLastingChannels remoteAddress={}", ch.getRemoteAddress());
MonitorUtils.logEvent(MonitorUtils.CLOSE_LONG_LASTING_CHANNEL, MonitorUtils.CLOSE_LONG_LASTING_CHANNEL);
}
}
log.info("closeLongLastingChannels size={}", longLastingChannels.size());
if (!longLastingChannels.isEmpty()) {
AccessMessage message = AccessMessageUtils.createRequest(CommandEnum.CLOSE_CHANNEL.getCommand(), null);
for (NettyChannel ch : longLastingChannels) {
ch.send(message);
}
Thread.sleep(2000L);
for (NettyChannel ch : longLastingChannels) {
if (ch.isConnected()) {
ch.close();
}
}
}
log.info("closeLongLastingChannels complete, elapsedTime={}", System.currentTimeMillis() - startTime);
} catch (Exception e) {
log.error("closeLongLastingChannels failed ! ", e);
}
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServerHandler.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServerHandler.java | package cn.bixin.sona.gateway.netty;
import cn.bixin.sona.gateway.channel.support.ChannelAttrs;
import cn.bixin.sona.gateway.channel.NettyChannel;
import cn.bixin.sona.gateway.channel.handler.ChannelHandler;
import cn.bixin.sona.gateway.util.NetUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
/**
* @author qinwei
*/
@Slf4j
@io.netty.channel.ChannelHandler.Sharable
public class NettyServerHandler extends ChannelDuplexHandler {
private final ChannelHandler handler;
public NettyServerHandler(ChannelHandler handler) {
this.handler = handler;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
int serverPort = NetUtil.getPort(ctx.channel().localAddress());
if (serverPort == NettyServer.PORT) {
// 非websocket连接初始化
initChannel(ctx.channel(), null);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
try {
log.info("The connection of {} -> {} is disconnected, channelId={}", channel.getRemoteAddress(), channel.getLocalAddress(), channel.getChannelId());
handler.disconnect(channel);
} finally {
NettyChannel.removeChannel(ctx.channel());
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
handler.receive(channel, msg);
//对于 websocket 场景, 这里接收到的 msg 可能是 websocketframe, 它是属于 ReferenceCounted,
// 需要触发 TailContext 的 channelRead 去执行 ReferenceCountUtil.release(msg)
super.channelRead(ctx, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
super.write(ctx, msg, promise);
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
handler.send(channel, msg);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
WebSocketServerProtocolHandler.HandshakeComplete handshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
int serverPort = NetUtil.getPort(ctx.channel().localAddress());
if (serverPort == NettyServer.PORT_WS) {
// websocket连接初始化
InetSocketAddress remoteAddr = NetUtil.getWsRemoteAddrFromHeader(handshakeComplete.requestHeaders(), ctx.channel());
initChannel(ctx.channel(), remoteAddr);
}
}
super.userEventTriggered(ctx, evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
handler.caught(channel, cause);
}
private NettyChannel initChannel(Channel ch, InetSocketAddress remoteAddr) throws Exception {
if (remoteAddr == null) {
remoteAddr = (InetSocketAddress) ch.remoteAddress();
}
ChannelAttrs.init(ch, remoteAddr);
NettyChannel channel = NettyChannel.getOrAddChannel(ch);
log.info("The connection of {} -> {} is established, channelId={}", channel.getRemoteAddress(), channel.getLocalAddress(), channel.getChannelId());
handler.connect(channel);
return channel;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServerInitializer.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/NettyServerInitializer.java | package cn.bixin.sona.gateway.netty;
import cn.bixin.sona.gateway.channel.handler.ChannelHandlerWrap;
import cn.bixin.sona.gateway.channel.handler.MercuryServerHandler;
import cn.bixin.sona.gateway.netty.codec.ServerMessageDecoder;
import cn.bixin.sona.gateway.netty.codec.ServerMessageEncoder;
import cn.bixin.sona.gateway.netty.codec.ServerMessageWebSocketDecoder;
import cn.bixin.sona.gateway.netty.codec.ServerMessageWebSocketEncoder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
/**
* @author qinwei
*/
@Slf4j
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
private static final NettyServerHandler NETTY_SERVER_HANDLER = new NettyServerHandler(ChannelHandlerWrap.wrap(new MercuryServerHandler()));
private static final ServerMessageEncoder TCP_ENCODER = new ServerMessageEncoder();
private static final ServerMessageWebSocketEncoder WEBSOCKET_ENCODER = new ServerMessageWebSocketEncoder();
private static final ServerMessageWebSocketDecoder WEBSOCKET_DECODER = new ServerMessageWebSocketDecoder();
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
int serverPort = socketChannel.localAddress().getPort();
if (serverPort == NettyServer.PORT) {
pipeline.addLast("encoder", TCP_ENCODER);
pipeline.addLast("decoder", new ServerMessageDecoder());
} else if (serverPort == NettyServer.PORT_WS) {
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(2048));
pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast("encoder", WEBSOCKET_ENCODER);
pipeline.addLast("decoder", WEBSOCKET_DECODER);
}
pipeline.addLast("handler", NETTY_SERVER_HANDLER);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
log.error("exceptionCaught, remoteAddress=" + ctx.channel().remoteAddress(), cause);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageWebSocketDecoder.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageWebSocketDecoder.java | package cn.bixin.sona.gateway.netty.codec;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.MessageCodec;
import cn.bixin.sona.gateway.exception.AccessMessageDecodeException;
import cn.bixin.sona.gateway.util.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import java.util.List;
/**
* @author qinwei
*/
@ChannelHandler.Sharable
public class ServerMessageWebSocketDecoder extends MessageToMessageDecoder<WebSocketFrame> {
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {
if (msg instanceof BinaryWebSocketFrame) {
ByteBuf buf = msg.content();
if (buf == null) {
return;
}
int flag = buf.getByte(buf.readerIndex());
if (flag != 0 && flag != 1) {
throw new AccessMessageDecodeException("unknown flag, flag=" + buf.getByte(buf.readerIndex()));
}
if (buf.readableBytes() < Constants.PROTOCOL_META_LEN) {
throw new AccessMessageDecodeException("current ByteBuf length less than meta, len=" + buf.readableBytes());
}
AccessMessage message = MessageCodec.decode(buf);
out.add(message);
} else {
throw new AccessMessageDecodeException("unsupported frame type: " + msg.getClass().getName());
}
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageDecoder.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageDecoder.java | package cn.bixin.sona.gateway.netty.codec;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.MessageCodec;
import cn.bixin.sona.gateway.exception.AccessMessageDecodeException;
import cn.bixin.sona.gateway.util.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* @author qinwei
*/
public class ServerMessageDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
int flag = in.getByte(in.readerIndex());
if (flag != 0 && flag != 1) {
throw new AccessMessageDecodeException("unknown flag, flag=" + in.getByte(in.readerIndex()));
}
if (in.readableBytes() < Constants.PROTOCOL_META_LEN) {
throw new AccessMessageDecodeException("current ByteBuf length less than meta, len=" + in.readableBytes());
}
AccessMessage message = MessageCodec.decode(in);
out.add(message);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageWebSocketEncoder.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageWebSocketEncoder.java | package cn.bixin.sona.gateway.netty.codec;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.MessageCodec;
import cn.bixin.sona.gateway.util.AccessMessageUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import java.util.List;
/**
* @author qinwei
*/
@ChannelHandler.Sharable
public class ServerMessageWebSocketEncoder extends MessageToMessageEncoder<AccessMessage> {
@Override
protected void encode(ChannelHandlerContext ctx, AccessMessage msg, List<Object> out) throws Exception {
ByteBuf buf = null;
try {
buf = ctx.alloc().ioBuffer();
MessageCodec.encode(buf, msg);
AccessMessageUtils.logOutboundMsgSize(msg);
WebSocketFrame frame = new BinaryWebSocketFrame(buf);
out.add(frame);
buf = null;
} finally {
if (buf != null) {
buf.release();
}
}
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageEncoder.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/netty/codec/ServerMessageEncoder.java | package cn.bixin.sona.gateway.netty.codec;
import cn.bixin.sona.gateway.common.AccessMessage;
import cn.bixin.sona.gateway.common.MessageCodec;
import cn.bixin.sona.gateway.util.AccessMessageUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* @author qinwei
*/
@ChannelHandler.Sharable
public class ServerMessageEncoder extends MessageToByteEncoder<AccessMessage> {
@Override
protected void encode(ChannelHandlerContext ctx, AccessMessage msg, ByteBuf out) throws Exception {
MessageCodec.encode(out, msg);
AccessMessageUtils.logOutboundMsgSize(msg);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/exception/AccessMessageDecodeException.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/exception/AccessMessageDecodeException.java | package cn.bixin.sona.gateway.exception;
/**
* @author qinwei
*/
public class AccessMessageDecodeException extends RuntimeException {
private static final long serialVersionUID = 7297511371816648440L;
public AccessMessageDecodeException() {
super();
}
public AccessMessageDecodeException(String message) {
super(message);
}
public AccessMessageDecodeException(String message, Throwable cause) {
super(message, cause);
}
public AccessMessageDecodeException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/exception/RemoteException.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/exception/RemoteException.java | package cn.bixin.sona.gateway.exception;
import cn.bixin.sona.gateway.channel.Channel;
import lombok.Getter;
import java.net.InetSocketAddress;
/**
* @author qinwei
*/
@Getter
public class RemoteException extends Exception {
private static final long serialVersionUID = -5072922462535211769L;
private InetSocketAddress localAddress;
private InetSocketAddress remoteAddress;
private Object msgBody;
public RemoteException(String msg) {
super(msg);
}
public RemoteException(Channel channel, String msg) {
this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), msg);
}
public RemoteException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String msg) {
super(msg);
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
}
public RemoteException(Channel channel, Throwable cause) {
this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), cause);
}
public RemoteException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) {
super(cause);
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
}
public RemoteException(Channel channel, String msg, Throwable cause) {
this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), msg, cause);
}
public RemoteException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String msg, Throwable cause) {
super(msg, cause);
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
}
public RemoteException(String msg, Throwable t) {
super(msg, t);
}
public RemoteException(String msg, Throwable t, Object msgBody) {
super(msg, t);
this.msgBody = msgBody;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/FastThreadPool.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/FastThreadPool.java | package cn.bixin.sona.gateway.concurrent;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* * 把生产者队列、消费者队列分开,用两个锁去控制同步
* * 当 consumer queue 为空时,且 producer queue 不为空条件满足时,会交换两个队列
*
* @author qinwei
*/
public class FastThreadPool {
private static final int DEFAULT_QUEUE_SIZE = 1024;
private BoundedQueue<Runnable> produced;
private BoundedQueue<Runnable> toConsume;
private final Lock consumerLock = new ReentrantLock();
private final Lock producerLock = new ReentrantLock();
private final Condition notFullCondition = producerLock.newCondition();
private final Condition notEmptyCondition = producerLock.newCondition();
private final List<Thread> threads;
private volatile boolean stopped;
public FastThreadPool(String name, int threadNum) {
this(name, threadNum, 0);
}
public FastThreadPool(String name, int threadNum, int queueSize) {
Assert.isTrue(threadNum > 0, "initialThreadNum=" + threadNum + " should be positive");
threads = new ArrayList<>(threadNum);
if (queueSize <= 0) {
queueSize = DEFAULT_QUEUE_SIZE;
}
produced = new BoundedQueue<>(queueSize);
toConsume = new BoundedQueue<>(queueSize);
NamedThreadFactory threadFactory = new NamedThreadFactory(name, true);
for (int i = 0; i < threadNum; i++) {
Thread thread = threadFactory.newThread(this::consume);
thread.start();
threads.add(thread);
}
}
private void consume() {
Runnable task = null;
while (true) {
while (true) {
consumerLock.lock();
try {
if (!toConsume.isEmpty()) {
task = toConsume.pop();
break;
}
} finally {
consumerLock.unlock();
}
producerLock.lock();
try {
while (!stopped && produced.isEmpty()) {
try {
notEmptyCondition.await();
} catch (InterruptedException ignored) {
}
}
if (!produced.isEmpty()) {
if (produced.isFull()) {
notFullCondition.signalAll();
}
consumerLock.lock();
try {
BoundedQueue<Runnable> tmp = produced;
produced = toConsume;
toConsume = tmp;
} finally {
consumerLock.unlock();
}
} else {
break;
}
} finally {
producerLock.unlock();
}
}
if (task != null) {
task.run();
} else {
break;
}
}
}
public void stop() {
stopped = true;
producerLock.lock();
try {
notEmptyCondition.signalAll();
notFullCondition.signalAll();
} finally {
producerLock.unlock();
}
}
public boolean submit(Runnable task) {
Runnable[] tasks = {task};
return submit(tasks, 0, 1) == 1;
}
public int submit(Runnable[] tasks, int offset, int len) {
int cur = offset;
int end = offset + len;
while (!stopped && cur < end) {
producerLock.lock();
try {
while (produced.isFull()) {
try {
notFullCondition.await();
} catch (InterruptedException ignored) {
}
}
int toProduce = Math.min(produced.remainingCapacity(), end - cur);
if (toProduce > 0) {
boolean wasEmpty = produced.isEmpty();
produced.addAll(tasks, cur, toProduce);
if (wasEmpty) {
notEmptyCondition.signalAll();
}
}
cur += toProduce;
} finally {
producerLock.unlock();
}
}
return cur - offset;
}
public boolean isStopped() {
return stopped;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/BoundedQueue.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/BoundedQueue.java | package cn.bixin.sona.gateway.concurrent;
import org.springframework.util.Assert;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
/**
* @author qinwei
*/
public class BoundedQueue<E> implements Queue<E> {
private final int capacity;
private int size;
private final ArrayDeque<E> queue;
public BoundedQueue(int capacity) {
this.capacity = capacity;
queue = new ArrayDeque<>(capacity);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
public final boolean isFull() {
return size == capacity;
}
@Override
public boolean contains(Object o) {
return queue.contains(o);
}
@Override
public Iterator<E> iterator() {
return queue.iterator();
}
@Override
public Object[] toArray() {
return queue.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return queue.toArray(a);
}
@Override
public boolean add(E e) {
if (isFull()) {
queue.pollFirst();
size--;
}
queue.addLast(e);
size++;
return true;
}
@Override
public boolean containsAll(Collection<?> c) {
return queue.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
int inputSize = c.size();
Assert.isTrue(inputSize <= capacity, "Size of added which is " + inputSize + " is larger " + "than capacity=" + capacity);
int toPop = Math.max(0, inputSize - remainingCapacity());
for (int i = 0; i < toPop; ++i) {
queue.pollFirst();
}
size -= toPop;
for (E e : c) {
queue.addLast(e);
}
size += inputSize;
return true;
}
public boolean addAll(E[] c, int offset, int len) {
Assert.isTrue(len <= capacity, "Size of added which is " + len + " is larger " + "than capacity=" + capacity);
int toPop = Math.max(0, len - remainingCapacity());
for (int i = 0; i < toPop; ++i) {
queue.pollFirst();
}
size -= toPop;
int last = offset + len;
for (int i = offset; i < last; i++) {
queue.addLast(c[i]);
}
size += len;
return true;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = queue.removeAll(c);
if (modified) {
size = queue.size();
return true;
}
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = queue.retainAll(c);
if (modified) {
size = queue.size();
return true;
}
return false;
}
@Override
public void clear() {
queue.clear();
size = 0;
}
@Override
public boolean offer(E e) {
return add(e);
}
@Override
public boolean remove(Object o) {
if (queue.remove(o)) {
size--;
return true;
}
return false;
}
@Override
public E remove() {
E e = queue.removeFirst();
size--;
return e;
}
@Override
public E poll() {
E e = queue.pollFirst();
if (e != null) {
size--;
}
return e;
}
@Override
public E element() {
return queue.element();
}
@Override
public E peek() {
return queue.peekFirst();
}
public int remainingCapacity() {
return capacity - size;
}
public E pop() {
E e = queue.pop();
size--;
return e;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/OrderedChannelExecutor.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/OrderedChannelExecutor.java | package cn.bixin.sona.gateway.concurrent;
import cn.bixin.sona.gateway.channel.support.ChannelEventTask;
import cn.bixin.sona.gateway.loadbalance.ConsistentHashLoadBalance;
import cn.bixin.sona.gateway.loadbalance.LoadBalance;
import cn.bixin.sona.gateway.util.NetUtil;
import io.netty.util.internal.PlatformDependent;
import net.openhft.affinity.AffinityStrategies;
import net.openhft.affinity.AffinityThreadFactory;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author qinwei
* <p>
* 自定义线程池,提升处理能力,并且可以保证单个 channel 的处理顺序
*/
public class OrderedChannelExecutor extends ThreadPoolExecutor {
/**
* 减少内存消耗
*/
private static final AtomicIntegerFieldUpdater<SerialExecutor> STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SerialExecutor.class, "state");
private LoadBalance<Executor> loadBalance;
public OrderedChannelExecutor(int poolSize, String name) {
this(poolSize, poolSize, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new AffinityThreadFactory(name, AffinityStrategies.DIFFERENT_CORE), new DiscardPolicy());
}
public OrderedChannelExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
init();
}
private void init() {
List<Executor> list = IntStream.range(0, 64).mapToObj(SerialExecutor::new).collect(Collectors.toList());
loadBalance = new ConsistentHashLoadBalance<>(list);
}
@Override
public void execute(Runnable command) {
if (!(command instanceof ChannelEventTask)) {
throw new RejectedExecutionException("command must be " + ChannelEventTask.class.getName() + "!");
}
ChannelEventTask task = (ChannelEventTask) command;
getSerialExecutor(task).execute(command);
}
private void dispatch(Runnable task) {
super.execute(task);
}
private Executor getSerialExecutor(ChannelEventTask task) {
String channelId = task.getChannel().getChannelId();
return loadBalance.selectNode(channelId);
}
private final class SerialExecutor implements Executor, Runnable {
private final Queue<Runnable> tasks = PlatformDependent.newMpscQueue();
public volatile int state;
private final int sequence;
SerialExecutor(int sequence) {
this.sequence = sequence;
}
@Override
public void execute(Runnable command) {
tasks.add(command);
if (STATE_UPDATER.get(this) == 0) {
dispatch(this);
}
}
@Override
public void run() {
if (STATE_UPDATER.compareAndSet(this, 0, 1)) {
try {
Thread thread = Thread.currentThread();
for (; ; ) {
final Runnable task = tasks.poll();
if (task == null) {
break;
}
boolean ran = false;
beforeExecute(thread, task);
try {
task.run();
ran = true;
afterExecute(task, null);
} catch (Exception e) {
if (!ran) {
afterExecute(task, e);
}
throw e;
}
}
} finally {
STATE_UPDATER.set(this, 0);
}
if (STATE_UPDATER.get(this) == 0 && tasks.peek() != null) {
dispatch(this);
}
}
}
@Override
public String toString() {
return NetUtil.LOCAL_IP_ADDR + "|" + sequence;
}
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/TimeSlidingWindow.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/TimeSlidingWindow.java | package cn.bixin.sona.gateway.concurrent.counter;
import java.util.concurrent.atomic.LongAdder;
/**
* @author qinwei
* <p>
* 这里时间窗使用 LongAdder 计数 ,它 的 add 相比 AtomicLong或者其他类似的,在高并发情况下可以减少竞争,避免长时间自旋消耗cpu
*/
public class TimeSlidingWindow extends SlidingWindow<LongAdder> {
private final int threshold;
public TimeSlidingWindow(int threshold) {
super();
this.threshold = threshold;
}
public void increment() {
add(1);
}
public void add(int x) {
currentWindow().value().add(x);
}
public boolean exceedThreshold() {
long total = values().stream().mapToLong(LongAdder::sum).sum();
return total >= threshold;
}
@Override
protected LongAdder newEmptyBucket(long timeMillis) {
return new LongAdder();
}
@Override
protected WindowHolder<LongAdder> resetWindowTo(WindowHolder<LongAdder> windowHolder, long startTime) {
windowHolder.resetTo(startTime);
windowHolder.value().reset();
return windowHolder;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/SystemClock.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/SystemClock.java | package cn.bixin.sona.gateway.concurrent.counter;
/**
* @author qinwei
* <p>
* SystemClock 每秒有1000次的系统调用,也就是说 qps 大于1000的时候收益比较大,在目前的场景中还是值得的
*/
public final class SystemClock {
private static volatile long currentTimeMillis;
static {
currentTimeMillis = System.currentTimeMillis();
Thread daemon = new Thread(() -> {
while (true) {
currentTimeMillis = System.currentTimeMillis();
try {
Thread.sleep(1);
} catch (Throwable ignored) {
}
}
});
daemon.setDaemon(true);
daemon.setName("system-clock");
daemon.start();
}
private SystemClock() {
}
public static long currentTimeMillis() {
return currentTimeMillis;
}
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
BixinTech/sona | https://github.com/BixinTech/sona/blob/96b4d7bafa534c8d0173abab992d61e4dbcfab47/sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/SlidingWindow.java | sona-gateway/src/main/java/cn/bixin/sona/gateway/concurrent/counter/SlidingWindow.java | package cn.bixin.sona.gateway.concurrent.counter;
import org.springframework.util.Assert;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author qinwei
* <p>
* thread safe ,精确的滑动窗口计数,主要借鉴了 sentinel 中的设计。
* <p>
* 时间越精细,空间消耗越大,总的桶个数最好控制在 10 以内,总的时间长度不要低于 1s
* <p>
* Hystrix里面是一个滑动窗口包含10个桶(Bucket),每个桶时间宽度是1秒,负责1秒的数据统计
* <p>
* 这里主要用于房间消息频率统计,所以我设的默认总的时间长度是1s,滑动窗口包含10个桶,就相当于是计算房间 qps 了
*/
public abstract class SlidingWindow<T> {
/**
* 单位时间窗口长度
*/
private final int windowLength;
/**
* 总的时间长度
*/
private final int timeSpan;
private final AtomicReferenceArray<WindowHolder<T>> array;
private final ReentrantLock updateLock = new ReentrantLock();
public SlidingWindow() {
this(10, 1000);
}
public SlidingWindow(int bucketCount, int timeSpan) {
Assert.isTrue(timeSpan % bucketCount == 0, "time span needs to be evenly divided");
this.windowLength = timeSpan / bucketCount;
this.timeSpan = timeSpan;
this.array = new AtomicReferenceArray<>(bucketCount);
}
public WindowHolder<T> currentWindow() {
return currentWindow(SystemClock.currentTimeMillis());
}
private int calculateTimeIdx(long timeMillis) {
long timeId = timeMillis / windowLength;
return (int) (timeId % array.length());
}
protected long calculateWindowStart(long timeMillis) {
return timeMillis - timeMillis % windowLength;
}
private WindowHolder<T> currentWindow(long timeMillis) {
int idx = calculateTimeIdx(timeMillis);
long windowStart = calculateWindowStart(timeMillis);
while (true) {
WindowHolder<T> old = array.get(idx);
if (old == null) {
WindowHolder<T> window = new WindowHolder<>(windowLength, windowStart, newEmptyBucket(timeMillis));
if (array.compareAndSet(idx, null, window)) {
return window;
}
Thread.yield();
} else if (windowStart == old.windowStart()) {
return old;
} else if (windowStart > old.windowStart()) {
if (updateLock.tryLock()) {
try {
return resetWindowTo(old, windowStart);
} finally {
updateLock.unlock();
}
}
Thread.yield();
} else if (windowStart < old.windowStart()) {
// Should not go through here
return new WindowHolder<>(windowLength, windowStart, newEmptyBucket(timeMillis));
}
}
}
private WindowHolder<T> getPreviousWindow(long timeMillis) {
int idx = calculateTimeIdx(timeMillis - windowLength);
timeMillis = timeMillis - windowLength;
WindowHolder<T> wrap = array.get(idx);
if (wrap == null || isWindowDeprecated(wrap)) {
return null;
}
if (wrap.windowStart() + windowLength < (timeMillis)) {
return null;
}
return wrap;
}
public WindowHolder<T> getPreviousWindow() {
return getPreviousWindow(SystemClock.currentTimeMillis());
}
public T getWindowValue(long timeMillis) {
int idx = calculateTimeIdx(timeMillis);
WindowHolder<T> bucket = array.get(idx);
if (bucket == null || !bucket.isTimeInWindow(timeMillis)) {
return null;
}
return bucket.value();
}
private boolean isWindowDeprecated(WindowHolder<T> windowHolder) {
return isWindowDeprecated(SystemClock.currentTimeMillis(), windowHolder);
}
private boolean isWindowDeprecated(long time, WindowHolder<T> windowHolder) {
return time - windowHolder.windowStart() > timeSpan;
}
public List<WindowHolder<T>> list() {
return list(SystemClock.currentTimeMillis());
}
private List<WindowHolder<T>> list(long validTime) {
return IntStream.range(0, array.length()).mapToObj(array::get).filter(windowHolder -> windowHolder != null && !isWindowDeprecated(validTime, windowHolder)).collect(Collectors.toList());
}
public List<WindowHolder<T>> listAll() {
return IntStream.range(0, array.length()).mapToObj(array::get).filter(Objects::nonNull).collect(Collectors.toList());
}
public List<T> values() {
return values(SystemClock.currentTimeMillis());
}
private List<T> values(long timeMillis) {
return IntStream.range(0, array.length()).mapToObj(array::get).filter(windowHolder -> windowHolder != null && !isWindowDeprecated(timeMillis, windowHolder)).map(WindowHolder::value).collect(Collectors.toList());
}
protected abstract T newEmptyBucket(long timeMillis);
protected abstract WindowHolder<T> resetWindowTo(WindowHolder<T> windowHolder, long startTime);
}
| java | Apache-2.0 | 96b4d7bafa534c8d0173abab992d61e4dbcfab47 | 2026-01-05T02:40:29.261548Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.