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
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/view/PaddingDecorationView.java
app/src/main/java/com/ronakmanglani/watchlist/ui/view/PaddingDecorationView.java
package com.ronakmanglani.watchlist.ui.view; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; public class PaddingDecorationView extends RecyclerView.ItemDecoration { private int mItemOffset; public PaddingDecorationView(int itemOffset) { mItemOffset = itemOffset; } public PaddingDecorationView(@NonNull Context context, @DimenRes int itemOffsetId) { this(context.getResources().getDimensionPixelSize(itemOffsetId)); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoLightTextView.java
app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoLightTextView.java
package com.ronakmanglani.watchlist.ui.view; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; import com.ronakmanglani.watchlist.util.FontUtil; public class RobotoLightTextView extends TextView { public RobotoLightTextView(Context context) { super(context); applyCustomFont(); } public RobotoLightTextView(Context context, AttributeSet attrs) { super(context, attrs); applyCustomFont(); } public RobotoLightTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); applyCustomFont(); } private void applyCustomFont() { Typeface customFont = FontUtil.getTypeface(FontUtil.ROBOTO_LIGHT); setTypeface(customFont); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoRegularTextView.java
app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoRegularTextView.java
package com.ronakmanglani.watchlist.ui.view; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; import com.ronakmanglani.watchlist.util.FontUtil; public class RobotoRegularTextView extends TextView { public RobotoRegularTextView(Context context) { super(context); applyCustomFont(); } public RobotoRegularTextView(Context context, AttributeSet attrs) { super(context, attrs); applyCustomFont(); } public RobotoRegularTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); applyCustomFont(); } private void applyCustomFont() { Typeface customFont = FontUtil.getTypeface(FontUtil.ROBOTO_REGULAR); setTypeface(customFont); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/CursorAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/CursorAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.database.Cursor; import android.database.DataSetObserver; import android.support.v7.widget.RecyclerView; /* * Credit to skyfishjy gist: * https://gist.github.com/skyfishjy/443b7448f59be978bc59 * for the CursorRecyclerViewApater.java code and idea. */ public abstract class CursorAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{ private static final String LOG_TAG = CursorAdapter.class.getSimpleName(); private int rowIdColumn; private boolean dataIsValid; private Cursor mCursor; private DataSetObserver mDataSetObserver; public CursorAdapter(Context context, Cursor cursor) { mCursor = cursor; dataIsValid = cursor != null; rowIdColumn = dataIsValid ? mCursor.getColumnIndex("_id") : -1; mDataSetObserver = new NotifyingDataSetObserver(); if (dataIsValid) { mCursor.registerDataSetObserver(mDataSetObserver); } } public Cursor getCursor() { return mCursor; } public Cursor swapCursor(Cursor newCursor) { if (newCursor == mCursor) { return null; } final Cursor oldCursor = mCursor; if (oldCursor != null && mDataSetObserver != null) { oldCursor.unregisterDataSetObserver(mDataSetObserver); } mCursor = newCursor; if (mCursor != null) { if (mDataSetObserver != null) { mCursor.registerDataSetObserver(mDataSetObserver); } rowIdColumn = newCursor.getColumnIndexOrThrow("_id"); dataIsValid = true; notifyDataSetChanged(); } else { rowIdColumn = -1; dataIsValid = false; notifyDataSetChanged(); } return oldCursor; } @Override public int getItemCount() { if (dataIsValid && mCursor != null) { return mCursor.getCount(); } return 0; } @Override public long getItemId(int position) { if (dataIsValid && mCursor != null && mCursor.moveToPosition(position)){ return mCursor.getLong(rowIdColumn); } return 0; } @Override public void setHasStableIds(boolean hasStableIds) { super.setHasStableIds(true); } @Override public void onBindViewHolder(VH viewHolder, int position) { if (!dataIsValid) { throw new IllegalStateException("This should only be called when Cursor is valid"); } if (!mCursor.moveToPosition(position)) { throw new IllegalStateException("Could not move Cursor to position: " + position); } onBindViewHolder(viewHolder, mCursor); } public abstract void onBindViewHolder(VH viewHolder, Cursor cursor); private class NotifyingDataSetObserver extends DataSetObserver{ @Override public void onChanged() { super.onChanged(); dataIsValid = true; notifyDataSetChanged(); } @Override public void onInvalidated() { super.onInvalidated(); dataIsValid = false; notifyDataSetChanged(); } } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/MovieAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/MovieAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.WatchlistApp; import com.ronakmanglani.watchlist.model.Movie; import com.ronakmanglani.watchlist.api.ApiHelper; import com.ronakmanglani.watchlist.util.TextUtil; import com.ronakmanglani.watchlist.api.VolleySingleton; import com.ronakmanglani.watchlist.ui.view.AutoResizeTextView; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class MovieAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private int imageWidth; private SharedPreferences sharedPref; public ArrayList<Movie> movieList; private final OnMovieClickListener onMovieClickListener; // Constructor public MovieAdapter(Context context, OnMovieClickListener onMovieClickListener) { this.context = context; this.movieList = new ArrayList<>(); this.onMovieClickListener = onMovieClickListener; sharedPref = context.getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE); imageWidth = sharedPref.getInt(WatchlistApp.THUMBNAIL_SIZE, 0); // Load image width for grid view } // RecyclerView methods @Override public int getItemCount() { return movieList.size(); } @Override public int getItemViewType(int position) { return (sharedPref.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID)); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == WatchlistApp.VIEW_MODE_GRID) { // GRID MODE final ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_grid, parent, false); ViewTreeObserver viewTreeObserver = v.getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Update width integer and save to storage for next use int width = v.findViewById(R.id.movie_poster).getWidth(); if (width > imageWidth) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(WatchlistApp.THUMBNAIL_SIZE, width); editor.apply(); } // Unregister LayoutListener if (Build.VERSION.SDK_INT >= 16) { v.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); } return new MovieGridViewHolder(v, onMovieClickListener); } else if (viewType == WatchlistApp.VIEW_MODE_LIST) { // LIST MODE ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_list, parent, false); return new MovieListViewHolder(v, onMovieClickListener); } else { // COMPACT MODE ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_compact, parent, false); return new MovieCompactViewHolder(v, onMovieClickListener); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { int viewType = getItemViewType(0); Movie movie = movieList.get(position); if (viewType == WatchlistApp.VIEW_MODE_GRID) { // GRID MODE MovieGridViewHolder movieViewHolder = (MovieGridViewHolder) viewHolder; // Title and year movieViewHolder.movieName.setText(movie.title); movieViewHolder.releaseYear.setText(movie.year); // Load image if (!TextUtil.isNullOrEmpty(movie.backdropImage)) { String imageUrl = ApiHelper.getImageURL(movie.backdropImage, imageWidth); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } else if (!TextUtil.isNullOrEmpty(movie.posterImage)) { String imageUrl = ApiHelper.getImageURL(movie.posterImage, imageWidth); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } else { movieViewHolder.defaultImageView.setVisibility(View.VISIBLE); movieViewHolder.imageView.setVisibility(View.GONE); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } else if (viewType == WatchlistApp.VIEW_MODE_LIST) { // LIST MODE MovieListViewHolder movieViewHolder = (MovieListViewHolder) viewHolder; // Title, year and overview movieViewHolder.movieName.setText(movie.title); movieViewHolder.releaseYear.setText(movie.year); movieViewHolder.overview.setText(movie.overview); // Load image if (TextUtil.isNullOrEmpty(movie.posterImage)) { movieViewHolder.imageView.setVisibility(View.GONE); movieViewHolder.defaultImageView.setVisibility(View.VISIBLE); } else { int imageSize = (int) context.getResources().getDimension(R.dimen.movie_list_poster_width); String imageUrl = ApiHelper.getImageURL(movie.posterImage, imageSize); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } else { // COMPACT MODE final MovieCompactViewHolder movieViewHolder = (MovieCompactViewHolder) viewHolder; // Title and year movieViewHolder.movieName.setText(movie.title); movieViewHolder.movieYear.setText(movie.year); // Load image if (TextUtil.isNullOrEmpty(movie.backdropImage)) { movieViewHolder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } else { int imageSize = (int) context.getResources().getDimension(R.dimen.movie_compact_image_size); String imageUrl = ApiHelper.getImageURL(movie.backdropImage, imageSize); VolleySingleton.getInstance().imageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { movieViewHolder.movieImage.setImageBitmap(response.getBitmap()); } @Override public void onErrorResponse(VolleyError error) { movieViewHolder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } }); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } } // ViewHolders public class MovieGridViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_card) CardView cardView; @BindView(R.id.movie_poster_default) ImageView defaultImageView; @BindView(R.id.movie_poster) NetworkImageView imageView; @BindView(R.id.movie_title) TextView movieName; @BindView(R.id.movie_year) TextView releaseYear; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieGridViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } public class MovieListViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_card) CardView cardView; @BindView(R.id.movie_poster_default) ImageView defaultImageView; @BindView(R.id.movie_poster) NetworkImageView imageView; @BindView(R.id.movie_title) TextView movieName; @BindView(R.id.movie_year) TextView releaseYear; @BindView(R.id.movie_overview) AutoResizeTextView overview; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieListViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } public class MovieCompactViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_item) View movieItem; @BindView(R.id.movie_image) ImageView movieImage; @BindView(R.id.movie_name) TextView movieName; @BindView(R.id.movie_year) TextView movieYear; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieCompactViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); movieItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnMovieClickListener { void onMovieClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/CreditAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/CreditAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.model.Credit; import com.ronakmanglani.watchlist.api.ApiHelper; import com.ronakmanglani.watchlist.util.TextUtil; import com.ronakmanglani.watchlist.api.VolleySingleton; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import de.hdodenhof.circleimageview.CircleImageView; public class CreditAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; public ArrayList<Credit> creditList; private OnCreditClickListener onCreditClickListener; // Constructor public CreditAdapter(Context context, ArrayList<Credit> creditList, OnCreditClickListener onCreditClickListener) { this.context = context; this.creditList = creditList; this.onCreditClickListener = onCreditClickListener; } // RecyclerView methods @Override public int getItemCount() { return creditList.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_credit, parent, false); return new CreditViewHolder(v, onCreditClickListener); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { Credit credit = creditList.get(position); final CreditViewHolder holder = (CreditViewHolder) viewHolder; int imageSize = (int) context.getResources().getDimension(R.dimen.detail_cast_image_width); if (TextUtil.isNullOrEmpty(credit.imagePath)) { holder.creditImage.setImageResource(R.drawable.default_cast_square); } else { VolleySingleton.getInstance().imageLoader.get(ApiHelper.getImageURL(credit.imagePath, imageSize), new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) { holder.creditImage.setImageBitmap(imageContainer.getBitmap()); } @Override public void onErrorResponse(VolleyError volleyError) { holder.creditImage.setImageResource(R.drawable.default_cast_square); } }); } holder.creditName.setText(credit.name); if (TextUtil.isNullOrEmpty(credit.role)) { holder.creditRole.setVisibility(View.GONE); } else { holder.creditRole.setText(credit.role); holder.creditRole.setVisibility(View.VISIBLE); } } // ViewHolder public class CreditViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.credit_item) View creditItem; @BindView(R.id.credit_image) CircleImageView creditImage; @BindView(R.id.credit_name) TextView creditName; @BindView(R.id.credit_role) TextView creditRole; public CreditViewHolder(final ViewGroup itemView, final OnCreditClickListener onCreditClickListener) { super(itemView); ButterKnife.bind(this, itemView); creditItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCreditClickListener.onCreditClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnCreditClickListener { void onCreditClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/SearchAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/SearchAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.model.Movie; import com.ronakmanglani.watchlist.api.ApiHelper; import com.ronakmanglani.watchlist.util.TextUtil; import com.ronakmanglani.watchlist.api.VolleySingleton; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class SearchAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; public ArrayList<Movie> movieList; private final OnMovieClickListener onMovieClickListener; // Constructor public SearchAdapter(Context context, OnMovieClickListener onMovieClickListener) { this.context = context; this.movieList = new ArrayList<>(); this.onMovieClickListener = onMovieClickListener; } // RecyclerView methods @Override public int getItemCount() { return movieList.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_compact, parent, false); return new SearchViewHolder(v, onMovieClickListener); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { Movie movie = movieList.get(position); final SearchViewHolder holder = (SearchViewHolder) viewHolder; // Load image if (TextUtil.isNullOrEmpty(movie.backdropImage)) { holder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } else { int imageSize = (int) context.getResources().getDimension(R.dimen.movie_compact_image_size); String imageUrl = ApiHelper.getImageURL(movie.backdropImage, imageSize); VolleySingleton.getInstance().imageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) { holder.movieImage.setImageBitmap(imageContainer.getBitmap()); } @Override public void onErrorResponse(VolleyError volleyError) { holder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } }); } // Set text holder.movieName.setText(movie.title); holder.movieYear.setText(movie.year); if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { holder.movieRatingHolder.setVisibility(View.GONE); } else { holder.movieRating.setText(movie.rating); holder.movieRatingHolder.setVisibility(View.VISIBLE); } } // ViewHolder public class SearchViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_item) View movieItem; @BindView(R.id.movie_image) ImageView movieImage; @BindView(R.id.movie_name) TextView movieName; @BindView(R.id.movie_year) TextView movieYear; @BindView(R.id.movie_rating_holder) View movieRatingHolder; @BindView(R.id.movie_rating) TextView movieRating; public SearchViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); movieItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnMovieClickListener { void onMovieClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/PhotoAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/PhotoAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.toolbox.NetworkImageView; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.api.ApiHelper; import com.ronakmanglani.watchlist.api.VolleySingleton; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class PhotoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; public ArrayList<String> photoList; private final OnPhotoClickListener onPhotoClickListener; // Constructor public PhotoAdapter(Context context, ArrayList<String> photoList, OnPhotoClickListener onPhotoClickListener) { this.context = context; this.photoList = photoList; this.onPhotoClickListener = onPhotoClickListener; } // RecyclerView methods @Override public int getItemCount() { return photoList.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false); return new PhotoViewHolder(v, onPhotoClickListener); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { PhotoViewHolder holder = (PhotoViewHolder) viewHolder; int imageSize = (int) context.getResources().getDimension(R.dimen.photo_item_width); holder.photoImage.setImageUrl(ApiHelper.getImageURL(photoList.get(position), imageSize), VolleySingleton.getInstance().imageLoader); } // ViewHolder public class PhotoViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.photo_item) View photoItem; @BindView(R.id.photo_image) NetworkImageView photoImage; public PhotoViewHolder(final ViewGroup itemView, final OnPhotoClickListener onPhotoClickListener) { super(itemView); ButterKnife.bind(this, itemView); photoItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onPhotoClickListener.onPhotoClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnPhotoClickListener { void onPhotoClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/ReviewAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/ReviewAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.model.Review; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class ReviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public ArrayList<Review> reviewList; private final OnReviewClickListener onReviewClickListener; // Constructor public ReviewAdapter(ArrayList<Review> reviewList, OnReviewClickListener onReviewClickListener) { this.reviewList = reviewList; this.onReviewClickListener = onReviewClickListener; } // RecyclerView methods @Override public int getItemCount() { return reviewList.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_review, parent, false); return new ReviewViewHolder(v, onReviewClickListener); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { Review review = reviewList.get(position); ReviewViewHolder holder = (ReviewViewHolder) viewHolder; holder.reviewAuthor.setText(review.userName); if (review.hasSpoiler) { holder.reviewBody.setVisibility(View.GONE); holder.reviewSpoiler.setVisibility(View.VISIBLE); } else { holder.reviewBody.setText(review.comment); holder.reviewBody.setVisibility(View.VISIBLE); holder.reviewSpoiler.setVisibility(View.GONE); } holder.reviewTime.setText(review.createdAt); } // ViewHolder public class ReviewViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.review_item) View reviewItem; @BindView(R.id.review_author) TextView reviewAuthor; @BindView(R.id.review_body) TextView reviewBody; @BindView(R.id.review_spoiler) TextView reviewSpoiler; @BindView(R.id.review_time) TextView reviewTime; public ReviewViewHolder(final ViewGroup itemView, final OnReviewClickListener onReviewClickListener) { super(itemView); ButterKnife.bind(this, itemView); reviewItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onReviewClickListener.onReviewClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnReviewClickListener { void onReviewClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/MovieCursorAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/MovieCursorAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Build; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.WatchlistApp; import com.ronakmanglani.watchlist.data.MovieColumns; import com.ronakmanglani.watchlist.model.Movie; import com.ronakmanglani.watchlist.api.ApiHelper; import com.ronakmanglani.watchlist.util.TextUtil; import com.ronakmanglani.watchlist.api.VolleySingleton; import com.ronakmanglani.watchlist.ui.view.AutoResizeTextView; import butterknife.BindView; import butterknife.ButterKnife; public class MovieCursorAdapter extends CursorAdapter<ViewHolder> { private Context context; private int imageWidth; private SharedPreferences sharedPref; private final OnMovieClickListener onMovieClickListener; // Constructor public MovieCursorAdapter(Context context, OnMovieClickListener onMovieClickListener, Cursor cursor) { super(context, cursor); this.context = context; this.onMovieClickListener = onMovieClickListener; sharedPref = context.getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE); imageWidth = sharedPref.getInt(WatchlistApp.THUMBNAIL_SIZE, 0); // Load image width for grid view } // RecyclerView methods @Override public int getItemCount() { return super.getItemCount(); } @Override public int getItemViewType(int position) { return (sharedPref.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID)); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == WatchlistApp.VIEW_MODE_GRID) { // GRID MODE final ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_grid, parent, false); ViewTreeObserver viewTreeObserver = v.getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Update width integer and save to storage for next use int width = v.findViewById(R.id.movie_poster).getWidth(); if (width > imageWidth) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(WatchlistApp.THUMBNAIL_SIZE, width); editor.apply(); } // Unregister LayoutListener if (Build.VERSION.SDK_INT >= 16) { v.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); } return new MovieGridViewHolder(v, onMovieClickListener); } else if (viewType == WatchlistApp.VIEW_MODE_LIST) { // LIST MODE ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_list, parent, false); return new MovieListViewHolder(v, onMovieClickListener); } else { // COMPACT MODE ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_compact, parent, false); return new MovieCompactViewHolder(v, onMovieClickListener); } } @Override public void onBindViewHolder(final ViewHolder viewHolder, final Cursor cursor) { // Get data from cursor String id = cursor.getString(cursor.getColumnIndex(MovieColumns.TMDB_ID)); String title = cursor.getString(cursor.getColumnIndex(MovieColumns.TITLE)); String year = cursor.getString(cursor.getColumnIndex(MovieColumns.YEAR)); String overview = cursor.getString(cursor.getColumnIndex(MovieColumns.OVERVIEW)); String rating = cursor.getString(cursor.getColumnIndex(MovieColumns.RATING)); String posterImage = cursor.getString(cursor.getColumnIndex(MovieColumns.POSTER)); String backdropImage = cursor.getString(cursor.getColumnIndex(MovieColumns.BACKDROP)); Movie movie = new Movie(id, title, year, overview, rating, posterImage, backdropImage); // Bind data to view int viewType = getItemViewType(0); if (viewType == WatchlistApp.VIEW_MODE_GRID) { // GRID MODE MovieGridViewHolder movieViewHolder = (MovieGridViewHolder) viewHolder; // Title and year movieViewHolder.movieName.setText(movie.title); movieViewHolder.releaseYear.setText(movie.year); // Load image if (!TextUtil.isNullOrEmpty(movie.backdropImage)) { String imageUrl = ApiHelper.getImageURL(movie.backdropImage, imageWidth); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } else if (!TextUtil.isNullOrEmpty(movie.posterImage)) { String imageUrl = ApiHelper.getImageURL(movie.posterImage, imageWidth); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } else { movieViewHolder.defaultImageView.setVisibility(View.VISIBLE); movieViewHolder.imageView.setVisibility(View.GONE); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } else if (viewType == WatchlistApp.VIEW_MODE_LIST) { // LIST MODE MovieListViewHolder movieViewHolder = (MovieListViewHolder) viewHolder; // Title, year and overview movieViewHolder.movieName.setText(movie.title); movieViewHolder.releaseYear.setText(movie.year); movieViewHolder.overview.setText(movie.overview); // Load image if (TextUtil.isNullOrEmpty(movie.posterImage)) { movieViewHolder.imageView.setVisibility(View.GONE); movieViewHolder.defaultImageView.setVisibility(View.VISIBLE); } else { int imageSize = (int) context.getResources().getDimension(R.dimen.movie_list_poster_width); String imageUrl = ApiHelper.getImageURL(movie.posterImage, imageSize); movieViewHolder.imageView.setImageUrl(imageUrl, VolleySingleton.getInstance().imageLoader); movieViewHolder.imageView.setVisibility(View.VISIBLE); movieViewHolder.defaultImageView.setVisibility(View.GONE); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } else { // COMPACT MODE final MovieCompactViewHolder movieViewHolder = (MovieCompactViewHolder) viewHolder; // Title and year movieViewHolder.movieName.setText(movie.title); movieViewHolder.movieYear.setText(movie.year); // Load image if (TextUtil.isNullOrEmpty(movie.backdropImage)) { movieViewHolder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } else { int imageSize = (int) context.getResources().getDimension(R.dimen.movie_compact_image_size); String imageUrl = ApiHelper.getImageURL(movie.backdropImage, imageSize); VolleySingleton.getInstance().imageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { movieViewHolder.movieImage.setImageBitmap(response.getBitmap()); } @Override public void onErrorResponse(VolleyError error) { movieViewHolder.movieImage.setImageResource(R.drawable.default_backdrop_circle); } }); } // Display movie rating if (TextUtil.isNullOrEmpty(movie.rating) || movie.rating.equals("0")) { movieViewHolder.movieRatingIcon.setVisibility(View.GONE); movieViewHolder.movieRating.setVisibility(View.GONE); } else { movieViewHolder.movieRatingIcon.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setVisibility(View.VISIBLE); movieViewHolder.movieRating.setText(movie.rating); } } } // ViewHolders public class MovieGridViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_card) CardView cardView; @BindView(R.id.movie_poster_default) ImageView defaultImageView; @BindView(R.id.movie_poster) NetworkImageView imageView; @BindView(R.id.movie_title) TextView movieName; @BindView(R.id.movie_year) TextView releaseYear; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieGridViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } public class MovieListViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_card) CardView cardView; @BindView(R.id.movie_poster_default) ImageView defaultImageView; @BindView(R.id.movie_poster) NetworkImageView imageView; @BindView(R.id.movie_title) TextView movieName; @BindView(R.id.movie_year) TextView releaseYear; @BindView(R.id.movie_overview) AutoResizeTextView overview; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieListViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } public class MovieCompactViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.movie_item) View movieItem; @BindView(R.id.movie_image) ImageView movieImage; @BindView(R.id.movie_name) TextView movieName; @BindView(R.id.movie_year) TextView movieYear; @BindView(R.id.movie_rating) TextView movieRating; @BindView(R.id.rating_icon) ImageView movieRatingIcon; public MovieCompactViewHolder(final ViewGroup itemView, final OnMovieClickListener onMovieClickListener) { super(itemView); ButterKnife.bind(this, itemView); movieItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMovieClickListener.onMovieClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnMovieClickListener { void onMovieClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
ronak-lm/android-watchlist
https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/VideoAdapter.java
app/src/main/java/com/ronakmanglani/watchlist/ui/adapter/VideoAdapter.java
package com.ronakmanglani.watchlist.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.toolbox.NetworkImageView; import com.ronakmanglani.watchlist.R; import com.ronakmanglani.watchlist.model.Video; import com.ronakmanglani.watchlist.api.VolleySingleton; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; public ArrayList<Video> videoList; private final OnVideoClickListener onVideoClickListener; // Constructor public VideoAdapter(Context context, ArrayList<Video> videoList, OnVideoClickListener onVideoClickListener) { this.context = context; this.videoList = videoList; this.onVideoClickListener = onVideoClickListener; } // RecyclerView methods @Override public int getItemCount() { return videoList.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_video, parent, false); return new VideoViewHolder(v, onVideoClickListener); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { Video video = videoList.get(position); VideoViewHolder holder = (VideoViewHolder) viewHolder; holder.videoImage.setImageUrl(video.imageURL, VolleySingleton.getInstance().imageLoader); holder.videoName.setText(video.title); holder.videoSize.setText(video.size); } // ViewHolder public class VideoViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.video_item) View videoItem; @BindView(R.id.video_image) NetworkImageView videoImage; @BindView(R.id.video_name) TextView videoName; @BindView(R.id.video_size) TextView videoSize; public VideoViewHolder(final ViewGroup itemView, final OnVideoClickListener onVideoClickListener) { super(itemView); ButterKnife.bind(this, itemView); videoItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onVideoClickListener.onVideoClicked(getAdapterPosition()); } }); } } // Click listener interface public interface OnVideoClickListener { void onVideoClicked(final int position); } }
java
Apache-2.0
fc6f8c312ebe031e4068b093e84de4ee769cd9db
2026-01-05T02:38:35.947030Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/AAA.java
src/test/java/com/wind/AAA.java
package com.wind; import javax.annotation.Resource; public class AAA { /** * 状态码 */ @Resource private Integer code; /** * 消息说明 */ private String msg; /** * 系统当前时间,GTM时间戳 */ private Long timestamp; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/BeanObj.java
src/test/java/com/wind/BeanObj.java
package com.wind; import java.util.Date; import java.util.List; import java.util.Map; public class BeanObj { private String name; private int age; private List<String> list; private Date date; private Map<String, String> map; private List<JsonObj> objList; private BeanObj(){ } public BeanObj(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } public List<JsonObj> getObjList() { return objList; } public void setObjList(List<JsonObj> objList) { this.objList = objList; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/JsonObj.java
src/test/java/com/wind/JsonObj.java
package com.wind; public class JsonObj { private int code; private String value; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/resource/ResourceTest.java
src/test/java/com/wind/resource/ResourceTest.java
package com.wind.resource; import com.wind.network.http.ResourceUtil; import org.junit.Test; import java.net.URL; public class ResourceTest { @Test public void test(){ URL url = ResourceUtil.getUrlFile("image/code.png"); URL url2 = ResourceUtil.getUrlFile("/image/code.png"); System.out.println(url); System.out.println(url2); String relPath = ResourceUtil.getProjectPath(); System.out.println(relPath); String path = ResourceUtil.getClassPath(); System.out.println(path); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/xml/XmlTest.java
src/test/java/com/wind/xml/XmlTest.java
package com.wind.xml; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.junit.Test; import java.io.File; public class XmlTest { @Test public void test(){ String filePath = "src/main/resources/xml/test.xml"; File file = new File(filePath); if(!file.exists()){ long s = System.currentTimeMillis(); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("root"); for(int i = 0; i <= 10000000; i++){ Element testElement = DocumentHelper.createElement("eleTest"); testElement.addAttribute("name", "testEle"); testElement.addText("this is another text"); root.add(testElement); } XmlUtil.writeXml("src/main/resources/xml/test.xml", doc); long e = System.currentTimeMillis(); System.out.println("共耗时:" + (e - s) + "ms"); } // parseXml(filePath); XmlUtil.parseHandler(filePath); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/json/JsonTest.java
src/test/java/com/wind/json/JsonTest.java
package com.wind.json; import com.wind.AAA; import com.wind.BeanObj; import com.wind.json.gson.GsonUtil; import com.wind.json.jsonlib.JsonUtil; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @package com.wind.json * @className JsonTest * @note json工具类测试 * json-lib 依赖第三方包多,json转bean无法识别date,大数量转换性能差,停止维护,只支持到jdk5 * jackson 依赖jar包比较少,json转bean日期类型,默认只识别yyyy-MM-dd,扩展性好,大数量转换性能不如fastjson,gson * fastjson ali开源,无额外依赖,fastjson性能比较快 * gson google,无依赖,Gson是目前功能最全的Json解析神器,Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距 * @author wind * @date 2018/7/29 22:38 */ public class JsonTest { private String jsonStr = "{name:'123', age:18, date:'2018-07-27 12:00:00', list:['123', '333'], " + "map:{name:'333', age:18}, objList:[{code:1,value:'1'}]}"; private String jsonStr2 = "{name:'123', age:18, date:null, list:['123', '333'], " + "map:{name:'333', age:18}, objList:[{code:1,value:'1'}]}"; private int count = 1000000; List<BeanObj> list = new ArrayList<>(); @Before public void init(){ for(int i = 0; i < count; i++){ BeanObj obj = new BeanObj(""); list.add(obj); } } /** * json-lib默认处理日期格式有问题 */ @Test public void testJsonLib(){ long start = System.currentTimeMillis(); BeanObj obj = JsonUtil.toBean(jsonStr, BeanObj.class); System.out.println(obj.getDate()); System.out.println(JsonUtil.toJson(obj)); long end = System.currentTimeMillis(); System.out.println(end - start); } @Test public void testJsonLib2(){ long start = System.currentTimeMillis(); for(int i = 0; i < count; i++){ BeanObj obj = JsonUtil.toBean(jsonStr, BeanObj.class); // System.out.println(obj.getDate()); } long end = System.currentTimeMillis(); System.out.println(end - start); long start2 = System.currentTimeMillis(); list.forEach(JsonUtil::toJson); long end2 = System.currentTimeMillis(); System.out.println(end2 - start2); } /** * jackson处理json字符串转bean日期,默认设置yyyy-MM-dd */ @Test public void testJackson(){ long start = System.currentTimeMillis(); BeanObj obj = com.wind.json.jackson.JsonUtil.toBean(jsonStr2, BeanObj.class); System.out.println(obj != null ? obj.getDate() : null); System.out.println(com.wind.json.jackson.JsonUtil.toJson(obj)); long end = System.currentTimeMillis(); System.out.println(end - start); } @Test public void testJackson2(){ long start = System.currentTimeMillis(); for(int i = 0; i < count; i++){ BeanObj obj = com.wind.json.jackson.JsonUtil.toBean(jsonStr, BeanObj.class); // System.out.println(obj != null ? obj.getDate() : null); } long end = System.currentTimeMillis(); System.out.println(end - start); long start2 = System.currentTimeMillis(); list.forEach(com.wind.json.jackson.JsonUtil::toJson); long end2 = System.currentTimeMillis(); System.out.println(end2 - start2); } @Test public void testFastjson(){ long start = System.currentTimeMillis(); BeanObj obj = com.wind.json.fastjson.JsonUtil.toBean(jsonStr, BeanObj.class); System.out.println(obj.getDate()); System.out.println(com.wind.json.fastjson.JsonUtil.toJson(obj, false)); long end = System.currentTimeMillis(); System.out.println(end - start); } @Test public void testFastjson2(){ long start = System.currentTimeMillis(); for(int i = 0; i < count; i++){ BeanObj obj = com.wind.json.fastjson.JsonUtil.toBean(jsonStr, BeanObj.class); // System.out.println(obj.getDate()); } long end = System.currentTimeMillis(); System.out.println(end - start); long start2 = System.currentTimeMillis(); list.forEach(obj -> com.wind.json.fastjson.JsonUtil.toJson(obj, false)); long end2 = System.currentTimeMillis(); System.out.println(end2 - start2); } @Test public void testGson(){ long start = System.currentTimeMillis(); BeanObj obj = GsonUtil.toBean(jsonStr, BeanObj.class); System.out.println(obj.getDate()); System.out.println(GsonUtil.toJson(obj)); long end = System.currentTimeMillis(); System.out.println(end - start); System.out.println(GsonUtil.format(jsonStr)); } @Test public void testGson2(){ long start = System.currentTimeMillis(); for(int i = 0; i < count; i++){ BeanObj obj = GsonUtil.toBean(jsonStr, BeanObj.class); // System.out.println(obj.getDate()); } long end = System.currentTimeMillis(); System.out.println(end - start); long start2 = System.currentTimeMillis(); list.forEach(GsonUtil::toJson); long end2 = System.currentTimeMillis(); System.out.println(end2 - start2); } @Test public void test(){ AAA aaa = com.wind.json.jackson.JsonUtil.toBean("{code:200}", AAA.class); System.out.println(aaa); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/common/CommonTest.java
src/test/java/com/wind/common/CommonTest.java
package com.wind.common; /** * @Title: CommonTest * @Package com.wind.common * @Description: TODO * @author wind * @date 2018/10/11 10:31 * @version V1.0 */ public class CommonTest { }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/crypt/CryptTest.java
src/test/java/com/wind/crypt/CryptTest.java
package com.wind.crypt; import com.wind.encrypt.CryptoUtil; import com.wind.encrypt.RsaUtil; import org.junit.Test; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; /** * @Title: CryptTest * @Package com.wind.crypt * @Description: TODO * @author wind * @date 2018/10/11 10:34 * @version V1.0 */ public class CryptTest { @Test public void testPBKDF2(){ try { String[] arr = CryptoUtil.createHash("123456"); System.err.println("password: " + arr[0]); System.err.println("salt: " + arr[1]); System.out.println(CryptoUtil.validatePassword("123456", arr[0], arr[1])); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } @Test public void testRsa(){ String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVtcGrsBopnFqv/AE2UjXKu5C2tewoRxhvsDdLt1FJNrF8+52Qtqbn428p26yK8kMhiwdAwDw7AfoRrJpsO2ZwsIeMKVGX0hir+ttevlSVaA/i0NF+7B0RCqL8+g5bcTqcCK9kw0dAXcz6nxqT1sVcVCuwJKpTiUnGUd40gkYEtjSD21ijYBXrrx3iXZLrSCI7mMM1RFgF4zPikqXRTOe+wPjprjtgmzyY+vkiu/8f9OiLi1kwhOgHPqskihfjSVaK8O0h6P0QPzzkkRQa3+fafWmuTj95R180KDuZ4IJ9686zZzIX7TGG2Ry933VxItw5lRAlbCal+90BFrtdqraHAgMBAAECggEBAI3kleoG39UedymjHPcCVi+PNKqnpGvMbpG1H8OovOc6amC+DmoRZAIWos62gUO0OAI7xiUNzkhTKFPGFxqL9hzKg75JjybpHy8pdO/IT1zII35jUpwMZ8Q2I6LH0gHDQLyQ0sQa/ZY5EUVctRD4F1jaAgpRxgmk7oKEJ6n26ywcnm8U86S8YVAVjQjtoYbxlTq3L0yPVhGEjF8r0SMC1APSKO0EJ3Euwx16UHYoodfHlIzBcZsVRwPxfJwwxtHZWPyECmkEH8PoUKjge/CYik4THizCJsCOf3/oilYkEcICeuBaxvwlEYzk3WhSQIFLbxjhzpsnI7BcEp0AzV/uOOECgYEAxTcTbb+FzFwO4xLqwOYHdhSDdbNp+NfLHP6fIsaypTWhBix2va75C4n+05zd4qn8aO03tNFUy3KZqRq5XNBPfxR/y9Q88zx0G8a+nJCChY6Ul3u6Wf/9eaYJO4saxUsb8FNVg7nle5IBv4qa63Y/ppO9hIzp//caAQhWixCP5XECgYEAwlWysYrPXIFRJvSlOipl8yA4Kl+bFMgHjguHM1au/HtTXy4r2ruaNAIqaM6G/Tke67zRGHtEdnA3uRQoj8Wx8udG873BTTD3IY6DPPeM/IU7arKaaQJS4p1sc9QsQDE9olChvA4EbFP2ECNGJrKaTxAoXilmpUcaQrSIJP00f3cCgYA4IxBNuim83SuDqZvXIuNW0koFU/fDVLHFZBkqTgMGEfjvB/MY1Vig1zwJQmrKnXZy66titf98Fff1cdz3tXgbhVtHSve6iSfHzE/vwxbUK5zSbe7CtaKSYRfZsiQBqvqd8yqxX1YaUZpbynmEstk1cnKM64ukR9NIHfZ8iU9ckQKBgQCM76vFmL7j/qEFGH3PnjoLxb0V9fo5awwXlwK5V89WKnZ/W7PQUSf3Oe7ZzZYWhVuIaYpXL+ap4p526ki0ZBK278YENQTAX5eKzZkeGQY1iMZbjiXvrBDCaprhselZsJxbYBC7morYqVeVwo84t2SznCs6htn7WYKRB+6IrN1q5wKBgEuEFoNgkA1i1BWPg+ymuguqhmNprRIpX/graxtXNKogLzG5QpI8vDj8umoeg6RpMMHcK6YE0ZDwmCc0x4teUMjzLjhPjGGHEtncSHDM9WmnYIsj2cMhoyIa7UjqbmlGc0tGxJm6vZFAu745NSTKgDmLa8g+wrEqy2lhEvINXrXF"; String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlbXBq7AaKZxar/wBNlI1yruQtrXsKEcYb7A3S7dRSTaxfPudkLam5+NvKdusivJDIYsHQMA8OwH6EayabDtmcLCHjClRl9IYq/rbXr5UlWgP4tDRfuwdEQqi/PoOW3E6nAivZMNHQF3M+p8ak9bFXFQrsCSqU4lJxlHeNIJGBLY0g9tYo2AV668d4l2S60giO5jDNURYBeMz4pKl0UznvsD46a47YJs8mPr5Irv/H/Toi4tZMIToBz6rJIoX40lWivDtIej9ED885JEUGt/n2n1prk4/eUdfNCg7meCCfevOs2cyF+0xhtkcvd91cSLcOZUQJWwmpfvdARa7Xaq2hwIDAQAB"; System.out.println(privateKey); System.out.println(publicKey); String content = String.valueOf(System.currentTimeMillis()); System.out.println(content); String sign = RsaUtil.genSign(privateKey, content, RsaUtil.SIGN_RSA2, RsaUtil.UTF8); System.out.println(sign); boolean flag = RsaUtil.checkRsa(publicKey, content, sign, RsaUtil.SIGN_RSA2, RsaUtil.UTF8); System.out.println(flag); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/reflect/AsmTest.java
src/test/java/com/wind/reflect/AsmTest.java
package com.wind.reflect; import com.wind.AAA; import org.junit.Test; import org.objectweb.asm.*; import java.io.IOException; /** * @Title: AsmTest * @Package com.wind.reflect * @Description: TODO * @author wind * @date 2018/10/13 9:29 * @version V1.0 */ public class AsmTest { @Test public void read() throws IOException { ClassReader classReader = new ClassReader("com.wind.AAA"); classReader.accept(new ClassVisitor(){ public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { System.out.println("class name:" + name); System.out.println("super class name:" + superName); System.out.println("class version:" + version); System.out.println("class access:" + access); System.out.println("class signature:" + signature); if(interfaces != null && interfaces.length > 0){ for(String str : interfaces){ System.out.println("implemented interface name:" + str); } } } public void visitSource(String source, String debug) { } public void visitOuterClass(String owner, String name, String desc) { } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { System.out.println(desc); return null; } public void visitAttribute(Attribute attribute) { } public void visitInnerClass(String name, String outerName, String innerName, int access) { } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { System.out.println(name + "-" + desc + "-" + signature + "-" + value); return null; } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // System.out.println(name); return null; } public void visitEnd() { System.out.println("-------------end------------"); } }, 0); } @Test public void write() throws IOException { AAA a = new AAA(); a.setCode(1); ClassReader cr = new ClassReader(AAA.class.getName()); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cr.accept(new ClassAdapter(cw){ @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { } @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { if("setCode".equals(name)){ //这里只是简单的比较了方法名字,其实还需要比较方法参数,参数信息在desc中 return cv.visitMethod(access, name + "$1", desc, signature, exceptions); } return cv.visitMethod(access, name, desc, signature, exceptions); } }, 0); //到这里,如果调用cr.toByteArray,生成的字节码中,已经没有execute方法了,而是execute$1 //我们接着需要增加一个execute方法 MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setCode", "()V", null, null); //开始增加代码 mv.visitCode(); //接下来,我们需要把新的execute方法的内容,增加到这个方法中 mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Before execute"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/vanadies/bytecode/example/asm3/ClassWriterAopExample$Foo$1", "execute$1", "()V"); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("End execute"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitInsn(Opcodes.RETURN); //这个地方,最大的操作数栈和最大的本地变量的空间,是自动计算的,是因为构造ClassWriter的时候使用了ClassWriter.COMPUTE_MAXS mv.visitMaxs(0, 0); mv.visitEnd(); //到这里,就完成了execute方法的添加。 //可以把字节码写入到文件,用javap -c,来看下具体的内容 } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/compress/ZipTest.java
src/test/java/com/wind/compress/ZipTest.java
package com.wind.compress; import org.junit.Test; /** * @Title: ZipTest * @Package com.wind.compress * @Description: TODO * @author wind * @date 2019/4/8 10:38 * @version V1.0 */ public class ZipTest { @Test public void testGZip(){ String source = "src/main/resources/image/head.jpg"; String target = "src/main/resources/"; GZipUtil.compress(source, target); GZipUtil.uncompress(target + "head.jpg.gz", target); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/media/Tess4jTest.java
src/test/java/com/wind/media/Tess4jTest.java
package com.wind.media; import com.wind.common.Constants; import org.junit.Test; public class Tess4jTest { @Test public void test(){ /*String path = "src/main/resources/image/text.png"; System.out.println(take(path));*/ String ch = "src/main/resources/image/ch.png"; System.out.println(Tess4jUtil.take(ch, "src/main/resources/tessdata", Constants.CHI_SIM)); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/media/HighGuiTest.java
src/test/java/com/wind/media/HighGuiTest.java
package com.wind.media; import com.wind.media.opencv.v3.HighGuiUtil; import org.junit.Test; public class HighGuiTest { @Test public void test(){ String fileName = "src/main/resources/image/face.jpg"; String destName = "src/main/resources/image/face2.jpg"; HighGuiUtil.drawRect(fileName, destName); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/test/java/com/wind/network/EmailTest.java
src/test/java/com/wind/network/EmailTest.java
package com.wind.network; import org.junit.Test; import javax.activation.DataSource; import javax.activation.FileDataSource; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class EmailTest { @Test public void test(){ Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.host", "smtp.163.com"); String sender = "*********@163.com"; String receiver = "*********@qq.com"; String title = "你好、Hello Mail"; String content = "Hello World!!!"; String username = "*********@163.com"; String password = "*********"; List<DataSource> attachments = new ArrayList<>(); DataSource dataSource1 = new FileDataSource("src/main/resources/image/你好.txt"); DataSource dataSource2 = new FileDataSource("src/main/resources/image/code.png"); attachments.add(dataSource1); attachments.add(dataSource2); // Email email = new Email(props, sender, username, password, receiver, title, content, attachments); // EmailUtil.sendEmail(email); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/ftl/FreeMarker.java
src/main/java/com/wind/ftl/FreeMarker.java
package com.wind.ftl; import java.util.Map; /** * @Title: FreeMarker * @Package com.wind.ftl * @Description: freeMarker实体类描述 * @author wind * @date 2018/10/13 11:02 * @version V1.0 */ public class FreeMarker { /** * 模板文件目录 */ private String cfgDir; /** * 模板文件名 */ private String cfgName; /** * 数据 */ private Map<String, Object> map; /** * 生成文件目录 */ private String fileDir; /** * 生成文件名 */ private String fileName; public String getCfgDir() { return cfgDir; } public void setCfgDir(String cfgDir) { this.cfgDir = cfgDir; } public String getCfgName() { return cfgName; } public void setCfgName(String cfgName) { this.cfgName = cfgName; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public String getFileDir() { return fileDir; } public void setFileDir(String fileDir) { this.fileDir = fileDir; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/ftl/FtlUtil.java
src/main/java/com/wind/ftl/FtlUtil.java
package com.wind.ftl; import com.wind.common.Constants; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.io.*; import java.util.HashMap; import java.util.Map; /** * freeMarker工具生成类 * @author wind */ public class FtlUtil { /** * 生成文件 * @param freeMarker */ public static void genCode(FreeMarker freeMarker){ String fileDir = freeMarker.getFileDir(); String fileName = freeMarker.getFileName(); try( OutputStream fos = new FileOutputStream( new File(fileDir, fileName)); Writer out = new OutputStreamWriter(fos) ) { File dir = new File(fileDir); boolean sign = true; if(!dir.exists()){ sign = dir.mkdirs(); } if(sign){ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File(freeMarker.getCfgDir())); cfg.setDefaultEncoding(Constants.UTF8); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Template temp = cfg.getTemplate(freeMarker.getCfgName()); Map<String, Object> map = freeMarker.getMap(); if(map == null){ map = new HashMap<>(16); } temp.process(map, out); fos.flush(); } } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/xml/XmlUtil.java
src/main/java/com/wind/xml/XmlUtil.java
package com.wind.xml; import com.wind.common.IoUtil; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.*; import java.util.Iterator; import java.util.List; /** * xml解析工具类 */ public class XmlUtil { /** * dom解析xml文件 * @param filePath */ public static void parseXml(String filePath){ //创建SAXReader对象 SAXReader reader = new SAXReader(); try { //读取文件 转换成Document Document document = reader.read(new File(filePath)); //获取根节点元素对象 Element root = document.getRootElement(); long s = System.currentTimeMillis(); getChildNodes(root); long e = System.currentTimeMillis(); System.out.println(root.getName() + "节点元素遍历结束,耗时共:" + (e - s) + " ms"); } catch (DocumentException e) { e.printStackTrace(); } } /** * 遍历节点下的所有子节点和属性 * @param ele 元素节点 */ private static void getChildNodes(Element ele){ String eleName = ele.getName(); System.out.println("开始遍历当前:" + eleName + "节点元素"); List<Attribute> attributes = ele.attributes(); for(Attribute attr : attributes){ System.out.println("name=" + attr.getName() + ",value=" + attr.getValue()); } //同时迭代当前节点下面的所有子节点 //使用递归 Iterator<Element> iterator = ele.elementIterator(); if(!iterator.hasNext()){ String text = ele.getTextTrim(); System.out.println("text=" + text); } while(iterator.hasNext()){ Element e = iterator.next(); getChildNodes(e); } } /** * sax解析xml配置文件 * @param filePath */ public static void parseHandler(String filePath){ //创建SAXReader对象 SAXReader reader = new SAXReader(); reader.setDefaultHandler(new ElementHandler(){ @Override public void onStart(ElementPath elementPath) { } @Override public void onEnd(ElementPath elementPath) { //获得当前节点 Element e = elementPath.getCurrent(); System.out.println(e.getName()); //记得从内存中移去 e.detach(); } }); try { reader.read(new BufferedInputStream(new FileInputStream(new File(filePath)))); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void writeXml(String filePath, Document doc){ // 设置XML文档格式 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1 outputFormat.setEncoding("UTF-8"); //是否生产xml头 outputFormat.setSuppressDeclaration(true); //设置是否缩进 outputFormat.setIndent(true); //以四个空格方式实现缩进 outputFormat.setIndent(" "); //设置是否换行 outputFormat.setNewlines(true); XMLWriter out = null; try{ out = new XMLWriter(new FileWriter(new File(filePath)), outputFormat); out.write(doc); }catch(IOException e){ e.printStackTrace(); } finally{ IoUtil.close(out); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/json/gson/GsonUtil.java
src/main/java/com/wind/json/gson/GsonUtil.java
package com.wind.json.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * @package com.wind.json.gson * @className GsonUtil 工具类 * @note gson * @author wind * @date 2018/7/28 23:46 */ public class GsonUtil { private static Logger logger = LoggerFactory.getLogger(GsonUtil.class); private static Gson gson; /** * 实例化 gson * @return */ private static Gson getInstance(){ if(gson == null){ gson = new Gson(); } return gson; } /** * java对象序列化为json字符串 * @param obj * @return */ public static String toJson(Object obj){ return getInstance().toJson(obj); } /** * 格式化json字符串 * @param jsonStr * @return */ public static String format(String jsonStr){ JsonParser parser = new JsonParser(); JsonElement ele = parser.parse(jsonStr); return new GsonBuilder().setPrettyPrinting().create().toJson(ele); } /** * 判断是否是json字符串 * @param jsonStr * @return */ public static boolean isJson(String jsonStr){ boolean jsonFlag; try { new JsonParser().parse(jsonStr).getAsJsonObject(); jsonFlag = true; } catch (Exception e) { logger.warn("json string error:" + jsonStr, e); jsonFlag = false; } return jsonFlag; } /** * json字符串反序列化为java对象 * @param jsonStr * @param c * @param <T> * @return */ public static <T> T toBean(String jsonStr, Class<T> c){ return getInstance().fromJson(jsonStr, c); } /** * json数组字符串反序列化为java List * @param jsonStr * @param typeToken * @param <T> * @return */ public static <T> List<T> toList(String jsonStr, TypeToken<List<T>> typeToken){ return getInstance().fromJson(jsonStr, typeToken.getType()); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/json/fastjson/JsonUtil.java
src/main/java/com/wind/json/fastjson/JsonUtil.java
package com.wind.json.fastjson; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import java.util.List; /** * @package com.wind.json.fastjson * @className JsonUtil * @note fastjson * @author wind * @date 2018/7/29 0:20 */ public class JsonUtil { /** * java对象序列化json字符串 * @param obj * @param flag true 将对象转换成格式化的json, false 将对象转换成非格式化的json * @return */ public static String toJson(Object obj, boolean flag){ return JSON.toJSONString(obj,flag); } /** * json字符串转bean对象 * @param jsonStr * @param <T> * @return */ public static <T> T toBean(String jsonStr, Class<T> c) { return JSON.parseObject(jsonStr, c); } /** * json字符串转list数组 * @param jsonStr * @return */ public static <T> List<T> toList(String jsonStr, TypeReference<List<T>> jsonTypeReference){ return JSON.parseObject(jsonStr, jsonTypeReference); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/json/jackson/JsonUtil.java
src/main/java/com/wind/json/jackson/JsonUtil.java
package com.wind.json.jackson; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; /** * @package com.wind.json.jackson * @className JsonUtil * @note jackson * @author wind * @date 2018/7/29 0:23 */ public class JsonUtil { private static Logger logger = LoggerFactory.getLogger(JsonUtil.class); private static ObjectMapper mapper; /** * 获取对象 */ public static ObjectMapper getInstance() { if (mapper == null){ mapper = new ObjectMapper(); // 允许单引号、允许不带引号的字段名称 mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSSZ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); // 空值处理为空串 mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){ @Override public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException{ jsonGenerator.writeString(""); } }); // 设置时区 getTimeZone("GMT+8:00") mapper.setTimeZone(TimeZone.getDefault()); } return mapper; } /** * json字符串转list数组 * @param jsonStr * @return */ public static <T> List<T> toList(String jsonStr, TypeReference<List<T>> jsonTypeReference){ try { if(jsonStr != null){ return getInstance().readValue(jsonStr, jsonTypeReference); } } catch (IOException e) { logger.warn("parse json string error:" + jsonStr, e); } return new ArrayList<>(); } /** * json字符串转bean对象 * @param jsonStr * @param <T> * @return */ public static <T> T toBean(String jsonStr, Class<T> c) { try { if(jsonStr != null){ return getInstance().readValue(jsonStr, c); } } catch (IOException e) { logger.warn("parse json string error:" + jsonStr, e); } return null; } /** * java对象序列化json字符串 * @param obj * @return */ public static String toJson(Object obj){ String result = null; try { result = getInstance().writeValueAsString(obj); } catch (JsonProcessingException e) { logger.warn("write to json string error:" + obj, e); } return result; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/json/jsonlib/JsonUtil.java
src/main/java/com/wind/json/jsonlib/JsonUtil.java
package com.wind.json.jsonlib; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; /** * @package com.wind.json.jsonlib * @className JsonUtil * @note json-lib * @author wind * @date 2018/7/29 0:24 */ public class JsonUtil { private static Logger logger = LoggerFactory.getLogger(JsonUtil.class); /** * java对象序列化返回json字符串 * @param obj * @return */ public static String toJson(Object obj){ try { if(obj instanceof Collection){ return JSONArray.fromObject(obj).toString(); }else{ return JSONObject.fromObject(obj).toString(); } } catch (Exception e) { logger.warn("write to json string error:" + obj, e); return null; } } /** * json字符串反序列化转换成java bean对象 * @param json * @param c * @return */ public static <T> T toBean(String json, Class<T> c){ JSONObject jsonObject = JSONObject.fromObject(json); Object obj = JSONObject.toBean(jsonObject, c); return (T)obj; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/ProcessUtil.java
src/main/java/com/wind/common/ProcessUtil.java
package com.wind.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * @Title: ProcessUtil * @Package com.wind.common.process * @Description: 进程执行工具类 * @author wind * @date 2018/10/11 9:23 * @version V1.0 */ public class ProcessUtil { /** * 获取进程命令执行打印出来的信息 * @return */ public static List<String> exec(String command){ Runtime r = Runtime.getRuntime(); BufferedReader in = null; Process pro = null; List<String> lists = new ArrayList<>(); try { pro = r.exec(command); in = new BufferedReader(new InputStreamReader(pro.getInputStream())); String line; while((line = in.readLine()) != null){ lists.add(line); } } catch (IOException e) { lists = null; e.printStackTrace(); } finally { if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(pro != null){ pro.destroy(); } } return lists; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/StringUtil.java
src/main/java/com/wind/common/StringUtil.java
package com.wind.common; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.StringTokenizer; /** * 字符串工具类 * @author wind */ public class StringUtil { /** * 判断字符串是否为null或空字符串 * @param str * @return */ public static boolean isNotBlank(String str){ return str != null && !"".equals(str.trim()); } /** * url编码 * @param str * @return */ public static String encodeUrl(String str){ String s = null; try { s = URLEncoder.encode(str, Constants.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return s; } /** * url解码 * @param str * @return */ public static String decodeUrl(String str){ String s = null; try { s = URLDecoder.decode(str, Constants.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return s; } /** * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的 * @param str * @param sign * @return */ public static String[] split(String str, String sign){ if(str == null){ return new String[]{}; } StringTokenizer token = new StringTokenizer(str,sign); String[] strArr = new String[token.countTokens()]; int i = 0; while(token.hasMoreElements()){ strArr[i] = token.nextElement().toString(); i++; } return strArr; } /** * 字符串拼接 * @param sign * @param strArr * @return */ public static String joinStr(String sign, String... strArr){ Optional<String> optional = Arrays.stream(strArr).filter(Objects::nonNull ).reduce((a, b) -> a + sign + b); return optional.orElse(""); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/BeanUtil.java
src/main/java/com/wind/common/BeanUtil.java
package com.wind.common; import org.springframework.cglib.beans.BeanCopier; /** * @Title: BeanUtil * @Package com.wind.common * @Description: 字节码java bean拷贝, 位于spring core包内 * @author wind * @date 2018/10/13 11:08 * @version V1.0 */ public class BeanUtil { /** * 对象拷贝复制 * @param source * @param target */ public static void copy(Object source, Object target){ if(source != null && target != null){ BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false); copier.copy(source, target, null); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/RegexUtil.java
src/main/java/com/wind/common/RegexUtil.java
package com.wind.common; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 正则表达式工具类 * @author wind */ public class RegexUtil { private final static String PHONE_NUMBER = "^(13[0-9]|14[579]|15[0-3,5-9]|16[0-9]|17[0135678]|18[0-9]|19[89])\\d{8}$"; private final static String EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; private final static String HK_PHONE_NUMBER = "^(5|6|8|9)\\d{7}$"; private final static String POSITIVE_INTEGER = "^\\d+$"; private final static String MONEY = "^(\\d+(?:\\.\\d+)?)$"; private final static String ID_CARD = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{4}$"; /** * 校验邮箱 * @param str * @return */ public static boolean checkEmail(String str){ return checkStr(EMAIL, str); } /** * 校验身份证 * @param str * @return */ public static boolean checkIdCard(String str){ return checkStr(ID_CARD, str); } /** * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 * * @param str * @return */ public static boolean checkPhone(String str){ return checkStr(PHONE_NUMBER, str); } /** * 校验香港 * @param str * @return */ public static boolean checkHKPhone(String str){ return checkStr(HK_PHONE_NUMBER, str); } /** * 校验正整数 * @param str * @return */ public static boolean checkPlusInteger(String str){ return checkStr(POSITIVE_INTEGER, str); } /** * 校验money * @param str * @return */ public static boolean checkMoney(String str){ return checkStr(MONEY, str); } /** * * @param regex * @param str * @return */ private static boolean checkStr(String regex, String str){ if(regex == null || str == null){ return false; } Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); return m.matches(); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/NumberUtil.java
src/main/java/com/wind/common/NumberUtil.java
package com.wind.common; import java.math.BigDecimal; /** * @Title: NumberUtil * @Package com.wind.common.math * @Description: 数字工具类 * @author wind * @date 2018/10/11 9:23 * @version V1.0 */ public class NumberUtil { /** * 获取double * @param d double数据 * @param newScale 保留几位小数点 * @return */ public static double getDouble(double d, int newScale){ BigDecimal b = BigDecimal.valueOf(d); return b.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 获取百分比 * @param free * @param total * @return */ public static double getPercent(long free, long total){ return getDouble((1 - free * 1.0 / total) * 100, 2); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/PropUtil.java
src/main/java/com/wind/common/PropUtil.java
package com.wind.common; import java.io.*; import java.util.*; /** * @Title: PropUtil * @Package com.wind.common * @Description: 解析properties文件工具类 * @author wind * @date 2018/10/11 9:30 * @version V1.0 */ public class PropUtil { /** * 解析properties文件 * @param filePath * @return */ public static Properties getProp(String filePath){ try { InputStream in = new BufferedInputStream(new FileInputStream(filePath)); return getProp(in); } catch (FileNotFoundException e) { e.printStackTrace(); } return new Properties(); } /** * 解析properties文件 * @param in * @return */ public static Properties getProp(InputStream in){ Properties props = new Properties(); try { props.load(in); } catch (IOException e) { e.printStackTrace(); } finally { if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return props; } /** * 写入properties信息 * @param filepath * @param map */ public static void setProp(String filepath, Map<String, String> map){ Properties props = getProp(filepath); OutputStream fos = null; try { fos = new FileOutputStream(filepath); map.forEach(props::setProperty); props.store(fos, ""); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/IoUtil.java
src/main/java/com/wind/common/IoUtil.java
package com.wind.common; import org.dom4j.io.XMLWriter; import javax.imageio.stream.ImageInputStream; import java.io.*; import java.util.Arrays; /** * @Title: IoUtil * @Package com.wind.common * @Description: io工具类 * @author wind * @date 2018/10/11 9:28 * @version V1.0 */ public class IoUtil { /** * 关闭字节输入流 * @param in */ public static void close(InputStream in){ if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭字节输入输出流 * @param in * @param out */ public static void close(InputStream in, OutputStream out){ close(in); close(out); } /** * 关闭字符输入流 * @param reader */ public static void close(Reader reader){ if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭字符输出流 * @param writer */ public static void close(Writer writer){ if(writer != null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭image输入流 * @param iis */ public static void close(ImageInputStream iis){ if(iis != null){ try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 批量关闭字节输入流 * @param ins */ public static void close(InputStream... ins){ Arrays.asList(ins).parallelStream().forEach(IoUtil::close); } /** * 批量关闭字节输出流 * @param outs */ public static void close(OutputStream... outs){ Arrays.asList(outs).parallelStream().forEach(IoUtil::close); } /** * 关闭字节输出流 * @param out */ public static void close(OutputStream out){ if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭XMLWriter输出流 * @param out */ public static void close(XMLWriter out){ if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/DateUtil.java
src/main/java/com/wind/common/DateUtil.java
package com.wind.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @Title: DateUtil * @Package com.wind.common * @Description: 日期工具类集合 * @author wind * @date 2018/10/11 9:24 * @version V1.0 */ public class DateUtil { private static Logger logger = LoggerFactory.getLogger(DateUtil.class); public final static String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; public final static String DATE_STR = "yyyy-MM-dd"; public static final String DATETIME_MS = "yyyyMMddHHmmssSSS"; public static final String DATE_SLASH_STR = "yyyy/MM/dd"; public final static int SECOND = 1000; public final static int MINUTE = 60 * SECOND; public final static int HOUR = 60 * MINUTE; public final static int DAY = 24 * HOUR; /** * 格式化字符串日期,转换成Date * @param date 字符串日期 * @param pattern 默认 yyyy-MM-dd HH:mm:ss * @return */ public static Date parse(String date, String pattern){ String p = pattern == null ? DATE_TIME : pattern; DateFormat dateFormat = new SimpleDateFormat(p); Date d = null; try { d = dateFormat.parse(date); } catch (ParseException e) { logger.warn("parse date string error, date:" + date + ", pattern:" + p, e); } return d; } /** * 日期按照指定格式转换成字符串 * @param date 日期 * @param pattern 默认 yyyy-MM-dd HH:mm:ss * @return */ public static String format(Date date, String pattern){ DateFormat dateFormat = new SimpleDateFormat(pattern == null ? DATE_TIME : pattern); return dateFormat.format(date); } /** * 获取日期 * @param date * @return */ public static Date getDate(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } /** * 获取星期 * @param date * @return */ public static int getWeek(Date date){ Calendar c = Calendar.getInstance(); c.setTime(date); return c.get(Calendar.DAY_OF_WEEK) - 1; } /** * 返回当前时间day天之后(day>0)或day天之前(day<0)的时间 * @param date 日期 * @param day * @return */ public static Date addDay(Date date, int day){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } /** * 返回当前时间month个月之后(month>0)或month个月之前(month<0)的时间 * * @param date * @param month * @return */ public static Date addMonth(Date date, int month) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, month); return calendar.getTime(); } /** * 返回当前时间year年之后(year>0)或year年之前(year<0)的时间 * * @param date * @param year * @return */ public static Date addYear(Date date, int year) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, year); return calendar.getTime(); } /** * 计算两个日期之间的天数差 * @param start * @param end * @return */ public static long daysBetween(Date start, Date end){ if(start == null || end == null){ logger.error("The date must not be null. start:" + start + ", end:" + end); return 0; } long endTime = end.getTime(); long startTime = start.getTime(); return (endTime - startTime) / (DAY); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/IdGenUtil.java
src/main/java/com/wind/common/IdGenUtil.java
package com.wind.common; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; /** * @Title: IdGenUtil * @Package com.wind.common * @Description: id主键生成工具 * @author wind * @date 2018/10/11 9:41 * @version V1.0 */ public class IdGenUtil { private static AtomicLong next = new AtomicLong(1); /** * 获取32位的UUID * @return */ public static String getUUID(){ return UUID.randomUUID().toString().replace(Constants.MINUS_STR, Constants.BLANK_STR); } /** * 生成一个13位数的唯一id * @return */ public static long getPKNum(){ return next.getAndIncrement() + System.currentTimeMillis(); } /** * 生成一个13位数的唯一id * @return */ public static String getPKStr(){ return String.valueOf(getPKNum()); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/common/Constants.java
src/main/java/com/wind/common/Constants.java
package com.wind.common; import java.io.File; /** * 常量字符集合 * @author wind */ public interface Constants { /**********************************************分隔符常量************************************************/ String POINT_STR = "."; String BLANK_STR = ""; String SPACE_STR = " "; String NEWLINE_STR = "\n"; String SYS_SEPARATOR = File.separator; String FILE_SEPARATOR = "/"; String BRACKET_LEFT = "["; String BRACKET_RIGHT = "]"; String UNDERLINE = "_"; String MINUS_STR = "-"; /**********************************************编码格式************************************************/ String UTF8 = "UTF-8"; /**********************************************文件后缀************************************************/ String EXCEL_XLS = ".xls"; String EXCEL_XLSX = ".xlsx"; String IMAGE_PNG = "png"; String IMAGE_JPG = "jpg"; String FILE_ZIP = ".zip"; String FILE_GZ = ".gz"; /**********************************************io流************************************************/ int BUFFER_1024 = 1024; int BUFFER_512 = 512; String USER_DIR = "user.dir"; /**********************************************tesseract for java语言字库************************************************/ String ENG = "eng"; String CHI_SIM = "chi_sim"; /**********************************************opencv************************************************/ String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/reflect/ReflectUtil.java
src/main/java/com/wind/reflect/ReflectUtil.java
package com.wind.reflect; import java.lang.reflect.Field; import java.util.*; /** * @Title: ReflectUtil * @Package com.wind.reflect * @Description: 类反射工具类 * @author wind * @date 2018/10/11 9:23 * @version V1.0 */ public class ReflectUtil { /** * 获取类成员属性 * @param c * @param flag false表示只获取当前类的成员属性 true表示获取父类的私有成员属性 * @return */ public static List<Field> getFields(Class c, boolean flag){ List<Field> fields = new ArrayList<>(); if(c == null){ return fields; } fields.addAll(Arrays.asList(c.getDeclaredFields())); if(flag){ Class supperClass = c.getSuperclass(); if(!Object.class.equals(supperClass)){ fields.addAll(getFields(supperClass, true)); } } return fields; } /** * 类成员属性赋值 * @param instance 实例 * @param name 属性名称 * @param value 属性值 */ public static void setField(Object instance, String name, Object value){ if(instance != null && !(instance instanceof Class)){ try { Field field = instance.getClass().getDeclaredField(name); setField(instance, field, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } } } /** * 类成员属性赋值 * @param instance 实例 * @param field 属性Field实例 * @param value 属性值 */ public static void setField(Object instance, Field field, Object value){ if(instance != null && !(instance instanceof Class)){ if(value == null || field == null){ return; } try { // 参数值为true,禁止访问控制检查 Class<?> clazz = field.getType(); field.setAccessible(true); String valStr = value.toString(); if(clazz.equals(Integer.class) || clazz.equals(int.class)){ field.set(instance, Integer.valueOf(valStr)); }else if(clazz.equals(Double.class) || clazz.equals(double.class)){ field.set(instance, Double.valueOf(valStr)); }else if(clazz.equals(Float.class) || clazz.equals(float.class)){ field.set(instance, Float.valueOf(valStr)); }else if(clazz.equals(Short.class) || clazz.equals(short.class)){ field.set(instance, Short.valueOf(valStr)); }else if(clazz.equals(Boolean.class) || clazz.equals(boolean.class)){ field.set(instance, Boolean.valueOf(valStr)); }else if(clazz.equals(Character.class) || clazz.equals(char.class)){ if(valStr.length() == 1){ field.set(instance, valStr.charAt(0)); } }else if(clazz.equals(String.class)){ field.set(instance, valStr); } } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/compress/GZipUtil.java
src/main/java/com/wind/compress/GZipUtil.java
package com.wind.compress; import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * @Title: GZipUtil * @Package com.wind.compress * @Description: GZIP压缩工具类 * @author wind * @date 2018/10/12 17:47 * @version V1.0 */ public class GZipUtil { /** * 文件压缩 * @param source 待压缩文件路径 * @param target */ public static void compress(String source, String target){ compress(new File(source), target); } /** * 文件压缩 * @param source File 待压缩 * @param target */ public static void compress(File source, String target){ FileInputStream fis = null; try { fis = new FileInputStream(source); File targetFile = new File(target); if(targetFile.isFile()){ System.err.println("target不能是文件,否则压缩失败"); return; } target += (source.getName() + Constants.FILE_GZ); FileOutputStream fos = new FileOutputStream(target); compress(fis, fos); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { IoUtil.close(fis); } } /** * 文件解压缩 * @param source 待压缩文件路径 * @param target */ public static void uncompress(String source, String target){ uncompress(new File(source), target); } /** * 文件解压缩 * @param source File 待解压缩 * @param target */ public static void uncompress(File source, String target){ FileInputStream fis = null; try { fis = new FileInputStream(source); target += source.getName().replace(Constants.FILE_GZ, ""); FileOutputStream fos = new FileOutputStream(target); uncompress(fis, fos); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { IoUtil.close(fis); } } /** * 文件流压缩 * @param in * @param out */ private static void compress(InputStream in, OutputStream out){ try(GZIPOutputStream gos = new GZIPOutputStream(out)) { int count; byte[] data = new byte[Constants.BUFFER_1024]; while ((count = in.read(data, 0, data.length)) != -1) { gos.write(data, 0, count); } gos.finish(); gos.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 文件流解压缩 * @param in * @param out */ private static void uncompress(InputStream in, OutputStream out){ try(GZIPInputStream gis = new GZIPInputStream(in)) { int count; byte[] data = new byte[Constants.BUFFER_1024]; while ((count = gis.read(data, 0, Constants.BUFFER_1024)) != -1) { out.write(data, 0, count); } } catch (IOException e) { e.printStackTrace(); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/compress/ZipUtil.java
src/main/java/com/wind/compress/ZipUtil.java
package com.wind.compress; import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * 通过Java的Zip输入输出流实现压缩和解压文件 * @author wind */ public class ZipUtil { /** * 压缩文件 * 若压缩文件,请指定目标文件目录和目标文件名 * @param source 源文件路径 * @param target 目标文件路径 */ public static void zip(String source, String target) { File sourceFile = new File(source); if (sourceFile.exists()) { File targetFile = new File(target); if(targetFile.isDirectory()){ String zipName = sourceFile.getName() + Constants.FILE_ZIP; targetFile = new File(target + zipName); } if (targetFile.exists()) { targetFile.delete(); // 删除旧的文件 } FileOutputStream fos = null; try { fos = new FileOutputStream(targetFile); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)); // 添加对应的文件Entry addEntry("", sourceFile, zos); } catch (IOException e) { e.printStackTrace(); } finally { IoUtil.close(fos); } } } /** * 扫描添加文件Entry * * @param base 基路径 * @param source 源文件 * @param zos Zip文件输出流 * @throws IOException */ private static void addEntry(String base, File source, ZipOutputStream zos){ // 按目录分级,形如:aaa/bbb.txt String entry = base + source.getName(); if (source.isDirectory()) { File[] files = source.listFiles(); if(files != null){ for (File file : files) { // 递归列出目录下的所有文件,添加文件Entry addEntry(entry + "/", file, zos); } } } else { FileInputStream fis = null; BufferedInputStream bis = null; try { byte[] buffer = new byte[1024 * 10]; fis = new FileInputStream(source); bis = new BufferedInputStream(fis, buffer.length); int read; zos.putNextEntry(new ZipEntry(entry)); while ((read = bis.read(buffer, 0, buffer.length)) != -1) { zos.write(buffer, 0, read); } zos.closeEntry(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IoUtil.close(fis, bis); } } } /** * 解压文件 * @param filePath 压缩文件路径 * @param targetPath 解压缩路径 */ public static void unzip(String filePath, String targetPath) { // TODO java.io.EOFException: Unexpected end of ZLIB input stream该异常目前未解决,不过不影响文件解压 File source = new File(filePath); if (source.exists()) { ZipInputStream zis = null; BufferedOutputStream bos = null; try { zis = new ZipInputStream(new FileInputStream(source)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null && !entry.isDirectory()) { File target = new File(targetPath, entry.getName()); if (!target.getParentFile().exists()) { // 创建文件父目录 target.getParentFile().mkdirs(); } // 写入文件 bos = new BufferedOutputStream(new FileOutputStream(target)); byte[] buffer = new byte[Constants.BUFFER_512]; while (true) { int len = zis.read(buffer); if(len == -1){ break; } bos.write(buffer, 0, len); } bos.flush(); } zis.closeEntry(); } catch (IOException e) { e.printStackTrace(); } finally { IoUtil.close(zis, bos); } } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/ImageUtil.java
src/main/java/com/wind/media/ImageUtil.java
package com.wind.media; import com.wind.common.Constants; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; /** * opencv图像处理工具类 * @author wind */ public class ImageUtil { /** * 读取图片,获取BufferedImage对象 * @param fileName * @return */ public static BufferedImage getImage(String fileName){ File picture = new File(fileName); BufferedImage sourceImg = null; try { sourceImg = ImageIO.read(new FileInputStream(picture)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sourceImg; } /** * 读取图片,获取ImageReader对象 * @param fileName * @return */ public static ImageReader getImageReader(String fileName){ if(fileName != null){ String suffix = ""; for(String str : ImageIO.getReaderFormatNames()){ if(fileName.lastIndexOf(Constants.POINT_STR + str) > 0){ suffix = str; } } if(!"".equals(suffix)){ try { // 将FileInputStream 转换为ImageInputStream ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(fileName)); // 根据图片类型获取该种类型的ImageReader Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(suffix); ImageReader reader = readers.next(); reader.setInput(iis, true); return reader; } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 图片截取 Graphic通过画布绘画 * @param image 源图片 * @param rect 待截取区域的坐标位置 */ public static BufferedImage cutImage(File image, Rectangle rect) { if (image.exists() && rect != null) { // 用ImageIO读取字节流 BufferedImage bufferedImage = getImage(image.getAbsolutePath()); int width = rect.width; int height = rect.height; int x = rect.x; int y = rect.y; BufferedImage dest = new BufferedImage(width, height, Transparency.TRANSLUCENT); Graphics g = dest.getGraphics(); g.drawImage(bufferedImage, 0, 0, width, height, x, y, x + width, height + y, null); return dest; } return null; } /** * 图片截取 ImageReader截取 速度比Graphic通过画布绘画快很多 * @param image 源图片 * @param rect 待截取区域的坐标位置 * @return */ public static BufferedImage cutImage2(File image, Rectangle rect) { if (image.exists() && rect != null) { BufferedImage bi = null; try { ImageReader reader = getImageReader(image.getAbsolutePath()); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect); bi = reader.read(0, param); } catch (IOException e) { e.printStackTrace(); } return bi; } return null; } /** * BufferedImage生成目标图片 * @param destImage * @param bufferedImage */ public static void writeImage(File destImage, BufferedImage bufferedImage){ try { ImageIO.write(bufferedImage, Constants.IMAGE_PNG, destImage); } catch (IOException e) { e.printStackTrace(); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/Tess4jUtil.java
src/main/java/com/wind/media/Tess4jUtil.java
package com.wind.media; import com.wind.common.Constants; import net.sourceforge.tess4j.ITesseract; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.TesseractException; import net.sourceforge.tess4j.util.LoadLibs; import java.io.File; /** * @Title: Tess4jUtil * @Package com.wind.image.ocr.tesseract * @Description: tesseract for java, ocr(Optical Character Recognition,光学字符识别) * @author huanghy * @date 2018/10/12 18:28 * @version V1.0 */ public class Tess4jUtil { /** * 从图片中提取文字,默认设置英文字库,使用classpath目录下的训练库 * @param path * @return */ public static String take(String path){ // JNA Interface Mapping ITesseract instance = new Tesseract(); // JNA Direct Mapping // ITesseract instance = new Tesseract1(); File imageFile = new File(path); //In case you don't have your own tessdata, let it also be extracted for you //这样就能使用classpath目录下的训练库了 File tessDataFolder = LoadLibs.extractTessResources("tessdata"); //Set the tessdata path instance.setDatapath(tessDataFolder.getAbsolutePath()); //英文库识别数字比较准确 instance.setLanguage(Constants.ENG); return getOCRText(instance, imageFile); } /** * 从图片中提取文字 * @param path * @param dataPath * @param language * @return */ public static String take(String path, String dataPath, String language){ File imageFile = new File(path); ITesseract instance = new Tesseract(); instance.setDatapath(dataPath); //英文库识别数字比较准确 instance.setLanguage(language); return getOCRText(instance, imageFile); } /** * 识别图片文件中的文字 * @param instance * @param imageFile * @return */ private static String getOCRText(ITesseract instance, File imageFile){ String result = null; try { result = instance.doOCR(imageFile); } catch (TesseractException e) { e.printStackTrace(); } return result; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/code/QrCodeUtil.java
src/main/java/com/wind/media/code/QrCodeUtil.java
package com.wind.media.code; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; import com.wind.common.Constants; import com.wind.media.ImageUtil; import jp.sourceforge.qrcode.QRCodeDecoder; import jp.sourceforge.qrcode.data.QRCodeImage; import jp.sourceforge.qrcode.exception.DecodingFailedException; /** * @Title: QrCodeUtil * @Package com.wind.media * @Description: QrCode工具类 * @author wind * @date 2018/10/12 19:08 * @version V1.0 */ public class QrCodeUtil { /** * 获取二维码输出内容 * @param content * version 共有版本号1-40 * @return */ private static boolean[][] getCode(String content){ boolean[][] result = null; Qrcode qrcode = new Qrcode(); /* *设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少, *但对二维码清晰度的要求越小 */ qrcode.setQrcodeErrorCorrect('M'); //编码模式:Numeric 数字, Alphanumeric 英文字母,Binary 二进制,Kanji 汉字(第一个大写字母表示) qrcode.setQrcodeEncodeMode('B'); /* 二维码的版本号:也象征着二维码的信息容量;二维码可以看成一个黑白方格矩阵,版本不同,矩阵长宽方向方格的总数量分别不同。 1-40总共40个版本,版本1为21*21矩阵,版本每增1,二维码的两个边长都增4; 版本2 为25x25模块,最高版本为是40,是177*177的矩阵; */ qrcode.setQrcodeVersion(7); try { byte[] contentBytes = content.getBytes("utf-8"); if (contentBytes.length > 0 && contentBytes.length < 120) { result = qrcode.calQrcode(contentBytes); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } /** * BufferedImage加载二维码输出内容并获取BufferedImage对象 * @param content * @param logo 若为null,则表示不带logo,否则输入logo路径 * @return */ public static BufferedImage getImage(String content, String logo){ boolean[][] codeOut = getCode(content); BufferedImage img = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB); Graphics2D gs = img.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 140, 140); // 设定图像颜色> BLACK gs.setColor(Color.BLACK); // 设置偏移量 不设置可能导致解析出错 int off = 2; // 输出内容> 二维码 for (int i = 0; i < codeOut.length; i++) { for (int j = 0; j < codeOut.length; j++) { if (codeOut[j][i]) { gs.fillRect(j * 3 + off, i * 3 + off, 3, 3); } } } if(logo != null){ Image image = null; try { //实例化一个Image对象。 image = ImageIO.read(new File(logo)); } catch (IOException e) { e.printStackTrace(); } gs.drawImage(image, 55, 55, 30, 30, null); } gs.dispose(); img.flush(); return img; } /** * 生成png类型的二维码 * @param path 生成二维码图片路径 * @param img */ public static void genCode(String path, BufferedImage img){ ImageUtil.writeImage(new File(path), img); } /** * 解析二维码 * @param imgPath * @return */ public static String parseCode(String imgPath) { // QRCode 二维码图片的文件 File imageFile = new File(imgPath); String decodedData = null; try { final BufferedImage img = ImageIO.read(imageFile); QRCodeDecoder decoder = new QRCodeDecoder(); QRCodeImage qrCodeImage = new QRCodeImage() { @Override public int getWidth() { return img.getWidth(); } @Override public int getHeight() { return img.getHeight(); } @Override public int getPixel(int x, int y) { return img.getRGB(x, y); } }; decodedData = new String(decoder.decode(qrCodeImage), Constants.UTF8); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); } catch (DecodingFailedException dfe) { System.out.println("Error: " + dfe.getMessage()); dfe.printStackTrace(); } return decodedData; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/code/ZxingUtil.java
src/main/java/com/wind/media/code/ZxingUtil.java
package com.wind.media.code; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.wind.common.Constants; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; /** * @Title: ZxingUtil * @Package com.wind.media * @Description: google zxing二维码工具类 * @author wind * @date 2018/9/15 15:29 * @version V1.0 */ public class ZxingUtil { /** * 设置二维码的参数 * @param content * @param width * @param height * @return */ private static BitMatrix getBitMatrix(String content, int width, int height){ /** * 设置二维码的参数 */ BitMatrix bitMatrix = null; try { Map<EncodeHintType, Object> hints = new HashMap<>(3); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); hints.put(EncodeHintType.CHARACTER_SET, Constants.UTF8); //设置白边 hints.put(EncodeHintType.MARGIN, 1); // 生成矩阵 bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,hints); } catch (Exception e) { e.printStackTrace(); } return bitMatrix; } /** * 生成指定目标文件的二维码 * @param content 内容 * @param width 宽度 * @param height 高度 * @param target 图片文件路径 * @param imageType 图片类型 */ public static void genCode(String content, int width, int height, String imageType, String target){ // 生成矩阵 BitMatrix bitMatrix = getBitMatrix(content, width, height); genCode(bitMatrix, imageType, target); } /** * 根据bitMatrix生成二维码 * @param bitMatrix * @param target * @param imageType */ public static void genCode(BitMatrix bitMatrix, String imageType, String target){ try { Path path = FileSystems.getDefault().getPath(target); // 输出图像 MatrixToImageWriter.writeToPath(bitMatrix, imageType, path); } catch (IOException e) { e.printStackTrace(); } } /** * 生成正方形二维码 * @param content 内容 * @param length 边长 * @param target 图片文件路径 * @param imageType 图片类型 */ public static void genCode(String content, int length, String imageType, String target){ genCode(content, length, length, imageType, target); } /** * 添加居中logo * @param content * @param imageType 图片类型 * @param logo logo路径 * @param logoLength * @param target 目标路径 */ public static void genCode(String content, int length, String imageType, String logo, int logoLength, String target){ BitMatrix matrix = getBitMatrix(content, length, length); File logoFile = new File(logo); if(!logoFile.exists()){ genCode(matrix, target, imageType); }else{ int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage codeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < length; x++) { for (int y = 0; y < length; y++) { codeImage.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } Graphics2D g = codeImage.createGraphics(); //读取Logo图片 try { BufferedImage logoImage = ImageIO.read(logoFile); //logo放在中心 int x = (length - logoLength) / 2; int y = (length - logoLength) / 2; g.drawImage(logoImage, x, y, logoLength, logoLength, null); g.dispose(); codeImage.flush(); logoImage.flush(); ImageIO.write(codeImage, imageType, new File(target)); } catch (IOException e) { e.printStackTrace(); } } } /** * 解析二维码 * @param filePath */ public static String parseCode(String filePath){ BufferedImage image; try { image = ImageIO.read(new File(filePath)); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map<DecodeHintType, Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, Constants.UTF8); // 对图像进行解码 Result result = new MultiFormatReader().decode(binaryBitmap, hints); return result.getText(); } catch (IOException e) { e.printStackTrace(); } catch (NotFoundException e) { e.printStackTrace(); } return ""; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/ffmpeg/AudioUtil.java
src/main/java/com/wind/media/ffmpeg/AudioUtil.java
package com.wind.media.ffmpeg; import org.bytedeco.javacv.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @Title: AudioUtil * @Package com.wind.media * @Description: 音频工具类 * @author wind * @date 2018/9/15 15:28 * @version V1.0 */ public class AudioUtil { private static Logger logger = LoggerFactory.getLogger(AudioUtil.class); /** * 音频格式转换 * @param inputFile -导入音频文件 * @param outputFile -导出音频文件 * @param audioCodec -音频编码 * @param sampleRate -音频采样率 * @param audioBitrate -音频比特率 */ public static void convert(String inputFile, String outputFile, int audioCodec, int sampleRate, int audioBitrate, int audioChannels) { Frame audioSamples; // 音频录制(输出地址,音频通道) FFmpegFrameRecorder recorder; //抓取器 FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile); // 开启抓取器 if (start(grabber)) { recorder = new FFmpegFrameRecorder(outputFile, audioChannels); recorder.setAudioOption("crf", "0"); recorder.setAudioCodec(audioCodec); recorder.setAudioBitrate(audioBitrate); recorder.setAudioChannels(audioChannels); recorder.setSampleRate(sampleRate); recorder.setAudioQuality(0); recorder.setAudioOption("aq", "10"); // 开启录制器 if (start(recorder)) { try { // 抓取音频 while ((audioSamples = grabber.grab()) != null) { recorder.setTimestamp(grabber.getTimestamp()); recorder.record(audioSamples); } } catch (org.bytedeco.javacv.FrameGrabber.Exception e1) { logger.error("抓取失败"); } catch (Exception e) { logger.error("录制失败"); } stop(grabber); stop(recorder); } } } /** * 打开抓取器 * @param grabber * @return */ private static boolean start(FrameGrabber grabber) { try { grabber.start(); return true; } catch (org.bytedeco.javacv.FrameGrabber.Exception e2) { try { logger.error("首次打开抓取器失败,准备重启抓取器..."); grabber.restart(); return true; } catch (org.bytedeco.javacv.FrameGrabber.Exception e) { try { logger.error("重启抓取器失败,正在关闭抓取器..."); grabber.stop(); } catch (org.bytedeco.javacv.FrameGrabber.Exception e1) { logger.error("停止抓取器失败!"); } } } return false; } /** * 打开录制器 * @param recorder * @return */ private static boolean start(FrameRecorder recorder) { try { recorder.start(); return true; } catch (Exception e2) { try { logger.error("首次打开录制器失败!准备重启录制器..."); recorder.stop(); recorder.start(); return true; } catch (Exception e) { try { logger.error("重启录制器失败!正在停止录制器..."); recorder.stop(); } catch (Exception e1) { logger.error("关闭录制器失败!"); } } } return false; } /** * 关闭抓取器 * @param grabber * @return */ private static void stop(FrameGrabber grabber) { try { grabber.flush(); grabber.stop(); } catch (org.bytedeco.javacv.FrameGrabber.Exception e) { logger.error("", e); try { grabber.stop(); } catch (org.bytedeco.javacv.FrameGrabber.Exception ex) { logger.error("关闭抓取器失败"); } } } /** * 录制器 * @param recorder * @return */ private static void stop(FrameRecorder recorder) { try { recorder.stop(); recorder.release(); } catch (Exception e) { logger.error("", e); try { recorder.stop(); } catch (Exception ex) { logger.error("关闭录制器失败"); } } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/ffmpeg/VideoUtil.java
src/main/java/com/wind/media/ffmpeg/VideoUtil.java
package com.wind.media.ffmpeg; import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.FrameGrabber; import org.bytedeco.javacv.Java2DFrameConverter; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; /** * @Title: VideoUtil * @Package com.wind.springboot.common.util * @Description: 视频处理 * @author huanghy * @date 2018/8/21 16:56 * @version V1.0 */ public class VideoUtil { /** * 获取指定视频的帧并保存为图片至指定目录 * @param videoFile 源视频文件路径 * @param photoFile 截取帧的图片存放路径 * @throws Exception */ public static void cutImage(String videoFile, String photoFile){ File targetFile = new File(photoFile); try(FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(videoFile)) { ff.start(); int length = ff.getLengthInFrames(); int i = 0; Frame frame = null; while (i < length) { // 过滤前5帧,避免出现全黑的图片,依自己情况而定 frame = ff.grabFrame(); if ((i > 5) && (frame.image != null)) { break; } i++; } if(frame != null){ Java2DFrameConverter converter = new Java2DFrameConverter(); BufferedImage bi = converter.getBufferedImage(frame); if(bi != null){ int oWidth = bi.getWidth(); int oHeight = bi.getHeight(); // 对截取的帧进行等比例缩放 int width = 800; int height = (int) (((double) width / oWidth) * oHeight); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); bufferedImage.getGraphics().drawImage(image, 0, 0, null); ImageIO.write(bufferedImage, "jpg", targetFile); ff.stop(); } } } catch (FrameGrabber.Exception e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/opencv/v2/HighGuiUtil.java
src/main/java/com/wind/media/opencv/v2/HighGuiUtil.java
package com.wind.media.opencv.v2; import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static { System.loadLibrary(Constants.OPENCV_LIB_NAME_246); } /** * 获取人脸范围 * @param fileName * @return */ public static MatOfRect takeFace(String fileName) { CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); Mat image = Highgui.imread(fileName); MatOfRect faceDetections = new MatOfRect(); // 指定人脸识别的最大和最小像素范围 Size minSize = new Size(120, 120); Size maxSize = new Size(250, 250); // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率 faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0, minSize, maxSize); return faceDetections; } /** * Detects faces in an image, draws boxes around them, and writes the results * @param fileName * @param destName */ public static void drawRect(String fileName, String destName){ Mat image = Highgui.imread(fileName); // Create a face detector from the cascade file in the resources // directory. CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // Detect faces in the image. // MatOfRect is a special container class for Rect. MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // Draw a bounding box around each face. for (Rect rect : faceDetections.toArray()) { Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } Highgui.imwrite(destName, image); } /** * 二值化 * * @param oriImg * @param outputImg */ public static void binarization(String oriImg, String outputImg) { Mat img = Highgui.imread(oriImg); Imgproc.cvtColor(img, img, Imgproc.COLOR_RGB2GRAY); // Imgproc.adaptiveThreshold(img, img, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 25, 10); Highgui.imwrite(outputImg, img); } /** * 边缘检测的原理:检测出图像中所有灰度值变化较大的点,而且这些点连起来构成若干线条,这些线条就称之为图像的边缘。 * @param oriImg * @param dstImg * @param threshold */ public static void canny(String oriImg, String dstImg, int threshold) { Mat img = Highgui.imread(oriImg); Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2GRAY); /**Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, boolean L2gradient) * 第一个参数,InputArray类型的image,输入图像,即源图像,填Mat类的对象即可,且需为单通道8位图像。 * 第二个参数,OutputArray类型的edges,输出的边缘图,需要和源图片有一样的尺寸和类型。 * 第三个参数,double类型的threshold1,第一个滞后性阈值。 * 第四个参数,double类型的threshold2,第二个滞后性阈值。 * 第五个参数,int类型的apertureSize,表示应用Sobel算子的孔径大小,其有默认值3。 * 第六个参数,bool类型的L2gradient,一个计算图像梯度幅值的标识,有默认值false。 */ Imgproc.Canny(img, img, threshold, threshold * 3, 3, true); Highgui.imwrite(dstImg, img); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java
src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java
package com.wind.media.opencv.v3; import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.objdetect.CascadeClassifier; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static { System.loadLibrary(Constants.OPENCV_LIB_NAME_330); } /** * 获取人脸范围 * @param fileName * @return */ public static MatOfRect takeFace(String fileName) { CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); Mat image = Imgcodecs.imread(fileName); MatOfRect faceDetections = new MatOfRect(); // 指定人脸识别的最大和最小像素范围 Size minSize = new Size(120, 120); Size maxSize = new Size(250, 250); // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率 faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0, minSize, maxSize); return faceDetections; } /** * Detects faces in an image, draws boxes around them, and writes the results * @param fileName * @param destName */ public static void drawRect(String fileName, String destName){ Mat image = Imgcodecs.imread(fileName); // Create a face detector from the cascade file in the resources // directory. CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // Detect faces in the image. // MatOfRect is a special container class for Rect. MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // Draw a bounding box around each face. for (Rect rect : faceDetections.toArray()) { Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } Imgcodecs.imwrite(destName, image); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/network/email/EmailUtil.java
src/main/java/com/wind/network/email/EmailUtil.java
package com.wind.network.email; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; /** * 邮件发送工具 * 1.SMTP(递送邮件机制) * 简单邮件传输协议 * SMTP服务器将邮件转发到接收者的SMTP服务器,直至最后被接收者通过POP或者IMAP协议获取。 * 2.POP(获取邮件机制) * 邮局协议,目前为第3个版本POP3 * 3.IMAP(多目录共享) * 接收信息的高级协议,目前版本为第4版IMAP4 * 接收新信息,将这些信息递送给用户,维护每个用户的多个目录。 * 4.MIME * 邮件扩展内容格式:信息格式、附件格式等等 * 5.NNTP * 第三方新闻组协议 * @author wind * */ public class EmailUtil { /** * 发送邮件 * @param email 邮件信息 */ public static void sendEmail(Email email) { // 邮件配置信息 Properties props = email.getProps(); String sender = email.getSender(); String receiver = email.getReceiver(); String title = email.getTitle(); String content = email.getContent(); String username = email.getUsername(); String password = email.getPassword(); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; // 根据属性新建一个邮件会话 Session session = Session.getInstance(props, authenticator); session.setDebug(false); List<DataSource> attachments = email.getAttachments(); // 由邮件会话新建一个消息对象 MimeMessage message = new MimeMessage(session); try { // 设置发件人的地址 message.setFrom(new InternetAddress(sender)); // 设置收件人,并设置其接收类型为TO message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); // 设置标题 message.setSubject(title); // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart("mixed"); // 设置邮件的文本内容 BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(content,"text/html;charset=utf-8"); multipart.addBodyPart(contentPart); //BASE64Encoder enc = new BASE64Encoder(); for(DataSource attach : attachments){ // 添加附件 BodyPart msgAttach = new MimeBodyPart(); // 添加附件的内容 msgAttach.setDataHandler(new DataHandler(attach)); // 添加附件的标题 msgAttach.setFileName(MimeUtility.encodeText(attach.getName())); multipart.addBodyPart(msgAttach); } // 将multipart对象放到message中 message.setContent(multipart); // 设置发信时间 message.setSentDate(new Date()); // 存储邮件信息 message.saveChanges(); // 发送邮件 Transport.send(message); } catch (AddressException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/network/email/Email.java
src/main/java/com/wind/network/email/Email.java
package com.wind.network.email; import java.util.List; import java.util.Properties; import javax.activation.DataSource; /** * @Title: Email * @Package com.wind.network.email * @Description: 邮件信息描述类 * @author wind * @date 2020/1/6 10:00 * @version V1.0 */ public class Email { /**配置session属性*/ private Properties props; /**发送者*/ private String sender; /**发送者邮箱账号*/ private String username; /**发送者邮箱密码*/ private String password; /**接收者*/ private String receiver; /**标题*/ private String title; /**邮件内容*/ private String content; /**附件*/ private List<DataSource> attachments; public Email() { } public Properties getProps() { return props; } public void setProps(Properties props) { this.props = props; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<DataSource> getAttachments() { return attachments; } public void setAttachments(List<DataSource> attachments) { this.attachments = attachments; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/network/http/ResourceUtil.java
src/main/java/com/wind/network/http/ResourceUtil.java
package com.wind.network.http; import com.wind.common.Constants; import java.io.InputStream; import java.net.URL; /** * @Title: ResourceUtil * @Package com.wind.resource * @Description: 资源文件加载工具类 * @author wind * @date 2018/10/11 10:46 * @version V1.0 */ public class ResourceUtil { /** * 获取资源文件的输入流 * @param fileName * @return */ public static InputStream getResFile(String fileName){ InputStream in = null; if(fileName != null){ if(fileName.startsWith(Constants.FILE_SEPARATOR)){ in = ResourceUtil.class.getResourceAsStream(fileName); }else{ in = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName); } } return in; } /** * 获取资源文件的url * @param fileName * @return */ public static URL getUrlFile(String fileName){ URL url = null; if(fileName != null){ if(fileName.startsWith(Constants.FILE_SEPARATOR)){ url = ResourceUtil.class.getResource(fileName); }else{ url = ClassLoader.getSystemClassLoader().getResource(fileName); } } return url; } /** * 获取class类的编译路径 * @return */ public static String getClassPath(){ URL url = Thread.currentThread().getContextClassLoader().getResource(Constants.BLANK_STR); return url != null ? url.getPath() : ""; } /** * 获取项目的路径 * @return */ public static String getProjectPath(){ return System.getProperty(Constants.USER_DIR); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/network/http/OkHttpUtil.java
src/main/java/com/wind/network/http/OkHttpUtil.java
package com.wind.network.http; import okhttp3.*; import java.io.*; import java.util.List; import java.util.Map; /** * http请求工具类 * @author wind * */ public class OkHttpUtil { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType FILE = MediaType.parse("File/*"); /** * 文件key */ public static final String FILE_KEY = "file"; private static OkHttpClient client = new OkHttpClient(); /** * 异步请求失败回调处理 */ @FunctionalInterface interface FailCallback{ /** * 异步请求失败回调处理 * @param call * @param e */ void call(Call call, IOException e); } /** * 异步请求成功回调处理 */ @FunctionalInterface interface OkCallback{ /** * 异步请求成功回调处理 * @param call * @param response */ void call(Call call, Response response); } /** * json get请求 * application/json; charset=utf-8 * @param url * @return */ public static String getJson(String url){ Request request = new Request.Builder().url(url).build(); return execAsync(request); } /** * json post请求 * application/json; charset=utf-8 * @param url * @param json * @return */ public static String postJson(String url, String json){ RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); return execAsync(request); } /** * post表单请求 * @param url * @param map * @return */ public static String postForm(String url, Map<String, String> map){ //创建表单请求体 FormBody.Builder formBody = new FormBody.Builder(); if(map != null && !map.isEmpty()){ map.forEach(formBody::add); } Request request = new Request.Builder().url(url).post(formBody.build()).build(); return execAsync(request); } /** * MultipartBody同时传递键值对参数和File对象 * @param url * @param map * @param files * @return */ public static String postMulti(String url, Map<String, String> map, List<File> files){ MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if(map != null && !map.isEmpty()){ map.forEach(builder::addFormDataPart); } if(files != null && !files.isEmpty()){ files.forEach(file -> { RequestBody body = RequestBody.create(FILE, file); builder.addFormDataPart(FILE_KEY, file.getName(), body); }); } Request request = new Request.Builder().url(url).post(builder.build()).build(); return execAsync(request); } /** * MultipartBody同时传递键值对参数和File对象 * @param url * @param multipartBody * @return */ public static String postMulti(String url, MultipartBody multipartBody){ Request request = new Request.Builder().url(url).post(multipartBody).build(); return execAsync(request); } /** * 下载文件 * @param request * @param targetFile */ public static void down(Request request, String targetFile){ ResponseBody responseBody = getBody(request); if(responseBody != null){ try( InputStream in = responseBody.byteStream(); FileOutputStream out = new FileOutputStream(targetFile, true) ) { byte[] bytes = new byte[1024]; int len; while((len = in.read(bytes, 0, bytes.length)) != -1){ out.write(bytes, 0, len); } out.flush(); } catch (IOException e) { e.printStackTrace(); } } } /** * 获取相应消息体 * @param request * @return */ public static ResponseBody getBody(Request request){ ResponseBody responseBody = null; try { Response response = client.newCall(request).execute(); responseBody = response.body(); } catch (IOException e) { e.printStackTrace(); } return responseBody; } /** * 同步请求调用 * @param request * @return */ public static String execAsync(Request request){ ResponseBody responseBody = getBody(request); String result = null; try { result = responseBody != null ? responseBody.string() : null; } catch (IOException e) { e.printStackTrace(); } return result; } /** * 异步调用 * @param request */ public static void execSync(Request request, OkCallback ok, FailCallback fail){ client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { fail.call(call, e); } @Override public void onResponse(Call call, Response response){ ok.call(call, response); } }); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/network/http/HttpUrlUtil.java
src/main/java/com/wind/network/http/HttpUrlUtil.java
package com.wind.network.http; import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @Title: HttpUrlUtil * @Package com.wind.network.http * @Description: HttpURLConnection网络工具类 * @author wind * @date 2018/10/13 10:01 * @version V1.0 */ public class HttpUrlUtil { /** * 解析url * @param url */ public static void parseUrl(String url) { BufferedReader reader = null; try { URL u = new URL(url); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); // 设置连接超时时间 connection.setConnectTimeout(1000 * 60); // 设置读超时时间 connection.setReadTimeout(1000 * 60); // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接) connection.connect(); // 获得响应状态信息 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("request fail..."); return; } // 获得头信息 Map<String, List<String>> headers = connection.getHeaderFields(); Iterator<Map.Entry<String, List<String>>> iterator = headers.entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry<String, List<String>> entry = iterator.next(); System.out.println(entry.getKey() + ":" + entry.getValue()); } System.out.println("response body:"); // 内容是文本,直接以缓冲字符流读取 reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), Constants.UTF8)); String data; while ((data = reader.readLine()) != null) { System.out.println(data); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IoUtil.close(reader); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/encrypt/CryptoUtil.java
src/main/java/com/wind/encrypt/CryptoUtil.java
package com.wind.encrypt; import com.wind.common.StringUtil; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; /** * @Title: CryptoUtil * @Package com.wind.encrypt * @Description: PBKDF2 * @author wind * @date 2018/10/11 10:12 * @version V1.0 */ public class CryptoUtil { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; /** * The following constants may be changed without breaking existing hashes. */ public static final int SALT_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 24; public static final int PBKDF2_ITERATIONS = 1000; public static final int ITERATION_INDEX = 0; public static final int SALT_INDEX = 1; public static final int PBKDF2_INDEX = 2; public static final int PWD_SALT_LEN = 2; /** * Returns a salted PBKDF2 hash of the password. * * @param password * the password to hash * @return a salted PBKDF2 hash of the password 数组第一个元素是密码,第二个元素是hash次数和随机盐 */ public static String[] createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { if (!StringUtil.isNotBlank(password)) { return new String[PWD_SALT_LEN]; } return createHash(password.toCharArray()); } /** * Returns a salted PBKDF2 hash of the password. * * @param password * the password to hash * @return a salted PBKDF2 hash of the password 数组第一个元素是密码,第二个元素是hash次数和随机盐 */ private static String[] createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTE_SIZE]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE); // format iterations:salt:hash return new String[] { toHex(hash), PBKDF2_ITERATIONS + ":" + toHex(salt)}; } /** * Validates a password using a hash. * * @param password * the password to check * @param salt * the hash of the valid password * @return true if the password is correct, false if not */ public static boolean validatePassword(String password, String hashPwd, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { if (!StringUtil.isNotBlank(password) || !StringUtil.isNotBlank(hashPwd) || !StringUtil.isNotBlank(salt)) { return false; } return validatePassword(password.toCharArray(), hashPwd, salt); } /** * Validates a password using a hash. * * @param password * the password to check * @param salt * the hash of the valid password * @return true if the password is correct, false if not */ private static boolean validatePassword(char[] password, String hashPwd, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // Decode the hash into its parameters String[] params = salt.split(":"); if (params.length != PWD_SALT_LEN) { return false; } int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] saltByte = fromHex(params[SALT_INDEX]); // fromHex(params[PBKDF2_INDEX]); byte[] hash = fromHex(hashPwd); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, saltByte, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); } /** * Validates a password using a hash. * * @param password * the password to check * @param salt * the hash of the valid password * @return true if the password is correct, false if not */ private static boolean validatePassword(char[] password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // Decode the hash into its parameters String[] params = salt.split(":"); int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] saltByte = fromHex(params[SALT_INDEX]); byte[] hash = fromHex(params[PBKDF2_INDEX]); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, saltByte, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); } /** * Compares two byte arrays in length-constant time. This comparison method * is used so that password hashes cannot be extracted from an on-line * system using a timing attack and then attacked off-line. * * @param a * the first byte array * @param b * the second byte array * @return true if both byte arrays are the same, false if not */ private static boolean slowEquals(byte[] a, byte[] b) { int diff = a.length ^ b.length; for (int i = 0; i < a.length && i < b.length; i++) { diff |= a[i] ^ b[i]; } return diff == 0; } /** * Computes the PBKDF2 hash of a password. * * @param password * the password to hash. * @param salt * the salt * @param iterations * the iteration count (slowness factor) * @param bytes * the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } /** * Converts a string of hexadecimal characters into a byte array. * * @param hex * the hex string * @return the hex string decoded into a byte array */ private static byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for (int i = 0; i < binary.length; i++) { binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return binary; } /** * Converts a byte array into a hexadecimal string. * * @param array * the byte array to convert * @return a length*2 character string encoding the byte array */ private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if (paddingLength > 0) { return String.format("%0" + paddingLength + "d", 0) + hex; } else { return hex; } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/encrypt/RsaUtil.java
src/main/java/com/wind/encrypt/RsaUtil.java
package com.wind.encrypt; import com.wind.common.StringUtil; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*; /** * @Title: RsaUtil * @Package com.ancda.payservice.util * @Description: rsa加密算法 * @author huanghy * @date 2018/7/12 10:24 * @version V1.0 */ public class RsaUtil { public static final String KEY_ALGORITHM = "RSA"; public static final String PUBLIC_KEY = "publicKey"; public static final String PRIVATE_KEY = "privateKey"; public static final int KEY_SIZE = 2048; public static final String SIGN_MD5 = "MD5withRSA"; public static final String SIGN_RSA2 = "SHA256WithRSA"; public static final String UTF8 = "utf-8"; /** * 生成rsa密钥对 * * @return */ public static Map<String, String> genKey(int size) { Map<String, String> keyMap = new HashMap<>(2); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGenerator.initialize(size); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded())); return keyMap; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return keyMap; } /** * 生成签名 * @param privateKey * @param content * @return */ public static String genSign(String privateKey, String content, String signType, String charset){ String sign = ""; try { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance(signType); signature.initSign(key); if(StringUtil.isNotBlank(charset)){ signature.update(content.getBytes(charset)); }else{ signature.update(content.getBytes()); } byte[] result = signature.sign(); sign = Base64.encodeBase64String(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return sign; } /** * 获取签名内容 * @param params * @return */ public static String getSignCheckContent(Map<String, String> params) { if (params == null) { return null; } else { params.remove("sign"); params.remove("sign_type"); StringBuilder content = new StringBuilder(); List<String> keys = new ArrayList<>(params.keySet()); Collections.sort(keys); for(int i = 0; i < keys.size(); ++i) { String key = keys.get(i); String value = params.get(key); content.append(i == 0 ? "" : "&").append(key).append("=").append(value); } return content.toString(); } } /** * 校验签名 * @param publicKey * @param params * @param sign * @param charset * @return */ public static boolean checkRsa(String publicKey, Map<String, String> params, String sign, String charset){ String content = getSignCheckContent(params); return rsa256CheckContent(publicKey, content, sign, charset); } /** * SHA256WithRSA签名校验 * @param publicKey * @param content * @param sign * @param charset * @return */ public static boolean rsa256CheckContent(String publicKey, String content, String sign, String charset){ return checkRsa(publicKey, content, sign, SIGN_RSA2, charset); } /** * rsa签名校验 * @param publicKey * @param content * @param sign * @param signType * @param charset * @return */ public static boolean checkRsa(String publicKey, String content, String sign, String signType, String charset){ X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey)); //为了数据的完整性 boolean bool = false; try { KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey key = keyFactory.generatePublic(x509EncodedKeySpec); Signature signature = Signature.getInstance(signType); signature.initVerify(key); if(StringUtil.isNotBlank(charset)){ signature.update(content.getBytes(charset)); }else{ signature.update(content.getBytes()); } bool = signature.verify(Base64.decodeBase64(sign)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return bool; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/encrypt/Md5Util.java
src/main/java/com/wind/encrypt/Md5Util.java
package com.wind.encrypt; import com.wind.common.Constants; import org.apache.commons.codec.binary.Hex; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * md5加密工具类 * MD5的全称是Message-Digest Algorithm 5(信息-摘要算法) * 默认为128bit * @author wind */ public class Md5Util { public static final String MD5_KEY = "MD5"; public static final String SHA_KEY = "SHA1"; /** * md5加密 * @param str * @param key MD5 SHA1 * @return */ public static String getMD5Str(String str, String key){ String s = ""; try { MessageDigest md = MessageDigest.getInstance(key); s = Hex.encodeHexString(md.digest(str.getBytes(Constants.UTF8))); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return s; } /** * 获得字符串的md5大写值 * * @param str 待加密的字符串 * @return md5加密后的大写字符串 */ public static String getMD5UpperStr(String str) { return getMD5Str(str, MD5_KEY).toUpperCase(); } /** * 获得文件的md5值 * @param file 文件对象 * @return 文件的md5 */ public static String getFileMD5Str(File file) { String r = ""; FileInputStream in = null; FileChannel ch = null; try { in = new FileInputStream(file); ch = in.getChannel(); ByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); MessageDigest md5 = MessageDigest.getInstance(MD5_KEY); md5.update(byteBuffer); r = Hex.encodeHexString(md5.digest()); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (ch != null) { try { ch.close(); } catch (IOException e) { e.printStackTrace(); } } } return r; } /** * 获得加盐md5,算法过程是原字符串md5后连接加盐字符串后再进行md5 * * @param str 待加密的字符串 * @param salt 盐 * @return 加盐md5 */ public static String getMD5AndSalt(String str, String salt) { return getMD5Str(getMD5Str(str, MD5_KEY).concat(salt), MD5_KEY); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/encrypt/AesUtil.java
src/main/java/com/wind/encrypt/AesUtil.java
package com.wind.encrypt; import com.wind.common.Constants; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * AES加密工具类 * AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据 * @author wind */ public class AesUtil { public static final String AES_KEY = "AES"; /** * des加密 * @param str 待加密对象 * @param key 密钥 长度为8的倍数 * @return */ public static byte[] encrypt(String str, String key) { byte[] bytes = null; try { Cipher cipher = init(Cipher.ENCRYPT_MODE, key); if(cipher == null){ return new byte[]{}; } bytes = cipher.doFinal(str.getBytes(Constants.UTF8)); } catch (IllegalBlockSizeException|BadPaddingException|UnsupportedEncodingException e) { e.printStackTrace(); } return bytes; } /** * des解密 * @param bytes 待解密对象 * @param key 密钥 长度为8的倍数 * @return */ public static String decrypt(byte[] bytes, String key) { String str = null; try { Cipher cipher = init(Cipher.DECRYPT_MODE, key); if(cipher == null){ return null; } str = new String(cipher.doFinal(bytes), Constants.UTF8); } catch (IllegalBlockSizeException|BadPaddingException|UnsupportedEncodingException e) { e.printStackTrace(); } return str; } private static Cipher init(int mode, String key){ Cipher cipher = null; try { KeyGenerator kGen = KeyGenerator.getInstance(AES_KEY); kGen.init(128, new SecureRandom(key.getBytes())); cipher = Cipher.getInstance(AES_KEY); cipher.init(mode, new SecretKeySpec(kGen.generateKey().getEncoded(), AES_KEY)); } catch (NoSuchAlgorithmException|NoSuchPaddingException|InvalidKeyException e) { e.printStackTrace(); } return cipher; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/encrypt/DesUtil.java
src/main/java/com/wind/encrypt/DesUtil.java
package com.wind.encrypt; import javax.crypto.*; import javax.crypto.spec.DESKeySpec; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; /** * DES加密工具类 * ES是一种对称加密算法,所谓对称加密算法即:加密和解密使用相同密钥的算法 * 注意:DES加密和解密过程中,密钥长度都必须是8的倍数 密匙长度是56位 * @author wind */ public class DesUtil { public final static String DES_KEY = "DES"; /** * des加密 * @param str 待加密对象 * @param key 密钥 长度为8的倍数 * @return */ public static String encrypt(String str,String key) { String encryptedData = null; try { Cipher cipher = init(Cipher.ENCRYPT_MODE, key); if(cipher == null){ return null; } // 加密,并把字节数组编码成字符串 sun.misc.BASE64Encoder不支持jdk9 encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(str.getBytes())); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return encryptedData; } /** * des解密 * @param str 待解密对象 * @param key 密钥 长度为8的倍数 * @return */ public static String decrypt(String str,String key) { String decryptedData = null; try { Cipher cipher = init(Cipher.DECRYPT_MODE, key); if(cipher == null){ return null; } // 把字符串解码为字节数组,并解密 decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(str))); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return decryptedData; } /** * 初始化加解密对象 * @param mode * @param key 密钥 长度为8的倍数 * @return */ private static Cipher init(int mode, String key){ Cipher cipher = null; try { SecureRandom sr = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_KEY); SecretKey secretKey = keyFactory.generateSecret(desKey); // 加解密对象 cipher = Cipher.getInstance(DES_KEY); cipher.init(mode, secretKey, sr); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } return cipher; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/office/poi/XSSFUtil.java
src/main/java/com/wind/office/poi/XSSFUtil.java
package com.wind.office.poi; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import java.io.InputStream; import java.util.Iterator; /** * */ public class XSSFUtil { public void processOneSheet(String filename) throws Exception { OPCPackage pkg = OPCPackage.open(filename); XSSFReader r = new XSSFReader( pkg ); SharedStringsTable sst = r.getSharedStringsTable(); XMLReader parser = fetchSheetParser(sst); // To look up the Sheet Name / Sheet Order / rID, // you need to process the core Workbook stream. // Normally it's of the form rId# or rSheet# InputStream sheet2 = r.getSheet("rId1"); InputSource sheetSource = new InputSource(sheet2); parser.parse(sheetSource); sheet2.close(); } public void processAllSheets(String filename) throws Exception { OPCPackage pkg = OPCPackage.open(filename); XSSFReader r = new XSSFReader( pkg ); SharedStringsTable sst = r.getSharedStringsTable(); XMLReader parser = fetchSheetParser(sst); Iterator<InputStream> sheets = r.getSheetsData(); while(sheets.hasNext()) { System.out.println("Processing new sheet:\n"); InputStream sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); sheet.close(); System.out.println(""); } } public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException { XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" ); ContentHandler handler = new SheetHandler(sst); parser.setContentHandler(handler); return parser; } /** * See org.xml.sax.helpers.DefaultHandler javadocs */ private static class SheetHandler extends DefaultHandler { private SharedStringsTable sst; private String lastContents; private boolean nextIsString; private SheetHandler(SharedStringsTable sst) { this.sst = sst; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { // c => cell if("c".equals(name)) { // Print the cell reference System.out.print(attributes.getValue("r") + " - "); // Figure out if the value is an index in the SST String cellType = attributes.getValue("t"); if(cellType != null && "s".equals(cellType)) { nextIsString = true; } else { nextIsString = false; } } // Clear contents cache lastContents = ""; } @Override public void endElement(String uri, String localName, String name) throws SAXException { // Process the last contents as required. // Do now, as characters() may be called more than once if(nextIsString) { int idx = Integer.parseInt(lastContents); lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); nextIsString = false; } // v => contents of a cell // Output after we've seen the string contents if("v".equals(name)) { System.out.println(lastContents); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { lastContents += new String(ch, start, length); } } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/office/poi/ExcelUtil.java
src/main/java/com/wind/office/poi/ExcelUtil.java
package com.wind.office.poi; import com.wind.common.Constants; import com.wind.common.DateUtil; import com.wind.common.IoUtil; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; /** * @Title: ExcelUtil * @Package com.wind.office.poi * @Description: poi组件excel工具类 * @author wind * @date 2018/10/13 10:50 * @version V1.0 */ public class ExcelUtil { /** * 写入文件 * @param path 文件路径 * @param list * @param sign true表示新建 false表示读取已存在新建sheet */ public static void writeExcel(String path, List<Object> list, boolean sign){ OutputStream out = null; Workbook wb = getWorkbook(path, sign); try { out = new FileOutputStream(path); Sheet sheet = wb.createSheet(); putSheet(sheet, list); wb.write(out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IoUtil.close(out); } } /** * 读取excel指定页的数据 * @param path * @param sheetNum * @return */ public static List<List<String>> readExcel(String path, int sheetNum) { List<List<String>> listSheet = null; Workbook wb = getWorkbook(path, false); int sheets = wb.getNumberOfSheets(); if(sheetNum <= sheets && sheetNum >=0){ //获取sheet Sheet sheet = wb.getSheetAt(sheetNum); System.out.println(sheet.getLastRowNum()); listSheet = getSheet(sheet); } return listSheet; } /** * 获取指定页sheet的数据 * @param sheet * @return */ private static List<List<String>> getSheet(Sheet sheet){ List<List<String>> list = new ArrayList<>(); // 获得表单的迭代器 Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { // 获得行数据 Row row = rows.next(); // 获得行的迭代器 Iterator<Cell> cells = row.cellIterator(); List<String> rowList = new ArrayList<>(); while (cells.hasNext()) { Cell cell = cells.next(); if(cell != null) { String value = getCellValue(cell); rowList.add(value); } } list.add(rowList); } return list; } /** * 获取cell数据 * @param cell * @return */ private static String getCellValue(Cell cell){ String value = ""; if(cell != null) { switch (cell.getCellTypeEnum()) { case FORMULA: value += cell.getCellFormula(); break; case NUMERIC: double cellValue = cell.getNumericCellValue(); if(HSSFDateUtil.isCellDateFormatted(cell)){ Date date = HSSFDateUtil.getJavaDate(cellValue); value += DateUtil.format(date, DateUtil.DATE_TIME); }else{ value += cell.getNumericCellValue(); } break; case STRING: value += cell.getStringCellValue(); break; case BLANK: break; case BOOLEAN: value += cell.getBooleanCellValue(); break; case ERROR: break; default:break; } } return value; } /** * 向指定页中写入数据 * @param sheet * @param list */ private static void putSheet(Sheet sheet, List<Object> list){ Row row; Cell c; if(sheet != null && list != null){ for(int i = 0; i < list.size(); i++){ row = sheet.createRow(i); Object obj = list.get(i); if(obj instanceof List){ List rowData = (List) obj; for(int j = 0; j < rowData.size(); j++){ Object colData = rowData.get(j); c = row.createCell(j); String value = colData != null ? colData.toString() : ""; if(colData instanceof String){ c.setCellValue(value); } } } } } } /** * 获取工作簿workbook * @param path * @param sign true表示新建 false表示读取 * @return */ private static Workbook getWorkbook(String path, boolean sign){ Workbook wb = null; InputStream input = null; try { if(sign){ if(path.endsWith(Constants.EXCEL_XLS)){ //2003-2007 wb = new HSSFWorkbook(); }else{ //2007+ wb = new XSSFWorkbook(); } }else{ input = new FileInputStream(path); if(path.endsWith(Constants.EXCEL_XLSX)){ //2007+ wb = new XSSFWorkbook(input); }else{ //2003-2007 wb = new HSSFWorkbook(input); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ IoUtil.close(input); } return wb; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/office/poi/SXSSFUtil.java
src/main/java/com/wind/office/poi/SXSSFUtil.java
package com.wind.office.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; /** * @author wind */ public class SXSSFUtil { public static void main(String[] args) throws Throwable { test1(); // test2(); } public static void test1() throws Throwable{ long start = System.currentTimeMillis(); // keep 100 rows in memory, exceeding rows will be flushed to disk SXSSFWorkbook wb = new SXSSFWorkbook(100); common(wb, "E:\\doc\\3.xlsx"); wb.dispose(); long end = System.currentTimeMillis(); System.out.println(end - start); } public static void test2() throws Throwable{ long start = System.currentTimeMillis(); // keep 100 rows in memory, exceeding rows will be flushed to disk Workbook wb = new XSSFWorkbook(); common(wb, "E:\\doc\\2.xlsx"); long end = System.currentTimeMillis(); System.out.println(end - start); } private static void common(Workbook wb, String filename) throws Throwable{ Sheet sh = wb.createSheet(); for(int rownum = 0; rownum < 1000; rownum++){ Row row = sh.createRow(rownum); for(int cellnum = 0; cellnum < 10; cellnum++){ Cell cell = row.createCell(cellnum); String address = new CellReference(cell).formatAsString(); cell.setCellValue(address); } } // Rows with rownum < 900 are flushed and not accessible for(int rownum = 0; rownum < 900; rownum++){ //Assert.assertNull(sh.getRow(rownum)); } // ther last 100 rows are still in memory for(int rownum = 900; rownum < 1000; rownum++){ //Assert.assertNotNull(sh.getRow(rownum)); } FileOutputStream out = new FileOutputStream(filename); wb.write(out); out.close(); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/jdbc/DbUtil.java
src/main/java/com/wind/jdbc/DbUtil.java
package com.wind.jdbc; import com.wind.common.Constants; import com.wind.common.PropUtil; import com.wind.common.StringUtil; import com.wind.jdbc.callback.DbCallBack; import com.wind.jdbc.entity.Column; import com.wind.jdbc.entity.PrimaryKey; import com.wind.jdbc.entity.Table; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @Title: DbUtil * @Package com.wind.jdbc * @Description: Db工具类 * @author wind * @date 2018/10/11 9:56 * @version V1.0 */ public class DbUtil { private static Properties props = PropUtil.getProp("src/main/resources/jdbc.properties"); static{ try { Class.forName(props.getProperty("driverClass")); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取数据库连接 * @return */ private static Connection getConn(){ Connection conn = null; try { conn = DriverManager.getConnection(props.getProperty("jdbcUrl"), props); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 获取元数据信息 * @param callBack */ private static void exec(DbCallBack callBack){ Connection con = getConn(); try { DatabaseMetaData db = con.getMetaData(); callBack.call(db); } catch (SQLException e) { e.printStackTrace(); } finally { close(con); } } /** * 获取所有数据库实例 * @return */ public static List<String> getAllDb(){ List<String> dbs = new ArrayList<>(); exec(db -> { ResultSet rs = db.getCatalogs(); while(rs.next()){ String dbName = rs.getString("TABLE_CAT"); dbs.add(dbName); } }); return dbs; } /** * 获取数据库所有表 * @param catalog * @return */ public static List<Table> getTables(String catalog){ List<Table> tables = new ArrayList<>(); exec(db -> { ResultSet rs = db.getTables(catalog,null,null, new String[]{"TABLE"}); while(rs.next()){ tables.add(getTable(rs)); } }); return tables; } /** * 组装table数据 * @param rs * @return * @throws SQLException */ private static Table getTable(ResultSet rs){ Table table = null; try { if(rs != null){ table = new Table(); String tableName = rs.getString("TABLE_NAME"); table.setTableName(tableName); table.setProperty(DbUtil.getCamelCase(tableName, true)); String catalog = rs.getString("TABLE_CAT"); table.setTableCat(catalog); table.setRemarks(rs.getString("REMARKS")); table.setPrimaryKeys(getPrimaryKeys(catalog, tableName)); table.setColumns(getColumns(catalog, tableName)); } } catch (SQLException e) { e.printStackTrace(); } return table; } /** * 获取数据库列信息 * @param catalog * @param tableName * @return */ public static List<Column> getColumns(String catalog, String tableName){ List<Column> columns = new ArrayList<>(); exec(db -> { ResultSet rs = db.getColumns(catalog,"%", tableName,"%"); while (rs.next()){ Column column = new Column(); String colName = rs.getString("COLUMN_NAME"); String typeName = rs.getString("TYPE_NAME"); column.setColumnName(colName); column.setColumnType(typeName); column.setProperty(DbUtil.getCamelCase(colName, false)); column.setType(getFieldType(typeName)); column.setColumnSize(rs.getInt("COLUMN_SIZE")); column.setNullable(rs.getInt("NULLABLE")); column.setRemarks(rs.getString("REMARKS")); column.setDigits(rs.getInt("DECIMAL_DIGITS")); columns.add(column); } }); return columns; } /** * TABLE_CAT String => 表类别(可为 null) * TABLE_SCHEM String => 表模式(可为 null) * TABLE_NAME String => 表名称 * COLUMN_NAME String => 列名称 * KEY_SEQ short => 主键中的序列号 * PK_NAME String => 主键的名称(可为 null) * @param catalog * @param tableName * @return */ public static List<PrimaryKey> getPrimaryKeys(String catalog, String tableName){ List<PrimaryKey> keys = new ArrayList<>(); exec(db -> { ResultSet rs = db.getPrimaryKeys(catalog, null, tableName); while(rs.next()) { PrimaryKey primaryKey = new PrimaryKey(); primaryKey.setColName(rs.getString("COLUMN_NAME")); primaryKey.setPkName(rs.getString("PK_NAME")); primaryKey.setKeySeq(rs.getShort("KEY_SEQ")); keys.add(primaryKey); } }); return keys; } /** * 获取数据库表的描述信息 * @param catalog * @param tableName * @return */ public static Table getTable(String catalog, String tableName){ Connection con = getConn(); Table table = null; try { DatabaseMetaData db = con.getMetaData(); ResultSet rs = db.getTables(catalog,null,tableName, new String[]{"TABLE"}); if(rs.first()) { table = getTable(rs); } } catch (SQLException e) { e.printStackTrace(); } finally { close(con); } return table; } /** * 表字段类型转换成java类型 * @param columnType * @return */ private static String getFieldType(String columnType){ String result; columnType = columnType != null ? columnType : ""; switch (columnType){ case "CHAR" : result = "String";break; case "VARCHAR" : result = "String";break; case "INT" : result = "Integer";break; case "DOUBLE" : result = "Double";break; case "TIMESTAMP" : result = "Date";break; default: result = "String"; break; } return result; } /** * * @param con */ private static void close(Connection con){ if(con != null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * java驼峰命名的类成员字段名 * @param name 字符串 * @param flag 首字母小写为false, 大写为true * @return */ public static String getCamelCase(String name, boolean flag){ StringBuilder sb = new StringBuilder(); if(name != null){ String[] arr = StringUtil.split(name, Constants.UNDERLINE); for(int i = 0; i < arr.length; i++){ String s = arr[i]; if(i == 0){ if(flag){ s = getFirst(s, true); } sb.append(s); }else{ int len = s.length(); if(len == 1){ sb.append(s.toUpperCase()); }else{ sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); } } } } return sb.toString(); } /** * 将单词首字母变大小写 * @param str * @param flag true变大写, false变小写 * @return */ public static String getFirst(String str, boolean flag){ StringBuilder sb = new StringBuilder(); if(str != null && str.length() > 1){ String first; if(flag){ first = str.substring(0, 1).toUpperCase(); }else{ first = str.substring(0, 1).toLowerCase(); } sb.append(first).append(str.substring(1)); } return sb.toString(); } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/jdbc/callback/DbCallBack.java
src/main/java/com/wind/jdbc/callback/DbCallBack.java
package com.wind.jdbc.callback; import java.sql.DatabaseMetaData; import java.sql.SQLException; /** * @author wind */ @FunctionalInterface public interface DbCallBack { /** * 数据库元数据操作 * @param db * @throws SQLException */ void call(DatabaseMetaData db) throws SQLException; }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/jdbc/entity/Table.java
src/main/java/com/wind/jdbc/entity/Table.java
package com.wind.jdbc.entity; import java.util.List; /** * 数据库表详情类 * @author wind */ public class Table { /** * 数据库实例名 */ private String tableCat; /** * 表名 */ private String tableName; /** * 表对应驼峰类名 */ private String property; /** * 主键 */ private List<PrimaryKey> primaryKeys; /** * 所有列的信息 */ private List<Column> columns; /** * 表注释 */ private String remarks; public Table() { } public Table(List<Column> columns) { this.columns = columns; } public List<Column> getColumns() { return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } public String getTableCat() { return tableCat; } public void setTableCat(String tableCat) { this.tableCat = tableCat; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List<PrimaryKey> getPrimaryKeys() { return primaryKeys; } public void setPrimaryKeys(List<PrimaryKey> primaryKeys) { this.primaryKeys = primaryKeys; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/jdbc/entity/PrimaryKey.java
src/main/java/com/wind/jdbc/entity/PrimaryKey.java
package com.wind.jdbc.entity; /** * 表中主键信息 * * @author wind */ public class PrimaryKey { /** * 列名称 */ private String colName; /** * 主键的名称(可为 null) */ private String pkName; /** * 主键中的序列号 */ private short keySeq; public String getColName() { return colName; } public void setColName(String colName) { this.colName = colName; } public String getPkName() { return pkName; } public void setPkName(String pkName) { this.pkName = pkName; } public short getKeySeq() { return keySeq; } public void setKeySeq(short keySeq) { this.keySeq = keySeq; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
followwwind/javautils
https://github.com/followwwind/javautils/blob/023b0689e78ddad076507e6ea510c0f2adcb9562/src/main/java/com/wind/jdbc/entity/Column.java
src/main/java/com/wind/jdbc/entity/Column.java
package com.wind.jdbc.entity; /** * 数据库列详情类 * @author wind */ public class Column { /** * 列名 */ private String columnName; /** * 类型 */ private String columnType; /** * 数据库列名对应的java类字段名 */ private String property; /** * 数据库表对应java类型 */ private String type; /** * 占用字节 */ private int columnSize; /** * 是否为空 * 1.columnNoNulls - 可能不允许使用 NULL 值 * 2.columnNullable - 明确允许使用 NULL 值 * 3.columnNullableUnknown - 不知道是否可使用 null */ private int nullable; /** * 小数部分的位数 */ private int digits; /** * 描述 */ private String remarks; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getColumnType() { return columnType; } public void setColumnType(String columnType) { this.columnType = columnType; } public int getColumnSize() { return columnSize; } public void setColumnSize(int columnSize) { this.columnSize = columnSize; } public int getNullable() { return nullable; } public void setNullable(int nullable) { this.nullable = nullable; } public int getDigits() { return digits; } public void setDigits(int digits) { this.digits = digits; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
java
Apache-2.0
023b0689e78ddad076507e6ea510c0f2adcb9562
2026-01-05T02:37:50.504104Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/test/java/org/killbill/xmlloader/TestXMLSchemaGenerator.java
xmlloader/src/test/java/org/killbill/xmlloader/TestXMLSchemaGenerator.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.xml.bind.JAXBException; import javax.xml.transform.TransformerException; import org.killbill.commons.utils.io.CharStreams; import org.testng.annotations.Test; public class TestXMLSchemaGenerator { @Test(groups = "fast", enabled = false) public void test() throws IOException, TransformerException, JAXBException { final InputStream stream = XMLSchemaGenerator.xmlSchema(XmlTestClass.class); final String result = CharStreams.toString(new InputStreamReader(stream, "UTF-8")); System.out.println(result); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/test/java/org/killbill/xmlloader/TestUriAccessor.java
xmlloader/src/test/java/org/killbill/xmlloader/TestUriAccessor.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.InputStream; import java.net.URL; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestUriAccessor { private static final Pattern GUAVA_PATTERN = Pattern.compile(".*/guava-(\\d{2}.\\d(\\.\\d+)?-jre).jar$"); private URL guavaUrl = null; private String guavaVersion = null; @BeforeClass(groups = "fast") public void setUp() throws Exception { // Find the Guava Jar on the filesystem final String[] urls = System.getProperty("java.class.path").split(":"); for (final String url : urls) { final Matcher matcher = GUAVA_PATTERN.matcher(url); if (matcher.matches()) { guavaUrl = new URL("file:" + url); guavaVersion = matcher.group(1); break; } } Assert.assertNotNull(guavaUrl); Assert.assertNotNull(guavaVersion); } @Test(groups = "fast") public void testAccessJar() throws Exception { final InputStream inputStream = UriAccessor.accessUri(guavaUrl.toString()); Assert.assertNotNull(inputStream); } @Test(groups = "fast", description = "https://github.com/killbill/killbill/issues/226") public void testAccessFileInJar() throws Exception { final String guavaPomProperties = "jar:" + guavaUrl.toString() + "!/META-INF/maven/com.google.guava/guava/pom.properties"; final InputStream inputStream = UriAccessor.accessUri(guavaPomProperties); Assert.assertNotNull(inputStream); final Properties properties = new Properties(); properties.load(inputStream); Assert.assertEquals(properties.getProperty("version"), guavaVersion); Assert.assertEquals(properties.getProperty("groupId"), "com.google.guava"); Assert.assertEquals(properties.getProperty("artifactId"), "guava"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/test/java/org/killbill/xmlloader/TestXMLWriter.java
xmlloader/src/test/java/org/killbill/xmlloader/TestXMLWriter.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestXMLWriter { public static final String TEST_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<xmlTestClass>" + "<foo>foo</foo>" + "<bar>1.0</bar>" + "<lala>42</lala>" + "</xmlTestClass>"; @Test(groups = "fast") public void test() throws Exception { final InputStream is = new ByteArrayInputStream(TEST_XML.getBytes()); final XmlTestClass test = XMLLoader.getObjectFromStream(is, XmlTestClass.class); assertEquals(test.getFoo(), "foo"); //noinspection RedundantCast assertEquals((double) test.getBar(), 1.0); assertEquals((double) test.getLala(), 42); final String output = XMLWriter.writeXML(test, XmlTestClass.class); //System.out.println(output); assertEquals(output.replaceAll("\\s", ""), TEST_XML.replaceAll("\\s", "")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/test/java/org/killbill/xmlloader/XmlTestClass.java
xmlloader/src/test/java/org/killbill/xmlloader/XmlTestClass.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class XmlTestClass extends ValidatingConfig<XmlTestClass> { private String foo; private Double bar; private int lala; public String getFoo() { return foo; } public Double getBar() { return bar; } public int getLala() { return lala; } @Override public ValidationErrors validate(final XmlTestClass root, final ValidationErrors errors) { return errors; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/test/java/org/killbill/xmlloader/TestXMLLoader.java
xmlloader/src/test/java/org/killbill/xmlloader/TestXMLLoader.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBException; import javax.xml.transform.TransformerException; import org.testng.annotations.Test; import org.xml.sax.SAXException; import static org.testng.Assert.assertEquals; public class TestXMLLoader { public static final String TEST_XML = "<xmlTestClass>" + " <foo>foo</foo>" + " <bar>1.0</bar>" + " <lala>42</lala>" + "</xmlTestClass>"; @Test(groups = "fast") public void test() throws SAXException, JAXBException, IOException, TransformerException, ValidationException { final InputStream is = new ByteArrayInputStream(TEST_XML.getBytes()); final XmlTestClass test = XMLLoader.getObjectFromStream(is, XmlTestClass.class); assertEquals(test.getFoo(), "foo"); //noinspection RedundantCast assertEquals((double) test.getBar(), 1.0); assertEquals((double) test.getLala(), 42); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/XMLSchemaGenerator.java
xmlloader/src/main/java/org/killbill/xmlloader/XMLSchemaGenerator.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.SchemaOutputResolver; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import static java.nio.charset.StandardCharsets.UTF_8; public class XMLSchemaGenerator { private static final int MAX_SCHEMA_SIZE_IN_BYTES = 100000; //Note: this main method is called by the maven build to generate the schema for the jar public static void main(final String[] args) throws IOException, TransformerException, JAXBException, ClassNotFoundException { if (args.length != 2) { printUsage(); System.exit(0); } final Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(args[1]); final JAXBContext context = JAXBContext.newInstance(clazz); String xsdFileName = "Schema.xsd"; xsdFileName = args[0] + "/" + xsdFileName; final FileOutputStream s = new FileOutputStream(xsdFileName); pojoToXSD(context, s); } private static void printUsage() { System.out.println(XMLSchemaGenerator.class.getName() + " <file> <class1>"); } public static String xmlSchemaAsString(final Class<?> clazz) throws IOException, TransformerException, JAXBException { final ByteArrayOutputStream output = new ByteArrayOutputStream(MAX_SCHEMA_SIZE_IN_BYTES); final JAXBContext context = JAXBContext.newInstance(clazz); pojoToXSD(context, output); return new String(output.toByteArray(), UTF_8); } public static InputStream xmlSchema(final Class<?> clazz) throws IOException, TransformerException, JAXBException { final ByteArrayOutputStream output = new ByteArrayOutputStream(MAX_SCHEMA_SIZE_IN_BYTES); final JAXBContext context = JAXBContext.newInstance(clazz); pojoToXSD(context, output); return new ByteArrayInputStream(output.toByteArray()); } public static void pojoToXSD(final JAXBContext context, final OutputStream out) throws IOException, TransformerException { final List<DOMResult> results = new ArrayList<DOMResult>(); context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(final String ns, final String file) throws IOException { final DOMResult result = new DOMResult(); result.setSystemId(file); results.add(result); return result; } }); final DOMResult domResult = results.get(0); final Document doc = (Document) domResult.getNode(); // Use a Transformer for output final TransformerFactory tFactory = TransformerFactory.newInstance(); final Transformer transformer = tFactory.newTransformer(); final DOMSource source = new DOMSource(doc); final StreamResult result = new StreamResult(out); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/ValidationErrors.java
xmlloader/src/main/java/org/killbill/xmlloader/ValidationErrors.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.util.ArrayList; import org.slf4j.Logger; public class ValidationErrors extends ArrayList<ValidationError> { private static final long serialVersionUID = 1L; public void add(final String description, final Class<?> objectType, final String objectName) { add(new ValidationError(description, objectType, objectName)); } public void log(final Logger log) { for (final ValidationError error : this) { error.log(log); } } public String toString() { final StringBuilder builder = new StringBuilder(); for (final ValidationError error : this) { builder.append(error.toString()); } return builder.toString(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/ValidationException.java
xmlloader/src/main/java/org/killbill/xmlloader/ValidationException.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.PrintStream; public class ValidationException extends Exception { private final ValidationErrors errors; ValidationException(final ValidationErrors errors) { this.errors = errors; } public ValidationErrors getErrors() { return errors; } @Override public void printStackTrace(final PrintStream arg0) { arg0.print(errors.toString()); super.printStackTrace(arg0); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/ValidationError.java
xmlloader/src/main/java/org/killbill/xmlloader/ValidationError.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import org.slf4j.Logger; public class ValidationError { private final String description; private final Class<?> objectType; private final String objectName; public ValidationError(final String description, final Class<?> objectType, final String objectName) { super(); this.description = description; this.objectType = objectType; this.objectName = objectName; } public String getDescription() { return description; } public Class<?> getObjectType() { return objectType; } public String getObjectName() { return objectName; } public void log(final Logger log) { log.error(String.format("%s (%s:%s)", description, objectType, objectName)); } public String toString() { return String.format("%s (%s:%s)%n", description, objectType, objectName); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/XMLWriter.java
xmlloader/src/main/java/org/killbill/xmlloader/XMLWriter.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import static java.nio.charset.StandardCharsets.UTF_8; public class XMLWriter<T> { private static final int MAX_XML_SIZE_IN_BYTES = 100000; public static <T> String writeXML(final T object, final Class<T> type) throws Exception { final JAXBContext context = JAXBContext.newInstance(type); final Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); final ByteArrayOutputStream output = new ByteArrayOutputStream(MAX_XML_SIZE_IN_BYTES); marshaller.marshal(object, output); return new String(output.toByteArray(), UTF_8); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/UriAccessor.java
xmlloader/src/main/java/org/killbill/xmlloader/UriAccessor.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Scanner; import org.killbill.commons.utils.io.Resources; import static java.nio.charset.StandardCharsets.UTF_8; public class UriAccessor { private static final String URI_SCHEME_FOR_ARCHIVE_FILE = "jar:file"; private static final String URI_SCHEME_FOR_CLASSPATH = "jar"; private static final String URI_SCHEME_FOR_FILE = "file"; public static URL toURL(final String uri) throws IOException, URISyntaxException { return toURL(new URI(uri)); } public static URL toURL(final URI inputURI) throws IOException, URISyntaxException { final String scheme = inputURI.getScheme(); final URI uri; if (scheme == null) { uri = new URI(Resources.getResource(inputURI.toString()).toExternalForm()); } else if (scheme.equals(URI_SCHEME_FOR_FILE) && !inputURI.getSchemeSpecificPart().startsWith("/")) { // interpret URIs of this form as relative path uris uri = new File(inputURI.getSchemeSpecificPart()).toURI(); } else { uri = inputURI; } return uri.toURL(); } public static InputStream accessUri(final String uri) throws IOException, URISyntaxException { return accessUri(new URI(uri)); } public static InputStream accessUri(final URI uri) throws IOException, URISyntaxException { final String scheme = uri.getScheme(); if (URI_SCHEME_FOR_CLASSPATH.equals(scheme)) { if (uri.toString().startsWith(URI_SCHEME_FOR_ARCHIVE_FILE)) { return getInputStreamFromJarFile(uri); } else { return UriAccessor.class.getResourceAsStream(uri.getPath()); } } final URL url = toURL(uri); return url.openConnection().getInputStream(); } /** * @param uri of the form jar:file:/path!/resource * @throws IOException if fail to extract InputStream */ private static InputStream getInputStreamFromJarFile(final URI uri) throws IOException { final URL url = uri.toURL(); final JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); return jarURLConnection.getJarFile().getInputStream(jarURLConnection.getJarEntry()); } public static String accessUriAsString(final String uri) throws IOException, URISyntaxException { return accessUriAsString(new URI(uri)); } public static String accessUriAsString(final URI uri) throws IOException, URISyntaxException { final InputStream stream = accessUri(uri); return new Scanner(stream, UTF_8.name()).useDelimiter("\\A").next(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/ValidatingConfig.java
xmlloader/src/main/java/org/killbill/xmlloader/ValidatingConfig.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @XmlAccessorType(XmlAccessType.NONE) public abstract class ValidatingConfig<Context> { protected Context root; public abstract ValidationErrors validate(Context root, ValidationErrors errors); public void initialize(final Context root) { this.root = root; } public Context getRoot() { return root; } protected void validateCollection(final Context context, final ValidationErrors errors, final ValidatingConfig<Context>[] configs) { for (final ValidatingConfig<Context> config : configs) { config.validate(context, errors); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/xmlloader/src/main/java/org/killbill/xmlloader/XMLLoader.java
xmlloader/src/main/java/org/killbill/xmlloader/XMLLoader.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.xmlloader; import java.io.IOException; import java.io.InputStream; import java.net.URI; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; public class XMLLoader { private static final String DISABLE_VALIDATION_PROP = "org.killbill.xmlloader.disable.validation"; public static final Logger log = LoggerFactory.getLogger(XMLLoader.class); public static <T extends ValidatingConfig<T>> T getObjectFromString(final String uri, final Class<T> objectType) throws Exception { if (uri == null) { return null; } log.info("Initializing an object of class " + objectType.getName() + " from xml file at: " + uri); return getObjectFromStream(UriAccessor.accessUri(uri), objectType); } public static <T extends ValidatingConfig<T>> T getObjectFromUri(final URI uri, final Class<T> objectType) throws Exception { if (uri == null) { return null; } log.info("Initializing an object of class " + objectType.getName() + " from xml file at: " + uri); return getObjectFromStream(UriAccessor.accessUri(uri), objectType); } public static <T extends ValidatingConfig<T>> T getObjectFromStream(final InputStream stream, final Class<T> clazz) throws SAXException, JAXBException, IOException, TransformerException, ValidationException { if (stream == null) { return null; } final Object o = unmarshaller(clazz).unmarshal(stream); if (clazz.isInstance(o)) { @SuppressWarnings("unchecked") final T castObject = (T) o; try { initializeAndValidate(castObject); } catch (final ValidationException e) { e.getErrors().log(log); throw e; } return castObject; } else { return null; } } public static <T> T getObjectFromStreamNoValidation(final InputStream stream, final Class<T> clazz) throws SAXException, JAXBException, IOException, TransformerException { final Object o = unmarshaller(clazz).unmarshal(stream); if (clazz.isInstance(o)) { @SuppressWarnings("unchecked") final T castObject = (T) o; return castObject; } else { return null; } } public static <T extends ValidatingConfig<T>> void initializeAndValidate(final T c) throws ValidationException { c.initialize(c); if (shouldDisableValidation()) { log.warn("Catalog validation has been disabled using property " + DISABLE_VALIDATION_PROP); return; } final ValidationErrors errs = c.validate(c, new ValidationErrors()); if (!errs.isEmpty()) { throw new ValidationException(errs); } } public static Unmarshaller unmarshaller(final Class<?> clazz) throws JAXBException, SAXException, IOException, TransformerException { final JAXBContext context = JAXBContext.newInstance(clazz); final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // Prevent XML External Entity (XXE) attack factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); final Unmarshaller um = context.createUnmarshaller(); final Schema schema = factory.newSchema(new StreamSource(XMLSchemaGenerator.xmlSchema(clazz))); um.setSchema(schema); return um; } private static boolean shouldDisableValidation() { final String disableValidationProp = System.getProperty(DISABLE_VALIDATION_PROP); return Boolean.parseBoolean(disableValidationProp); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/impl/HealthyResultBuilder.java
metrics-api/src/main/java/org/killbill/commons/health/impl/HealthyResultBuilder.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class HealthyResultBuilder { private String message; private long time; private Map<String, Object> details; public HealthyResultBuilder setMessage(final String message) { this.message = message; return this; } public HealthyResultBuilder setTime(final long time) { this.time = time; return this; } public HealthyResultBuilder setDetails(final Map<String, Object> details) { this.details = Collections.unmodifiableMap(details); return this; } public HealthyResult createHealthyResult() { return new HealthyResult(message, time, details); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/impl/UnhealthyResult.java
metrics-api/src/main/java/org/killbill/commons/health/impl/UnhealthyResult.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.killbill.commons.health.api.Result; public class UnhealthyResult implements Result { private final String message; private final Throwable error; private final long time; private final Map<String, Object> details; public UnhealthyResult(final String message, final Throwable error, final long time, final Map<String, Object> details) { this.message = message; this.error = new Throwable(error); this.time = time; this.details = details == null ? Collections.emptyMap() : new HashMap<>(details); } @Override public boolean isHealthy() { return false; } @Override public String getMessage() { return message; } @Override public Throwable getError() { return new Throwable(error); } @Override public long getTime() { return time; } @Override public Map<String, Object> getDetails() { return new HashMap<>(details); } @Override public String toString() { return "UnhealthyResult{" + "message='" + message + '\'' + ", error=" + error + ", time=" + time + ", details=" + details + '}'; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/impl/HealthyResult.java
metrics-api/src/main/java/org/killbill/commons/health/impl/HealthyResult.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.killbill.commons.health.api.Result; public class HealthyResult implements Result { private final String message; private final long time; private final Map<String, Object> details; public HealthyResult(final String message, final long time, final Map<String, Object> details) { this.message = message; this.time = time; this.details = details == null ? Collections.emptyMap() : new HashMap<>(details); } @Override public boolean isHealthy() { return true; } @Override public String getMessage() { return message; } @Override public Throwable getError() { return null; } @Override public long getTime() { return time; } @Override public Map<String, Object> getDetails() { return new HashMap<>(details); } @Override public String toString() { return "HealthyResult{" + "message='" + message + '\'' + ", time=" + time + ", details=" + details + '}'; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/impl/UnhealthyResultBuilder.java
metrics-api/src/main/java/org/killbill/commons/health/impl/UnhealthyResultBuilder.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.impl; import java.util.Collections; import java.util.Map; public class UnhealthyResultBuilder { private String message; private Throwable error; private long time; private Map<String, Object> details; public UnhealthyResultBuilder setMessage(final String message) { this.message = message; return this; } public UnhealthyResultBuilder setError(final Throwable error) { this.error = new Throwable(error); return this; } public UnhealthyResultBuilder setTime(final long time) { this.time = time; return this; } public UnhealthyResultBuilder setDetails(final Map<String, Object> details) { this.details = Collections.unmodifiableMap(details); return this; } public UnhealthyResult createUnhealthyResult() { return new UnhealthyResult(message, error, time, details); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/api/Result.java
metrics-api/src/main/java/org/killbill/commons/health/api/Result.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.api; import java.util.Map; public interface Result { boolean isHealthy(); /** * Returns any additional message for the result, or {@code null} if the result has no * message. * * @return any additional message for the result, or {@code null} */ String getMessage(); /** * Returns any exception for the result, or {@code null} if the result has no exception. * * @return any exception for the result, or {@code null} */ Throwable getError(); /** * Returns the time when the result was created, in milliseconds since Epoch * * @return the time when the result was created */ long getTime(); Map<String, Object> getDetails(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/api/HealthCheck.java
metrics-api/src/main/java/org/killbill/commons/health/api/HealthCheck.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.api; public interface HealthCheck { /** * Perform a check of the application component. * * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link * Result} with a descriptive error message or exception * @throws Exception if there is an unhandled error during the health check; this will result in * a failed health check */ Result check() throws Exception; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/health/api/HealthCheckRegistry.java
metrics-api/src/main/java/org/killbill/commons/health/api/HealthCheckRegistry.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.health.api; import java.util.NoSuchElementException; import java.util.Set; public interface HealthCheckRegistry { /** * Returns a set of the names of all registered health checks. * * @return the names of all registered health checks */ Set<String> getNames(); /** * Runs the health check with the given name. * * @param name the health check's name * @return the result of the health check * @throws NoSuchElementException if there is no health check with the given name */ Result runHealthCheck(String name) throws NoSuchElementException; /** * Registers an application {@link HealthCheck}. * * @param name the name of the health check * @param healthCheck the {@link HealthCheck} instance */ void register(String name, HealthCheck healthCheck); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpMetricRegistry.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpMetricRegistry.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import java.util.HashMap; import java.util.Map; import org.killbill.commons.metrics.api.Counter; import org.killbill.commons.metrics.api.Gauge; import org.killbill.commons.metrics.api.Histogram; import org.killbill.commons.metrics.api.Meter; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.api.Timer; public class NoOpMetricRegistry implements MetricRegistry { private final Map<String, Counter> counters = new HashMap<>(); private final Map<String, Gauge<?>> gauges = new HashMap<>(); private final Map<String, Meter> meters = new HashMap<>(); private final Map<String, Histogram> histograms = new HashMap<>(); private final Map<String, Timer> timers = new HashMap<>(); @Override public Counter counter(final String name) { final Counter counter = new NoOpCounter(); counters.put(name, counter); return counter; } @Override public <T> Gauge<T> gauge(final String name, final Gauge<T> gauge) { gauges.put(name, gauge); return gauge; } @Override public Meter meter(final String name) { final Meter meter = new NoOpMeter(); meters.put(name, meter); return meter; } @Override public Histogram histogram(final String name) { final Histogram histogram = new NoOpHistogram(); histograms.put(name, histogram); return histogram; } @Override public Timer timer(final String name) { final Timer timer = new NoOpTimer(); timers.put(name, timer); return timer; } @Override public boolean remove(final String name) { if (gauges.remove(name) != null) { return true; } else if (counters.remove(name) != null) { return true; } else if (histograms.remove(name) != null) { return true; } else if (meters.remove(name) != null) { return true; } else { return timers.remove(name) != null; } } @Override public Map<String, ?> getMetrics() { final Map<String, Object> metrics = new HashMap<>(); metrics.putAll(gauges); metrics.putAll(counters); metrics.putAll(histograms); metrics.putAll(meters); metrics.putAll(timers); return metrics; } @Override public Map<String, Gauge<?>> getGauges() { return new HashMap<>(gauges); } @Override public Map<String, Counter> getCounters() { return new HashMap<>(counters); } @Override public Map<String, Histogram> getHistograms() { return new HashMap<>(histograms); } @Override public Map<String, Meter> getMeters() { return new HashMap<>(meters); } @Override public Map<String, Timer> getTimers() { return new HashMap<>(timers); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpMeter.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpMeter.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import java.util.concurrent.atomic.LongAdder; import org.killbill.commons.metrics.api.Meter; public class NoOpMeter implements Meter { private final LongAdder count = new LongAdder(); @Override public long getCount() { return count.sum(); } @Override public void mark(final long n) { count.add(n); } @Override public double getFifteenMinuteRate() { return 0; } @Override public double getFiveMinuteRate() { return 0; } @Override public double getMeanRate() { return 0; } @Override public double getOneMinuteRate() { return 0; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpHistogram.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpHistogram.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import java.util.concurrent.atomic.LongAdder; import org.killbill.commons.metrics.api.Histogram; import org.killbill.commons.metrics.api.Snapshot; public class NoOpHistogram implements Histogram { private final LongAdder count = new LongAdder(); @Override public void update(final long value) { count.increment(); } @Override public long getCount() { return count.sum(); } @Override public Snapshot getSnapshot() { return null; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpTimer.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpTimer.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import java.util.concurrent.TimeUnit; import org.killbill.commons.metrics.api.Histogram; import org.killbill.commons.metrics.api.Meter; import org.killbill.commons.metrics.api.Snapshot; import org.killbill.commons.metrics.api.Timer; public class NoOpTimer implements Timer { private final Meter meter; private final Histogram histogram; public NoOpTimer() { this.meter = new NoOpMeter(); this.histogram = new NoOpHistogram(); } @Override public void update(final long duration, final TimeUnit unit) { if (duration >= 0) { histogram.update(unit.toNanos(duration)); meter.mark(1); } } @Override public long getCount() { return histogram.getCount(); } @Override public double getFifteenMinuteRate() { return meter.getFifteenMinuteRate(); } @Override public double getFiveMinuteRate() { return meter.getFiveMinuteRate(); } @Override public double getMeanRate() { return meter.getMeanRate(); } @Override public double getOneMinuteRate() { return meter.getOneMinuteRate(); } @Override public Snapshot getSnapshot() { return histogram.getSnapshot(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpCounter.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpCounter.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import java.util.concurrent.atomic.LongAdder; import org.killbill.commons.metrics.api.Counter; public class NoOpCounter implements Counter { private final LongAdder count = new LongAdder(); @Override public long getCount() { return count.sum(); } @Override public void inc(final long n) { count.add(n); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpGauge.java
metrics-api/src/main/java/org/killbill/commons/metrics/impl/NoOpGauge.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.impl; import org.killbill.commons.metrics.api.Gauge; public class NoOpGauge<T> implements Gauge<T> { private final T value; public NoOpGauge(final T value) { this.value = value; } @Override public T getValue() { return value; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Counting.java
metrics-api/src/main/java/org/killbill/commons/metrics/api/Counting.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.api; /** * An interface for metric types which have counts. */ public interface Counting { /** * Returns the current count. * * @return the current count */ long getCount(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Metric.java
metrics-api/src/main/java/org/killbill/commons/metrics/api/Metric.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.api; /** * A tag interface to indicate that a class is a metric. */ public interface Metric { }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Timer.java
metrics-api/src/main/java/org/killbill/commons/metrics/api/Timer.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.api; import java.util.concurrent.TimeUnit; /** * A timer metric which aggregates timing durations and provides duration statistics, plus * throughput statistics. */ public interface Timer extends Metered, Sampling { /** * Returns the number of events which have been marked. * * @return the number of events which have been marked */ long getCount(); /** * Adds a recorded duration. * * @param duration the length of the duration * @param unit the scale unit of {@code duration} */ void update(long duration, TimeUnit unit); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/MetricRegistry.java
metrics-api/src/main/java/org/killbill/commons/metrics/api/MetricRegistry.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.metrics.api; import java.util.Map; public interface MetricRegistry { /** * Return the {@link Counter} registered under this name; or create and register * a new {@link Counter} if none is registered. * * @param name the name of the metric * @return a new or pre-existing {@link Counter} */ public Counter counter(String name); /** * Return the {@link Gauge} registered under this name; or create and register * a new {@link Gauge} if none is registered. * * @param name the name of the metric * @param supplier the underlying Gauge * @return a new or pre-existing {@link Gauge} */ <T> Gauge<T> gauge(String name, Gauge<T> supplier); /** * Return the {@link Histogram} registered under this name; or create and register * a new {@link Histogram} if none is registered. * * @param name the name of the metric * @return a new or pre-existing {@link Histogram} */ Histogram histogram(String name); /** * Return the {@link Meter} registered under this name; or create and register * a new {@link Meter} if none is registered. * * @param name the name of the metric * @return a new or pre-existing {@link Meter} */ public Meter meter(String name); /** * Return the {@link Timer} registered under this name; or create and register * a new {@link Timer} if none is registered. * * @param name the name of the metric * @return a new or pre-existing {@link Timer} */ Timer timer(String name); /** * Removes the metric with the given name. * * @param name the name of the metric * @return whether or not the metric was removed */ boolean remove(String name); Map<String, ?> getMetrics(); Map<String, Counter> getCounters(); Map<String, Histogram> getHistograms(); Map<String, Gauge<?>> getGauges(); Map<String, Meter> getMeters(); Map<String, Timer> getTimers(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false