repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // }
import java.util.Random; import pitt.search.semanticvectors.vectors.ComplexVector.Mode;
/** Copyright (c) 2011, the SemanticVectors AUTHORS. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors.vectors; /** * Class for building vectors, designed to be used externally. * * @author Dominic Widdows */ public class VectorFactory { private static final BinaryVector binaryInstance = new BinaryVector(0); private static final RealVector realInstance = new RealVector(0); private static final ComplexVector complexInstance =
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // } // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java import java.util.Random; import pitt.search.semanticvectors.vectors.ComplexVector.Mode; /** Copyright (c) 2011, the SemanticVectors AUTHORS. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors.vectors; /** * Class for building vectors, designed to be used externally. * * @author Dominic Widdows */ public class VectorFactory { private static final BinaryVector binaryInstance = new BinaryVector(0); private static final RealVector realInstance = new RealVector(0); private static final ComplexVector complexInstance =
new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE);
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/vectors/ComplexVectorUtils.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // }
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Logger; import pitt.search.semanticvectors.vectors.ComplexVector.Mode;
package pitt.search.semanticvectors.vectors; /** * Complex number utilities class. * * Contains static methods for various operation on complex vectors. * * @author Lance De Vine */ public class ComplexVectorUtils { public static final Logger logger = Logger.getLogger(RealVector.class.getCanonicalName()); /** * Superposes vec2 with vec1. * vec1 is in CARTESIAN mode. * vec2 is in POLAR mode. */ public static void superposeWithAngle( ComplexVector vec1, ComplexVector vec2 ) { int dim = vec1.getDimension(); assert(dim == vec2.getDimension());
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // } // Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVectorUtils.java import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Logger; import pitt.search.semanticvectors.vectors.ComplexVector.Mode; package pitt.search.semanticvectors.vectors; /** * Complex number utilities class. * * Contains static methods for various operation on complex vectors. * * @author Lance De Vine */ public class ComplexVectorUtils { public static final Logger logger = Logger.getLogger(RealVector.class.getCanonicalName()); /** * Superposes vec2 with vec1. * vec1 is in CARTESIAN mode. * vec2 is in POLAR mode. */ public static void superposeWithAngle( ComplexVector vec1, ComplexVector vec2 ) { int dim = vec1.getDimension(); assert(dim == vec2.getDimension());
assert(vec1.getOpMode() == ComplexVector.Mode.CARTESIAN || vec1.getOpMode() == ComplexVector.Mode.HERMITIAN);
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/adapters/VideoAdapter.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/videos/Video.java // public class Video { // // @SerializedName("id") // private String id; // //iso_639_1 missing // //iso_3166_1 missing // @SerializedName("key") // private String key; // @SerializedName("name") // private String name; // @SerializedName("site") // private String site; // @SerializedName("size") // private Integer size; // @SerializedName("type") // private String type; // // public Video(String id, String key, String name, String site, Integer size, String type) { // this.id = id; // this.key = key; // this.name = name; // this.site = site; // this.size = size; // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSite() { // return site; // } // // public void setSite(String site) { // this.site = site; // } // // public Integer getSize() { // return size; // } // // public void setSize(Integer size) { // this.size = size; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/Constants.java // public class Constants { // // public static final String FIRST_TIME_LAUNCH = "first_time_launch"; // public static final String MOVIE_ID = "movie_id"; // public static final String TV_SHOW_ID = "tv_show_id"; // public static final String VIEW_ALL_MOVIES_TYPE = "type_view_all_movies"; // public static final int NOW_SHOWING_MOVIES_TYPE = 1; // public static final int POPULAR_MOVIES_TYPE = 2; // public static final int UPCOMING_MOVIES_TYPE = 3; // public static final int TOP_RATED_MOVIES_TYPE = 4; // public static final String VIEW_ALL_TV_SHOWS_TYPE = "type_view_all_tv_shows"; // public static final int AIRING_TODAY_TV_SHOWS_TYPE = 1; // public static final int ON_THE_AIR_TV_SHOWS_TYPE = 2; // public static final int POPULAR_TV_SHOWS_TYPE = 3; // public static final int TOP_RATED_TV_SHOWS_TYPE = 4; // public static final String PERSON_ID = "person_id"; // public static final String QUERY = "query"; // public static final String RATING_SYMBOL = "\u2605"; // public static final String IMAGE_LOADING_BASE_URL_1280 = "https://image.tmdb.org/t/p/w1280/"; // public static final String IMAGE_LOADING_BASE_URL_342 = "https://image.tmdb.org/t/p/w342/"; // public static final String IMAGE_LOADING_BASE_URL_780 = "https://image.tmdb.org/t/p/w780/"; // public static final String YOUTUBE_WATCH_BASE_URL = "https://www.youtube.com/watch?v="; // public static final String YOUTUBE_THUMBNAIL_BASE_URL = "http://img.youtube.com/vi/"; // public static final String YOUTUBE_THUMBNAIL_IMAGE_QUALITY = "/hqdefault.jpg"; // public static final String IMDB_BASE_URL = "http://www.imdb.com/title/"; // public static final int TAG_FAV = 0; // public static final int TAG_NOT_FAV = 1; // //public static final String TAG_MOVIES_FRAGMENT = "tag_movies_fragment"; // //public static final String TAG_TV_SHOWS_FRAGMENT = "tag_tv_shows_fragment"; // //public static final String TAG_FAV_FRAGMENT = "tag_fav_fragment"; // // }
import android.content.Context; import android.content.Intent; import android.net.Uri; 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.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.network.videos.Video; import com.hitanshudhawan.popcorn.utils.Constants; import java.util.List;
package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 2/8/17. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private Context mContext;
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/videos/Video.java // public class Video { // // @SerializedName("id") // private String id; // //iso_639_1 missing // //iso_3166_1 missing // @SerializedName("key") // private String key; // @SerializedName("name") // private String name; // @SerializedName("site") // private String site; // @SerializedName("size") // private Integer size; // @SerializedName("type") // private String type; // // public Video(String id, String key, String name, String site, Integer size, String type) { // this.id = id; // this.key = key; // this.name = name; // this.site = site; // this.size = size; // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSite() { // return site; // } // // public void setSite(String site) { // this.site = site; // } // // public Integer getSize() { // return size; // } // // public void setSize(Integer size) { // this.size = size; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/Constants.java // public class Constants { // // public static final String FIRST_TIME_LAUNCH = "first_time_launch"; // public static final String MOVIE_ID = "movie_id"; // public static final String TV_SHOW_ID = "tv_show_id"; // public static final String VIEW_ALL_MOVIES_TYPE = "type_view_all_movies"; // public static final int NOW_SHOWING_MOVIES_TYPE = 1; // public static final int POPULAR_MOVIES_TYPE = 2; // public static final int UPCOMING_MOVIES_TYPE = 3; // public static final int TOP_RATED_MOVIES_TYPE = 4; // public static final String VIEW_ALL_TV_SHOWS_TYPE = "type_view_all_tv_shows"; // public static final int AIRING_TODAY_TV_SHOWS_TYPE = 1; // public static final int ON_THE_AIR_TV_SHOWS_TYPE = 2; // public static final int POPULAR_TV_SHOWS_TYPE = 3; // public static final int TOP_RATED_TV_SHOWS_TYPE = 4; // public static final String PERSON_ID = "person_id"; // public static final String QUERY = "query"; // public static final String RATING_SYMBOL = "\u2605"; // public static final String IMAGE_LOADING_BASE_URL_1280 = "https://image.tmdb.org/t/p/w1280/"; // public static final String IMAGE_LOADING_BASE_URL_342 = "https://image.tmdb.org/t/p/w342/"; // public static final String IMAGE_LOADING_BASE_URL_780 = "https://image.tmdb.org/t/p/w780/"; // public static final String YOUTUBE_WATCH_BASE_URL = "https://www.youtube.com/watch?v="; // public static final String YOUTUBE_THUMBNAIL_BASE_URL = "http://img.youtube.com/vi/"; // public static final String YOUTUBE_THUMBNAIL_IMAGE_QUALITY = "/hqdefault.jpg"; // public static final String IMDB_BASE_URL = "http://www.imdb.com/title/"; // public static final int TAG_FAV = 0; // public static final int TAG_NOT_FAV = 1; // //public static final String TAG_MOVIES_FRAGMENT = "tag_movies_fragment"; // //public static final String TAG_TV_SHOWS_FRAGMENT = "tag_tv_shows_fragment"; // //public static final String TAG_FAV_FRAGMENT = "tag_fav_fragment"; // // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/VideoAdapter.java import android.content.Context; import android.content.Intent; import android.net.Uri; 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.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.network.videos.Video; import com.hitanshudhawan.popcorn.utils.Constants; import java.util.List; package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 2/8/17. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private Context mContext;
private List<Video> mVideos;
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/adapters/VideoAdapter.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/videos/Video.java // public class Video { // // @SerializedName("id") // private String id; // //iso_639_1 missing // //iso_3166_1 missing // @SerializedName("key") // private String key; // @SerializedName("name") // private String name; // @SerializedName("site") // private String site; // @SerializedName("size") // private Integer size; // @SerializedName("type") // private String type; // // public Video(String id, String key, String name, String site, Integer size, String type) { // this.id = id; // this.key = key; // this.name = name; // this.site = site; // this.size = size; // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSite() { // return site; // } // // public void setSite(String site) { // this.site = site; // } // // public Integer getSize() { // return size; // } // // public void setSize(Integer size) { // this.size = size; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/Constants.java // public class Constants { // // public static final String FIRST_TIME_LAUNCH = "first_time_launch"; // public static final String MOVIE_ID = "movie_id"; // public static final String TV_SHOW_ID = "tv_show_id"; // public static final String VIEW_ALL_MOVIES_TYPE = "type_view_all_movies"; // public static final int NOW_SHOWING_MOVIES_TYPE = 1; // public static final int POPULAR_MOVIES_TYPE = 2; // public static final int UPCOMING_MOVIES_TYPE = 3; // public static final int TOP_RATED_MOVIES_TYPE = 4; // public static final String VIEW_ALL_TV_SHOWS_TYPE = "type_view_all_tv_shows"; // public static final int AIRING_TODAY_TV_SHOWS_TYPE = 1; // public static final int ON_THE_AIR_TV_SHOWS_TYPE = 2; // public static final int POPULAR_TV_SHOWS_TYPE = 3; // public static final int TOP_RATED_TV_SHOWS_TYPE = 4; // public static final String PERSON_ID = "person_id"; // public static final String QUERY = "query"; // public static final String RATING_SYMBOL = "\u2605"; // public static final String IMAGE_LOADING_BASE_URL_1280 = "https://image.tmdb.org/t/p/w1280/"; // public static final String IMAGE_LOADING_BASE_URL_342 = "https://image.tmdb.org/t/p/w342/"; // public static final String IMAGE_LOADING_BASE_URL_780 = "https://image.tmdb.org/t/p/w780/"; // public static final String YOUTUBE_WATCH_BASE_URL = "https://www.youtube.com/watch?v="; // public static final String YOUTUBE_THUMBNAIL_BASE_URL = "http://img.youtube.com/vi/"; // public static final String YOUTUBE_THUMBNAIL_IMAGE_QUALITY = "/hqdefault.jpg"; // public static final String IMDB_BASE_URL = "http://www.imdb.com/title/"; // public static final int TAG_FAV = 0; // public static final int TAG_NOT_FAV = 1; // //public static final String TAG_MOVIES_FRAGMENT = "tag_movies_fragment"; // //public static final String TAG_TV_SHOWS_FRAGMENT = "tag_tv_shows_fragment"; // //public static final String TAG_FAV_FRAGMENT = "tag_fav_fragment"; // // }
import android.content.Context; import android.content.Intent; import android.net.Uri; 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.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.network.videos.Video; import com.hitanshudhawan.popcorn.utils.Constants; import java.util.List;
package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 2/8/17. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private Context mContext; private List<Video> mVideos; public VideoAdapter(Context mContext, List<Video> videos) { this.mContext = mContext; this.mVideos = videos; } @Override public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VideoViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_video, parent, false)); } @Override public void onBindViewHolder(VideoViewHolder holder, int position) {
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/videos/Video.java // public class Video { // // @SerializedName("id") // private String id; // //iso_639_1 missing // //iso_3166_1 missing // @SerializedName("key") // private String key; // @SerializedName("name") // private String name; // @SerializedName("site") // private String site; // @SerializedName("size") // private Integer size; // @SerializedName("type") // private String type; // // public Video(String id, String key, String name, String site, Integer size, String type) { // this.id = id; // this.key = key; // this.name = name; // this.site = site; // this.size = size; // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSite() { // return site; // } // // public void setSite(String site) { // this.site = site; // } // // public Integer getSize() { // return size; // } // // public void setSize(Integer size) { // this.size = size; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/Constants.java // public class Constants { // // public static final String FIRST_TIME_LAUNCH = "first_time_launch"; // public static final String MOVIE_ID = "movie_id"; // public static final String TV_SHOW_ID = "tv_show_id"; // public static final String VIEW_ALL_MOVIES_TYPE = "type_view_all_movies"; // public static final int NOW_SHOWING_MOVIES_TYPE = 1; // public static final int POPULAR_MOVIES_TYPE = 2; // public static final int UPCOMING_MOVIES_TYPE = 3; // public static final int TOP_RATED_MOVIES_TYPE = 4; // public static final String VIEW_ALL_TV_SHOWS_TYPE = "type_view_all_tv_shows"; // public static final int AIRING_TODAY_TV_SHOWS_TYPE = 1; // public static final int ON_THE_AIR_TV_SHOWS_TYPE = 2; // public static final int POPULAR_TV_SHOWS_TYPE = 3; // public static final int TOP_RATED_TV_SHOWS_TYPE = 4; // public static final String PERSON_ID = "person_id"; // public static final String QUERY = "query"; // public static final String RATING_SYMBOL = "\u2605"; // public static final String IMAGE_LOADING_BASE_URL_1280 = "https://image.tmdb.org/t/p/w1280/"; // public static final String IMAGE_LOADING_BASE_URL_342 = "https://image.tmdb.org/t/p/w342/"; // public static final String IMAGE_LOADING_BASE_URL_780 = "https://image.tmdb.org/t/p/w780/"; // public static final String YOUTUBE_WATCH_BASE_URL = "https://www.youtube.com/watch?v="; // public static final String YOUTUBE_THUMBNAIL_BASE_URL = "http://img.youtube.com/vi/"; // public static final String YOUTUBE_THUMBNAIL_IMAGE_QUALITY = "/hqdefault.jpg"; // public static final String IMDB_BASE_URL = "http://www.imdb.com/title/"; // public static final int TAG_FAV = 0; // public static final int TAG_NOT_FAV = 1; // //public static final String TAG_MOVIES_FRAGMENT = "tag_movies_fragment"; // //public static final String TAG_TV_SHOWS_FRAGMENT = "tag_tv_shows_fragment"; // //public static final String TAG_FAV_FRAGMENT = "tag_fav_fragment"; // // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/VideoAdapter.java import android.content.Context; import android.content.Intent; import android.net.Uri; 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.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.network.videos.Video; import com.hitanshudhawan.popcorn.utils.Constants; import java.util.List; package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 2/8/17. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private Context mContext; private List<Video> mVideos; public VideoAdapter(Context mContext, List<Video> videos) { this.mContext = mContext; this.mVideos = videos; } @Override public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VideoViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_video, parent, false)); } @Override public void onBindViewHolder(VideoViewHolder holder, int position) {
Glide.with(mContext.getApplicationContext()).load(Constants.YOUTUBE_THUMBNAIL_BASE_URL + mVideos.get(position).getKey() + Constants.YOUTUBE_THUMBNAIL_IMAGE_QUALITY)
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/broadcastreceivers/ConnectivityBroadcastReceiver.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/NetworkConnection.java // public class NetworkConnection { // // public static boolean isConnected(Context context) { // ConnectivityManager connectivityManager // = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.hitanshudhawan.popcorn.utils.NetworkConnection;
package com.hitanshudhawan.popcorn.broadcastreceivers; /** * Created by hitanshu on 26/8/17. */ public class ConnectivityBroadcastReceiver extends BroadcastReceiver { private ConnectivityReceiverListener mConnectivityReceiverListener; public ConnectivityBroadcastReceiver(ConnectivityReceiverListener mConnectivityReceiverListener) { this.mConnectivityReceiverListener = mConnectivityReceiverListener; } @Override public void onReceive(Context context, Intent intent) {
// Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/NetworkConnection.java // public class NetworkConnection { // // public static boolean isConnected(Context context) { // ConnectivityManager connectivityManager // = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/broadcastreceivers/ConnectivityBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.hitanshudhawan.popcorn.utils.NetworkConnection; package com.hitanshudhawan.popcorn.broadcastreceivers; /** * Created by hitanshu on 26/8/17. */ public class ConnectivityBroadcastReceiver extends BroadcastReceiver { private ConnectivityReceiverListener mConnectivityReceiverListener; public ConnectivityBroadcastReceiver(ConnectivityReceiverListener mConnectivityReceiverListener) { this.mConnectivityReceiverListener = mConnectivityReceiverListener; } @Override public void onReceive(Context context, Intent intent) {
if (mConnectivityReceiverListener != null && NetworkConnection.isConnected(context))
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/utils/TVShowGenres.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/tvshows/Genre.java // public class Genre { // // @SerializedName("id") // private Integer id; // @SerializedName("name") // private String genreName; // // public Genre(Integer id, String genreName) { // this.id = id; // this.genreName = genreName; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getGenreName() { // return genreName; // } // // public void setGenreName(String genreName) { // this.genreName = genreName; // } // }
import com.hitanshudhawan.popcorn.network.tvshows.Genre; import java.util.HashMap; import java.util.List;
package com.hitanshudhawan.popcorn.utils; /** * Created by hitanshu on 13/8/17. */ public class TVShowGenres { private static HashMap<Integer, String> genresMap; public static boolean isGenresListLoaded() { return (genresMap != null); }
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/tvshows/Genre.java // public class Genre { // // @SerializedName("id") // private Integer id; // @SerializedName("name") // private String genreName; // // public Genre(Integer id, String genreName) { // this.id = id; // this.genreName = genreName; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getGenreName() { // return genreName; // } // // public void setGenreName(String genreName) { // this.genreName = genreName; // } // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/TVShowGenres.java import com.hitanshudhawan.popcorn.network.tvshows.Genre; import java.util.HashMap; import java.util.List; package com.hitanshudhawan.popcorn.utils; /** * Created by hitanshu on 13/8/17. */ public class TVShowGenres { private static HashMap<Integer, String> genresMap; public static boolean isGenresListLoaded() { return (genresMap != null); }
public static void loadGenresList(List<Genre> genres) {
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/utils/MovieGenres.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/movies/Genre.java // public class Genre { // // @SerializedName("id") // private Integer id; // @SerializedName("name") // private String genreName; // // public Genre(Integer id, String genreName) { // this.id = id; // this.genreName = genreName; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getGenreName() { // return genreName; // } // // public void setGenreName(String genreName) { // this.genreName = genreName; // } // }
import com.hitanshudhawan.popcorn.network.movies.Genre; import java.util.HashMap; import java.util.List;
package com.hitanshudhawan.popcorn.utils; /** * Created by hitanshu on 13/8/17. */ public class MovieGenres { private static HashMap<Integer, String> genresMap; public static boolean isGenresListLoaded() { return (genresMap != null); }
// Path: app/src/main/java/com/hitanshudhawan/popcorn/network/movies/Genre.java // public class Genre { // // @SerializedName("id") // private Integer id; // @SerializedName("name") // private String genreName; // // public Genre(Integer id, String genreName) { // this.id = id; // this.genreName = genreName; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getGenreName() { // return genreName; // } // // public void setGenreName(String genreName) { // this.genreName = genreName; // } // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/utils/MovieGenres.java import com.hitanshudhawan.popcorn.network.movies.Genre; import java.util.HashMap; import java.util.List; package com.hitanshudhawan.popcorn.utils; /** * Created by hitanshu on 13/8/17. */ public class MovieGenres { private static HashMap<Integer, String> genresMap; public static boolean isGenresListLoaded() { return (genresMap != null); }
public static void loadGenresList(List<Genre> genres) {
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteMoviesFragment.java // public class FavouriteMoviesFragment extends Fragment { // // private RecyclerView mFavMoviesRecyclerView; // private List<MovieBrief> mFavMovies; // private MovieBriefsSmallAdapter mFavMoviesAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_movies, container, false); // // mFavMoviesRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_movies); // mFavMovies = new ArrayList<>(); // mFavMoviesAdapter = new MovieBriefsSmallAdapter(getContext(), mFavMovies); // mFavMoviesRecyclerView.setAdapter(mFavMoviesAdapter); // mFavMoviesRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_movies_empty); // // loadFavMovies(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavMoviesAdapter.notifyDataSetChanged(); // } // // private void loadFavMovies() { // List<MovieBrief> favMovieBriefs = Favourite.getFavMovieBriefs(getContext()); // if (favMovieBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (MovieBrief movieBrief : favMovieBriefs) { // mFavMovies.add(movieBrief); // } // mFavMoviesAdapter.notifyDataSetChanged(); // } // // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteTVShowsFragment.java // public class FavouriteTVShowsFragment extends Fragment { // // private RecyclerView mFavTVShowsRecyclerView; // private List<TVShowBrief> mFavTVShows; // private TVShowBriefsSmallAdapter mFavTVShowsAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_tv_shows, container, false); // // mFavTVShowsRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_tv_shows); // mFavTVShows = new ArrayList<>(); // mFavTVShowsAdapter = new TVShowBriefsSmallAdapter(getContext(), mFavTVShows); // mFavTVShowsRecyclerView.setAdapter(mFavTVShowsAdapter); // mFavTVShowsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_tv_shows_empty); // // loadFavTVShows(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // private void loadFavTVShows() { // List<TVShowBrief> favTVShowBriefs = Favourite.getFavTVShowBriefs(getContext()); // if (favTVShowBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (TVShowBrief tvShowBrief : favTVShowBriefs) { // mFavTVShows.add(tvShowBrief); // } // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.fragments.FavouriteMoviesFragment; import com.hitanshudhawan.popcorn.fragments.FavouriteTVShowsFragment;
package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 10/8/17. */ public class FavouritesPagerAdapter extends FragmentPagerAdapter { private Context mContext; public FavouritesPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position) { case 0:
// Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteMoviesFragment.java // public class FavouriteMoviesFragment extends Fragment { // // private RecyclerView mFavMoviesRecyclerView; // private List<MovieBrief> mFavMovies; // private MovieBriefsSmallAdapter mFavMoviesAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_movies, container, false); // // mFavMoviesRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_movies); // mFavMovies = new ArrayList<>(); // mFavMoviesAdapter = new MovieBriefsSmallAdapter(getContext(), mFavMovies); // mFavMoviesRecyclerView.setAdapter(mFavMoviesAdapter); // mFavMoviesRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_movies_empty); // // loadFavMovies(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavMoviesAdapter.notifyDataSetChanged(); // } // // private void loadFavMovies() { // List<MovieBrief> favMovieBriefs = Favourite.getFavMovieBriefs(getContext()); // if (favMovieBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (MovieBrief movieBrief : favMovieBriefs) { // mFavMovies.add(movieBrief); // } // mFavMoviesAdapter.notifyDataSetChanged(); // } // // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteTVShowsFragment.java // public class FavouriteTVShowsFragment extends Fragment { // // private RecyclerView mFavTVShowsRecyclerView; // private List<TVShowBrief> mFavTVShows; // private TVShowBriefsSmallAdapter mFavTVShowsAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_tv_shows, container, false); // // mFavTVShowsRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_tv_shows); // mFavTVShows = new ArrayList<>(); // mFavTVShowsAdapter = new TVShowBriefsSmallAdapter(getContext(), mFavTVShows); // mFavTVShowsRecyclerView.setAdapter(mFavTVShowsAdapter); // mFavTVShowsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_tv_shows_empty); // // loadFavTVShows(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // private void loadFavTVShows() { // List<TVShowBrief> favTVShowBriefs = Favourite.getFavTVShowBriefs(getContext()); // if (favTVShowBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (TVShowBrief tvShowBrief : favTVShowBriefs) { // mFavTVShows.add(tvShowBrief); // } // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.fragments.FavouriteMoviesFragment; import com.hitanshudhawan.popcorn.fragments.FavouriteTVShowsFragment; package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 10/8/17. */ public class FavouritesPagerAdapter extends FragmentPagerAdapter { private Context mContext; public FavouritesPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position) { case 0:
return new FavouriteMoviesFragment();
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteMoviesFragment.java // public class FavouriteMoviesFragment extends Fragment { // // private RecyclerView mFavMoviesRecyclerView; // private List<MovieBrief> mFavMovies; // private MovieBriefsSmallAdapter mFavMoviesAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_movies, container, false); // // mFavMoviesRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_movies); // mFavMovies = new ArrayList<>(); // mFavMoviesAdapter = new MovieBriefsSmallAdapter(getContext(), mFavMovies); // mFavMoviesRecyclerView.setAdapter(mFavMoviesAdapter); // mFavMoviesRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_movies_empty); // // loadFavMovies(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavMoviesAdapter.notifyDataSetChanged(); // } // // private void loadFavMovies() { // List<MovieBrief> favMovieBriefs = Favourite.getFavMovieBriefs(getContext()); // if (favMovieBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (MovieBrief movieBrief : favMovieBriefs) { // mFavMovies.add(movieBrief); // } // mFavMoviesAdapter.notifyDataSetChanged(); // } // // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteTVShowsFragment.java // public class FavouriteTVShowsFragment extends Fragment { // // private RecyclerView mFavTVShowsRecyclerView; // private List<TVShowBrief> mFavTVShows; // private TVShowBriefsSmallAdapter mFavTVShowsAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_tv_shows, container, false); // // mFavTVShowsRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_tv_shows); // mFavTVShows = new ArrayList<>(); // mFavTVShowsAdapter = new TVShowBriefsSmallAdapter(getContext(), mFavTVShows); // mFavTVShowsRecyclerView.setAdapter(mFavTVShowsAdapter); // mFavTVShowsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_tv_shows_empty); // // loadFavTVShows(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // private void loadFavTVShows() { // List<TVShowBrief> favTVShowBriefs = Favourite.getFavTVShowBriefs(getContext()); // if (favTVShowBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (TVShowBrief tvShowBrief : favTVShowBriefs) { // mFavTVShows.add(tvShowBrief); // } // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.fragments.FavouriteMoviesFragment; import com.hitanshudhawan.popcorn.fragments.FavouriteTVShowsFragment;
package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 10/8/17. */ public class FavouritesPagerAdapter extends FragmentPagerAdapter { private Context mContext; public FavouritesPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new FavouriteMoviesFragment(); case 1:
// Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteMoviesFragment.java // public class FavouriteMoviesFragment extends Fragment { // // private RecyclerView mFavMoviesRecyclerView; // private List<MovieBrief> mFavMovies; // private MovieBriefsSmallAdapter mFavMoviesAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_movies, container, false); // // mFavMoviesRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_movies); // mFavMovies = new ArrayList<>(); // mFavMoviesAdapter = new MovieBriefsSmallAdapter(getContext(), mFavMovies); // mFavMoviesRecyclerView.setAdapter(mFavMoviesAdapter); // mFavMoviesRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_movies_empty); // // loadFavMovies(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavMoviesAdapter.notifyDataSetChanged(); // } // // private void loadFavMovies() { // List<MovieBrief> favMovieBriefs = Favourite.getFavMovieBriefs(getContext()); // if (favMovieBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (MovieBrief movieBrief : favMovieBriefs) { // mFavMovies.add(movieBrief); // } // mFavMoviesAdapter.notifyDataSetChanged(); // } // // } // // Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouriteTVShowsFragment.java // public class FavouriteTVShowsFragment extends Fragment { // // private RecyclerView mFavTVShowsRecyclerView; // private List<TVShowBrief> mFavTVShows; // private TVShowBriefsSmallAdapter mFavTVShowsAdapter; // // private LinearLayout mEmptyLayout; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_favourite_tv_shows, container, false); // // mFavTVShowsRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_fav_tv_shows); // mFavTVShows = new ArrayList<>(); // mFavTVShowsAdapter = new TVShowBriefsSmallAdapter(getContext(), mFavTVShows); // mFavTVShowsRecyclerView.setAdapter(mFavTVShowsAdapter); // mFavTVShowsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3)); // // mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_recycler_view_fav_tv_shows_empty); // // loadFavTVShows(); // // return view; // } // // @Override // public void onStart() { // super.onStart(); // // TODO (feature or a bug? :P) // // hitanshu : use Room with LiveData to solve this problem // // for now when coming back to this activity after removing from fav it shows border heart. // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // private void loadFavTVShows() { // List<TVShowBrief> favTVShowBriefs = Favourite.getFavTVShowBriefs(getContext()); // if (favTVShowBriefs.isEmpty()) { // mEmptyLayout.setVisibility(View.VISIBLE); // return; // } // // for (TVShowBrief tvShowBrief : favTVShowBriefs) { // mFavTVShows.add(tvShowBrief); // } // mFavTVShowsAdapter.notifyDataSetChanged(); // } // // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.fragments.FavouriteMoviesFragment; import com.hitanshudhawan.popcorn.fragments.FavouriteTVShowsFragment; package com.hitanshudhawan.popcorn.adapters; /** * Created by hitanshu on 10/8/17. */ public class FavouritesPagerAdapter extends FragmentPagerAdapter { private Context mContext; public FavouritesPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new FavouriteMoviesFragment(); case 1:
return new FavouriteTVShowsFragment();
hitanshu-dhawan/PopCorn
app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouritesFragment.java
// Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java // public class FavouritesPagerAdapter extends FragmentPagerAdapter { // // private Context mContext; // // public FavouritesPagerAdapter(FragmentManager fm, Context context) { // super(fm); // mContext = context; // } // // @Override // public Fragment getItem(int position) { // switch (position) { // case 0: // return new FavouriteMoviesFragment(); // case 1: // return new FavouriteTVShowsFragment(); // } // return null; // } // // @Override // public int getCount() { // return 2; // } // // @Override // public CharSequence getPageTitle(int position) { // switch (position) { // case 0: // return mContext.getResources().getString(R.string.movies); // case 1: // return mContext.getResources().getString(R.string.tv_shows); // } // return null; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.adapters.FavouritesPagerAdapter; import com.ogaclejapan.smarttablayout.SmartTabLayout;
package com.hitanshudhawan.popcorn.fragments; /** * Created by hitanshu on 10/8/17. */ public class FavouritesFragment extends Fragment { private SmartTabLayout mSmartTabLayout; private ViewPager mViewPager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_favourites, container, false); mSmartTabLayout = (SmartTabLayout) view.findViewById(R.id.tab_view_pager_fav); mViewPager = (ViewPager) view.findViewById(R.id.view_pager_fav);
// Path: app/src/main/java/com/hitanshudhawan/popcorn/adapters/FavouritesPagerAdapter.java // public class FavouritesPagerAdapter extends FragmentPagerAdapter { // // private Context mContext; // // public FavouritesPagerAdapter(FragmentManager fm, Context context) { // super(fm); // mContext = context; // } // // @Override // public Fragment getItem(int position) { // switch (position) { // case 0: // return new FavouriteMoviesFragment(); // case 1: // return new FavouriteTVShowsFragment(); // } // return null; // } // // @Override // public int getCount() { // return 2; // } // // @Override // public CharSequence getPageTitle(int position) { // switch (position) { // case 0: // return mContext.getResources().getString(R.string.movies); // case 1: // return mContext.getResources().getString(R.string.tv_shows); // } // return null; // } // } // Path: app/src/main/java/com/hitanshudhawan/popcorn/fragments/FavouritesFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hitanshudhawan.popcorn.R; import com.hitanshudhawan.popcorn.adapters.FavouritesPagerAdapter; import com.ogaclejapan.smarttablayout.SmartTabLayout; package com.hitanshudhawan.popcorn.fragments; /** * Created by hitanshu on 10/8/17. */ public class FavouritesFragment extends Fragment { private SmartTabLayout mSmartTabLayout; private ViewPager mViewPager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_favourites, container, false); mSmartTabLayout = (SmartTabLayout) view.findViewById(R.id.tab_view_pager_fav); mViewPager = (ViewPager) view.findViewById(R.id.view_pager_fav);
mViewPager.setAdapter(new FavouritesPagerAdapter(getChildFragmentManager(), getContext()));
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent .AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent .AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.axonframework.correlation.CorrelationDataHolder .getCorrelationData;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FlowTestConfiguration.class) public final class FlowIT { @Autowired private CommandGateway commands; @Autowired
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent .AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent .AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.axonframework.correlation.CorrelationDataHolder .getCorrelationData; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FlowTestConfiguration.class) public final class FlowIT { @Autowired private CommandGateway commands; @Autowired
private TestAuditEventRepository trail;
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent .AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent .AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.axonframework.correlation.CorrelationDataHolder .getCorrelationData;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FlowTestConfiguration.class) public final class FlowIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditCommandToEventToCommand() { final String aggregateId = "abc"; final InitialCommand payload = new InitialCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(3); final AuditEvent initialCommandAuditEvent = trail.eventAt(2); assertThat(initialCommandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> initialCommandData = initialCommandAuditEvent.getData();
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent .AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent .AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.axonframework.correlation.CorrelationDataHolder .getCorrelationData; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FlowTestConfiguration.class) public final class FlowIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditCommandToEventToCommand() { final String aggregateId = "abc"; final InitialCommand payload = new InitialCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(3); final AuditEvent initialCommandAuditEvent = trail.eventAt(2); assertThat(initialCommandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> initialCommandData = initialCommandAuditEvent.getData();
assertThat(initialCommandData.get(MESSAGE_TYPE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataTestConfiguration.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // }
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.eventstore.EventStore; import org.axonframework.eventstore.supporting.VolatileEventStore;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @Configuration @EnableAutoConfiguration public class MetaDataTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataTestConfiguration.java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.eventstore.EventStore; import org.axonframework.eventstore.supporting.VolatileEventStore; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @Configuration @EnableAutoConfiguration public class MetaDataTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
public TestAuditEventRepository testAuditEventRepository() {
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired
private TestAuditEventRepository trail;
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()).
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()).
isEqualTo(AXON_COMMAND_AUDIT_TYPE);
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData();
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData();
assertThat(commandData.get(MESSAGE_TYPE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName());
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName());
assertThat(commandData.get(RETURN_VALUE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName()); assertThat(commandData.get(RETURN_VALUE)). isEqualTo(aggregateId);
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.metadata; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MetaDataTestConfiguration.class) public final class MetaDataIT { @Autowired private CommandGateway commands; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName()); assertThat(commandData.get(RETURN_VALUE)). isEqualTo(aggregateId);
assertThat(commandData.get(FAILURE_CAUSE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat;
@Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName()); assertThat(commandData.get(RETURN_VALUE)). isEqualTo(aggregateId); assertThat(commandData.get(FAILURE_CAUSE)). isNull(); final AuditEvent eventAuditEvent = trail.eventAt(0); assertThat(eventAuditEvent.getType()).
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/metadata/MetaDataIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.gateway.CommandGateway; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditWhenSuccessful() { final String aggregateId = "abc"; final SuccessfulCommand payload = new SuccessfulCommand(aggregateId); commands.send(payload); assertThat(trail.received()). isEqualTo(2); final AuditEvent commandAuditEvent = trail.eventAt(1); assertThat(commandAuditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> commandData = commandAuditEvent.getData(); assertThat(commandData.get(MESSAGE_TYPE)). isEqualTo(SuccessfulCommand.class.getName()); assertThat(commandData.get(RETURN_VALUE)). isEqualTo(aggregateId); assertThat(commandData.get(FAILURE_CAUSE)). isNull(); final AuditEvent eventAuditEvent = trail.eventAt(0); assertThat(eventAuditEvent.getType()).
isEqualTo(AXON_EVENT_AUDIT_TYPE);
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired
private TestAuditEventRepository trail;
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()).
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()).
isEqualTo(AXON_COMMAND_AUDIT_TYPE);
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData();
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData();
assertThat(data.get(MESSAGE_TYPE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName());
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName());
assertThat(data.get(RETURN_VALUE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName()); assertThat(data.get(RETURN_VALUE)). isEqualTo(3);
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuditTestConfiguration.class) public final class AuditIT { @Autowired private CommandGateway commands; @Autowired private Cluster events; @Autowired private TestAuditEventRepository trail; @After public void resetTrail() { trail.reset(); } @Test public void shouldAuditSuccessfulCommands() { final SuccessfulCommand payload = new SuccessfulCommand(); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName()); assertThat(data.get(RETURN_VALUE)). isEqualTo(3);
assertThat(data.get(FAILURE_CAUSE)).
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value");
import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
@Test public void shouldAuditFailedCommands() { final FailedException cause = new FailedException(); final FailedCommand payload = new FailedCommand(cause); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName()); assertThat(data.get(RETURN_VALUE)). isNull(); assertThat(data.get(FAILURE_CAUSE)). isSameAs(cause); } @Test public void shouldAuditSuccessfulEvents() { final SuccessfulEvent payload = new SuccessfulEvent(); events.publish(new GenericDomainEventMessage<>("abc", 1L, payload)); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()).
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonCommandAuditEvent.java // public static final String AXON_COMMAND_AUDIT_TYPE = CommandMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/AxonEventAuditEvent.java // public static final String AXON_EVENT_AUDIT_TYPE = EventMessage.class // .getName(); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String FAILURE_CAUSE = inNamespace("failure-cause"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String MESSAGE_TYPE = inNamespace("message-type"); // // Path: axon-spring-boot-starter-monitoring/src/main/java/hm/binkley/spring/axon/SpringBootAuditLogger.java // public static final String RETURN_VALUE = inNamespace("return-value"); // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditIT.java import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.domain.GenericDomainEventMessage; import org.axonframework.eventhandling.Cluster; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Map; import static hm.binkley.spring.axon.AxonCommandAuditEvent.AXON_COMMAND_AUDIT_TYPE; import static hm.binkley.spring.axon.AxonEventAuditEvent.AXON_EVENT_AUDIT_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.FAILURE_CAUSE; import static hm.binkley.spring.axon.SpringBootAuditLogger.MESSAGE_TYPE; import static hm.binkley.spring.axon.SpringBootAuditLogger.RETURN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @Test public void shouldAuditFailedCommands() { final FailedException cause = new FailedException(); final FailedCommand payload = new FailedCommand(cause); commands.send(payload); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()). isEqualTo(AXON_COMMAND_AUDIT_TYPE); final Map<String, Object> data = auditEvent.getData(); assertThat(data.get(MESSAGE_TYPE)). isEqualTo(payload.getClass().getName()); assertThat(data.get(RETURN_VALUE)). isNull(); assertThat(data.get(FAILURE_CAUSE)). isSameAs(cause); } @Test public void shouldAuditSuccessfulEvents() { final SuccessfulEvent payload = new SuccessfulEvent(); events.publish(new GenericDomainEventMessage<>("abc", 1L, payload)); assertThat(trail.received()). isEqualTo(1); final AuditEvent auditEvent = trail.eventAt(0); assertThat(auditEvent.getType()).
isEqualTo(AXON_EVENT_AUDIT_TYPE);
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowTestConfiguration.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // }
import org.axonframework.eventstore.supporting.VolatileEventStore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.eventstore.EventStore;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @Configuration @EnableAutoConfiguration public class FlowTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/flow/FlowTestConfiguration.java import org.axonframework.eventstore.supporting.VolatileEventStore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.eventstore.EventStore; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.flow; @Configuration @EnableAutoConfiguration public class FlowTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
public TestAuditEventRepository testAuditEventRepository() {
binkley/axon-spring-boot-starter
axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditTestConfiguration.java
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // }
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.eventstore.EventStore; import org.axonframework.eventstore.supporting.VolatileEventStore;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @Configuration @EnableAutoConfiguration public class AuditTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
// Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/shared/TestAuditEventRepository.java // public class TestAuditEventRepository // implements AuditEventRepository { // private final List<AuditEvent> trail = new ArrayList<>(); // // @Override // public List<AuditEvent> find(final String principal, final Date after) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(final AuditEvent event) { // trail.add(event); // } // // public void reset() { // trail.clear(); // } // // public int received() { // return trail.size(); // } // // public AuditEvent eventAt(final int sequence) { // return trail.get(sequence); // } // } // Path: axon-spring-boot-starter-monitoring/src/test/java/hm/binkley/spring/axon/audit/AuditTestConfiguration.java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import hm.binkley.spring.axon.shared.TestAuditEventRepository; import org.axonframework.eventstore.EventStore; import org.axonframework.eventstore.supporting.VolatileEventStore; /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.spring.axon.audit; @Configuration @EnableAutoConfiguration public class AuditTestConfiguration { @Bean public EventStore eventStore() { return new VolatileEventStore(); } @Bean
public TestAuditEventRepository testAuditEventRepository() {
optimatika/ojAlgo-finance
src/main/java/org/ojalgo/finance/business/ModernAsset.java
// Path: src/main/java/org/ojalgo/finance/portfolio/SimpleAsset.java // public final class SimpleAsset extends FinancePortfolio { // // private final double myMeanReturn; // private final double myVolatility; // private final BigDecimal myWeight; // // public SimpleAsset(final FinancePortfolio portfolio) { // this(portfolio.getMeanReturn(), portfolio.getVolatility(), BigMath.ONE); // } // // public SimpleAsset(final FinancePortfolio portfolio, final Comparable<?> weight) { // this(portfolio.getMeanReturn(), portfolio.getVolatility(), weight); // } // // public SimpleAsset(final Comparable<?> weight) { // this(PrimitiveMath.ZERO, PrimitiveMath.ZERO, weight); // } // // public SimpleAsset(final Comparable<?> meanReturn, final Comparable<?> volatility) { // this(meanReturn, volatility, BigMath.ONE); // } // // public SimpleAsset(final Comparable<?> meanReturn, final Comparable<?> volatility, final Comparable<?> weight) { // // super(); // // myMeanReturn = meanReturn != null ? Scalar.doubleValue(meanReturn) : PrimitiveMath.ZERO; // myVolatility = volatility != null ? Scalar.doubleValue(volatility) : PrimitiveMath.ZERO; // myWeight = TypeUtils.toBigDecimal(weight); // } // // @SuppressWarnings("unused") // private SimpleAsset() { // this(BigMath.ZERO, BigMath.ZERO, BigMath.ONE); // } // // @Override // public double getMeanReturn() { // return myMeanReturn; // } // // @Override // public double getVolatility() { // return myVolatility; // } // // /** // * Assuming there is precisely 1 weight - this class is used to describe 1 asset (portfolio member). // */ // public BigDecimal getWeight() { // return myWeight; // } // // @Override // public List<BigDecimal> getWeights() { // return Collections.singletonList(myWeight); // } // // @Override // protected void reset() { // // } // // }
import java.math.BigDecimal; import java.util.Collection; import org.ojalgo.finance.portfolio.SimpleAsset; import java.awt.Color;
tmpR += 255; } while (tmpG < 0) { tmpG += 255; } while (tmpB < 0) { tmpB += 255; } while (tmpR > 255) { tmpR -= 255; } while (tmpG > 255) { tmpG -= 255; } while (tmpB > 255) { tmpB -= 255; } return new Color(tmpR, tmpG, tmpB); } Color getAssetColour(); String getAssetKey(); BigDecimal getWeight(); int index();
// Path: src/main/java/org/ojalgo/finance/portfolio/SimpleAsset.java // public final class SimpleAsset extends FinancePortfolio { // // private final double myMeanReturn; // private final double myVolatility; // private final BigDecimal myWeight; // // public SimpleAsset(final FinancePortfolio portfolio) { // this(portfolio.getMeanReturn(), portfolio.getVolatility(), BigMath.ONE); // } // // public SimpleAsset(final FinancePortfolio portfolio, final Comparable<?> weight) { // this(portfolio.getMeanReturn(), portfolio.getVolatility(), weight); // } // // public SimpleAsset(final Comparable<?> weight) { // this(PrimitiveMath.ZERO, PrimitiveMath.ZERO, weight); // } // // public SimpleAsset(final Comparable<?> meanReturn, final Comparable<?> volatility) { // this(meanReturn, volatility, BigMath.ONE); // } // // public SimpleAsset(final Comparable<?> meanReturn, final Comparable<?> volatility, final Comparable<?> weight) { // // super(); // // myMeanReturn = meanReturn != null ? Scalar.doubleValue(meanReturn) : PrimitiveMath.ZERO; // myVolatility = volatility != null ? Scalar.doubleValue(volatility) : PrimitiveMath.ZERO; // myWeight = TypeUtils.toBigDecimal(weight); // } // // @SuppressWarnings("unused") // private SimpleAsset() { // this(BigMath.ZERO, BigMath.ZERO, BigMath.ONE); // } // // @Override // public double getMeanReturn() { // return myMeanReturn; // } // // @Override // public double getVolatility() { // return myVolatility; // } // // /** // * Assuming there is precisely 1 weight - this class is used to describe 1 asset (portfolio member). // */ // public BigDecimal getWeight() { // return myWeight; // } // // @Override // public List<BigDecimal> getWeights() { // return Collections.singletonList(myWeight); // } // // @Override // protected void reset() { // // } // // } // Path: src/main/java/org/ojalgo/finance/business/ModernAsset.java import java.math.BigDecimal; import java.util.Collection; import org.ojalgo.finance.portfolio.SimpleAsset; import java.awt.Color; tmpR += 255; } while (tmpG < 0) { tmpG += 255; } while (tmpB < 0) { tmpB += 255; } while (tmpR > 255) { tmpR -= 255; } while (tmpG > 255) { tmpG -= 255; } while (tmpB > 255) { tmpB -= 255; } return new Color(tmpR, tmpG, tmpB); } Color getAssetColour(); String getAssetKey(); BigDecimal getWeight(); int index();
SimpleAsset toDefinitionPortfolio();
optimatika/ojAlgo-finance
src/main/java/org/ojalgo/finance/portfolio/SimplePortfolio.java
// Path: src/main/java/org/ojalgo/finance/portfolio/FinancePortfolio.java // public interface Context { // // double calculatePortfolioReturn(final FinancePortfolio weightsPortfolio); // // double calculatePortfolioVariance(final FinancePortfolio weightsPortfolio); // // Primitive64Matrix getAssetReturns(); // // Primitive64Matrix getAssetVolatilities(); // // Primitive64Matrix getCorrelations(); // // Primitive64Matrix getCovariances(); // // int size(); // // } // // Path: src/main/java/org/ojalgo/finance/portfolio/simulator/PortfolioSimulator.java // public class PortfolioSimulator { // // private GeometricBrownian1D myProcess; // // public PortfolioSimulator(final Access2D<?> correlations, final List<GeometricBrownianMotion> assetProcesses) { // // super(); // // if (assetProcesses == null || assetProcesses.size() < 1) { // throw new IllegalArgumentException(); // } // // if (correlations != null) { // myProcess = new GeometricBrownian1D(correlations, assetProcesses); // } else { // myProcess = new GeometricBrownian1D(assetProcesses); // } // } // // @SuppressWarnings("unused") // private PortfolioSimulator() { // super(); // } // // public RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize) { // return this.simulate(aNumberOfRealisations, aNumberOfSteps, aStepSize, null); // } // // public RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize, // final int rebalancingInterval) { // return this.simulate(aNumberOfRealisations, aNumberOfSteps, aStepSize, Integer.valueOf(rebalancingInterval)); // } // // RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize, // final Integer rebalancingInterval) { // // final int tmpProcDim = myProcess.size(); // // final Primitive64Array tmpInitialValues = myProcess.getValues(); // final Comparable<?>[] tmpValues = new Comparable<?>[tmpProcDim]; // for (int p = 0; p < tmpProcDim; p++) { // tmpValues[p] = tmpInitialValues.get(p); // } // final List<BigDecimal> tmpWeights = new SimplePortfolio(tmpValues).normalise().getWeights(); // // final Array2D<Double> tmpRealisationValues = Array2D.PRIMITIVE64.make(aNumberOfRealisations, aNumberOfSteps); // // for (int r = 0; r < aNumberOfRealisations; r++) { // // for (int s = 0; s < aNumberOfSteps; s++) { // // if (rebalancingInterval != null && s != 0 && s % rebalancingInterval == 0) { // // final double tmpPortfolioValue = tmpRealisationValues.doubleValue(r, s - 1); // // for (int p = 0; p < tmpProcDim; p++) { // myProcess.setValue(p, tmpPortfolioValue * tmpWeights.get(p).doubleValue()); // } // } // // final Array1D<Double> tmpRealisation = myProcess.step(aStepSize); // // final AggregatorFunction<Double> tmpAggregator = Aggregator.SUM.getFunction(PrimitiveAggregator.getSet()); // tmpRealisation.visitAll(tmpAggregator); // tmpRealisationValues.set(r, s, tmpAggregator.doubleValue()); // } // // myProcess.setValues(tmpInitialValues); // } // // final AggregatorFunction<Double> tmpAggregator = Aggregator.SUM.getFunction(PrimitiveAggregator.getSet()); // for (int i = 0; i < tmpInitialValues.count(); i++) { // tmpAggregator.invoke(tmpInitialValues.doubleValue(i)); // } // // return new RandomProcess.SimulationResults(tmpAggregator.doubleValue(), tmpRealisationValues); // } // }
import org.ojalgo.scalar.Scalar; import org.ojalgo.structure.Access2D; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.ojalgo.finance.portfolio.FinancePortfolio.Context; import org.ojalgo.finance.portfolio.simulator.PortfolioSimulator; import org.ojalgo.function.constant.PrimitiveMath; import org.ojalgo.matrix.Primitive64Matrix; import org.ojalgo.random.process.GeometricBrownianMotion;
if (myMeanReturn == null) { final Primitive64Matrix tmpWeightsVector = this.getAssetWeights(); final Primitive64Matrix tmpReturnsVector = this.getAssetReturns(); myMeanReturn = MarketEquilibrium.calculatePortfolioReturn(tmpWeightsVector, tmpReturnsVector).get(); } return Scalar.doubleValue(myMeanReturn); } public double getMeanReturn(final int index) { return myComponents.get(index).getMeanReturn(); } @Override public double getReturnVariance() { if (myReturnVariance == null) { final MarketEquilibrium tmpMarketEquilibrium = new MarketEquilibrium(this.getCovariances()); final Primitive64Matrix tmpWeightsVector = this.getAssetWeights(); myReturnVariance = tmpMarketEquilibrium.calculatePortfolioVariance(tmpWeightsVector).get(); } return Scalar.doubleValue(myReturnVariance); } public double getReturnVariance(final int index) { return myComponents.get(index).getReturnVariance(); }
// Path: src/main/java/org/ojalgo/finance/portfolio/FinancePortfolio.java // public interface Context { // // double calculatePortfolioReturn(final FinancePortfolio weightsPortfolio); // // double calculatePortfolioVariance(final FinancePortfolio weightsPortfolio); // // Primitive64Matrix getAssetReturns(); // // Primitive64Matrix getAssetVolatilities(); // // Primitive64Matrix getCorrelations(); // // Primitive64Matrix getCovariances(); // // int size(); // // } // // Path: src/main/java/org/ojalgo/finance/portfolio/simulator/PortfolioSimulator.java // public class PortfolioSimulator { // // private GeometricBrownian1D myProcess; // // public PortfolioSimulator(final Access2D<?> correlations, final List<GeometricBrownianMotion> assetProcesses) { // // super(); // // if (assetProcesses == null || assetProcesses.size() < 1) { // throw new IllegalArgumentException(); // } // // if (correlations != null) { // myProcess = new GeometricBrownian1D(correlations, assetProcesses); // } else { // myProcess = new GeometricBrownian1D(assetProcesses); // } // } // // @SuppressWarnings("unused") // private PortfolioSimulator() { // super(); // } // // public RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize) { // return this.simulate(aNumberOfRealisations, aNumberOfSteps, aStepSize, null); // } // // public RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize, // final int rebalancingInterval) { // return this.simulate(aNumberOfRealisations, aNumberOfSteps, aStepSize, Integer.valueOf(rebalancingInterval)); // } // // RandomProcess.SimulationResults simulate(final int aNumberOfRealisations, final int aNumberOfSteps, final double aStepSize, // final Integer rebalancingInterval) { // // final int tmpProcDim = myProcess.size(); // // final Primitive64Array tmpInitialValues = myProcess.getValues(); // final Comparable<?>[] tmpValues = new Comparable<?>[tmpProcDim]; // for (int p = 0; p < tmpProcDim; p++) { // tmpValues[p] = tmpInitialValues.get(p); // } // final List<BigDecimal> tmpWeights = new SimplePortfolio(tmpValues).normalise().getWeights(); // // final Array2D<Double> tmpRealisationValues = Array2D.PRIMITIVE64.make(aNumberOfRealisations, aNumberOfSteps); // // for (int r = 0; r < aNumberOfRealisations; r++) { // // for (int s = 0; s < aNumberOfSteps; s++) { // // if (rebalancingInterval != null && s != 0 && s % rebalancingInterval == 0) { // // final double tmpPortfolioValue = tmpRealisationValues.doubleValue(r, s - 1); // // for (int p = 0; p < tmpProcDim; p++) { // myProcess.setValue(p, tmpPortfolioValue * tmpWeights.get(p).doubleValue()); // } // } // // final Array1D<Double> tmpRealisation = myProcess.step(aStepSize); // // final AggregatorFunction<Double> tmpAggregator = Aggregator.SUM.getFunction(PrimitiveAggregator.getSet()); // tmpRealisation.visitAll(tmpAggregator); // tmpRealisationValues.set(r, s, tmpAggregator.doubleValue()); // } // // myProcess.setValues(tmpInitialValues); // } // // final AggregatorFunction<Double> tmpAggregator = Aggregator.SUM.getFunction(PrimitiveAggregator.getSet()); // for (int i = 0; i < tmpInitialValues.count(); i++) { // tmpAggregator.invoke(tmpInitialValues.doubleValue(i)); // } // // return new RandomProcess.SimulationResults(tmpAggregator.doubleValue(), tmpRealisationValues); // } // } // Path: src/main/java/org/ojalgo/finance/portfolio/SimplePortfolio.java import org.ojalgo.scalar.Scalar; import org.ojalgo.structure.Access2D; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.ojalgo.finance.portfolio.FinancePortfolio.Context; import org.ojalgo.finance.portfolio.simulator.PortfolioSimulator; import org.ojalgo.function.constant.PrimitiveMath; import org.ojalgo.matrix.Primitive64Matrix; import org.ojalgo.random.process.GeometricBrownianMotion; if (myMeanReturn == null) { final Primitive64Matrix tmpWeightsVector = this.getAssetWeights(); final Primitive64Matrix tmpReturnsVector = this.getAssetReturns(); myMeanReturn = MarketEquilibrium.calculatePortfolioReturn(tmpWeightsVector, tmpReturnsVector).get(); } return Scalar.doubleValue(myMeanReturn); } public double getMeanReturn(final int index) { return myComponents.get(index).getMeanReturn(); } @Override public double getReturnVariance() { if (myReturnVariance == null) { final MarketEquilibrium tmpMarketEquilibrium = new MarketEquilibrium(this.getCovariances()); final Primitive64Matrix tmpWeightsVector = this.getAssetWeights(); myReturnVariance = tmpMarketEquilibrium.calculatePortfolioVariance(tmpWeightsVector).get(); } return Scalar.doubleValue(myReturnVariance); } public double getReturnVariance(final int index) { return myComponents.get(index).getReturnVariance(); }
public PortfolioSimulator getSimulator() {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/IrregularUtil.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/morph/WordEntry.java // public class WordEntry implements Serializable { // // private static final long serialVersionUID = -5847413036811319308L; // // public static final int IDX_NOUN = 0; // public static final int IDX_VERB = 1; // public static final int IDX_BUSA = 2; // public static final int IDX_DOV = 3; // public static final int IDX_BEV = 4; // public static final int IDX_NE = 5; // public static final int IDX_ADJ = 6; // 형용사 // public static final int IDX_NPR = 7; // 명사의 분류 (M:Measure) // public static final int IDX_CNOUNX = 8; // public static final int IDX_REGURA = 9; // // /** 단어 */ // private String word; // // /** 단어특성 */ // private char[] features; // // private List<CompoundEntry> compounds = new ArrayList<CompoundEntry>(); // // public WordEntry() { } // // public WordEntry(String word) { // this.word = word; // } // // public WordEntry(String word, char[] cs) { // this.word = word; // this.features = Arrays.copyOf(cs, cs.length); // } // // public WordEntry(String word, List<CompoundEntry> c) { // this.word = word; // this.compounds = c; // } // // public void setWord(String w) { // this.word = w; // } // // public String getWord() { // return this.word; // } // // public void setFeatures(char[] cs) { // this.features = cs; // } // // public char getFeature(int index) { // if (features == null || features.length < index) return '0'; // return features[index]; // } // // public char[] getFeatures() { // return this.features; // } // // public void setCompounds(List<CompoundEntry> c) { // this.compounds = c; // } // // public List<CompoundEntry> getCompounds() { // return this.compounds; // } // }
import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.morph.WordEntry;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * 동사의 불규칙 변형을 처리하는 Utility Class * * @author S.M.Lee */ public class IrregularUtil { // ㅂ 불규칙 public static final char IRR_TYPE_BIUP = 'B'; // ㅎ 불규칙 public static final char IRR_TYPE_HIOOT = 'H'; // ㄹ 불규칙 public static final char IRR_TYPE_LIUL = 'U'; // 르 불규칙 public static final char IRR_TYPE_LOO = 'L'; // ㅅ 불규칙 public static final char IRR_TYPE_SIUT = 'S'; // ㄷ 불규칙 public static final char IRR_TYPE_DI = 'D'; // 러 불규칙 public static final char IRR_TYPE_RU = 'R'; // 으 탈락 public static final char IRR_TYPE_UI = 'X'; // 규칙형 public static final char IRR_TYPE_REGULAR = 'X';
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/morph/WordEntry.java // public class WordEntry implements Serializable { // // private static final long serialVersionUID = -5847413036811319308L; // // public static final int IDX_NOUN = 0; // public static final int IDX_VERB = 1; // public static final int IDX_BUSA = 2; // public static final int IDX_DOV = 3; // public static final int IDX_BEV = 4; // public static final int IDX_NE = 5; // public static final int IDX_ADJ = 6; // 형용사 // public static final int IDX_NPR = 7; // 명사의 분류 (M:Measure) // public static final int IDX_CNOUNX = 8; // public static final int IDX_REGURA = 9; // // /** 단어 */ // private String word; // // /** 단어특성 */ // private char[] features; // // private List<CompoundEntry> compounds = new ArrayList<CompoundEntry>(); // // public WordEntry() { } // // public WordEntry(String word) { // this.word = word; // } // // public WordEntry(String word, char[] cs) { // this.word = word; // this.features = Arrays.copyOf(cs, cs.length); // } // // public WordEntry(String word, List<CompoundEntry> c) { // this.word = word; // this.compounds = c; // } // // public void setWord(String w) { // this.word = w; // } // // public String getWord() { // return this.word; // } // // public void setFeatures(char[] cs) { // this.features = cs; // } // // public char getFeature(int index) { // if (features == null || features.length < index) return '0'; // return features[index]; // } // // public char[] getFeatures() { // return this.features; // } // // public void setCompounds(List<CompoundEntry> c) { // this.compounds = c; // } // // public List<CompoundEntry> getCompounds() { // return this.compounds; // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/IrregularUtil.java import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.morph.WordEntry; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * 동사의 불규칙 변형을 처리하는 Utility Class * * @author S.M.Lee */ public class IrregularUtil { // ㅂ 불규칙 public static final char IRR_TYPE_BIUP = 'B'; // ㅎ 불규칙 public static final char IRR_TYPE_HIOOT = 'H'; // ㄹ 불규칙 public static final char IRR_TYPE_LIUL = 'U'; // 르 불규칙 public static final char IRR_TYPE_LOO = 'L'; // ㅅ 불규칙 public static final char IRR_TYPE_SIUT = 'S'; // ㄷ 불규칙 public static final char IRR_TYPE_DI = 'D'; // 러 불규칙 public static final char IRR_TYPE_RU = 'R'; // 으 탈락 public static final char IRR_TYPE_UI = 'X'; // 규칙형 public static final char IRR_TYPE_REGULAR = 'X';
public static String[] restoreIrregularVerb(String start, String end) throws MorphException {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/IrregularUtil.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/morph/WordEntry.java // public class WordEntry implements Serializable { // // private static final long serialVersionUID = -5847413036811319308L; // // public static final int IDX_NOUN = 0; // public static final int IDX_VERB = 1; // public static final int IDX_BUSA = 2; // public static final int IDX_DOV = 3; // public static final int IDX_BEV = 4; // public static final int IDX_NE = 5; // public static final int IDX_ADJ = 6; // 형용사 // public static final int IDX_NPR = 7; // 명사의 분류 (M:Measure) // public static final int IDX_CNOUNX = 8; // public static final int IDX_REGURA = 9; // // /** 단어 */ // private String word; // // /** 단어특성 */ // private char[] features; // // private List<CompoundEntry> compounds = new ArrayList<CompoundEntry>(); // // public WordEntry() { } // // public WordEntry(String word) { // this.word = word; // } // // public WordEntry(String word, char[] cs) { // this.word = word; // this.features = Arrays.copyOf(cs, cs.length); // } // // public WordEntry(String word, List<CompoundEntry> c) { // this.word = word; // this.compounds = c; // } // // public void setWord(String w) { // this.word = w; // } // // public String getWord() { // return this.word; // } // // public void setFeatures(char[] cs) { // this.features = cs; // } // // public char getFeature(int index) { // if (features == null || features.length < index) return '0'; // return features[index]; // } // // public char[] getFeatures() { // return this.features; // } // // public void setCompounds(List<CompoundEntry> c) { // this.compounds = c; // } // // public List<CompoundEntry> getCompounds() { // return this.compounds; // } // }
import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.morph.WordEntry;
return null; } /** * ㅂ 불규칙 원형을 복원한다. (돕다, 곱다) * * @throws org.apache.lucene.analysis.kr.morph.MorphException * */ private static String[] restoreBIrregular(String start, String end) throws MorphException { if (start == null || "".equals(start) || end == null) return null; if (start.length() < 2) return null; if (!(start.endsWith("오") || start.endsWith("우"))) return null; char convEnd = MorphUtil.makeChar(end.charAt(0), 0); if ("ㅁ".equals(end) || "ㄴ".equals(end) || "ㄹ".equals(end) || convEnd == '아' || convEnd == '어') { // 도우(돕), 고오(곱), 스러우(스럽) 등으로 변형되므로 반드시 2자 이상임 char ch = start.charAt(start.length() - 2); ch = MorphUtil.makeChar(ch, 17); if (start.length() > 2) start = Utilities.arrayToString(new String[] { start.substring(0, start.length() - 2), Character.toString(ch) }); else start = Character.toString(ch);
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/morph/WordEntry.java // public class WordEntry implements Serializable { // // private static final long serialVersionUID = -5847413036811319308L; // // public static final int IDX_NOUN = 0; // public static final int IDX_VERB = 1; // public static final int IDX_BUSA = 2; // public static final int IDX_DOV = 3; // public static final int IDX_BEV = 4; // public static final int IDX_NE = 5; // public static final int IDX_ADJ = 6; // 형용사 // public static final int IDX_NPR = 7; // 명사의 분류 (M:Measure) // public static final int IDX_CNOUNX = 8; // public static final int IDX_REGURA = 9; // // /** 단어 */ // private String word; // // /** 단어특성 */ // private char[] features; // // private List<CompoundEntry> compounds = new ArrayList<CompoundEntry>(); // // public WordEntry() { } // // public WordEntry(String word) { // this.word = word; // } // // public WordEntry(String word, char[] cs) { // this.word = word; // this.features = Arrays.copyOf(cs, cs.length); // } // // public WordEntry(String word, List<CompoundEntry> c) { // this.word = word; // this.compounds = c; // } // // public void setWord(String w) { // this.word = w; // } // // public String getWord() { // return this.word; // } // // public void setFeatures(char[] cs) { // this.features = cs; // } // // public char getFeature(int index) { // if (features == null || features.length < index) return '0'; // return features[index]; // } // // public char[] getFeatures() { // return this.features; // } // // public void setCompounds(List<CompoundEntry> c) { // this.compounds = c; // } // // public List<CompoundEntry> getCompounds() { // return this.compounds; // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/IrregularUtil.java import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.morph.WordEntry; return null; } /** * ㅂ 불규칙 원형을 복원한다. (돕다, 곱다) * * @throws org.apache.lucene.analysis.kr.morph.MorphException * */ private static String[] restoreBIrregular(String start, String end) throws MorphException { if (start == null || "".equals(start) || end == null) return null; if (start.length() < 2) return null; if (!(start.endsWith("오") || start.endsWith("우"))) return null; char convEnd = MorphUtil.makeChar(end.charAt(0), 0); if ("ㅁ".equals(end) || "ㄴ".equals(end) || "ㄹ".equals(end) || convEnd == '아' || convEnd == '어') { // 도우(돕), 고오(곱), 스러우(스럽) 등으로 변형되므로 반드시 2자 이상임 char ch = start.charAt(start.length() - 2); ch = MorphUtil.makeChar(ch, 17); if (start.length() > 2) start = Utilities.arrayToString(new String[] { start.substring(0, start.length() - 2), Character.toString(ch) }); else start = Character.toString(ch);
WordEntry entry = DictionaryUtil.getVerb(start);
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // }
import com.google.common.base.Joiner; import com.google.common.collect.SetMultimap; import com.google.common.collect.TreeMultimap; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * 동의어 분석을 수행합니다. * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 12:31 */ public class SynonymUtil { private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); private static final boolean isTraceEnabled = log.isTraceEnabled(); private static final boolean isDebugEnabled = log.isDebugEnabled(); /** 동의어 사전 */ private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); private static final Set<String> EMPTY_SET = new HashSet<String>(); static { final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); List<String> lines = FileUtil.readLines(filename, "UTF-8"); log.info("동의어 사전을 빌드합니다..."); for (String line : lines) { String[] words = StringUtils.split(line, ","); if (words != null && words.length > 1) { synonymMap.putAll(words[0], Arrays.asList(words)); if (isTraceEnabled) log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); } } log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); } /** * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. * * @throws MorphException */
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java import com.google.common.base.Joiner; import com.google.common.collect.SetMultimap; import com.google.common.collect.TreeMultimap; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * 동의어 분석을 수행합니다. * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 12:31 */ public class SynonymUtil { private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); private static final boolean isTraceEnabled = log.isTraceEnabled(); private static final boolean isDebugEnabled = log.isDebugEnabled(); /** 동의어 사전 */ private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); private static final Set<String> EMPTY_SET = new HashSet<String>(); static { final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); List<String> lines = FileUtil.readLines(filename, "UTF-8"); log.info("동의어 사전을 빌드합니다..."); for (String line : lines) { String[] words = StringUtils.split(line, ","); if (words != null && words.length > 1) { synonymMap.putAll(words[0], Arrays.asList(words)); if (isTraceEnabled) log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); } } log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); } /** * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. * * @throws MorphException */
public static Set<String> getSynonym(String word) throws MorphException {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/KoreanEnv.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // }
import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.kr.morph.MorphException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Properties;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; @Slf4j public class KoreanEnv { public static final Charset UTF8 = Charset.forName("UTF-8"); public static final String FILE_SYLLABLE_FEATURE = "syllable.dic"; public static final String FILE_DICTIONARY = "dictionary.dic"; public static final String FILE_JOSA = "josa.dic"; public static final String FILE_EOMI = "eomi.dic"; public static final String FILE_EXTENSION = "extension.dic"; public static final String FILE_MAPHANJA = "mapHanja.dic"; public static final String FILE_PREFIX = "prefix.dic"; public static final String FILE_SUFFIX = "suffix.dic"; public static final String FILE_COMPOUNDS = "compounds.dic"; public static final String FILE_UNCOMPOUNDS = "uncompounds.dic"; public static final String FILE_CJ = "cj.dic"; public static final String FILE_SYNONYM = "synonym.dic"; public static final String FILE_CUSTOM = "custom.dic"; public static final String FILE_KOREAN_PROPERTY = "org/apache/lucene/analysis/kr/korean.properties"; private Properties defaults = null; /** The props member gets its values from the configuration in the property file. */ private Properties props = null; private static KoreanEnv instance = new KoreanEnv(); /** The constructor loads property values from the property file. */
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/KoreanEnv.java import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.kr.morph.MorphException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Properties; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; @Slf4j public class KoreanEnv { public static final Charset UTF8 = Charset.forName("UTF-8"); public static final String FILE_SYLLABLE_FEATURE = "syllable.dic"; public static final String FILE_DICTIONARY = "dictionary.dic"; public static final String FILE_JOSA = "josa.dic"; public static final String FILE_EOMI = "eomi.dic"; public static final String FILE_EXTENSION = "extension.dic"; public static final String FILE_MAPHANJA = "mapHanja.dic"; public static final String FILE_PREFIX = "prefix.dic"; public static final String FILE_SUFFIX = "suffix.dic"; public static final String FILE_COMPOUNDS = "compounds.dic"; public static final String FILE_UNCOMPOUNDS = "uncompounds.dic"; public static final String FILE_CJ = "cj.dic"; public static final String FILE_SYNONYM = "synonym.dic"; public static final String FILE_CUSTOM = "custom.dic"; public static final String FILE_KOREAN_PROPERTY = "org/apache/lucene/analysis/kr/korean.properties"; private Properties defaults = null; /** The props member gets its values from the configuration in the property file. */ private Properties props = null; private static KoreanEnv instance = new KoreanEnv(); /** The constructor loads property values from the property file. */
private KoreanEnv() throws MorphException {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/FileUtil.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // }
import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * file utility class * * @author S.M.Lee */ public class FileUtil { private static final Logger log = LoggerFactory.getLogger(FileUtil.class); public static InputStream getResourceFileStream(String filename) { ClassLoader classLoader = FileUtil.class.getClassLoader(); InputStream stream = classLoader.getResourceAsStream(filename); if (stream == null) { stream = ClassLoader.getSystemResourceAsStream(filename); } return stream; } /** * Given a file name for a file that is located somewhere in the application * classpath, return a File object representing the file. * * @param filename The name of the file (relative to the classpath) that is * to be retrieved. * @return A file object representing the requested filename * @throws MorphException Thrown if the classloader can not be found or if * the file can not be found in the classpath. */
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/FileUtil.java import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; /** * file utility class * * @author S.M.Lee */ public class FileUtil { private static final Logger log = LoggerFactory.getLogger(FileUtil.class); public static InputStream getResourceFileStream(String filename) { ClassLoader classLoader = FileUtil.class.getClassLoader(); InputStream stream = classLoader.getResourceAsStream(filename); if (stream == null) { stream = ClassLoader.getSystemResourceAsStream(filename); } return stream; } /** * Given a file name for a file that is located somewhere in the application * classpath, return a File object representing the file. * * @param filename The name of the file (relative to the classpath) that is * to be retrieved. * @return A file object representing the requested filename * @throws MorphException Thrown if the classloader can not be found or if * the file can not be found in the classpath. */
public synchronized static File getClassLoaderFile(String filename) throws MorphException {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/KoreanSynonymFilter.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java // public class SynonymUtil { // // private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); // private static final boolean isTraceEnabled = log.isTraceEnabled(); // private static final boolean isDebugEnabled = log.isDebugEnabled(); // // /** 동의어 사전 */ // private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); // private static final Set<String> EMPTY_SET = new HashSet<String>(); // // static { // final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); // log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); // List<String> lines = FileUtil.readLines(filename, "UTF-8"); // log.info("동의어 사전을 빌드합니다..."); // // for (String line : lines) { // String[] words = StringUtils.split(line, ","); // if (words != null && words.length > 1) { // synonymMap.putAll(words[0], Arrays.asList(words)); // if (isTraceEnabled) // log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); // } // } // log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); // } // // /** // * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. // * // * @throws MorphException // */ // public static Set<String> getSynonym(String word) throws MorphException { // if (word == null || word.length() == 0) // return new HashSet<String>(); // // word = word.toLowerCase(); // // if (isTraceEnabled) // log.trace("동의어를 찾습니다... word=[{}]", word); // // if (synonymMap == null || synonymMap.size() == 0) // return EMPTY_SET; // // for (String key : synonymMap.keySet()) { // Set<String> synonyms = synonymMap.get(key); // if (key.equalsIgnoreCase(word) || synonyms.contains(word)) { // if (isTraceEnabled) // log.trace("동의어를 찾았습니다. word=[{}], synonyms=[{}]", word, StringUtil.join(synonyms, ",")); // return synonyms; // } // } // if (isTraceEnabled) // log.trace("동의어가 없습니다."); // // return EMPTY_SET; // } // }
import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.utils.SynonymUtil; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import java.io.IOException; import java.util.Set;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr; /** * org.apache.lucene.analysis.KoreanSynonymFilter * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 1:41 */ @Slf4j public class KoreanSynonymFilter extends TokenFilter { private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); /** Construct a token stream filtering the given input. */ protected KoreanSynonymFilter(TokenStream input) { super(input); } @Override public boolean incrementToken() throws IOException { if (input.incrementToken()) { try {
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java // public class SynonymUtil { // // private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); // private static final boolean isTraceEnabled = log.isTraceEnabled(); // private static final boolean isDebugEnabled = log.isDebugEnabled(); // // /** 동의어 사전 */ // private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); // private static final Set<String> EMPTY_SET = new HashSet<String>(); // // static { // final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); // log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); // List<String> lines = FileUtil.readLines(filename, "UTF-8"); // log.info("동의어 사전을 빌드합니다..."); // // for (String line : lines) { // String[] words = StringUtils.split(line, ","); // if (words != null && words.length > 1) { // synonymMap.putAll(words[0], Arrays.asList(words)); // if (isTraceEnabled) // log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); // } // } // log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); // } // // /** // * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. // * // * @throws MorphException // */ // public static Set<String> getSynonym(String word) throws MorphException { // if (word == null || word.length() == 0) // return new HashSet<String>(); // // word = word.toLowerCase(); // // if (isTraceEnabled) // log.trace("동의어를 찾습니다... word=[{}]", word); // // if (synonymMap == null || synonymMap.size() == 0) // return EMPTY_SET; // // for (String key : synonymMap.keySet()) { // Set<String> synonyms = synonymMap.get(key); // if (key.equalsIgnoreCase(word) || synonyms.contains(word)) { // if (isTraceEnabled) // log.trace("동의어를 찾았습니다. word=[{}], synonyms=[{}]", word, StringUtil.join(synonyms, ",")); // return synonyms; // } // } // if (isTraceEnabled) // log.trace("동의어가 없습니다."); // // return EMPTY_SET; // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/KoreanSynonymFilter.java import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.utils.SynonymUtil; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import java.io.IOException; import java.util.Set; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr; /** * org.apache.lucene.analysis.KoreanSynonymFilter * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 1:41 */ @Slf4j public class KoreanSynonymFilter extends TokenFilter { private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); /** Construct a token stream filtering the given input. */ protected KoreanSynonymFilter(TokenStream input) { super(input); } @Override public boolean incrementToken() throws IOException { if (input.incrementToken()) { try {
Set<String> words = SynonymUtil.getSynonym(termAtt.toString());
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/KoreanSynonymFilter.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java // public class SynonymUtil { // // private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); // private static final boolean isTraceEnabled = log.isTraceEnabled(); // private static final boolean isDebugEnabled = log.isDebugEnabled(); // // /** 동의어 사전 */ // private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); // private static final Set<String> EMPTY_SET = new HashSet<String>(); // // static { // final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); // log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); // List<String> lines = FileUtil.readLines(filename, "UTF-8"); // log.info("동의어 사전을 빌드합니다..."); // // for (String line : lines) { // String[] words = StringUtils.split(line, ","); // if (words != null && words.length > 1) { // synonymMap.putAll(words[0], Arrays.asList(words)); // if (isTraceEnabled) // log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); // } // } // log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); // } // // /** // * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. // * // * @throws MorphException // */ // public static Set<String> getSynonym(String word) throws MorphException { // if (word == null || word.length() == 0) // return new HashSet<String>(); // // word = word.toLowerCase(); // // if (isTraceEnabled) // log.trace("동의어를 찾습니다... word=[{}]", word); // // if (synonymMap == null || synonymMap.size() == 0) // return EMPTY_SET; // // for (String key : synonymMap.keySet()) { // Set<String> synonyms = synonymMap.get(key); // if (key.equalsIgnoreCase(word) || synonyms.contains(word)) { // if (isTraceEnabled) // log.trace("동의어를 찾았습니다. word=[{}], synonyms=[{}]", word, StringUtil.join(synonyms, ",")); // return synonyms; // } // } // if (isTraceEnabled) // log.trace("동의어가 없습니다."); // // return EMPTY_SET; // } // }
import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.utils.SynonymUtil; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import java.io.IOException; import java.util.Set;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr; /** * org.apache.lucene.analysis.KoreanSynonymFilter * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 1:41 */ @Slf4j public class KoreanSynonymFilter extends TokenFilter { private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); /** Construct a token stream filtering the given input. */ protected KoreanSynonymFilter(TokenStream input) { super(input); } @Override public boolean incrementToken() throws IOException { if (input.incrementToken()) { try { Set<String> words = SynonymUtil.getSynonym(termAtt.toString()); for (String word : words) { termAtt.append(word); }
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/org/apache/lucene/analysis/kr/utils/SynonymUtil.java // public class SynonymUtil { // // private static final Logger log = LoggerFactory.getLogger(SynonymUtil.class); // private static final boolean isTraceEnabled = log.isTraceEnabled(); // private static final boolean isDebugEnabled = log.isDebugEnabled(); // // /** 동의어 사전 */ // private static final SetMultimap<String, String> synonymMap = TreeMultimap.create(); // private static final Set<String> EMPTY_SET = new HashSet<String>(); // // static { // final String filename = KoreanEnv.getInstance().getValue(KoreanEnv.FILE_SYNONYM); // log.info("동의어 사전에서 동의어 정보를 로드합니다... filename=[{}]", filename); // List<String> lines = FileUtil.readLines(filename, "UTF-8"); // log.info("동의어 사전을 빌드합니다..."); // // for (String line : lines) { // String[] words = StringUtils.split(line, ","); // if (words != null && words.length > 1) { // synonymMap.putAll(words[0], Arrays.asList(words)); // if (isTraceEnabled) // log.trace("동의어를 추가합니다. words=[{}]", Joiner.on(",").join(words)); // } // } // log.info("동의어 사전을 빌드했습니다. 라인수=[{}], 동의어수=[{}]", lines.size(), synonymMap.values().size()); // } // // /** // * 지정한 단어의 동의어가 있으면, 모든 동의어를 반환합니다. // * // * @throws MorphException // */ // public static Set<String> getSynonym(String word) throws MorphException { // if (word == null || word.length() == 0) // return new HashSet<String>(); // // word = word.toLowerCase(); // // if (isTraceEnabled) // log.trace("동의어를 찾습니다... word=[{}]", word); // // if (synonymMap == null || synonymMap.size() == 0) // return EMPTY_SET; // // for (String key : synonymMap.keySet()) { // Set<String> synonyms = synonymMap.get(key); // if (key.equalsIgnoreCase(word) || synonyms.contains(word)) { // if (isTraceEnabled) // log.trace("동의어를 찾았습니다. word=[{}], synonyms=[{}]", word, StringUtil.join(synonyms, ",")); // return synonyms; // } // } // if (isTraceEnabled) // log.trace("동의어가 없습니다."); // // return EMPTY_SET; // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/KoreanSynonymFilter.java import lombok.extern.slf4j.Slf4j; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.kr.morph.MorphException; import org.apache.lucene.analysis.kr.utils.SynonymUtil; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import java.io.IOException; import java.util.Set; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr; /** * org.apache.lucene.analysis.KoreanSynonymFilter * * @author 배성혁 [email protected] * @since 13. 4. 27. 오전 1:41 */ @Slf4j public class KoreanSynonymFilter extends TokenFilter { private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); /** Construct a token stream filtering the given input. */ protected KoreanSynonymFilter(TokenStream input) { super(input); } @Override public boolean incrementToken() throws IOException { if (input.incrementToken()) { try { Set<String> words = SynonymUtil.getSynonym(termAtt.toString()); for (String word : words) { termAtt.append(word); }
} catch (MorphException e) {
debop/lucene-korean
src/main/java/org/apache/lucene/analysis/kr/utils/HanjaUtils.java
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // }
import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; public class HanjaUtils { private static final Logger log = LoggerFactory.getLogger(HanjaUtils.class); private static final Map<String, char[]> mapHanja = new HashMap<String, char[]>(); static { List<String> strList = FileUtil.readLines(KoreanEnv.getInstance().getValue(KoreanEnv.FILE_MAPHANJA), KoreanEnv.UTF8); log.info("한자 사전을 빌드합니다..."); for (String str : strList) { if (str.length() < 1 || !str.contains(",")) continue; String[] hanInfos = StringUtil.split(str, ","); if (hanInfos.length != 2) continue; String hanja = StringEscapeUtil.unescapeJava(hanInfos[0]); mapHanja.put(hanja, hanInfos[1].toCharArray()); } log.info("한자 사전을 빌드했습니다. 단어수=[{}], 로드수=[{}]", strList.size(), mapHanja.size()); } /** * 한자에 대응하는 한글을 찾아서 반환한다. * 하나의 한자는 여러 음으로 읽일 수 있으므로 가능한 모든 음을 한글로 반환한다. * * @throws org.apache.lucene.analysis.kr.morph.MorphException * */
// Path: src/main/java/org/apache/lucene/analysis/kr/morph/MorphException.java // public class MorphException extends RuntimeException { // // private static final long serialVersionUID = 7605164221652820591L; // // public MorphException() { // super(); // } // // public MorphException(String message) { // super(message); // } // // public MorphException(String message, Throwable cause) { // super(message, cause); // } // // public MorphException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/org/apache/lucene/analysis/kr/utils/HanjaUtils.java import org.apache.lucene.analysis.kr.morph.MorphException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apache.lucene.analysis.kr.utils; public class HanjaUtils { private static final Logger log = LoggerFactory.getLogger(HanjaUtils.class); private static final Map<String, char[]> mapHanja = new HashMap<String, char[]>(); static { List<String> strList = FileUtil.readLines(KoreanEnv.getInstance().getValue(KoreanEnv.FILE_MAPHANJA), KoreanEnv.UTF8); log.info("한자 사전을 빌드합니다..."); for (String str : strList) { if (str.length() < 1 || !str.contains(",")) continue; String[] hanInfos = StringUtil.split(str, ","); if (hanInfos.length != 2) continue; String hanja = StringEscapeUtil.unescapeJava(hanInfos[0]); mapHanja.put(hanja, hanInfos[1].toCharArray()); } log.info("한자 사전을 빌드했습니다. 단어수=[{}], 로드수=[{}]", strList.size(), mapHanja.size()); } /** * 한자에 대응하는 한글을 찾아서 반환한다. * 하나의 한자는 여러 음으로 읽일 수 있으므로 가능한 모든 음을 한글로 반환한다. * * @throws org.apache.lucene.analysis.kr.morph.MorphException * */
public static char[] convertToHangul(char hanja) throws MorphException {
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/app/SmartPreferenceActivity.java
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // }
import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuItem;
public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } /** * SmartableActivity implementation. */ public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); }
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // } // Path: library/src/main/java/com/smartnsoft/droid4me/app/SmartPreferenceActivity.java import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuItem; public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } /** * SmartableActivity implementation. */ public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); }
public void registerBroadcastListeners(BroadcastListener[] broadcastListeners)
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/app/SmartDialogFragment.java
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // }
import android.os.Handler; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.annotation.TargetApi; import android.app.Activity; import android.app.DialogFragment; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build.VERSION_CODES; import android.os.Bundle;
/** * Smartable implementation. */ public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); }
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // } // Path: library/src/main/java/com/smartnsoft/droid4me/app/SmartDialogFragment.java import android.os.Handler; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.annotation.TargetApi; import android.app.Activity; import android.app.DialogFragment; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build.VERSION_CODES; import android.os.Bundle; /** * Smartable implementation. */ public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); }
public void registerBroadcastListeners(BroadcastListener[] broadcastListeners)
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java
// Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // }
import java.io.IOException; import java.io.InputStream; import android.view.View; import android.widget.ImageView; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable;
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.download; /** * Gathers in one place the download instructions contracts used by {@link BitmapDownloader}. * * @author Édouard Mercier * @since 2011.07.03 */ public class BasisDownloadInstructions { /** * Enables the {@link CoreBitmapDownloader bitmap downloader} to know on how to handle a command. * * @since 2009.03.04 */
// Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // } // Path: library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java import java.io.IOException; import java.io.InputStream; import android.view.View; import android.widget.ImageView; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable; // The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.download; /** * Gathers in one place the download instructions contracts used by {@link BitmapDownloader}. * * @author Édouard Mercier * @since 2011.07.03 */ public class BasisDownloadInstructions { /** * Enables the {@link CoreBitmapDownloader bitmap downloader} to know on how to handle a command. * * @since 2009.03.04 */
public interface Instructions<BitmapClass extends Bitmapable, ViewClass extends Viewable>
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java
// Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // }
import java.io.IOException; import java.io.InputStream; import android.view.View; import android.widget.ImageView; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable;
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.download; /** * Gathers in one place the download instructions contracts used by {@link BitmapDownloader}. * * @author Édouard Mercier * @since 2011.07.03 */ public class BasisDownloadInstructions { /** * Enables the {@link CoreBitmapDownloader bitmap downloader} to know on how to handle a command. * * @since 2009.03.04 */
// Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // } // Path: library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java import java.io.IOException; import java.io.InputStream; import android.view.View; import android.widget.ImageView; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable; // The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.download; /** * Gathers in one place the download instructions contracts used by {@link BitmapDownloader}. * * @author Édouard Mercier * @since 2011.07.03 */ public class BasisDownloadInstructions { /** * Enables the {@link CoreBitmapDownloader bitmap downloader} to know on how to handle a command. * * @since 2009.03.04 */
public interface Instructions<BitmapClass extends Bitmapable, ViewClass extends Viewable>
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/ui/SimpleWrappedListView.java
// Path: library/src/main/java/com/smartnsoft/droid4me/framework/DetailsProvider.java // public interface ForList<BusinessObjectClass, ViewClass> // extends DetailsProvider.ForListHandler<BusinessObjectClass>, DetailsProvider.ForListView<BusinessObjectClass, ViewClass> // { // // }
import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.RelativeLayout; import com.smartnsoft.droid4me.framework.DetailsProvider.ForList; import android.app.Activity; import android.content.Context; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener;
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.ui; /** * A simple (not expandable) smart list view. * * @author Édouard Mercier * @since 2008.11.14 */ public class SimpleWrappedListView<BusinessObjectClass, ViewClass extends View> extends WrappedListView<BusinessObjectClass, ListView, ViewClass> { private final ListView listView;
// Path: library/src/main/java/com/smartnsoft/droid4me/framework/DetailsProvider.java // public interface ForList<BusinessObjectClass, ViewClass> // extends DetailsProvider.ForListHandler<BusinessObjectClass>, DetailsProvider.ForListView<BusinessObjectClass, ViewClass> // { // // } // Path: library/src/main/java/com/smartnsoft/droid4me/ui/SimpleWrappedListView.java import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.RelativeLayout; import com.smartnsoft.droid4me.framework.DetailsProvider.ForList; import android.app.Activity; import android.content.Context; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; // The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.droid4me.ui; /** * A simple (not expandable) smart list view. * * @author Édouard Mercier * @since 2008.11.14 */ public class SimpleWrappedListView<BusinessObjectClass, ViewClass extends View> extends WrappedListView<BusinessObjectClass, ListView, ViewClass> { private final ListView listView;
private final ForList<BusinessObjectClass, ViewClass> forListProvider;
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/app/SmartActivity.java
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // }
import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuItem;
public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); } /** * SmartableActivity implementation. */
// Path: library/src/main/java/com/smartnsoft/droid4me/app/AppPublics.java // public interface BroadcastListener // { // // /** // * This method will be invoked by the framework to determine what {@link IntentFilter} should be associated to the current listener. // * <p> // * <p> // * The returned value of the method will be used to invoke the {@link Context#registerReceiver(android.content.BroadcastReceiver, IntentFilter)} // * method. If this method is annotated with {@link AppPublics.UseNativeBroadcast}, the implementation will use the {@link LocalBroadcastManager} // * implementation. // * </p> // * // * @return if not {@code null}, only the {@link Intent intents} that match with this returned value, will be received by the activity // * @see #onReceive(Intent) // */ // IntentFilter getIntentFilter(); // // /** // * Is invoked every time an intent that matches is received by the underlying activity. // * // * @param intent the broadcast {@link Intent} which has been received, and which matches the declared {@link IntentFilter} // * @see #getIntentFilter() // */ // void onReceive(Intent intent); // // } // Path: library/src/main/java/com/smartnsoft/droid4me/app/SmartActivity.java import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuItem; public AggregateClass getAggregate() { return droid4mizer.getAggregate(); } public void setAggregate(AggregateClass aggregate) { droid4mizer.setAggregate(aggregate); } public Handler getHandler() { return droid4mizer.getHandler(); } public SharedPreferences getPreferences() { return droid4mizer.getPreferences(); } public void onException(Throwable throwable, boolean fromGuiThread) { droid4mizer.onException(throwable, fromGuiThread); } /** * SmartableActivity implementation. */
public void registerBroadcastListeners(BroadcastListener[] broadcastListeners)
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceClient.java
// Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class HttpResponse // { // // public final Map<String, List<String>> headers; // // public final int statusCode; // // public final InputStream inputStream; // // public final InputStream errorInputStream; // // public HttpResponse(Map<String, List<String>> headers, int statusCode, InputStream inputStream, // InputStream errorInputStream) // { // this.headers = headers; // this.statusCode = statusCode; // this.inputStream = inputStream; // this.errorInputStream = errorInputStream; // } // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class MultipartFile // { // // public final String name; // // public final String fileName; // // public final String contentType; // // public final InputStream inputStream; // // public MultipartFile(String name, String fileName, String contentType, InputStream inputStream) // { // this.name = name; // this.fileName = fileName; // this.contentType = contentType; // this.inputStream = inputStream; // } // // }
import com.smartnsoft.droid4me.ws.WebServiceCaller.HttpResponse; import com.smartnsoft.droid4me.ws.WebServiceCaller.MultipartFile; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import javax.net.ssl.SSLException;
{ /** * The actual URL of the HTTP request to execute. */ public final String url; /** * The HTTP request method. */ public final CallType callType; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the body of the request. */ public final String body; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the body of the request (form-data). */ public final Map<String, String> parameters; /** * The HTTP request headers. */ public final Map<String, String> headers; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the files of the request (form-data). */
// Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class HttpResponse // { // // public final Map<String, List<String>> headers; // // public final int statusCode; // // public final InputStream inputStream; // // public final InputStream errorInputStream; // // public HttpResponse(Map<String, List<String>> headers, int statusCode, InputStream inputStream, // InputStream errorInputStream) // { // this.headers = headers; // this.statusCode = statusCode; // this.inputStream = inputStream; // this.errorInputStream = errorInputStream; // } // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class MultipartFile // { // // public final String name; // // public final String fileName; // // public final String contentType; // // public final InputStream inputStream; // // public MultipartFile(String name, String fileName, String contentType, InputStream inputStream) // { // this.name = name; // this.fileName = fileName; // this.contentType = contentType; // this.inputStream = inputStream; // } // // } // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceClient.java import com.smartnsoft.droid4me.ws.WebServiceCaller.HttpResponse; import com.smartnsoft.droid4me.ws.WebServiceCaller.MultipartFile; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import javax.net.ssl.SSLException; { /** * The actual URL of the HTTP request to execute. */ public final String url; /** * The HTTP request method. */ public final CallType callType; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the body of the request. */ public final String body; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the body of the request (form-data). */ public final Map<String, String> parameters; /** * The HTTP request headers. */ public final Map<String, String> headers; /** * If the HTTP method is a {@link Verb#Post} or a {@link Verb#Put}, the files of the request (form-data). */
public final List<MultipartFile> files;
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceClient.java
// Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class HttpResponse // { // // public final Map<String, List<String>> headers; // // public final int statusCode; // // public final InputStream inputStream; // // public final InputStream errorInputStream; // // public HttpResponse(Map<String, List<String>> headers, int statusCode, InputStream inputStream, // InputStream errorInputStream) // { // this.headers = headers; // this.statusCode = statusCode; // this.inputStream = inputStream; // this.errorInputStream = errorInputStream; // } // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class MultipartFile // { // // public final String name; // // public final String fileName; // // public final String contentType; // // public final InputStream inputStream; // // public MultipartFile(String name, String fileName, String contentType, InputStream inputStream) // { // this.name = name; // this.fileName = fileName; // this.contentType = contentType; // this.inputStream = inputStream; // } // // }
import com.smartnsoft.droid4me.ws.WebServiceCaller.HttpResponse; import com.smartnsoft.droid4me.ws.WebServiceCaller.MultipartFile; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import javax.net.ssl.SSLException;
/** * @return {@code true} is the current exception is linked to a connectivity problem with Internet. * @see #isConnectivityProblem(Throwable) */ public final boolean isConnectivityProblem() { return WebServiceClient.CallException.isConnectivityProblem(this); } } /** * Is responsible for converting the given URI parameters into a stringified URI. * * @param methodUriPrefix the prefix of the URI * @param methodUriSuffix the suffix of the URI, not containing the query parameters. A <code>/</code> will split the methodUriPrefix and methodUriSuffix * parameters in the final URI * @param uriParameters a map of key/values that will be used as query parameters in the final URI * @return a properly encoded URI */ String computeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters); /** * Is responsible to actually run the relevant HTTP method. * * @param uri the URI against which the HTTP request should be run * @return a {@link HttpResponse} object that wraps the headers and the input stream resulting to the HTTP request, which are taken from the response * @throws WebServiceClient.CallException in case an error occurred during the HTTP request execution, or if the HTTP request status code is not {@code 2XX} */
// Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class HttpResponse // { // // public final Map<String, List<String>> headers; // // public final int statusCode; // // public final InputStream inputStream; // // public final InputStream errorInputStream; // // public HttpResponse(Map<String, List<String>> headers, int statusCode, InputStream inputStream, // InputStream errorInputStream) // { // this.headers = headers; // this.statusCode = statusCode; // this.inputStream = inputStream; // this.errorInputStream = errorInputStream; // } // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceCaller.java // public static final class MultipartFile // { // // public final String name; // // public final String fileName; // // public final String contentType; // // public final InputStream inputStream; // // public MultipartFile(String name, String fileName, String contentType, InputStream inputStream) // { // this.name = name; // this.fileName = fileName; // this.contentType = contentType; // this.inputStream = inputStream; // } // // } // Path: library/src/main/java/com/smartnsoft/droid4me/ws/WebServiceClient.java import com.smartnsoft.droid4me.ws.WebServiceCaller.HttpResponse; import com.smartnsoft.droid4me.ws.WebServiceCaller.MultipartFile; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import javax.net.ssl.SSLException; /** * @return {@code true} is the current exception is linked to a connectivity problem with Internet. * @see #isConnectivityProblem(Throwable) */ public final boolean isConnectivityProblem() { return WebServiceClient.CallException.isConnectivityProblem(this); } } /** * Is responsible for converting the given URI parameters into a stringified URI. * * @param methodUriPrefix the prefix of the URI * @param methodUriSuffix the suffix of the URI, not containing the query parameters. A <code>/</code> will split the methodUriPrefix and methodUriSuffix * parameters in the final URI * @param uriParameters a map of key/values that will be used as query parameters in the final URI * @return a properly encoded URI */ String computeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters); /** * Is responsible to actually run the relevant HTTP method. * * @param uri the URI against which the HTTP request should be run * @return a {@link HttpResponse} object that wraps the headers and the input stream resulting to the HTTP request, which are taken from the response * @throws WebServiceClient.CallException in case an error occurred during the HTTP request execution, or if the HTTP request status code is not {@code 2XX} */
HttpResponse runRequest(String uri)
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/download/BasisBitmapDownloader.java
// Path: library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java // public interface InputStreamDownloadInstructor // { // // /** // * Indicates that the input stream should be asynchronous. // */ // void setAsynchronous(); // // /** // * Should be called when the input stream has just been downloaded. // * // * @param inputStream should not be {@code null} // */ // void onDownloaded(InputStream inputStream); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Handlerable // { // // /** // * Is supposed to run the given command in the UI thread. // * // * @param runnnable the command that should be executed // * @return {@code true} if and only if the execution in the UI thread has actually successfuly started // */ // boolean post(Runnable runnnable); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadInstructions.java // public final static class BitmapableGif // implements Bitmapable // { // // private final Gif gif; // // private final Bitmap bitmap; // // public BitmapableGif(Gif gif) // { // this.gif = gif; // bitmap = gif.getBitmap(0); // } // // @Override // public int getSizeInBytes() // { // if (gif == null) // { // return 0; // } // else // { // return gif.getHeight() * gif.getWidth() * gif.getFramesCount(); // } // } // // @Override // public void recycle() // { // if (gif != null && gif.getBitmaps().isEmpty() == false) // { // for (Bitmap bitmap : gif.getBitmaps()) // { // bitmap.recycle(); // } // } // } // // public void endAnimation() // { // if (gif != null) // { // gif.endAnimation(); // } // } // // public Gif getGif() // { // return gif; // } // }
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import android.view.View; import com.smartnsoft.droid4me.download.BasisDownloadInstructions.InputStreamDownloadInstructor; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Handlerable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable; import com.smartnsoft.droid4me.download.DownloadInstructions.BitmapableGif; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory;
else { instructions.onOver(true, alreadyStackedCommand.view, alreadyStackedCommand.bitmapUid, alreadyStackedCommand.imageSpecs); } } } // We need to download the bitmap or take it from a local persistence place // Hence, we stack the bitmap download command final DownloadBitmapCommand downloadCommand = computeDownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions); if (view != null) { prioritiesDownloadStack.put(view, downloadCommand); dump(); } if (resumeWorkflowOnSameThread == false) { BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.execute(downloadCommand); } else { // In that case, we want the workflow to keep on running from the calling thread downloadCommand.executeStart(true, false); } } } protected class DownloadBitmapCommand extends BasisCommand
// Path: library/src/main/java/com/smartnsoft/droid4me/download/BasisDownloadInstructions.java // public interface InputStreamDownloadInstructor // { // // /** // * Indicates that the input stream should be asynchronous. // */ // void setAsynchronous(); // // /** // * Should be called when the input stream has just been downloaded. // * // * @param inputStream should not be {@code null} // */ // void onDownloaded(InputStream inputStream); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Bitmapable // { // // /** // * @return the underlying bitmap size expressed in bytes // */ // int getSizeInBytes(); // // /** // * Should release the memory hold by the underlying bitmap, when reclaimed. // */ // void recycle(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Handlerable // { // // /** // * Is supposed to run the given command in the UI thread. // * // * @param runnnable the command that should be executed // * @return {@code true} if and only if the execution in the UI thread has actually successfuly started // */ // boolean post(Runnable runnnable); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadContracts.java // public interface Viewable // { // // /** // * @return a tag object associated to the underlying view. // */ // Object getTag(); // // /** // * Sets the tag object associated to the underlying view. // * // * @param tag // */ // void setTag(Object tag); // // /** // * The identifier returned here is just use for logging purposes. // * // * @return the unique identifier of the underlying view: two physical different views should not have the same identifier // */ // int getId(); // // } // // Path: library/src/main/java/com/smartnsoft/droid4me/download/DownloadInstructions.java // public final static class BitmapableGif // implements Bitmapable // { // // private final Gif gif; // // private final Bitmap bitmap; // // public BitmapableGif(Gif gif) // { // this.gif = gif; // bitmap = gif.getBitmap(0); // } // // @Override // public int getSizeInBytes() // { // if (gif == null) // { // return 0; // } // else // { // return gif.getHeight() * gif.getWidth() * gif.getFramesCount(); // } // } // // @Override // public void recycle() // { // if (gif != null && gif.getBitmaps().isEmpty() == false) // { // for (Bitmap bitmap : gif.getBitmaps()) // { // bitmap.recycle(); // } // } // } // // public void endAnimation() // { // if (gif != null) // { // gif.endAnimation(); // } // } // // public Gif getGif() // { // return gif; // } // } // Path: library/src/main/java/com/smartnsoft/droid4me/download/BasisBitmapDownloader.java import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import android.view.View; import com.smartnsoft.droid4me.download.BasisDownloadInstructions.InputStreamDownloadInstructor; import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable; import com.smartnsoft.droid4me.download.DownloadContracts.Handlerable; import com.smartnsoft.droid4me.download.DownloadContracts.Viewable; import com.smartnsoft.droid4me.download.DownloadInstructions.BitmapableGif; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; else { instructions.onOver(true, alreadyStackedCommand.view, alreadyStackedCommand.bitmapUid, alreadyStackedCommand.imageSpecs); } } } // We need to download the bitmap or take it from a local persistence place // Hence, we stack the bitmap download command final DownloadBitmapCommand downloadCommand = computeDownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions); if (view != null) { prioritiesDownloadStack.put(view, downloadCommand); dump(); } if (resumeWorkflowOnSameThread == false) { BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.execute(downloadCommand); } else { // In that case, we want the workflow to keep on running from the calling thread downloadCommand.executeStart(true, false); } } } protected class DownloadBitmapCommand extends BasisCommand
implements InputStreamDownloadInstructor
OpenIchano/Viewer
src/com/zhongyun/viewer/login/UserLoginHandler.java
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // }
import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; import android.content.Context; import android.os.Handler; import android.util.Log;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserLoginHandler implements Callable<String>, CallbackMessage<String>{ public static final int THIRD_LOGIN = 1; Context context; int request; Handler handler; String email,pwd; int cidFlag; boolean isResigter = false; private UserInfo mUserInfo; public static final int LOGIN_SUCCESS = 0; public static final int LOGIN_FAIL = 1; public UserLoginHandler(Context context, Handler handler){ this.context = context; this.handler = handler; mUserInfo = UserInfo.getUserInfo(context.getApplicationContext()); } public void setRequestValue(String email,String pwd){ this.email = email; this.pwd= pwd; } public void doThing(int request){ this.request = request;
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // } // Path: src/com/zhongyun/viewer/login/UserLoginHandler.java import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; import android.content.Context; import android.os.Handler; import android.util.Log; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserLoginHandler implements Callable<String>, CallbackMessage<String>{ public static final int THIRD_LOGIN = 1; Context context; int request; Handler handler; String email,pwd; int cidFlag; boolean isResigter = false; private UserInfo mUserInfo; public static final int LOGIN_SUCCESS = 0; public static final int LOGIN_FAIL = 1; public UserLoginHandler(Context context, Handler handler){ this.context = context; this.handler = handler; mUserInfo = UserInfo.getUserInfo(context.getApplicationContext()); } public void setRequestValue(String email,String pwd){ this.email = email; this.pwd= pwd; } public void doThing(int request){ this.request = request;
AsyncUtil.doAsync(request, context, this, this);
OpenIchano/Viewer
src/com/zhongyun/viewer/login/UserLoginHandler.java
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // }
import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; import android.content.Context; import android.os.Handler; import android.util.Log;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserLoginHandler implements Callable<String>, CallbackMessage<String>{ public static final int THIRD_LOGIN = 1; Context context; int request; Handler handler; String email,pwd; int cidFlag; boolean isResigter = false; private UserInfo mUserInfo; public static final int LOGIN_SUCCESS = 0; public static final int LOGIN_FAIL = 1; public UserLoginHandler(Context context, Handler handler){ this.context = context; this.handler = handler; mUserInfo = UserInfo.getUserInfo(context.getApplicationContext()); } public void setRequestValue(String email,String pwd){ this.email = email; this.pwd= pwd; } public void doThing(int request){ this.request = request; AsyncUtil.doAsync(request, context, this, this); } @Override public void onComplete(int requestid, String pCallbackValue) {
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // } // Path: src/com/zhongyun/viewer/login/UserLoginHandler.java import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; import android.content.Context; import android.os.Handler; import android.util.Log; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserLoginHandler implements Callable<String>, CallbackMessage<String>{ public static final int THIRD_LOGIN = 1; Context context; int request; Handler handler; String email,pwd; int cidFlag; boolean isResigter = false; private UserInfo mUserInfo; public static final int LOGIN_SUCCESS = 0; public static final int LOGIN_FAIL = 1; public UserLoginHandler(Context context, Handler handler){ this.context = context; this.handler = handler; mUserInfo = UserInfo.getUserInfo(context.getApplicationContext()); } public void setRequestValue(String email,String pwd){ this.email = email; this.pwd= pwd; } public void doThing(int request){ this.request = request; AsyncUtil.doAsync(request, context, this, this); } @Override public void onComplete(int requestid, String pCallbackValue) {
if (StringUtils.isEmpty(pCallbackValue)) {
OpenIchano/Viewer
src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/CameraInstance.java
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // } // // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Util.java // public class Util { // public static void validateMainThread() { // if (Looper.getMainLooper() != Looper.myLooper()) { // throw new IllegalStateException("Must be called from the main thread."); // } // } // }
import com.zhongyun.viewer.R; import com.zhongyun.zxing.journeyapps.barcodescanner.Size; import com.zhongyun.zxing.journeyapps.barcodescanner.Util; import android.content.Context; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder;
package com.zhongyun.zxing.journeyapps.barcodescanner.camera; /** * */ public class CameraInstance { private static final String TAG = CameraInstance.class.getSimpleName(); private CameraThread cameraThread; private SurfaceHolder surfaceHolder; private CameraManager cameraManager; private Handler readyHandler; private DisplayConfiguration displayConfiguration; private boolean open = false; private CameraSettings cameraSettings = new CameraSettings(); public CameraInstance(Context context) {
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // } // // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Util.java // public class Util { // public static void validateMainThread() { // if (Looper.getMainLooper() != Looper.myLooper()) { // throw new IllegalStateException("Must be called from the main thread."); // } // } // } // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/CameraInstance.java import com.zhongyun.viewer.R; import com.zhongyun.zxing.journeyapps.barcodescanner.Size; import com.zhongyun.zxing.journeyapps.barcodescanner.Util; import android.content.Context; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; package com.zhongyun.zxing.journeyapps.barcodescanner.camera; /** * */ public class CameraInstance { private static final String TAG = CameraInstance.class.getSimpleName(); private CameraThread cameraThread; private SurfaceHolder surfaceHolder; private CameraManager cameraManager; private Handler readyHandler; private DisplayConfiguration displayConfiguration; private boolean open = false; private CameraSettings cameraSettings = new CameraSettings(); public CameraInstance(Context context) {
Util.validateMainThread();
OpenIchano/Viewer
src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/CameraInstance.java
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // } // // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Util.java // public class Util { // public static void validateMainThread() { // if (Looper.getMainLooper() != Looper.myLooper()) { // throw new IllegalStateException("Must be called from the main thread."); // } // } // }
import com.zhongyun.viewer.R; import com.zhongyun.zxing.journeyapps.barcodescanner.Size; import com.zhongyun.zxing.journeyapps.barcodescanner.Util; import android.content.Context; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder;
public void setReadyHandler(Handler readyHandler) { this.readyHandler = readyHandler; } public void setSurfaceHolder(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; } public CameraSettings getCameraSettings() { return cameraSettings; } /** * This only has an effect if the camera is not opened yet. * * @param cameraSettings the new camera settings */ public void setCameraSettings(CameraSettings cameraSettings) { if (!open) { this.cameraSettings = cameraSettings; this.cameraManager.setCameraSettings(cameraSettings); } } /** * Actual preview size in current rotation. null if not determined yet. * * @return preview size */
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // } // // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Util.java // public class Util { // public static void validateMainThread() { // if (Looper.getMainLooper() != Looper.myLooper()) { // throw new IllegalStateException("Must be called from the main thread."); // } // } // } // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/CameraInstance.java import com.zhongyun.viewer.R; import com.zhongyun.zxing.journeyapps.barcodescanner.Size; import com.zhongyun.zxing.journeyapps.barcodescanner.Util; import android.content.Context; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; public void setReadyHandler(Handler readyHandler) { this.readyHandler = readyHandler; } public void setSurfaceHolder(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; } public CameraSettings getCameraSettings() { return cameraSettings; } /** * This only has an effect if the camera is not opened yet. * * @param cameraSettings the new camera settings */ public void setCameraSettings(CameraSettings cameraSettings) { if (!open) { this.cameraSettings = cameraSettings; this.cameraManager.setCameraSettings(cameraSettings); } } /** * Actual preview size in current rotation. null if not determined yet. * * @return preview size */
private Size getPreviewSize() {
OpenIchano/Viewer
src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/DisplayConfiguration.java
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // }
import android.graphics.Rect; import android.util.Log; import android.view.Surface; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.zhongyun.zxing.journeyapps.barcodescanner.Size;
package com.zhongyun.zxing.journeyapps.barcodescanner.camera; /** * */ public class DisplayConfiguration { private static final String TAG = DisplayConfiguration.class.getSimpleName();
// Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/Size.java // public class Size implements Comparable<Size> { // public final int width; // public final int height; // // public Size(int width, int height) { // this.width = width; // this.height = height; // } // // /** // * Swap width and height. // * // * @return a new Size with swapped width and height // */ // public Size rotate() { // //noinspection SuspiciousNameCombination // return new Size(height, width); // } // // /** // * Scale by n / d. // * // * @param n numerator // * @param d denominator // * @return the scaled size // */ // public Size scale(int n, int d) { // return new Size(width * n / d, height * n / d); // } // // /** // * Checks if both dimensions of the other size are at least as large as this size. // * // * @param other the size to compare with // * @return true if this size fits into the other size // */ // public boolean fitsIn(Size other) { // return width <= other.width && height <= other.height; // } // // /** // * Default sort order is ascending by size. // */ // @Override // public int compareTo(Size other) { // int aPixels = this.height * this.width; // int bPixels = other.height * other.width; // if (bPixels < aPixels) { // return 1; // } // if (bPixels > aPixels) { // return -1; // } // return 0; // } // // public String toString() { // return width + "x" + height; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Size size = (Size) o; // // if (width != size.width) return false; // return height == size.height; // // } // // @Override // public int hashCode() { // int result = width; // result = 31 * result + height; // return result; // } // } // Path: src/com/zhongyun/zxing/journeyapps/barcodescanner/camera/DisplayConfiguration.java import android.graphics.Rect; import android.util.Log; import android.view.Surface; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.zhongyun.zxing.journeyapps.barcodescanner.Size; package com.zhongyun.zxing.journeyapps.barcodescanner.camera; /** * */ public class DisplayConfiguration { private static final String TAG = DisplayConfiguration.class.getSimpleName();
private Size viewfinderSize;
OpenIchano/Viewer
src/com/zhongyun/viewer/setting/TimeView.java
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // // Path: src/com/zhongyun/viewer/widget/ToggleButton.java // public interface OnToggleChanged{ // /** // * @param on // */ // public void onToggle(boolean on); // }
import com.ichano.rvs.viewer.StreamerInfoMgr; import com.ichano.rvs.viewer.Viewer; import com.ichano.rvs.viewer.bean.RvsAlarmRecordInfo; import com.ichano.rvs.viewer.bean.RvsTimeRecordInfo; import com.ichano.rvs.viewer.bean.ScheduleSetting; import com.ichano.rvs.viewer.bean.StreamerInfo; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import com.zhongyun.viewer.widget.ToggleButton.OnToggleChanged; import android.app.AlertDialog; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ToggleButton; import android.widget.CompoundButton.OnCheckedChangeListener;
eDataText = (TextView)findViewById(R.id.show_end_time_txt); mSensit = (TextView) findViewById(R.id.sensit); mOpenBtn1 = (com.zhongyun.viewer.widget.ToggleButton) findViewById(R.id.open_btn1); mSunBtn1 = (ToggleButton) findViewById(R.id.sun_btn); mMonBtn1 = (ToggleButton) findViewById(R.id.mon_btn); mTueBtn1 = (ToggleButton) findViewById(R.id.tue_btn); mWedBtn1 = (ToggleButton) findViewById(R.id.wed_btn); mThuBtn1 = (ToggleButton) findViewById(R.id.thu_btn); mFriBtn1 = (ToggleButton) findViewById(R.id.fri_btn); mSatBtn1 = (ToggleButton) findViewById(R.id.sat_btn); mSwitchText = (TextView)findViewById(R.id.text_switch); } private void setBtnEvent() { sDataText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimeDlg(sDataText); } }); eDataText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimeDlg(eDataText); } });
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // // Path: src/com/zhongyun/viewer/widget/ToggleButton.java // public interface OnToggleChanged{ // /** // * @param on // */ // public void onToggle(boolean on); // } // Path: src/com/zhongyun/viewer/setting/TimeView.java import com.ichano.rvs.viewer.StreamerInfoMgr; import com.ichano.rvs.viewer.Viewer; import com.ichano.rvs.viewer.bean.RvsAlarmRecordInfo; import com.ichano.rvs.viewer.bean.RvsTimeRecordInfo; import com.ichano.rvs.viewer.bean.ScheduleSetting; import com.ichano.rvs.viewer.bean.StreamerInfo; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import com.zhongyun.viewer.widget.ToggleButton.OnToggleChanged; import android.app.AlertDialog; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ToggleButton; import android.widget.CompoundButton.OnCheckedChangeListener; eDataText = (TextView)findViewById(R.id.show_end_time_txt); mSensit = (TextView) findViewById(R.id.sensit); mOpenBtn1 = (com.zhongyun.viewer.widget.ToggleButton) findViewById(R.id.open_btn1); mSunBtn1 = (ToggleButton) findViewById(R.id.sun_btn); mMonBtn1 = (ToggleButton) findViewById(R.id.mon_btn); mTueBtn1 = (ToggleButton) findViewById(R.id.tue_btn); mWedBtn1 = (ToggleButton) findViewById(R.id.wed_btn); mThuBtn1 = (ToggleButton) findViewById(R.id.thu_btn); mFriBtn1 = (ToggleButton) findViewById(R.id.fri_btn); mSatBtn1 = (ToggleButton) findViewById(R.id.sat_btn); mSwitchText = (TextView)findViewById(R.id.text_switch); } private void setBtnEvent() { sDataText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimeDlg(sDataText); } }); eDataText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimeDlg(eDataText); } });
mOpenBtn1.setOnToggleChanged(new OnToggleChanged() {
OpenIchano/Viewer
src/com/zhongyun/viewer/video/BaseActivity.java
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // // Path: src/com/zhongyun/viewer/utils/NetWorkUtil.java // public class NetWorkUtil // { // // public static int netWorkIsAvailable(Context context) // { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); // // if ("0.0.0.0".endsWith(NetUtil.getLocalIp())) // { // return 0; // } else // { // return 1; // } // // if (activeNetInfo == null || !activeNetInfo.isConnected()) { // // return 0; // // } else { // // return 1; // // } // } // // public static void openDialog(final Activity context) // { // final Builder builder = new AlertDialog.Builder(context); // builder.setTitle("网络不可用"); // builder.setMessage("请连接网络"); // builder.setPositiveButton("确定", new DialogInterface.OnClickListener() // { // @Override // public void onClick(DialogInterface dialog, int which) // { // builder.create().dismiss(); // context.finish(); // } // }); // builder.show(); // } // // public static int getNetType(Context context) // { // ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netWorkInfo = cwjManager.getActiveNetworkInfo(); // if (netWorkInfo != null) // { // boolean flag = netWorkInfo.isAvailable(); // if (flag) // { // if (netWorkInfo.getTypeName().equals("WIFI")) // { // return 1; // } else // { // return 0; // } // } else // { // return -1; // } // } else // { // return -1; // } // } // // public static String getWifiName(Context context) // { // ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo wifi_connect = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // WifiInfo info = wifi.getConnectionInfo(); // if (wifi_connect.isConnected()) // { // return info.getSSID().toString().replaceAll("\"", ""); // } else // { // return ""; // } // } // }
import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.ichano.rvs.viewer.constant.RvsSessionState; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import com.zhongyun.viewer.utils.NetWorkUtil;
// backBtn.setOnClickListener(this); // } // optBtn.setOnClickListener(this); // titleText.setText(titleId); // } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back_linlayout) { this.finish(); } } public void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } public void showLongToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } public void showToast(int messageId) { Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } int lastType = -1; private final BroadcastReceiver broadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Constants.CONNECTIVITY_CHANGE_ACTION)) {
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // // Path: src/com/zhongyun/viewer/utils/NetWorkUtil.java // public class NetWorkUtil // { // // public static int netWorkIsAvailable(Context context) // { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); // // if ("0.0.0.0".endsWith(NetUtil.getLocalIp())) // { // return 0; // } else // { // return 1; // } // // if (activeNetInfo == null || !activeNetInfo.isConnected()) { // // return 0; // // } else { // // return 1; // // } // } // // public static void openDialog(final Activity context) // { // final Builder builder = new AlertDialog.Builder(context); // builder.setTitle("网络不可用"); // builder.setMessage("请连接网络"); // builder.setPositiveButton("确定", new DialogInterface.OnClickListener() // { // @Override // public void onClick(DialogInterface dialog, int which) // { // builder.create().dismiss(); // context.finish(); // } // }); // builder.show(); // } // // public static int getNetType(Context context) // { // ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netWorkInfo = cwjManager.getActiveNetworkInfo(); // if (netWorkInfo != null) // { // boolean flag = netWorkInfo.isAvailable(); // if (flag) // { // if (netWorkInfo.getTypeName().equals("WIFI")) // { // return 1; // } else // { // return 0; // } // } else // { // return -1; // } // } else // { // return -1; // } // } // // public static String getWifiName(Context context) // { // ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo wifi_connect = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // WifiInfo info = wifi.getConnectionInfo(); // if (wifi_connect.isConnected()) // { // return info.getSSID().toString().replaceAll("\"", ""); // } else // { // return ""; // } // } // } // Path: src/com/zhongyun/viewer/video/BaseActivity.java import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.ichano.rvs.viewer.constant.RvsSessionState; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import com.zhongyun.viewer.utils.NetWorkUtil; // backBtn.setOnClickListener(this); // } // optBtn.setOnClickListener(this); // titleText.setText(titleId); // } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back_linlayout) { this.finish(); } } public void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } public void showLongToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } public void showToast(int messageId) { Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } int lastType = -1; private final BroadcastReceiver broadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Constants.CONNECTIVITY_CHANGE_ACTION)) {
int type = NetWorkUtil.netWorkIsAvailable(BaseActivity.this);
OpenIchano/Viewer
src/com/zhongyun/viewer/cameralist/AddCidHandler.java
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/login/UserInfo.java // public class UserInfo { // // public static final String CLIENT_CID = "CLIENT_CID"; // public static final String IS_LOGIN = "IS_LOGIN"; // public static final String USER_NAME = "USER_NAME"; // public static final String USER_SESSION_ID = "USER_SESSION_ID"; // public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; // public static final String TS = "TS"; // // private static UserInfo mUserInfo; // private Context mContext; // public boolean isLogin; // public long clientCid = 0; // public String name; // public String sessionId; // public String recommandURL; // public String ts = ""; // // private UserInfo(Context context){ // mContext = context; // String str = PrefUtils.getString(mContext, CLIENT_CID); // if(!StringUtils.isEmpty(str)){ // clientCid = Long.parseLong(str); // } // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // isLogin = sp.getBoolean(IS_LOGIN, false); // name = sp.getString(USER_NAME, ""); // sessionId = sp.getString(USER_SESSION_ID, ""); // recommandURL = sp.getString(USER_RECOMMAND_URL, ""); // ts = sp.getString(TS, ""); // } // // public static UserInfo getUserInfo(Context context){ // if(null == mUserInfo){ // mUserInfo = new UserInfo(context); // } // return mUserInfo; // } // // public void saveClientCid(long cid){ // if(cid > 0){ // if(cid != clientCid) // clientCid = cid; // PrefUtils.putString(mContext, CLIENT_CID, String.valueOf(cid)); // } // } // // public void setLoginInfo(boolean isLogin, String name, String sessionId, String recommandURL){ // this.isLogin = isLogin; // this.name = name; // this.sessionId = sessionId; // this.recommandURL = recommandURL; // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); // Editor editor = sp.edit(); // editor.putBoolean(IS_LOGIN, isLogin); // editor.putString(USER_NAME, name); // editor.putString(USER_SESSION_ID, sessionId); // editor.putString(USER_RECOMMAND_URL, recommandURL); // editor.commit(); // } // // public void setTS(String ts){ // if(!ts.equals(this.ts)){ // this.ts = ts; // PrefUtils.putString(mContext, TS, ts); // } // } // }
import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.login.UserInfo; import android.content.Context; import android.os.Handler; import android.os.Message;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.cameralist; /** * * @author handler返回值 * 0.成功 1.失败 2,session失效,3.qrcode失效 */ public class AddCidHandler implements Callable<String>, CallbackMessage<String>{ Context context; String sessionid; int request; Handler handler; String cidStr,userStr,passStr; int cidFlag;
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/login/UserInfo.java // public class UserInfo { // // public static final String CLIENT_CID = "CLIENT_CID"; // public static final String IS_LOGIN = "IS_LOGIN"; // public static final String USER_NAME = "USER_NAME"; // public static final String USER_SESSION_ID = "USER_SESSION_ID"; // public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; // public static final String TS = "TS"; // // private static UserInfo mUserInfo; // private Context mContext; // public boolean isLogin; // public long clientCid = 0; // public String name; // public String sessionId; // public String recommandURL; // public String ts = ""; // // private UserInfo(Context context){ // mContext = context; // String str = PrefUtils.getString(mContext, CLIENT_CID); // if(!StringUtils.isEmpty(str)){ // clientCid = Long.parseLong(str); // } // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // isLogin = sp.getBoolean(IS_LOGIN, false); // name = sp.getString(USER_NAME, ""); // sessionId = sp.getString(USER_SESSION_ID, ""); // recommandURL = sp.getString(USER_RECOMMAND_URL, ""); // ts = sp.getString(TS, ""); // } // // public static UserInfo getUserInfo(Context context){ // if(null == mUserInfo){ // mUserInfo = new UserInfo(context); // } // return mUserInfo; // } // // public void saveClientCid(long cid){ // if(cid > 0){ // if(cid != clientCid) // clientCid = cid; // PrefUtils.putString(mContext, CLIENT_CID, String.valueOf(cid)); // } // } // // public void setLoginInfo(boolean isLogin, String name, String sessionId, String recommandURL){ // this.isLogin = isLogin; // this.name = name; // this.sessionId = sessionId; // this.recommandURL = recommandURL; // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); // Editor editor = sp.edit(); // editor.putBoolean(IS_LOGIN, isLogin); // editor.putString(USER_NAME, name); // editor.putString(USER_SESSION_ID, sessionId); // editor.putString(USER_RECOMMAND_URL, recommandURL); // editor.commit(); // } // // public void setTS(String ts){ // if(!ts.equals(this.ts)){ // this.ts = ts; // PrefUtils.putString(mContext, TS, ts); // } // } // } // Path: src/com/zhongyun/viewer/cameralist/AddCidHandler.java import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.login.UserInfo; import android.content.Context; import android.os.Handler; import android.os.Message; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.cameralist; /** * * @author handler返回值 * 0.成功 1.失败 2,session失效,3.qrcode失效 */ public class AddCidHandler implements Callable<String>, CallbackMessage<String>{ Context context; String sessionid; int request; Handler handler; String cidStr,userStr,passStr; int cidFlag;
private UserInfo mUserInfo;
OpenIchano/Viewer
src/com/zhongyun/viewer/BaseActivity.java
// Path: src/com/zhongyun/viewer/utils/AppUtils.java // public class AppUtils { // // public static String getAppVersionName(Context context){ // PackageManager manager = context.getPackageManager(); // PackageInfo info; // try { // info = manager.getPackageInfo(context.getPackageName(), 0); // return info.versionName; // } catch (NameNotFoundException e) { // e.printStackTrace(); // return "1.0"; // } // } // // @SuppressLint("NewApi") // public static void setStatusBarTransparent(Activity context, int tintColor){ // // create our manager instance after the content view is set // SystemBarTintManager tintManager = new SystemBarTintManager(context); // // enable status bar tint // tintManager.setStatusBarTintEnabled(true); // // enable navigation bar tint // tintManager.setNavigationBarTintEnabled(true); // // if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // context.getWindow().setStatusBarColor(tintColor); // }else{ // tintManager.setTintColor(tintColor); // } // } // }
import com.zhongyun.viewer.utils.AppUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.Window;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer; public class BaseActivity extends Activity{ protected ProgressDialog dialog = null; private boolean isActivityVisible = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);
// Path: src/com/zhongyun/viewer/utils/AppUtils.java // public class AppUtils { // // public static String getAppVersionName(Context context){ // PackageManager manager = context.getPackageManager(); // PackageInfo info; // try { // info = manager.getPackageInfo(context.getPackageName(), 0); // return info.versionName; // } catch (NameNotFoundException e) { // e.printStackTrace(); // return "1.0"; // } // } // // @SuppressLint("NewApi") // public static void setStatusBarTransparent(Activity context, int tintColor){ // // create our manager instance after the content view is set // SystemBarTintManager tintManager = new SystemBarTintManager(context); // // enable status bar tint // tintManager.setStatusBarTintEnabled(true); // // enable navigation bar tint // tintManager.setNavigationBarTintEnabled(true); // // if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // context.getWindow().setStatusBarColor(tintColor); // }else{ // tintManager.setTintColor(tintColor); // } // } // } // Path: src/com/zhongyun/viewer/BaseActivity.java import com.zhongyun.viewer.utils.AppUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.Window; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer; public class BaseActivity extends Activity{ protected ProgressDialog dialog = null; private boolean isActivityVisible = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);
AppUtils.setStatusBarTransparent(this, getResources().getColor(R.color.title_red));
OpenIchano/Viewer
src/com/zhongyun/viewer/login/UserInfo.java
// Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserInfo { public static final String CLIENT_CID = "CLIENT_CID"; public static final String IS_LOGIN = "IS_LOGIN"; public static final String USER_NAME = "USER_NAME"; public static final String USER_SESSION_ID = "USER_SESSION_ID"; public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; public static final String TS = "TS"; private static UserInfo mUserInfo; private Context mContext; public boolean isLogin; public long clientCid = 0; public String name; public String sessionId; public String recommandURL; public String ts = ""; private UserInfo(Context context){ mContext = context;
// Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // } // Path: src/com/zhongyun/viewer/login/UserInfo.java import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserInfo { public static final String CLIENT_CID = "CLIENT_CID"; public static final String IS_LOGIN = "IS_LOGIN"; public static final String USER_NAME = "USER_NAME"; public static final String USER_SESSION_ID = "USER_SESSION_ID"; public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; public static final String TS = "TS"; private static UserInfo mUserInfo; private Context mContext; public boolean isLogin; public long clientCid = 0; public String name; public String sessionId; public String recommandURL; public String ts = ""; private UserInfo(Context context){ mContext = context;
String str = PrefUtils.getString(mContext, CLIENT_CID);
OpenIchano/Viewer
src/com/zhongyun/viewer/login/UserInfo.java
// Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserInfo { public static final String CLIENT_CID = "CLIENT_CID"; public static final String IS_LOGIN = "IS_LOGIN"; public static final String USER_NAME = "USER_NAME"; public static final String USER_SESSION_ID = "USER_SESSION_ID"; public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; public static final String TS = "TS"; private static UserInfo mUserInfo; private Context mContext; public boolean isLogin; public long clientCid = 0; public String name; public String sessionId; public String recommandURL; public String ts = ""; private UserInfo(Context context){ mContext = context; String str = PrefUtils.getString(mContext, CLIENT_CID);
// Path: src/com/zhongyun/viewer/utils/PrefUtils.java // public class PrefUtils { // // public static final String HAVE_SHOW_GUIDE = "have_show_guide"; // // public static void putBoolean(Context context, String key, boolean value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public static boolean getBoolean(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getBoolean(key, false); // } // // public static void putString(Context context, String key, String value){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Editor editor = sp.edit(); // editor.putString(key, value); // editor.commit(); // } // // public static String getString(Context context, String key){ // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // return sp.getString(key, ""); // } // } // // Path: src/com/zhongyun/viewer/utils/StringUtils.java // public class StringUtils { // // // Just in case TextUtils.isEmpty() not found on certain system // public static boolean isEmpty(String str){ // if(null == str){ // return true; // }else if("".equals(str)){ // return true; // } // return false; // } // // public static boolean notEmpty(String str) { // return (str != null && !str.equals("") && !str.equals("null") && !str.equals(" ") && !str.equals(" ")); // } // } // Path: src/com/zhongyun/viewer/login/UserInfo.java import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.zhongyun.viewer.utils.PrefUtils; import com.zhongyun.viewer.utils.StringUtils; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.login; public class UserInfo { public static final String CLIENT_CID = "CLIENT_CID"; public static final String IS_LOGIN = "IS_LOGIN"; public static final String USER_NAME = "USER_NAME"; public static final String USER_SESSION_ID = "USER_SESSION_ID"; public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; public static final String TS = "TS"; private static UserInfo mUserInfo; private Context mContext; public boolean isLogin; public long clientCid = 0; public String name; public String sessionId; public String recommandURL; public String ts = ""; private UserInfo(Context context){ mContext = context; String str = PrefUtils.getString(mContext, CLIENT_CID);
if(!StringUtils.isEmpty(str)){
OpenIchano/Viewer
src/com/zhongyun/viewer/video/RecordingVideoTypeList.java
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // }
import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; import com.ichano.rvs.viewer.constant.RvsRecordType; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.video; public class RecordingVideoTypeList extends BaseActivity{ RelativeLayout relayout_time_recording_video,relayout_alarm_video; // private AvsInfoBean avsInfoBean; String cidStr; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); super.onCreate(savedInstanceState); if(null == savedInstanceState){ setContentView(R.layout.recording_videotypelist); customTitleBar(R.layout.athome_camera_title_bar_with_button, R.string.menu_watch_recorded_video_label,R.string.back_nav_item,R.string.video_list_controller_del_settings_btn,0); isShowConnect = true;
// Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // Path: src/com/zhongyun/viewer/video/RecordingVideoTypeList.java import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; import com.ichano.rvs.viewer.constant.RvsRecordType; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.video; public class RecordingVideoTypeList extends BaseActivity{ RelativeLayout relayout_time_recording_video,relayout_alarm_video; // private AvsInfoBean avsInfoBean; String cidStr; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); super.onCreate(savedInstanceState); if(null == savedInstanceState){ setContentView(R.layout.recording_videotypelist); customTitleBar(R.layout.athome_camera_title_bar_with_button, R.string.menu_watch_recorded_video_label,R.string.back_nav_item,R.string.video_list_controller_del_settings_btn,0); isShowConnect = true;
cidStr = getIntent().getExtras().getString(Constants.INTENT_CID);
OpenIchano/Viewer
src/com/zhongyun/viewer/cameralist/CameraListHandler.java
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/login/UserInfo.java // public class UserInfo { // // public static final String CLIENT_CID = "CLIENT_CID"; // public static final String IS_LOGIN = "IS_LOGIN"; // public static final String USER_NAME = "USER_NAME"; // public static final String USER_SESSION_ID = "USER_SESSION_ID"; // public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; // public static final String TS = "TS"; // // private static UserInfo mUserInfo; // private Context mContext; // public boolean isLogin; // public long clientCid = 0; // public String name; // public String sessionId; // public String recommandURL; // public String ts = ""; // // private UserInfo(Context context){ // mContext = context; // String str = PrefUtils.getString(mContext, CLIENT_CID); // if(!StringUtils.isEmpty(str)){ // clientCid = Long.parseLong(str); // } // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // isLogin = sp.getBoolean(IS_LOGIN, false); // name = sp.getString(USER_NAME, ""); // sessionId = sp.getString(USER_SESSION_ID, ""); // recommandURL = sp.getString(USER_RECOMMAND_URL, ""); // ts = sp.getString(TS, ""); // } // // public static UserInfo getUserInfo(Context context){ // if(null == mUserInfo){ // mUserInfo = new UserInfo(context); // } // return mUserInfo; // } // // public void saveClientCid(long cid){ // if(cid > 0){ // if(cid != clientCid) // clientCid = cid; // PrefUtils.putString(mContext, CLIENT_CID, String.valueOf(cid)); // } // } // // public void setLoginInfo(boolean isLogin, String name, String sessionId, String recommandURL){ // this.isLogin = isLogin; // this.name = name; // this.sessionId = sessionId; // this.recommandURL = recommandURL; // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); // Editor editor = sp.edit(); // editor.putBoolean(IS_LOGIN, isLogin); // editor.putString(USER_NAME, name); // editor.putString(USER_SESSION_ID, sessionId); // editor.putString(USER_RECOMMAND_URL, recommandURL); // editor.commit(); // } // // public void setTS(String ts){ // if(!ts.equals(this.ts)){ // this.ts = ts; // PrefUtils.putString(mContext, TS, ts); // } // } // }
import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.login.UserInfo; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.util.Log; import com.umeng.analytics.MobclickAgent; import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.cameralist; public class CameraListHandler implements Callable<String>, CallbackMessage<String>{ private static final String TAG = CameraListHandler.class.getSimpleName(); Context context; String sessionid; int request; Handler handler;
// Path: src/com/zhongyun/viewer/async/AsyncUtil.java // public class AsyncUtil { // // public static <T> void doAsync(final int requestid, final Context pContext, final Callable<T> pCallable, final CallbackMessage<T> pCallback) { // new AsyncTask<Void, Void, T>() { // private Exception mException; // protected void onPreExecute() { // super.onPreExecute(); // } // // @Override // protected T doInBackground(Void... params) { // try { // T result = pCallable.call(); // return result; // } catch (final Exception e) { // this.mException = e; // } // return null; // } // // protected void onPostExecute(T result) { // pCallback.onComplete(requestid, result); // if(this.mException != null) { // Log.e("Error", this.mException.toString()); // } // super.onPostExecute(result); // } // }.execute((Void[]) null); // } // // } // // Path: src/com/zhongyun/viewer/async/Callable.java // public interface Callable<T> { // // public T call() throws Exception; // } // // Path: src/com/zhongyun/viewer/async/CallbackMessage.java // public interface CallbackMessage<T> { // public void onComplete(final int requestid, final T pCallbackValue); // } // // Path: src/com/zhongyun/viewer/login/UserInfo.java // public class UserInfo { // // public static final String CLIENT_CID = "CLIENT_CID"; // public static final String IS_LOGIN = "IS_LOGIN"; // public static final String USER_NAME = "USER_NAME"; // public static final String USER_SESSION_ID = "USER_SESSION_ID"; // public static final String USER_RECOMMAND_URL = "USER_RECOMMAND_URL"; // public static final String TS = "TS"; // // private static UserInfo mUserInfo; // private Context mContext; // public boolean isLogin; // public long clientCid = 0; // public String name; // public String sessionId; // public String recommandURL; // public String ts = ""; // // private UserInfo(Context context){ // mContext = context; // String str = PrefUtils.getString(mContext, CLIENT_CID); // if(!StringUtils.isEmpty(str)){ // clientCid = Long.parseLong(str); // } // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // isLogin = sp.getBoolean(IS_LOGIN, false); // name = sp.getString(USER_NAME, ""); // sessionId = sp.getString(USER_SESSION_ID, ""); // recommandURL = sp.getString(USER_RECOMMAND_URL, ""); // ts = sp.getString(TS, ""); // } // // public static UserInfo getUserInfo(Context context){ // if(null == mUserInfo){ // mUserInfo = new UserInfo(context); // } // return mUserInfo; // } // // public void saveClientCid(long cid){ // if(cid > 0){ // if(cid != clientCid) // clientCid = cid; // PrefUtils.putString(mContext, CLIENT_CID, String.valueOf(cid)); // } // } // // public void setLoginInfo(boolean isLogin, String name, String sessionId, String recommandURL){ // this.isLogin = isLogin; // this.name = name; // this.sessionId = sessionId; // this.recommandURL = recommandURL; // // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); // Editor editor = sp.edit(); // editor.putBoolean(IS_LOGIN, isLogin); // editor.putString(USER_NAME, name); // editor.putString(USER_SESSION_ID, sessionId); // editor.putString(USER_RECOMMAND_URL, recommandURL); // editor.commit(); // } // // public void setTS(String ts){ // if(!ts.equals(this.ts)){ // this.ts = ts; // PrefUtils.putString(mContext, TS, ts); // } // } // } // Path: src/com/zhongyun/viewer/cameralist/CameraListHandler.java import com.zhongyun.viewer.http.bean.JsonReturn; import com.zhongyun.viewer.login.UserInfo; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.util.Log; import com.umeng.analytics.MobclickAgent; import com.zhongyun.viewer.async.AsyncUtil; import com.zhongyun.viewer.async.Callable; import com.zhongyun.viewer.async.CallbackMessage; import com.zhongyun.viewer.http.JsonReturnCode; import com.zhongyun.viewer.http.JsonSerializer; import com.zhongyun.viewer.http.UserHttpApi; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.cameralist; public class CameraListHandler implements Callable<String>, CallbackMessage<String>{ private static final String TAG = CameraListHandler.class.getSimpleName(); Context context; String sessionid; int request; Handler handler;
private UserInfo mUserInfo;
OpenIchano/Viewer
src/com/zhongyun/viewer/setting/CameraSettingsTabActivity.java
// Path: src/com/zhongyun/viewer/MyViewPagerAdapter.java // public class MyViewPagerAdapter extends FragmentStatePagerAdapter { // // private int[] mTitles; // private List<Fragment> mFragments; // private Context mContext; // // public MyViewPagerAdapter(Context context,FragmentManager fm, int[] mTitles, List<Fragment> mFragments) { // super(fm); // mContext = context; // this.mTitles = mTitles; // this.mFragments = mFragments; // } // // @Override // public CharSequence getPageTitle(int position) { // return mContext.getString(mTitles[position]); // } // // @Override // public Fragment getItem(int position) { // return mFragments.get(position); // } // // @Override // public int getCount() { // return mFragments.size(); // } // } // // Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // }
import java.util.ArrayList; import java.util.List; import com.zhongyun.viewer.MyViewPagerAdapter; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.setting; public class CameraSettingsTabActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, OnClickListener { // private Toolbar mToolbar; // private TabLayout mTabLayout; private ViewPager mViewPager; // TabLayout中的tab标题 private int[] mTitles; // 填充到ViewPager中的Fragment private List<Fragment> mFragments;
// Path: src/com/zhongyun/viewer/MyViewPagerAdapter.java // public class MyViewPagerAdapter extends FragmentStatePagerAdapter { // // private int[] mTitles; // private List<Fragment> mFragments; // private Context mContext; // // public MyViewPagerAdapter(Context context,FragmentManager fm, int[] mTitles, List<Fragment> mFragments) { // super(fm); // mContext = context; // this.mTitles = mTitles; // this.mFragments = mFragments; // } // // @Override // public CharSequence getPageTitle(int position) { // return mContext.getString(mTitles[position]); // } // // @Override // public Fragment getItem(int position) { // return mFragments.get(position); // } // // @Override // public int getCount() { // return mFragments.size(); // } // } // // Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // Path: src/com/zhongyun/viewer/setting/CameraSettingsTabActivity.java import java.util.ArrayList; import java.util.List; import com.zhongyun.viewer.MyViewPagerAdapter; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer.setting; public class CameraSettingsTabActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, OnClickListener { // private Toolbar mToolbar; // private TabLayout mTabLayout; private ViewPager mViewPager; // TabLayout中的tab标题 private int[] mTitles; // 填充到ViewPager中的Fragment private List<Fragment> mFragments;
MyViewPagerAdapter mViewPagerAdapter;
OpenIchano/Viewer
src/com/zhongyun/viewer/setting/CameraSettingsTabActivity.java
// Path: src/com/zhongyun/viewer/MyViewPagerAdapter.java // public class MyViewPagerAdapter extends FragmentStatePagerAdapter { // // private int[] mTitles; // private List<Fragment> mFragments; // private Context mContext; // // public MyViewPagerAdapter(Context context,FragmentManager fm, int[] mTitles, List<Fragment> mFragments) { // super(fm); // mContext = context; // this.mTitles = mTitles; // this.mFragments = mFragments; // } // // @Override // public CharSequence getPageTitle(int position) { // return mContext.getString(mTitles[position]); // } // // @Override // public Fragment getItem(int position) { // return mFragments.get(position); // } // // @Override // public int getCount() { // return mFragments.size(); // } // } // // Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // }
import java.util.ArrayList; import java.util.List; import com.zhongyun.viewer.MyViewPagerAdapter; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView;
// 对各种控件进行设置、适配、填充数据 configViews(); } private void initViews() { // mCoordinatorLayout = (CoordinatorLayout) // findViewById(R.id.id_coordinatorlayout); // mAppBarLayout = (AppBarLayout) findViewById(R.id.id_appbarlayout); // mToolbar = (Toolbar) findViewById(R.id.id_toolbar); titlebar_back_text = (TextView) findViewById(R.id.titlebar_back_text); findViewById(R.id.titlebar_opt_image).setBackgroundResource(R.drawable.save); findViewById(R.id.alarm_settings_label).setOnClickListener(this); findViewById(R.id.scheduled_recording_label).setOnClickListener(this); findViewById(R.id.change_password_label).setOnClickListener(this); findViewById(R.id.opt_linlayout).setOnClickListener(this); alarm_settings_label_text = (TextView) findViewById(R.id.alarm_settings_label_text); scheduled_recording_label_text = (TextView) findViewById(R.id.scheduled_recording_label_text); change_password_label_text = (TextView) findViewById(R.id.change_password_label_text); id_tab_line_iv_left = (ImageView) findViewById(R.id.id_tab_line_iv_left); id_tab_line_iv_mid = (ImageView) findViewById(R.id.id_tab_line_iv_mid); id_tab_line_iv_right = (ImageView) findViewById(R.id.id_tab_line_iv_right); // mTabLayout = (TabLayout) findViewById(R.id.id_tablayout); mViewPager = (ViewPager) findViewById(R.id.id_viewpager); onSelectColor = getResources().getColor(R.color.athome_title); unSelectColor = getResources().getColor(R.color.title_text_no_select); } private void initData() {
// Path: src/com/zhongyun/viewer/MyViewPagerAdapter.java // public class MyViewPagerAdapter extends FragmentStatePagerAdapter { // // private int[] mTitles; // private List<Fragment> mFragments; // private Context mContext; // // public MyViewPagerAdapter(Context context,FragmentManager fm, int[] mTitles, List<Fragment> mFragments) { // super(fm); // mContext = context; // this.mTitles = mTitles; // this.mFragments = mFragments; // } // // @Override // public CharSequence getPageTitle(int position) { // return mContext.getString(mTitles[position]); // } // // @Override // public Fragment getItem(int position) { // return mFragments.get(position); // } // // @Override // public int getCount() { // return mFragments.size(); // } // } // // Path: src/com/zhongyun/viewer/utils/Constants.java // public class Constants { // // public static final String INTENT_CID = "cid"; // public static final String INTENT_CAMERA_NAME = "camera_name"; // // public static final String BARCODE_SPLITER = "&"; // public static final String BARCODE_DEVICE_ID = "deviceid="; // public static final String BARCODE_CID = "cid="; // public static final String BARCODE_NAME = "name="; // public static final String BARCODE_USER_NAME = "username="; // public static final String BARCODE_PASSWORD = "password="; // // public static final String VIDEO_MP4 = ".mp4"; // public static final String IMG_JPG = ".jpg"; // public static final String RECORD_VIDEO_PATH = "ZhongYun/recordVideo"; // public static final String CAPTURE_IAMGE_PATH = "ZhongYun/capture"; // public static final String LOCAL_ICON_PATH = "ZhongYun/icon"; // public static final String LOCAL_CID_ICON_PATH = "ZhongYun/cid_icon"; // // public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; // public static final String CONNECTIVITY_SESSION_STATE = "zhongyun.viewer.session_state"; // } // Path: src/com/zhongyun/viewer/setting/CameraSettingsTabActivity.java import java.util.ArrayList; import java.util.List; import com.zhongyun.viewer.MyViewPagerAdapter; import com.zhongyun.viewer.R; import com.zhongyun.viewer.utils.Constants; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; // 对各种控件进行设置、适配、填充数据 configViews(); } private void initViews() { // mCoordinatorLayout = (CoordinatorLayout) // findViewById(R.id.id_coordinatorlayout); // mAppBarLayout = (AppBarLayout) findViewById(R.id.id_appbarlayout); // mToolbar = (Toolbar) findViewById(R.id.id_toolbar); titlebar_back_text = (TextView) findViewById(R.id.titlebar_back_text); findViewById(R.id.titlebar_opt_image).setBackgroundResource(R.drawable.save); findViewById(R.id.alarm_settings_label).setOnClickListener(this); findViewById(R.id.scheduled_recording_label).setOnClickListener(this); findViewById(R.id.change_password_label).setOnClickListener(this); findViewById(R.id.opt_linlayout).setOnClickListener(this); alarm_settings_label_text = (TextView) findViewById(R.id.alarm_settings_label_text); scheduled_recording_label_text = (TextView) findViewById(R.id.scheduled_recording_label_text); change_password_label_text = (TextView) findViewById(R.id.change_password_label_text); id_tab_line_iv_left = (ImageView) findViewById(R.id.id_tab_line_iv_left); id_tab_line_iv_mid = (ImageView) findViewById(R.id.id_tab_line_iv_mid); id_tab_line_iv_right = (ImageView) findViewById(R.id.id_tab_line_iv_right); // mTabLayout = (TabLayout) findViewById(R.id.id_tablayout); mViewPager = (ViewPager) findViewById(R.id.id_viewpager); onSelectColor = getResources().getColor(R.color.athome_title); unSelectColor = getResources().getColor(R.color.title_text_no_select); } private void initData() {
long cid = getIntent().getLongExtra(Constants.INTENT_CID, 0);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> {
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> {
protected Wrapper<T> wrapper;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanResultSetHadler(Class<T> type) {
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanResultSetHadler(Class<T> type) {
this(new BeanWrapper<T>(new FieldBinder(type)),type);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanResultSetHadler(Class<T> type) {
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanResultSetHadler.java import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanResultSetHadler<T> implements ResultSetHandler<T> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanResultSetHadler(Class<T> type) {
this(new BeanWrapper<T>(new FieldBinder(type)),type);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/wrapper/BaseTypeWrapper.java
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JAVAType.java // public enum JAVAType { // INT(int.class,Integer.class), // CHAR(char.class,Character.class), // FLOAT(float.class,Float.class), // DOUBLE(double.class,Double.class), // LONG(long.class,Long.class), // SHORT(short.class,Short.class), // BOOL(boolean.class,Boolean.class), // BYTE(byte.class,Byte.class), // BYTEARRAY(byte[].class,Byte[].class), // STRING(String.class,String.class), // DATE(Date.class, java.sql.Date.class), // TIMESTAMP(Timestamp.class, Timestamp.class); // // public Class obj; // public Class base; // // JAVAType(Class base,Class obj) { // this.obj = obj; // this.base = base; // } // // public static JAVAType getType(Class cls){ // for (JAVAType type:values()){ // if (type.base.equals(cls)||type.obj.equals(cls)){ // return type; // } // } // throw new IllegalArgumentException("there is no type named "+cls.getTypeName()+" here"); // } // }
import org.easyarch.slardar.jdbc.type.JAVAType; import java.sql.ResultSet; import java.sql.SQLException;
package org.easyarch.slardar.jdbc.wrapper; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:18 * description: */ public class BaseTypeWrapper<T> extends BeanWrapper<T> { public BaseTypeWrapper() { super(null); } @Override public T bean(ResultSet rs, Class<T> type) { try { if (rs.next()) {
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JAVAType.java // public enum JAVAType { // INT(int.class,Integer.class), // CHAR(char.class,Character.class), // FLOAT(float.class,Float.class), // DOUBLE(double.class,Double.class), // LONG(long.class,Long.class), // SHORT(short.class,Short.class), // BOOL(boolean.class,Boolean.class), // BYTE(byte.class,Byte.class), // BYTEARRAY(byte[].class,Byte[].class), // STRING(String.class,String.class), // DATE(Date.class, java.sql.Date.class), // TIMESTAMP(Timestamp.class, Timestamp.class); // // public Class obj; // public Class base; // // JAVAType(Class base,Class obj) { // this.obj = obj; // this.base = base; // } // // public static JAVAType getType(Class cls){ // for (JAVAType type:values()){ // if (type.base.equals(cls)||type.obj.equals(cls)){ // return type; // } // } // throw new IllegalArgumentException("there is no type named "+cls.getTypeName()+" here"); // } // } // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BaseTypeWrapper.java import org.easyarch.slardar.jdbc.type.JAVAType; import java.sql.ResultSet; import java.sql.SQLException; package org.easyarch.slardar.jdbc.wrapper; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:18 * description: */ public class BaseTypeWrapper<T> extends BeanWrapper<T> { public BaseTypeWrapper() { super(null); } @Override public T bean(ResultSet rs, Class<T> type) { try { if (rs.next()) {
switch (JAVAType.getType(type)){
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/mapping/ClassItem.java
// Path: src/main/java/org/easyarch/slardar/utils/CollectionUtils.java // public class CollectionUtils { // // public static <T> boolean isEmpty(Collection<T> col) { // return col == null || col.isEmpty(); // } // // public static <T> boolean isNotEmpty(Collection<T> col) { // return !isEmpty(col); // } // // public static <T> ArrayList<T> newArrayList(final T... beans) { // ArrayList<T> list = new ArrayList<T>(); // for (T t : beans) { // list.add(t); // } // return list; // } // // public static <T> ArrayList<T> newArrayList(final int capacity) { // if (capacity <= 0) { // return new ArrayList<T>(0); // } // return new ArrayList<T>(capacity); // } // // public static <T> ArrayList<T> newArrayList(final Iterator<? extends T> elements) { // ArrayList<T> list = newArrayList(); // if (elements == null) { // return list; // } // while (elements.hasNext()) { // list.add(elements.next()); // } // return list; // } // // // public static <T> LinkedList<T> newLinkedList(final T... beans) { // LinkedList<T> list = new LinkedList<T>(); // for (T t : beans) { // list.add(t); // } // return list; // } // // public static <T> T[] toArray(final Collection<T> col,Class<T> clazz){ // return col.toArray((T[]) Array.newInstance(clazz,col.size())); // } // // /** // * 聚合操作,给maplist降低维度到统一的map中 // * @param mapList // * @return // */ // public static Map<String,Object> collectMapLists(List<Map<String,Object>> mapList){ // Map<String,Object> collectMap = new HashMap<>(); // for (Map<String,Object> map:mapList){ // collectMap.putAll(map); // } // return collectMap; // } // // /** // * 平铺操作,将map中的每个元素作为一个键值放入list // * @param flatMap // * @return // */ // public static List<Map<String,Object>> flatMapLists(Map<String,Object> flatMap){ // List<Map<String,Object>> mapList = new ArrayList<>(); // for (Map.Entry<String,Object> entry : flatMap.entrySet()){ // Map<String,Object> map = new HashMap<>(); // map.put(entry.getKey(),entry.getValue()); // mapList.add(map); // } // return mapList; // } // // /** // * 统计maplist的值,返回数组 // * @param mapList // * @return // */ // public static Object[] gatherMapListsValues(List<Map<String,Object>> mapList){ // List valueList = new ArrayList(); // for (Map<String,Object> map:mapList){ // for (Map.Entry<String,Object> entry:map.entrySet()){ // valueList.add(entry.getValue()); // } // } // return valueList.toArray(); // } // /** // * 统计maplist的值,返回数组 // * @param map // * @return // */ // public static Object[] gatherMapListsValues(Map<String,Object> map){ // List valueList = new ArrayList(); // valueList.addAll(map.values()); // return valueList.toArray(); // } // // }
import org.easyarch.slardar.utils.CollectionUtils; import java.lang.reflect.Method; import java.util.List;
package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-21 * 下午11:31 * description: */ public class ClassItem { private String itemName; private Class clazz; private List<Method> methods; public ClassItem(String itemName, Class clazz, Method[] methods) { this.itemName = itemName; this.clazz = clazz;
// Path: src/main/java/org/easyarch/slardar/utils/CollectionUtils.java // public class CollectionUtils { // // public static <T> boolean isEmpty(Collection<T> col) { // return col == null || col.isEmpty(); // } // // public static <T> boolean isNotEmpty(Collection<T> col) { // return !isEmpty(col); // } // // public static <T> ArrayList<T> newArrayList(final T... beans) { // ArrayList<T> list = new ArrayList<T>(); // for (T t : beans) { // list.add(t); // } // return list; // } // // public static <T> ArrayList<T> newArrayList(final int capacity) { // if (capacity <= 0) { // return new ArrayList<T>(0); // } // return new ArrayList<T>(capacity); // } // // public static <T> ArrayList<T> newArrayList(final Iterator<? extends T> elements) { // ArrayList<T> list = newArrayList(); // if (elements == null) { // return list; // } // while (elements.hasNext()) { // list.add(elements.next()); // } // return list; // } // // // public static <T> LinkedList<T> newLinkedList(final T... beans) { // LinkedList<T> list = new LinkedList<T>(); // for (T t : beans) { // list.add(t); // } // return list; // } // // public static <T> T[] toArray(final Collection<T> col,Class<T> clazz){ // return col.toArray((T[]) Array.newInstance(clazz,col.size())); // } // // /** // * 聚合操作,给maplist降低维度到统一的map中 // * @param mapList // * @return // */ // public static Map<String,Object> collectMapLists(List<Map<String,Object>> mapList){ // Map<String,Object> collectMap = new HashMap<>(); // for (Map<String,Object> map:mapList){ // collectMap.putAll(map); // } // return collectMap; // } // // /** // * 平铺操作,将map中的每个元素作为一个键值放入list // * @param flatMap // * @return // */ // public static List<Map<String,Object>> flatMapLists(Map<String,Object> flatMap){ // List<Map<String,Object>> mapList = new ArrayList<>(); // for (Map.Entry<String,Object> entry : flatMap.entrySet()){ // Map<String,Object> map = new HashMap<>(); // map.put(entry.getKey(),entry.getValue()); // mapList.add(map); // } // return mapList; // } // // /** // * 统计maplist的值,返回数组 // * @param mapList // * @return // */ // public static Object[] gatherMapListsValues(List<Map<String,Object>> mapList){ // List valueList = new ArrayList(); // for (Map<String,Object> map:mapList){ // for (Map.Entry<String,Object> entry:map.entrySet()){ // valueList.add(entry.getValue()); // } // } // return valueList.toArray(); // } // /** // * 统计maplist的值,返回数组 // * @param map // * @return // */ // public static Object[] gatherMapListsValues(Map<String,Object> map){ // List valueList = new ArrayList(); // valueList.addAll(map.values()); // return valueList.toArray(); // } // // } // Path: src/main/java/org/easyarch/slardar/mapping/ClassItem.java import org.easyarch.slardar.utils.CollectionUtils; import java.lang.reflect.Method; import java.util.List; package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-21 * 下午11:31 * description: */ public class ClassItem { private String itemName; private Class clazz; private List<Method> methods; public ClassItem(String itemName, Class clazz, Method[] methods) { this.itemName = itemName; this.clazz = clazz;
this.methods = CollectionUtils.newArrayList(methods);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> {
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> {
protected Wrapper<T> wrapper;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanListResultSetHadler(Class<T> type){
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanListResultSetHadler(Class<T> type){
this(new BeanWrapper<T>(new FieldBinder(type)),type);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanListResultSetHadler(Class<T> type){
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BeanWrapper.java // public class BeanWrapper<T> extends WrapperAdapter<T> implements Wrapper<T> { // // // public BeanWrapper(FieldBinder fieldBinder) { // super(fieldBinder); // } // // @Override // public List<T> list(ResultSet rs, Class<T> type) { // List<T> list = new CopyOnWriteArrayList<T>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createBean(rs,meta,type)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // ResultSetMetaData meta = rs.getMetaData(); // if (rs.next()) { // return createBean(rs,meta,type); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * bean生成模块抽取 // * @param rs // * @param meta // * @param type // * @return // */ // private T createBean(ResultSet rs, ResultSetMetaData meta,Class<T> type) { // Object object = ReflectUtils.newInstance(type); // try { // int count = meta.getColumnCount(); // // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // String propertyName = fieldBinder.getProperty(type, meta.getColumnName(i + 1)); // if (StringUtils.isEmpty(propertyName)){ // ReflectUtils.setFieldValue(object,meta.getColumnName(i + 1), value); // }else{ // ReflectUtils.setFieldValue(object,propertyName, value); // } // } // return (T) object; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BeanListResultSetHadler.java import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.jdbc.wrapper.BeanWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-3 * 上午12:00 */ /** * Description : * Created by code4j on 16-11-3 * 上午12:00 */ public class BeanListResultSetHadler<T> implements ResultSetHandler<List<T>> { protected Wrapper<T> wrapper; protected Class<T> type; public BeanListResultSetHadler(Class<T> type){
this(new BeanWrapper<T>(new FieldBinder(type)),type);
rpgmakervx/slardar
src/main/java/org/easyarch/test/JDBCUtil.java
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/ConnConfig.java // public class ConnConfig { // // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // public static final String URL = "url"; // public static final String DRIVERNAME = "driverClassName"; // // private static String user; // private static String password; // private static String url; // private static String drivername; // // // public static void config(String user,String password, // String url,String drivername){ // ConnConfig.user = user; // ConnConfig.password = password; // ConnConfig.url = url; // ConnConfig.drivername = drivername; // registerDriver(); // } // // public static void config(Properties props){ // config(props.getProperty(USERNAME), // props.getProperty(PASSWORD), // props.getProperty(URL), // props.getProperty(DRIVERNAME)); // registerDriver(); // } // // public static void config(String path){ // Properties prop = new Properties(); // FileInputStream fis = null; // try { // fis = new FileInputStream(path); // prop.load(fis); // config(prop); // } catch (IOException e) { // e.printStackTrace(); // }finally { // IOUtils.closeIO(fis); // } // } // // private static void registerDriver(){ // try { // Class.forName(drivername); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public static String getUsername() { // return user; // } // // public static String getPassword() { // return password; // } // // public static String getUrl() { // return url; // } // // public static String getDrivername() { // return drivername; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java // public class DBCPoolFactory { // // public static DataSource newFixedDBCPool(int maxPoolSize) { // return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, // 1000 * 30L, new LinkedBlockingQueue<Connection>()); // } // // public static DataSource newCachedDBCPool() { // return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, // 0L, new LinkedTransferQueue()); // } // public static DataSource newConfigedDBCPool(Properties prop) { // return new DBCPool(PoolConfig.config(prop)); // } // public static DataSource newCustomDBCPool(PoolConfig config) { // return new DBCPool(config); // } // // }
import org.easyarch.slardar.jdbc.cfg.ConnConfig; import org.easyarch.slardar.jdbc.pool.DBCPoolFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException;
package org.easyarch.test; /** * Description : * Created by xingtianyu on 17-2-11 * 下午3:18 * description: */ public class JDBCUtil { static {
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/ConnConfig.java // public class ConnConfig { // // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // public static final String URL = "url"; // public static final String DRIVERNAME = "driverClassName"; // // private static String user; // private static String password; // private static String url; // private static String drivername; // // // public static void config(String user,String password, // String url,String drivername){ // ConnConfig.user = user; // ConnConfig.password = password; // ConnConfig.url = url; // ConnConfig.drivername = drivername; // registerDriver(); // } // // public static void config(Properties props){ // config(props.getProperty(USERNAME), // props.getProperty(PASSWORD), // props.getProperty(URL), // props.getProperty(DRIVERNAME)); // registerDriver(); // } // // public static void config(String path){ // Properties prop = new Properties(); // FileInputStream fis = null; // try { // fis = new FileInputStream(path); // prop.load(fis); // config(prop); // } catch (IOException e) { // e.printStackTrace(); // }finally { // IOUtils.closeIO(fis); // } // } // // private static void registerDriver(){ // try { // Class.forName(drivername); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public static String getUsername() { // return user; // } // // public static String getPassword() { // return password; // } // // public static String getUrl() { // return url; // } // // public static String getDrivername() { // return drivername; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java // public class DBCPoolFactory { // // public static DataSource newFixedDBCPool(int maxPoolSize) { // return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, // 1000 * 30L, new LinkedBlockingQueue<Connection>()); // } // // public static DataSource newCachedDBCPool() { // return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, // 0L, new LinkedTransferQueue()); // } // public static DataSource newConfigedDBCPool(Properties prop) { // return new DBCPool(PoolConfig.config(prop)); // } // public static DataSource newCustomDBCPool(PoolConfig config) { // return new DBCPool(config); // } // // } // Path: src/main/java/org/easyarch/test/JDBCUtil.java import org.easyarch.slardar.jdbc.cfg.ConnConfig; import org.easyarch.slardar.jdbc.pool.DBCPoolFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; package org.easyarch.test; /** * Description : * Created by xingtianyu on 17-2-11 * 下午3:18 * description: */ public class JDBCUtil { static {
ConnConfig.config("root","123456",
rpgmakervx/slardar
src/main/java/org/easyarch/test/JDBCUtil.java
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/ConnConfig.java // public class ConnConfig { // // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // public static final String URL = "url"; // public static final String DRIVERNAME = "driverClassName"; // // private static String user; // private static String password; // private static String url; // private static String drivername; // // // public static void config(String user,String password, // String url,String drivername){ // ConnConfig.user = user; // ConnConfig.password = password; // ConnConfig.url = url; // ConnConfig.drivername = drivername; // registerDriver(); // } // // public static void config(Properties props){ // config(props.getProperty(USERNAME), // props.getProperty(PASSWORD), // props.getProperty(URL), // props.getProperty(DRIVERNAME)); // registerDriver(); // } // // public static void config(String path){ // Properties prop = new Properties(); // FileInputStream fis = null; // try { // fis = new FileInputStream(path); // prop.load(fis); // config(prop); // } catch (IOException e) { // e.printStackTrace(); // }finally { // IOUtils.closeIO(fis); // } // } // // private static void registerDriver(){ // try { // Class.forName(drivername); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public static String getUsername() { // return user; // } // // public static String getPassword() { // return password; // } // // public static String getUrl() { // return url; // } // // public static String getDrivername() { // return drivername; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java // public class DBCPoolFactory { // // public static DataSource newFixedDBCPool(int maxPoolSize) { // return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, // 1000 * 30L, new LinkedBlockingQueue<Connection>()); // } // // public static DataSource newCachedDBCPool() { // return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, // 0L, new LinkedTransferQueue()); // } // public static DataSource newConfigedDBCPool(Properties prop) { // return new DBCPool(PoolConfig.config(prop)); // } // public static DataSource newCustomDBCPool(PoolConfig config) { // return new DBCPool(config); // } // // }
import org.easyarch.slardar.jdbc.cfg.ConnConfig; import org.easyarch.slardar.jdbc.pool.DBCPoolFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException;
package org.easyarch.test; /** * Description : * Created by xingtianyu on 17-2-11 * 下午3:18 * description: */ public class JDBCUtil { static { ConnConfig.config("root","123456", "jdbc:mysql://localhost:3306/shopping?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false", "com.mysql.jdbc.Driver"); }
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/ConnConfig.java // public class ConnConfig { // // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // public static final String URL = "url"; // public static final String DRIVERNAME = "driverClassName"; // // private static String user; // private static String password; // private static String url; // private static String drivername; // // // public static void config(String user,String password, // String url,String drivername){ // ConnConfig.user = user; // ConnConfig.password = password; // ConnConfig.url = url; // ConnConfig.drivername = drivername; // registerDriver(); // } // // public static void config(Properties props){ // config(props.getProperty(USERNAME), // props.getProperty(PASSWORD), // props.getProperty(URL), // props.getProperty(DRIVERNAME)); // registerDriver(); // } // // public static void config(String path){ // Properties prop = new Properties(); // FileInputStream fis = null; // try { // fis = new FileInputStream(path); // prop.load(fis); // config(prop); // } catch (IOException e) { // e.printStackTrace(); // }finally { // IOUtils.closeIO(fis); // } // } // // private static void registerDriver(){ // try { // Class.forName(drivername); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public static String getUsername() { // return user; // } // // public static String getPassword() { // return password; // } // // public static String getUrl() { // return url; // } // // public static String getDrivername() { // return drivername; // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java // public class DBCPoolFactory { // // public static DataSource newFixedDBCPool(int maxPoolSize) { // return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, // 1000 * 30L, new LinkedBlockingQueue<Connection>()); // } // // public static DataSource newCachedDBCPool() { // return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, // 0L, new LinkedTransferQueue()); // } // public static DataSource newConfigedDBCPool(Properties prop) { // return new DBCPool(PoolConfig.config(prop)); // } // public static DataSource newCustomDBCPool(PoolConfig config) { // return new DBCPool(config); // } // // } // Path: src/main/java/org/easyarch/test/JDBCUtil.java import org.easyarch.slardar.jdbc.cfg.ConnConfig; import org.easyarch.slardar.jdbc.pool.DBCPoolFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; package org.easyarch.test; /** * Description : * Created by xingtianyu on 17-2-11 * 下午3:18 * description: */ public class JDBCUtil { static { ConnConfig.config("root","123456", "jdbc:mysql://localhost:3306/shopping?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false", "com.mysql.jdbc.Driver"); }
public static DataSource pool = DBCPoolFactory.newCachedDBCPool();
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/entity/SqlEntity.java
// Path: src/main/java/org/easyarch/slardar/mapping/SqlType.java // public enum SqlType { // INSERT,UPDATE,DELETE,SELECT // } // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String BIND_SEPARATOR = "@";
import org.easyarch.slardar.mapping.SqlType; import java.util.*; import static org.easyarch.slardar.parser.Token.BIND_SEPARATOR;
package org.easyarch.slardar.entity; /** * Description : * Created by xingtianyu on 17-1-21 * 下午7:19 * description: */ public class SqlEntity { private String sql; private String preparedSql; private Map<String, Object> params;
// Path: src/main/java/org/easyarch/slardar/mapping/SqlType.java // public enum SqlType { // INSERT,UPDATE,DELETE,SELECT // } // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String BIND_SEPARATOR = "@"; // Path: src/main/java/org/easyarch/slardar/entity/SqlEntity.java import org.easyarch.slardar.mapping.SqlType; import java.util.*; import static org.easyarch.slardar.parser.Token.BIND_SEPARATOR; package org.easyarch.slardar.entity; /** * Description : * Created by xingtianyu on 17-1-21 * 下午7:19 * description: */ public class SqlEntity { private String sql; private String preparedSql; private Map<String, Object> params;
private SqlType type;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/entity/SqlEntity.java
// Path: src/main/java/org/easyarch/slardar/mapping/SqlType.java // public enum SqlType { // INSERT,UPDATE,DELETE,SELECT // } // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String BIND_SEPARATOR = "@";
import org.easyarch.slardar.mapping.SqlType; import java.util.*; import static org.easyarch.slardar.parser.Token.BIND_SEPARATOR;
} public void setParams(Map<String, Object> params) { this.params = params; } public void addParam(String name, Object value) { params.put(name,value); } public void addParam(Map<String,Object> params) { this.params.putAll(params); } public void delParam(String name){ params.remove(name); } public void clear(){ params.clear(); } public String getBinder() { return binder; } public void setBinder(String binder) { this.binder = binder; } public String getPrefix() {
// Path: src/main/java/org/easyarch/slardar/mapping/SqlType.java // public enum SqlType { // INSERT,UPDATE,DELETE,SELECT // } // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String BIND_SEPARATOR = "@"; // Path: src/main/java/org/easyarch/slardar/entity/SqlEntity.java import org.easyarch.slardar.mapping.SqlType; import java.util.*; import static org.easyarch.slardar.parser.Token.BIND_SEPARATOR; } public void setParams(Map<String, Object> params) { this.params = params; } public void addParam(String name, Object value) { params.put(name,value); } public void addParam(Map<String,Object> params) { this.params.putAll(params); } public void delParam(String name){ params.remove(name); } public void clear(){ params.clear(); } public String getBinder() { return binder; } public void setBinder(String binder) { this.binder = binder; } public String getPrefix() {
String[] segements = binder.split(BIND_SEPARATOR);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/utils/CodecUtils.java
// Path: src/main/java/org/easyarch/slardar/utils/CodecUtils.java // public enum HashType{ // SHA1("SHA-1"),MD5("MD5"),SHA256("SHA-256"),HMACSHA1("HmacSHA1"); // public String name; // // HashType(String name) { // this.name = name; // } // }
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import static org.easyarch.slardar.utils.CodecUtils.HashType.*;
/** * BASE64 解密 * @param key 需要解密的字符串 * @return 字节数组 * @throws Exception */ public static byte[] decodeBase64(String key) { try { return (new BASE64Decoder()).decodeBuffer(key); } catch (IOException e) { e.printStackTrace(); return null; } } private static String bytes2Hex(byte[] bts) { StringBuffer des = new StringBuffer(); String tmp = null; for (int i = 0; i < bts.length; i++) { tmp = (Integer.toHexString(bts[i] & 0xFF)); if (tmp.length() == 1) { des.append("0"); } des.append(tmp); } return des.toString(); }
// Path: src/main/java/org/easyarch/slardar/utils/CodecUtils.java // public enum HashType{ // SHA1("SHA-1"),MD5("MD5"),SHA256("SHA-256"),HMACSHA1("HmacSHA1"); // public String name; // // HashType(String name) { // this.name = name; // } // } // Path: src/main/java/org/easyarch/slardar/utils/CodecUtils.java import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import static org.easyarch.slardar.utils.CodecUtils.HashType.*; /** * BASE64 解密 * @param key 需要解密的字符串 * @return 字节数组 * @throws Exception */ public static byte[] decodeBase64(String key) { try { return (new BASE64Decoder()).decodeBuffer(key); } catch (IOException e) { e.printStackTrace(); return null; } } private static String bytes2Hex(byte[] bts) { StringBuffer des = new StringBuffer(); String tmp = null; for (int i = 0; i < bts.length; i++) { tmp = (Integer.toHexString(bts[i] & 0xFF)); if (tmp.length() == 1) { des.append("0"); } des.append(tmp); } return des.toString(); }
public enum HashType{
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/annotation/entity/Column.java
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JDBCType.java // public enum JDBCType { // // CHAR(0), // VARCHAR(1), // LONGVARCHAR(2), // NUMERIC(3), // DECIMAL(4), // BOOL(5), // TINYINT(6), // SMALLINT(7), // INTEGER(8), // BIGINT(9), // FLOAT(10), // DOUBLE(11), // BINARY(12), // BLOB(13), // DATE(14), // DATETIME(15), // TIMESTAMP(16); // // public final int TYPE_CODE; // private static Map<Integer,JDBCType> codeLookup = new HashMap<Integer,JDBCType>(); // // static { // for (JDBCType type : JDBCType.values()) { // codeLookup.put(type.TYPE_CODE, type); // } // } // // JDBCType(int code) { // this.TYPE_CODE = code; // } // // public static JDBCType forCode(int code) { // return codeLookup.get(code); // } // }
import org.easyarch.slardar.jdbc.type.JDBCType; import java.lang.annotation.*;
package org.easyarch.slardar.annotation.entity; /** * Description : * Created by code4j on 16-12-25 * 下午10:00 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @Documented public @interface Column { String name() default "";
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JDBCType.java // public enum JDBCType { // // CHAR(0), // VARCHAR(1), // LONGVARCHAR(2), // NUMERIC(3), // DECIMAL(4), // BOOL(5), // TINYINT(6), // SMALLINT(7), // INTEGER(8), // BIGINT(9), // FLOAT(10), // DOUBLE(11), // BINARY(12), // BLOB(13), // DATE(14), // DATETIME(15), // TIMESTAMP(16); // // public final int TYPE_CODE; // private static Map<Integer,JDBCType> codeLookup = new HashMap<Integer,JDBCType>(); // // static { // for (JDBCType type : JDBCType.values()) { // codeLookup.put(type.TYPE_CODE, type); // } // } // // JDBCType(int code) { // this.TYPE_CODE = code; // } // // public static JDBCType forCode(int code) { // return codeLookup.get(code); // } // } // Path: src/main/java/org/easyarch/slardar/annotation/entity/Column.java import org.easyarch.slardar.jdbc.type.JDBCType; import java.lang.annotation.*; package org.easyarch.slardar.annotation.entity; /** * Description : * Created by code4j on 16-12-25 * 下午10:00 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @Documented public @interface Column { String name() default "";
JDBCType type() default JDBCType.VARCHAR;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/PoolConfig.java // public class PoolConfig { // // public static final String MAXACTIVE = "maxActive"; // public static final String MINIDLE = "minIdle"; // public static final String INITIAL_SIZE = "initialSize"; // public static final String MAXWAIT = "maxWait"; // // private int maxActive; // // private int minIdle; // // private int maxIdle; // // private long maxWait; // // private Properties properties; // private PoolConfig(){ // properties = new Properties(); // } // // public static PoolConfig config(int maxPoolSize, int maxIdle, // int minIdle, long keepAliveTime){ // PoolConfig config = new PoolConfig(); // config.maxActive = maxPoolSize<=0?Integer.MAX_VALUE:maxPoolSize; // config.minIdle = minIdle<=0?0:minIdle; // config.maxIdle = maxIdle<=0?Integer.MAX_VALUE:maxIdle; // config.maxWait = keepAliveTime<=0?60:keepAliveTime; // return config; // } // // public static PoolConfig config(Properties prop){ // PoolConfig config = new PoolConfig(); // int maxPoolSize = prop.getProperty(MAXACTIVE)==null? // Runtime.getRuntime().availableProcessors()*4:Integer.parseInt(prop.getProperty(MAXACTIVE)); // int minIdle = prop.getProperty(MINIDLE)==null? // 0:Integer.parseInt(prop.getProperty(MINIDLE)); // int maxIdle = prop.getProperty(INITIAL_SIZE)==null? // 512:Integer.parseInt(prop.getProperty(INITIAL_SIZE)); // int keepAliveTime = prop.getProperty(MAXWAIT)==null? // 60:Integer.parseInt(prop.getProperty(MAXWAIT)); // config.maxActive = maxPoolSize<=0?Integer.MAX_VALUE:maxPoolSize; // config.minIdle = minIdle<=0?0:minIdle; // config.maxIdle = maxIdle<=0?Integer.MAX_VALUE:maxIdle; // config.maxWait = keepAliveTime<=0?60:keepAliveTime; // ConnConfig.config(prop); // return config; // } // // public Properties getProperties(){ // properties.setProperty(MAXACTIVE,String.valueOf(maxActive)); // properties.setProperty(MINIDLE,String.valueOf(maxIdle)); // properties.setProperty(INITIAL_SIZE,String.valueOf(maxIdle)); // properties.setProperty(MAXWAIT,String.valueOf(maxWait)); // return properties; // } // // public int getMaxActive() { // return maxActive; // } // // public int getMinIdle() { // return minIdle; // } // // public int getMaxIdle() { // return maxIdle; // } // // public long getMaxWait() { // return maxWait; // } // // public void print() { // System.out.println("maxActive:"+ maxActive + // "\nmaxIdle:"+maxIdle+ // "\nminIdle:"+minIdle+ // "\nmaxWait:"+ maxWait); // } // }
import org.easyarch.slardar.jdbc.cfg.PoolConfig; import javax.sql.DataSource; import java.sql.Connection; import java.util.Properties; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue;
package org.easyarch.slardar.jdbc.pool;/** * Description : * Created by YangZH on 16-11-4 * 上午2:00 */ /** * Description : * Created by code4j on 16-11-4 * 上午2:00 */ public class DBCPoolFactory { public static DataSource newFixedDBCPool(int maxPoolSize) { return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, 1000 * 30L, new LinkedBlockingQueue<Connection>()); } public static DataSource newCachedDBCPool() { return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, 0L, new LinkedTransferQueue()); } public static DataSource newConfigedDBCPool(Properties prop) {
// Path: src/main/java/org/easyarch/slardar/jdbc/cfg/PoolConfig.java // public class PoolConfig { // // public static final String MAXACTIVE = "maxActive"; // public static final String MINIDLE = "minIdle"; // public static final String INITIAL_SIZE = "initialSize"; // public static final String MAXWAIT = "maxWait"; // // private int maxActive; // // private int minIdle; // // private int maxIdle; // // private long maxWait; // // private Properties properties; // private PoolConfig(){ // properties = new Properties(); // } // // public static PoolConfig config(int maxPoolSize, int maxIdle, // int minIdle, long keepAliveTime){ // PoolConfig config = new PoolConfig(); // config.maxActive = maxPoolSize<=0?Integer.MAX_VALUE:maxPoolSize; // config.minIdle = minIdle<=0?0:minIdle; // config.maxIdle = maxIdle<=0?Integer.MAX_VALUE:maxIdle; // config.maxWait = keepAliveTime<=0?60:keepAliveTime; // return config; // } // // public static PoolConfig config(Properties prop){ // PoolConfig config = new PoolConfig(); // int maxPoolSize = prop.getProperty(MAXACTIVE)==null? // Runtime.getRuntime().availableProcessors()*4:Integer.parseInt(prop.getProperty(MAXACTIVE)); // int minIdle = prop.getProperty(MINIDLE)==null? // 0:Integer.parseInt(prop.getProperty(MINIDLE)); // int maxIdle = prop.getProperty(INITIAL_SIZE)==null? // 512:Integer.parseInt(prop.getProperty(INITIAL_SIZE)); // int keepAliveTime = prop.getProperty(MAXWAIT)==null? // 60:Integer.parseInt(prop.getProperty(MAXWAIT)); // config.maxActive = maxPoolSize<=0?Integer.MAX_VALUE:maxPoolSize; // config.minIdle = minIdle<=0?0:minIdle; // config.maxIdle = maxIdle<=0?Integer.MAX_VALUE:maxIdle; // config.maxWait = keepAliveTime<=0?60:keepAliveTime; // ConnConfig.config(prop); // return config; // } // // public Properties getProperties(){ // properties.setProperty(MAXACTIVE,String.valueOf(maxActive)); // properties.setProperty(MINIDLE,String.valueOf(maxIdle)); // properties.setProperty(INITIAL_SIZE,String.valueOf(maxIdle)); // properties.setProperty(MAXWAIT,String.valueOf(maxWait)); // return properties; // } // // public int getMaxActive() { // return maxActive; // } // // public int getMinIdle() { // return minIdle; // } // // public int getMaxIdle() { // return maxIdle; // } // // public long getMaxWait() { // return maxWait; // } // // public void print() { // System.out.println("maxActive:"+ maxActive + // "\nmaxIdle:"+maxIdle+ // "\nminIdle:"+minIdle+ // "\nmaxWait:"+ maxWait); // } // } // Path: src/main/java/org/easyarch/slardar/jdbc/pool/DBCPoolFactory.java import org.easyarch.slardar.jdbc.cfg.PoolConfig; import javax.sql.DataSource; import java.sql.Connection; import java.util.Properties; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; package org.easyarch.slardar.jdbc.pool;/** * Description : * Created by YangZH on 16-11-4 * 上午2:00 */ /** * Description : * Created by code4j on 16-11-4 * 上午2:00 */ public class DBCPoolFactory { public static DataSource newFixedDBCPool(int maxPoolSize) { return new DBCPool(maxPoolSize, maxPoolSize >> 2, maxPoolSize >> 3, 1000 * 30L, new LinkedBlockingQueue<Connection>()); } public static DataSource newCachedDBCPool() { return new DBCPool(Integer.MAX_VALUE, Integer.MAX_VALUE, 10, 0L, new LinkedTransferQueue()); } public static DataSource newConfigedDBCPool(Properties prop) {
return new DBCPool(PoolConfig.config(prop));
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/pool/ProcessWatcher.java
// Path: src/main/java/org/easyarch/slardar/jdbc/exec/ConnectionUtils.java // public final class ConnectionUtils { // // public static void closeAll(Connection conn, Statement stmt, // ResultSet rs) { // try { // if (rs != null&&!rs.isClosed()){ // rs.close(); // } // } catch (Exception e) { // e.printStackTrace(); // } // try { // if (stmt != null&&!stmt.isClosed()) // stmt.close(); // } catch (SQLException e) { // e.printStackTrace(); // } // try { // if (conn!=null){ // if (!conn.isClosed()){ // conn.close(); // System.out.println("connection close from DBUtils "+conn.isClosed()); // } // } // } catch (SQLException e) { // e.printStackTrace(); // } // // } // // public static void close(Connection conn) { // closeAll(conn, null, null); // } // // public static void close(ResultSet rs) { // closeAll(null, null, rs); // } // // public static void close(Statement stmt) { // closeAll(null,stmt,null); // } // // public static void beginTransaction(Connection conn){ // beginTransaction(conn,Connection.TRANSACTION_READ_COMMITTED); // } // // public static void beginTransaction(Connection conn,int level){ // if (conn == null){ // new IllegalStateException("connection cannot be null!"); // } // try { // conn.setAutoCommit(false); // conn.setTransactionIsolation(level); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void commit(Connection conn){ // try { // conn.commit(); // } catch (SQLException e) { // e.printStackTrace(); // rollBack(conn); // } // } // // public static void endTransaction(Connection conn){ // endTransaction(conn,Connection.TRANSACTION_READ_COMMITTED); // } // // public static void endTransaction(Connection conn,int level){ // if (conn == null){ // new IllegalStateException("connection cannot be null!"); // } // try { // conn.setAutoCommit(true); // conn.setTransactionIsolation(level); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void rollBack(Connection conn){ // try { // if (conn != null){ // conn.rollback(); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void rollBackAndClose(Connection conn){ // if (conn != null){ // try { // conn.rollback(); // } catch (SQLException e) { // e.printStackTrace(); // }finally { // close(conn); // } // } // } // // public static boolean isClose(Connection connection){ // try { // connection.isValid(1000); // return connection == null||connection.isClosed(); // } catch (SQLException e) { // return false; // } // } // // public static boolean isValid(Connection connection){ // try { // return connection == null||connection.isValid(3); // } catch (SQLException e) { // return false; // } // } // // }
import org.easyarch.slardar.jdbc.exec.ConnectionUtils;
package org.easyarch.slardar.jdbc.pool;/** * Description : * Created by YangZH on 16-11-7 * 下午8:23 */ /** * Description : * Created by code4j on 16-11-7 * 下午8:23 */ public class ProcessWatcher{ static Runtime rt = Runtime.getRuntime(); static{ System.out.println("watcher is ready."); rt.addShutdownHook(new Thread() { public void run() { // System.out.println("programme exit,ready to close all dbcpool connections ... "); // System.out.println("connections count is :"+ RealCPool.getConnections().size()); kill(); } }); } private static void kill() { for (ConnectionWrapper wrapper : RealCPool.getConnections()) {
// Path: src/main/java/org/easyarch/slardar/jdbc/exec/ConnectionUtils.java // public final class ConnectionUtils { // // public static void closeAll(Connection conn, Statement stmt, // ResultSet rs) { // try { // if (rs != null&&!rs.isClosed()){ // rs.close(); // } // } catch (Exception e) { // e.printStackTrace(); // } // try { // if (stmt != null&&!stmt.isClosed()) // stmt.close(); // } catch (SQLException e) { // e.printStackTrace(); // } // try { // if (conn!=null){ // if (!conn.isClosed()){ // conn.close(); // System.out.println("connection close from DBUtils "+conn.isClosed()); // } // } // } catch (SQLException e) { // e.printStackTrace(); // } // // } // // public static void close(Connection conn) { // closeAll(conn, null, null); // } // // public static void close(ResultSet rs) { // closeAll(null, null, rs); // } // // public static void close(Statement stmt) { // closeAll(null,stmt,null); // } // // public static void beginTransaction(Connection conn){ // beginTransaction(conn,Connection.TRANSACTION_READ_COMMITTED); // } // // public static void beginTransaction(Connection conn,int level){ // if (conn == null){ // new IllegalStateException("connection cannot be null!"); // } // try { // conn.setAutoCommit(false); // conn.setTransactionIsolation(level); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void commit(Connection conn){ // try { // conn.commit(); // } catch (SQLException e) { // e.printStackTrace(); // rollBack(conn); // } // } // // public static void endTransaction(Connection conn){ // endTransaction(conn,Connection.TRANSACTION_READ_COMMITTED); // } // // public static void endTransaction(Connection conn,int level){ // if (conn == null){ // new IllegalStateException("connection cannot be null!"); // } // try { // conn.setAutoCommit(true); // conn.setTransactionIsolation(level); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void rollBack(Connection conn){ // try { // if (conn != null){ // conn.rollback(); // } // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public static void rollBackAndClose(Connection conn){ // if (conn != null){ // try { // conn.rollback(); // } catch (SQLException e) { // e.printStackTrace(); // }finally { // close(conn); // } // } // } // // public static boolean isClose(Connection connection){ // try { // connection.isValid(1000); // return connection == null||connection.isClosed(); // } catch (SQLException e) { // return false; // } // } // // public static boolean isValid(Connection connection){ // try { // return connection == null||connection.isValid(3); // } catch (SQLException e) { // return false; // } // } // // } // Path: src/main/java/org/easyarch/slardar/jdbc/pool/ProcessWatcher.java import org.easyarch.slardar.jdbc.exec.ConnectionUtils; package org.easyarch.slardar.jdbc.pool;/** * Description : * Created by YangZH on 16-11-7 * 下午8:23 */ /** * Description : * Created by code4j on 16-11-7 * 下午8:23 */ public class ProcessWatcher{ static Runtime rt = Runtime.getRuntime(); static{ System.out.println("watcher is ready."); rt.addShutdownHook(new Thread() { public void run() { // System.out.println("programme exit,ready to close all dbcpool connections ... "); // System.out.println("connections count is :"+ RealCPool.getConnections().size()); kill(); } }); } private static void kill() { for (ConnectionWrapper wrapper : RealCPool.getConnections()) {
ConnectionUtils.close(wrapper.connection());
rpgmakervx/slardar
src/main/java/org/easyarch/test/TestMain.java
// Path: src/main/java/org/easyarch/slardar/parser/script/JSContext.java // public class JSContext { // // public static final String CONTEXT = "ctx"; // // public static final String WHERE = "where"; // public static final String WHERE_CONTENT = " where 1 = 1 "; // //默认namespace为空,需要用户自己设置 // public static final String NAMESPACE = "namespace"; // // public Map<String,Map<String ,Object>> defaultVars; // // public JSContext(){ // defaultVars = new HashMap<>(); // init(); // } // // private void init(){ // Map<String,Object> vars = new HashMap<>(); // vars.put(WHERE,WHERE_CONTENT); // vars.put(NAMESPACE,""); // defaultVars.put(CONTEXT,vars); // } // // public Map<String,Object> getCtx(){ // return defaultVars.get(CONTEXT); // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // }
import org.easyarch.slardar.parser.script.JSContext; import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; import org.junit.jupiter.api.Test; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; import java.util.List;
package org.easyarch.test; /** * Description : * Created by code4j on 16-11-7 * 下午2:13 */ public class TestMain { @Test public void testOne(){
// Path: src/main/java/org/easyarch/slardar/parser/script/JSContext.java // public class JSContext { // // public static final String CONTEXT = "ctx"; // // public static final String WHERE = "where"; // public static final String WHERE_CONTENT = " where 1 = 1 "; // //默认namespace为空,需要用户自己设置 // public static final String NAMESPACE = "namespace"; // // public Map<String,Map<String ,Object>> defaultVars; // // public JSContext(){ // defaultVars = new HashMap<>(); // init(); // } // // private void init(){ // Map<String,Object> vars = new HashMap<>(); // vars.put(WHERE,WHERE_CONTENT); // vars.put(NAMESPACE,""); // defaultVars.put(CONTEXT,vars); // } // // public Map<String,Object> getCtx(){ // return defaultVars.get(CONTEXT); // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // } // Path: src/main/java/org/easyarch/test/TestMain.java import org.easyarch.slardar.parser.script.JSContext; import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; import org.junit.jupiter.api.Test; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; import java.util.List; package org.easyarch.test; /** * Description : * Created by code4j on 16-11-7 * 下午2:13 */ public class TestMain { @Test public void testOne(){
UserService service = new UserService();
rpgmakervx/slardar
src/main/java/org/easyarch/test/TestMain.java
// Path: src/main/java/org/easyarch/slardar/parser/script/JSContext.java // public class JSContext { // // public static final String CONTEXT = "ctx"; // // public static final String WHERE = "where"; // public static final String WHERE_CONTENT = " where 1 = 1 "; // //默认namespace为空,需要用户自己设置 // public static final String NAMESPACE = "namespace"; // // public Map<String,Map<String ,Object>> defaultVars; // // public JSContext(){ // defaultVars = new HashMap<>(); // init(); // } // // private void init(){ // Map<String,Object> vars = new HashMap<>(); // vars.put(WHERE,WHERE_CONTENT); // vars.put(NAMESPACE,""); // defaultVars.put(CONTEXT,vars); // } // // public Map<String,Object> getCtx(){ // return defaultVars.get(CONTEXT); // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // }
import org.easyarch.slardar.parser.script.JSContext; import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; import org.junit.jupiter.api.Test; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; import java.util.List;
package org.easyarch.test; /** * Description : * Created by code4j on 16-11-7 * 下午2:13 */ public class TestMain { @Test public void testOne(){ UserService service = new UserService();
// Path: src/main/java/org/easyarch/slardar/parser/script/JSContext.java // public class JSContext { // // public static final String CONTEXT = "ctx"; // // public static final String WHERE = "where"; // public static final String WHERE_CONTENT = " where 1 = 1 "; // //默认namespace为空,需要用户自己设置 // public static final String NAMESPACE = "namespace"; // // public Map<String,Map<String ,Object>> defaultVars; // // public JSContext(){ // defaultVars = new HashMap<>(); // init(); // } // // private void init(){ // Map<String,Object> vars = new HashMap<>(); // vars.put(WHERE,WHERE_CONTENT); // vars.put(NAMESPACE,""); // defaultVars.put(CONTEXT,vars); // } // // public Map<String,Object> getCtx(){ // return defaultVars.get(CONTEXT); // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // } // Path: src/main/java/org/easyarch/test/TestMain.java import org.easyarch.slardar.parser.script.JSContext; import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; import org.junit.jupiter.api.Test; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; import java.util.List; package org.easyarch.test; /** * Description : * Created by code4j on 16-11-7 * 下午2:13 */ public class TestMain { @Test public void testOne(){ UserService service = new UserService();
User user = service.getUser("1234567");
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/BaseTypeResultSetHandler.java
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BaseTypeWrapper.java // public class BaseTypeWrapper<T> extends BeanWrapper<T> { // // public BaseTypeWrapper() { // super(null); // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // if (rs.next()) { // switch (JAVAType.getType(type)){ // case INT:return (T) new Integer(rs.getInt(1)); // case FLOAT:return (T) new Float(rs.getFloat(1)); // case LONG:return (T) new Long(rs.getLong(1)); // } // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // }
import org.easyarch.slardar.jdbc.wrapper.BaseTypeWrapper;
package org.easyarch.slardar.jdbc.handler; /** * Description : * Created by xingtianyu on 17-1-30 * 下午8:09 * description: */ public class BaseTypeResultSetHandler<T> extends BeanResultSetHadler<T> { public BaseTypeResultSetHandler(Class<T> type) {
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/BaseTypeWrapper.java // public class BaseTypeWrapper<T> extends BeanWrapper<T> { // // public BaseTypeWrapper() { // super(null); // } // // @Override // public T bean(ResultSet rs, Class<T> type) { // try { // if (rs.next()) { // switch (JAVAType.getType(type)){ // case INT:return (T) new Integer(rs.getInt(1)); // case FLOAT:return (T) new Float(rs.getFloat(1)); // case LONG:return (T) new Long(rs.getLong(1)); // } // } // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/BaseTypeResultSetHandler.java import org.easyarch.slardar.jdbc.wrapper.BaseTypeWrapper; package org.easyarch.slardar.jdbc.handler; /** * Description : * Created by xingtianyu on 17-1-30 * 下午8:09 * description: */ public class BaseTypeResultSetHandler<T> extends BeanResultSetHadler<T> { public BaseTypeResultSetHandler(Class<T> type) {
super(new BaseTypeWrapper(),type);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/utils/ParamUtil.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/entity/Parameter.java // public class Parameter { // // private String name; // private Object value; // // public Parameter(String name, Object value) { // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // }
import org.easyarch.slardar.annotation.entity.Column; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.entity.Parameter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map;
package org.easyarch.slardar.utils; /** * Description : * Created by xingtianyu on 17-2-19 * 下午12:56 * description: * 提供用户使用,在使用DefaultDBSession时将基本类型或对象 以及 定义对象转换成Parameter作为参数使用 */ public class ParamUtil { public static Parameter create(String name,Object value){ if (StringUtils.isEmpty(name)||value == null){ return null; } return new Parameter(name,value); } public static Parameter[] create(Map<String,Object> params){ Parameter[] parameters = new Parameter[params.size()]; int index = 0; for (Map.Entry<String,Object> entry : params.entrySet()){ parameters[index] = new Parameter(entry.getKey(),entry.getValue()); } return parameters; } public static Parameter[] create(Object bean){
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // // Path: src/main/java/org/easyarch/slardar/entity/Parameter.java // public class Parameter { // // private String name; // private Object value; // // public Parameter(String name, Object value) { // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // } // Path: src/main/java/org/easyarch/slardar/utils/ParamUtil.java import org.easyarch.slardar.annotation.entity.Column; import org.easyarch.slardar.binding.FieldBinder; import org.easyarch.slardar.entity.Parameter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; package org.easyarch.slardar.utils; /** * Description : * Created by xingtianyu on 17-2-19 * 下午12:56 * description: * 提供用户使用,在使用DefaultDBSession时将基本类型或对象 以及 定义对象转换成Parameter作为参数使用 */ public class ParamUtil { public static Parameter create(String name,Object value){ if (StringUtils.isEmpty(name)||value == null){ return null; } return new Parameter(name,value); } public static Parameter[] create(Map<String,Object> params){ Parameter[] parameters = new Parameter[params.size()]; int index = 0; for (Map.Entry<String,Object> entry : params.entrySet()){ parameters[index] = new Parameter(entry.getKey(),entry.getValue()); } return parameters; } public static Parameter[] create(Object bean){
FieldBinder binder = new FieldBinder(bean.getClass());
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/annotation/entity/NotColumn.java
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JDBCType.java // public enum JDBCType { // // CHAR(0), // VARCHAR(1), // LONGVARCHAR(2), // NUMERIC(3), // DECIMAL(4), // BOOL(5), // TINYINT(6), // SMALLINT(7), // INTEGER(8), // BIGINT(9), // FLOAT(10), // DOUBLE(11), // BINARY(12), // BLOB(13), // DATE(14), // DATETIME(15), // TIMESTAMP(16); // // public final int TYPE_CODE; // private static Map<Integer,JDBCType> codeLookup = new HashMap<Integer,JDBCType>(); // // static { // for (JDBCType type : JDBCType.values()) { // codeLookup.put(type.TYPE_CODE, type); // } // } // // JDBCType(int code) { // this.TYPE_CODE = code; // } // // public static JDBCType forCode(int code) { // return codeLookup.get(code); // } // }
import org.easyarch.slardar.jdbc.type.JDBCType; import java.lang.annotation.*;
package org.easyarch.slardar.annotation.entity; /** * Description : * Created by code4j on 16-12-25 * 下午10:00 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @Documented public @interface NotColumn { String name() default "";
// Path: src/main/java/org/easyarch/slardar/jdbc/type/JDBCType.java // public enum JDBCType { // // CHAR(0), // VARCHAR(1), // LONGVARCHAR(2), // NUMERIC(3), // DECIMAL(4), // BOOL(5), // TINYINT(6), // SMALLINT(7), // INTEGER(8), // BIGINT(9), // FLOAT(10), // DOUBLE(11), // BINARY(12), // BLOB(13), // DATE(14), // DATETIME(15), // TIMESTAMP(16); // // public final int TYPE_CODE; // private static Map<Integer,JDBCType> codeLookup = new HashMap<Integer,JDBCType>(); // // static { // for (JDBCType type : JDBCType.values()) { // codeLookup.put(type.TYPE_CODE, type); // } // } // // JDBCType(int code) { // this.TYPE_CODE = code; // } // // public static JDBCType forCode(int code) { // return codeLookup.get(code); // } // } // Path: src/main/java/org/easyarch/slardar/annotation/entity/NotColumn.java import org.easyarch.slardar.jdbc.type.JDBCType; import java.lang.annotation.*; package org.easyarch.slardar.annotation.entity; /** * Description : * Created by code4j on 16-12-25 * 下午10:00 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @Documented public @interface NotColumn { String name() default "";
JDBCType type() default JDBCType.VARCHAR;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/entity/CacheEntity.java
// Path: src/main/java/org/easyarch/slardar/cache/mode/CacheMode.java // public enum CacheMode { // LRU("lru"), // FIFO("fifo"), // TIMEOUT("timeout"); // private String mode; // // CacheMode(String mode) { // this.mode = mode; // } // // public String getMode(){ // return mode; // } // }
import org.easyarch.slardar.cache.mode.CacheMode;
package org.easyarch.slardar.entity; /** * Description : * Created by xingtianyu on 17-2-16 * 上午12:47 * description: */ public class CacheEntity { private int size;
// Path: src/main/java/org/easyarch/slardar/cache/mode/CacheMode.java // public enum CacheMode { // LRU("lru"), // FIFO("fifo"), // TIMEOUT("timeout"); // private String mode; // // CacheMode(String mode) { // this.mode = mode; // } // // public String getMode(){ // return mode; // } // } // Path: src/main/java/org/easyarch/slardar/entity/CacheEntity.java import org.easyarch.slardar.cache.mode.CacheMode; package org.easyarch.slardar.entity; /** * Description : * Created by xingtianyu on 17-2-16 * 上午12:47 * description: */ public class CacheEntity { private int size;
private CacheMode mode;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/wrapper/WrapperAdapter.java
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // }
import java.sql.ResultSet; import java.util.List; import org.easyarch.slardar.binding.FieldBinder;
package org.easyarch.slardar.jdbc.wrapper;/** * Description : * Created by YangZH on 16-11-3 * 上午10:34 */ /** * Description : * Created by code4j on 16-11-3 * 上午10:34 */ public class WrapperAdapter<T> implements Wrapper<T> {
// Path: src/main/java/org/easyarch/slardar/binding/FieldBinder.java // public class FieldBinder<T> { // // protected static Map<Class<?>,Map<String,String>> fieldMapper = new HashMap<>(); // // private Class<T> cls; // // public FieldBinder(Class<T> cls){ // this.cls = cls; // init(); // } // // /** // * 初始化的时候只根据是不是标准实体来初始化(即有没有注解) // */ // private void init(){ // if (fieldMapper.containsKey(cls)){ // return; // } // Field[] fields = cls.getDeclaredFields(); // Map<String,String> mapper = new HashMap<>(); // for (Field field : fields){ // field.setAccessible(true); // Column column = field.getAnnotation(Column.class); // if (column == null){ // mapper.put(field.getName(),field.getName()); // }else{ // mapper.put(column.name(),field.getName()); // } // } // fieldMapper.put(cls,mapper); // } // // public void bind(String column,String property){ // fieldMapper.get(cls).put(column,property); // } // // public void bind(Map<String,String> mapper){ // fieldMapper.get(cls).putAll(mapper); // } // // public String getProperty(String column){ // return getProperty(cls,column); // } // // public String getProperty(Class<?> cls,String column){ // if (fieldMapper.containsKey(cls)){ // return fieldMapper.get(cls).get(column); // } // return ""; // } // } // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/WrapperAdapter.java import java.sql.ResultSet; import java.util.List; import org.easyarch.slardar.binding.FieldBinder; package org.easyarch.slardar.jdbc.wrapper;/** * Description : * Created by YangZH on 16-11-3 * 上午10:34 */ /** * Description : * Created by code4j on 16-11-3 * 上午10:34 */ public class WrapperAdapter<T> implements Wrapper<T> {
protected FieldBinder fieldBinder;
rpgmakervx/slardar
src/main/java/org/easyarch/test/sharding/ShardingTest.java
// Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloDatabaseShardingAlgorithm.java // public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // System.out.println("datasource:"+dataSourceNames+" , ShardingValue:"+shardingValue); // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // // Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloTableShardingAlgorithm.java // public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // }
import com.dangdang.ddframe.rdb.sharding.api.rule.BindingTableRule; import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule; import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule; import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule; import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy; import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy; import com.dangdang.ddframe.rdb.sharding.jdbc.ShardingDataSource; import org.apache.commons.dbcp.BasicDataSource; import org.easyarch.test.sharding.algorithm.ModuloDatabaseShardingAlgorithm; import org.easyarch.test.sharding.algorithm.ModuloTableShardingAlgorithm; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package org.easyarch.test.sharding; /** * Description : * Created by xingtianyu on 17-2-21 * 上午10:11 * description: */ public class ShardingTest { private static ShardingDataSource getShardingDataSource() { DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap()); TableRule orderTableRule = TableRule.builder("t_order").actualTables(Arrays.asList( "db0.t_order_0", "db0.t_order_1", "db1.t_order_0", "db1.t_order_1" )).dataSourceRule(dataSourceRule).build(); TableRule orderItemTableRule = TableRule.builder("t_order_item").actualTables(Arrays.asList( "db0.t_order_item_0", "db0.t_order_item_1", "db1.t_order_item_0", "db1.t_order_item_1" )).dataSourceRule(dataSourceRule).build(); ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(Arrays.asList(orderTableRule, orderItemTableRule)) .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule))))
// Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloDatabaseShardingAlgorithm.java // public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // System.out.println("datasource:"+dataSourceNames+" , ShardingValue:"+shardingValue); // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // // Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloTableShardingAlgorithm.java // public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // Path: src/main/java/org/easyarch/test/sharding/ShardingTest.java import com.dangdang.ddframe.rdb.sharding.api.rule.BindingTableRule; import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule; import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule; import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule; import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy; import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy; import com.dangdang.ddframe.rdb.sharding.jdbc.ShardingDataSource; import org.apache.commons.dbcp.BasicDataSource; import org.easyarch.test.sharding.algorithm.ModuloDatabaseShardingAlgorithm; import org.easyarch.test.sharding.algorithm.ModuloTableShardingAlgorithm; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; package org.easyarch.test.sharding; /** * Description : * Created by xingtianyu on 17-2-21 * 上午10:11 * description: */ public class ShardingTest { private static ShardingDataSource getShardingDataSource() { DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap()); TableRule orderTableRule = TableRule.builder("t_order").actualTables(Arrays.asList( "db0.t_order_0", "db0.t_order_1", "db1.t_order_0", "db1.t_order_1" )).dataSourceRule(dataSourceRule).build(); TableRule orderItemTableRule = TableRule.builder("t_order_item").actualTables(Arrays.asList( "db0.t_order_item_0", "db0.t_order_item_1", "db1.t_order_item_0", "db1.t_order_item_1" )).dataSourceRule(dataSourceRule).build(); ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(Arrays.asList(orderTableRule, orderItemTableRule)) .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule))))
.databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
rpgmakervx/slardar
src/main/java/org/easyarch/test/sharding/ShardingTest.java
// Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloDatabaseShardingAlgorithm.java // public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // System.out.println("datasource:"+dataSourceNames+" , ShardingValue:"+shardingValue); // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // // Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloTableShardingAlgorithm.java // public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // }
import com.dangdang.ddframe.rdb.sharding.api.rule.BindingTableRule; import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule; import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule; import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule; import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy; import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy; import com.dangdang.ddframe.rdb.sharding.jdbc.ShardingDataSource; import org.apache.commons.dbcp.BasicDataSource; import org.easyarch.test.sharding.algorithm.ModuloDatabaseShardingAlgorithm; import org.easyarch.test.sharding.algorithm.ModuloTableShardingAlgorithm; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package org.easyarch.test.sharding; /** * Description : * Created by xingtianyu on 17-2-21 * 上午10:11 * description: */ public class ShardingTest { private static ShardingDataSource getShardingDataSource() { DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap()); TableRule orderTableRule = TableRule.builder("t_order").actualTables(Arrays.asList( "db0.t_order_0", "db0.t_order_1", "db1.t_order_0", "db1.t_order_1" )).dataSourceRule(dataSourceRule).build(); TableRule orderItemTableRule = TableRule.builder("t_order_item").actualTables(Arrays.asList( "db0.t_order_item_0", "db0.t_order_item_1", "db1.t_order_item_0", "db1.t_order_item_1" )).dataSourceRule(dataSourceRule).build(); ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(Arrays.asList(orderTableRule, orderItemTableRule)) .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule)))) .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
// Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloDatabaseShardingAlgorithm.java // public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // System.out.println("datasource:"+dataSourceNames+" , ShardingValue:"+shardingValue); // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // // Path: src/main/java/org/easyarch/test/sharding/algorithm/ModuloTableShardingAlgorithm.java // public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> { // @Override // public String doEqualSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // for (String each : dataSourceNames) { // if (each.endsWith(shardingValue.getValue() % 2 + "")) { // return each; // } // } // throw new IllegalArgumentException(); // } // // @Override // public Collection<String> doInSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // for (Integer value : shardingValue.getValues()) { // for (String dataSourceName : dataSourceNames) { // if (dataSourceName.endsWith(value % 2 + "")) { // result.add(dataSourceName); // } // } // } // return result; // } // // @Override // public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) { // Collection<String> result = new LinkedHashSet<>(dataSourceNames.size()); // Range<Integer> range = shardingValue.getValueRange(); // for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) { // for (String each : dataSourceNames) { // if (each.endsWith(i % 2 + "")) { // result.add(each); // } // } // } // return result; // } // } // Path: src/main/java/org/easyarch/test/sharding/ShardingTest.java import com.dangdang.ddframe.rdb.sharding.api.rule.BindingTableRule; import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule; import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule; import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule; import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy; import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy; import com.dangdang.ddframe.rdb.sharding.jdbc.ShardingDataSource; import org.apache.commons.dbcp.BasicDataSource; import org.easyarch.test.sharding.algorithm.ModuloDatabaseShardingAlgorithm; import org.easyarch.test.sharding.algorithm.ModuloTableShardingAlgorithm; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; package org.easyarch.test.sharding; /** * Description : * Created by xingtianyu on 17-2-21 * 上午10:11 * description: */ public class ShardingTest { private static ShardingDataSource getShardingDataSource() { DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap()); TableRule orderTableRule = TableRule.builder("t_order").actualTables(Arrays.asList( "db0.t_order_0", "db0.t_order_1", "db1.t_order_0", "db1.t_order_1" )).dataSourceRule(dataSourceRule).build(); TableRule orderItemTableRule = TableRule.builder("t_order_item").actualTables(Arrays.asList( "db0.t_order_item_0", "db0.t_order_item_1", "db1.t_order_item_0", "db1.t_order_item_1" )).dataSourceRule(dataSourceRule).build(); ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(Arrays.asList(orderTableRule, orderItemTableRule)) .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule)))) .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
.tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm())).build();
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/AbstractResultSetHandler.java
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.annotation.entity.Column; import org.easyarch.slardar.annotation.entity.Table; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map;
package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-2 * 下午7:08 */ /** * Description : * Created by code4j on 16-11-2 * 下午7:08 */ abstract public class AbstractResultSetHandler<T> implements ResultSetHandler<T>{
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/AbstractResultSetHandler.java import org.easyarch.slardar.annotation.entity.Column; import org.easyarch.slardar.annotation.entity.Table; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; package org.easyarch.slardar.jdbc.handler;/** * Description : * Created by YangZH on 16-11-2 * 下午7:08 */ /** * Description : * Created by code4j on 16-11-2 * 下午7:08 */ abstract public class AbstractResultSetHandler<T> implements ResultSetHandler<T>{
protected Wrapper<T> wrapper;
rpgmakervx/slardar
src/main/java/org/easyarch/test/dao/UserMapper.java
// Path: src/main/java/org/easyarch/test/pojo/Query.java // @Table(tableName = "user") // public class Query { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // private int pageIndex; // // private int pageSize; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // 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; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public int getPageIndex() { // return pageIndex; // } // // public void setPageIndex(int pageIndex) { // this.pageIndex = pageIndex; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize; // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // }
import org.easyarch.slardar.annotation.sql.SqlParam; import org.easyarch.test.pojo.Query; import org.easyarch.test.pojo.User; import java.util.List;
package org.easyarch.test.dao; /** * Description : * Created by xingtianyu on 17-2-9 * 上午2:07 * description: */ public interface UserMapper { public User findById(@SqlParam(name = "id") String id); public List<User> findByUser(User user);
// Path: src/main/java/org/easyarch/test/pojo/Query.java // @Table(tableName = "user") // public class Query { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // private int pageIndex; // // private int pageSize; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId; // } // // 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; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public int getPageIndex() { // return pageIndex; // } // // public void setPageIndex(int pageIndex) { // this.pageIndex = pageIndex; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize; // } // } // // Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // Path: src/main/java/org/easyarch/test/dao/UserMapper.java import org.easyarch.slardar.annotation.sql.SqlParam; import org.easyarch.test.pojo.Query; import org.easyarch.test.pojo.User; import java.util.List; package org.easyarch.test.dao; /** * Description : * Created by xingtianyu on 17-2-9 * 上午2:07 * description: */ public interface UserMapper { public User findById(@SqlParam(name = "id") String id); public List<User> findByUser(User user);
public List<User> findByQuery(Query query);
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/jdbc/handler/MapResultHandler.java
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/MapWrapper.java // public class MapWrapper extends WrapperAdapter<Map<String,Object>> implements Wrapper<Map<String,Object>> { // // public MapWrapper() { // super(null); // } // // @Override // public List<Map<String, Object>> list(ResultSet rs, Class<Map<String, Object>> type) { // List<Map<String, Object>> list = new CopyOnWriteArrayList<Map<String, Object>>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createMap(rs,meta)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // private Map<String,Object> createMap(ResultSet rs, ResultSetMetaData meta) { // Map<String,Object> resultMap = new HashMap<String, Object>(); // try { // int count = meta.getColumnCount(); // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // resultMap.put(rs.getCursorName(), value); // } // return resultMap; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // }
import org.easyarch.slardar.jdbc.wrapper.MapWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List; import java.util.Map;
package org.easyarch.slardar.jdbc.handler; /** * Description : * Created by xingtianyu on 17-1-25 * 下午4:17 * description: */ public class MapResultHandler implements ResultSetHandler<List<Map<String,Object>>> { protected Wrapper wrapper; public MapResultHandler() {
// Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/MapWrapper.java // public class MapWrapper extends WrapperAdapter<Map<String,Object>> implements Wrapper<Map<String,Object>> { // // public MapWrapper() { // super(null); // } // // @Override // public List<Map<String, Object>> list(ResultSet rs, Class<Map<String, Object>> type) { // List<Map<String, Object>> list = new CopyOnWriteArrayList<Map<String, Object>>(); // try { // ResultSetMetaData meta = rs.getMetaData(); // while (rs.next()) { // list.add(createMap(rs,meta)); // } // return list; // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // private Map<String,Object> createMap(ResultSet rs, ResultSetMetaData meta) { // Map<String,Object> resultMap = new HashMap<String, Object>(); // try { // int count = meta.getColumnCount(); // for (int i = 0; i < count; i++) { // Object value = rs.getObject(i + 1); // resultMap.put(rs.getCursorName(), value); // } // return resultMap; // } catch (SQLException e) { // e.printStackTrace(); // return null; // } // } // } // // Path: src/main/java/org/easyarch/slardar/jdbc/wrapper/Wrapper.java // public interface Wrapper<T> { // // public List<T> list(ResultSet rs, Class<T> type); // // public T bean(ResultSet rs, Class<T> type); // // } // Path: src/main/java/org/easyarch/slardar/jdbc/handler/MapResultHandler.java import org.easyarch.slardar.jdbc.wrapper.MapWrapper; import org.easyarch.slardar.jdbc.wrapper.Wrapper; import java.sql.ResultSet; import java.util.List; import java.util.Map; package org.easyarch.slardar.jdbc.handler; /** * Description : * Created by xingtianyu on 17-1-25 * 下午4:17 * description: */ public class MapResultHandler implements ResultSetHandler<List<Map<String,Object>>> { protected Wrapper wrapper; public MapResultHandler() {
this.wrapper = new MapWrapper();
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/mapping/MapperProxy.java
// Path: src/main/java/org/easyarch/slardar/cache/InterfaceCache.java // public class InterfaceCache implements Cache<Class,ClassItem>{ // // private volatile Cache<Class,ClassItem> cache; // // public InterfaceCache(Cache<Class,ClassItem> cache){ // this.cache = cache; // } // // @Override // public ClassItem get(Class key) { // return cache.get(key); // } // // @Override // public void set(Class key, ClassItem value) { // if (value == null){ // return; // } // cache.set(key,value); // } // // @Override // public ClassItem remove(Class key) { // return cache.remove(key); // } // // @Override // public boolean isHit(Class key) { // return cache.isHit(key); // } // // @Override // public void clear() { // cache.clear(); // } // } // // Path: src/main/java/org/easyarch/slardar/cache/factory/InterfaceCacheFactory.java // public class InterfaceCacheFactory extends AbstractCacheFactory<InterfaceCache> { // // private static InterfaceCacheFactory interfaceCacheFactory; // // private volatile InterfaceCache interfaceCache; // // public static InterfaceCacheFactory getInstance() { // synchronized (InterfaceCacheFactory.class){ // if (interfaceCacheFactory == null){ // synchronized (InterfaceCacheFactory.class){ // interfaceCacheFactory = new InterfaceCacheFactory(); // } // } // } // return interfaceCacheFactory; // } // // private InterfaceCacheFactory(){ // // } // @Override // public InterfaceCache createCache(CacheEntity entity) { // if (interfaceCache == null){ // if (entity != null &&entity.isEnable()){ // switch (entity.getMode()){ // case FIFO: // interfaceCache = new InterfaceCache(new FIFOCache<>(entity.getSize())); // return interfaceCache; // case LRU: // interfaceCache = new InterfaceCache(new LRUCache<>(entity.getSize())); // return interfaceCache; // case TIMEOUT: // interfaceCache = new InterfaceCache(new TimeOutCache<>(entity.getSize())); // return interfaceCache; // default: // interfaceCache = new InterfaceCache(new DefaultCache<>()); // return interfaceCache; // } // } // interfaceCache = new InterfaceCache(new DefaultCache<>()); // } // return interfaceCache; // } // } // // Path: src/main/java/org/easyarch/slardar/session/impl/MapperDBSession.java // public class MapperDBSession extends DBSessionAdapter { // // private ProxyCacheFactory factory; // // private Configuration configuration; // // private AbstractExecutor executor; // // public MapperDBSession(Configuration configuration, AbstractExecutor executor) { // this.executor = executor; // this.configuration = configuration; // factory = ProxyCacheFactory.getInstance(); // } // // @Override // public <T> T selectOne(String sql, Class<T> clazz, Object... parameters) { // return executor.query(sql,new BeanResultSetHadler<T>(clazz),parameters); // } // // @Override // public <E> List<E> selectList(String sql, Class<E> clazz, Object... parameters) { // List<E> list = executor.query(sql, new BeanListResultSetHadler<>(clazz), parameters); // return list; // } // // @Override // public int selectCount(String sql, Object... parameters) { // return executor.query(sql, new BaseTypeResultSetHandler<>(Integer.class), parameters); // } // // @Override // public List<Map<String, Object>> selectMap(String sql, Object... parameters) { // List<Map<String, Object>> list = executor.query(sql, new MapResultHandler(), parameters); // return list; // } // // @Override // public int update(String sql, Object... parameter) { // return executor.alter(sql, parameter); // } // // @Override // public int delete(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public int insert(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public <T> T getMapper(Class<T> clazz) { // ProxyCache proxyCache = factory.createCache(configuration.getCacheEntity()); // if (proxyCache.isHit(clazz)){ // return (T) proxyCache.get(clazz); // } // MapperProxyFactory<T> mapperProxyFactory = new MapperProxyFactory(configuration,clazz); // return mapperProxyFactory.newInstance(this); // } // // @Override // public Configuration getConfiguration() { // return configuration; // } // // @Override // public void close() { // executor.close(); // } // // @Override // public void rollback() { // executor.rollback(); // } // }
import org.easyarch.slardar.annotation.sql.Mapper; import org.easyarch.slardar.cache.InterfaceCache; import org.easyarch.slardar.cache.factory.InterfaceCacheFactory; import org.easyarch.slardar.session.impl.MapperDBSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-24 * 下午8:17 * description: */ public class MapperProxy<T> implements InvocationHandler { private MapperDBSession session; private Class<T> interfaceClass;
// Path: src/main/java/org/easyarch/slardar/cache/InterfaceCache.java // public class InterfaceCache implements Cache<Class,ClassItem>{ // // private volatile Cache<Class,ClassItem> cache; // // public InterfaceCache(Cache<Class,ClassItem> cache){ // this.cache = cache; // } // // @Override // public ClassItem get(Class key) { // return cache.get(key); // } // // @Override // public void set(Class key, ClassItem value) { // if (value == null){ // return; // } // cache.set(key,value); // } // // @Override // public ClassItem remove(Class key) { // return cache.remove(key); // } // // @Override // public boolean isHit(Class key) { // return cache.isHit(key); // } // // @Override // public void clear() { // cache.clear(); // } // } // // Path: src/main/java/org/easyarch/slardar/cache/factory/InterfaceCacheFactory.java // public class InterfaceCacheFactory extends AbstractCacheFactory<InterfaceCache> { // // private static InterfaceCacheFactory interfaceCacheFactory; // // private volatile InterfaceCache interfaceCache; // // public static InterfaceCacheFactory getInstance() { // synchronized (InterfaceCacheFactory.class){ // if (interfaceCacheFactory == null){ // synchronized (InterfaceCacheFactory.class){ // interfaceCacheFactory = new InterfaceCacheFactory(); // } // } // } // return interfaceCacheFactory; // } // // private InterfaceCacheFactory(){ // // } // @Override // public InterfaceCache createCache(CacheEntity entity) { // if (interfaceCache == null){ // if (entity != null &&entity.isEnable()){ // switch (entity.getMode()){ // case FIFO: // interfaceCache = new InterfaceCache(new FIFOCache<>(entity.getSize())); // return interfaceCache; // case LRU: // interfaceCache = new InterfaceCache(new LRUCache<>(entity.getSize())); // return interfaceCache; // case TIMEOUT: // interfaceCache = new InterfaceCache(new TimeOutCache<>(entity.getSize())); // return interfaceCache; // default: // interfaceCache = new InterfaceCache(new DefaultCache<>()); // return interfaceCache; // } // } // interfaceCache = new InterfaceCache(new DefaultCache<>()); // } // return interfaceCache; // } // } // // Path: src/main/java/org/easyarch/slardar/session/impl/MapperDBSession.java // public class MapperDBSession extends DBSessionAdapter { // // private ProxyCacheFactory factory; // // private Configuration configuration; // // private AbstractExecutor executor; // // public MapperDBSession(Configuration configuration, AbstractExecutor executor) { // this.executor = executor; // this.configuration = configuration; // factory = ProxyCacheFactory.getInstance(); // } // // @Override // public <T> T selectOne(String sql, Class<T> clazz, Object... parameters) { // return executor.query(sql,new BeanResultSetHadler<T>(clazz),parameters); // } // // @Override // public <E> List<E> selectList(String sql, Class<E> clazz, Object... parameters) { // List<E> list = executor.query(sql, new BeanListResultSetHadler<>(clazz), parameters); // return list; // } // // @Override // public int selectCount(String sql, Object... parameters) { // return executor.query(sql, new BaseTypeResultSetHandler<>(Integer.class), parameters); // } // // @Override // public List<Map<String, Object>> selectMap(String sql, Object... parameters) { // List<Map<String, Object>> list = executor.query(sql, new MapResultHandler(), parameters); // return list; // } // // @Override // public int update(String sql, Object... parameter) { // return executor.alter(sql, parameter); // } // // @Override // public int delete(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public int insert(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public <T> T getMapper(Class<T> clazz) { // ProxyCache proxyCache = factory.createCache(configuration.getCacheEntity()); // if (proxyCache.isHit(clazz)){ // return (T) proxyCache.get(clazz); // } // MapperProxyFactory<T> mapperProxyFactory = new MapperProxyFactory(configuration,clazz); // return mapperProxyFactory.newInstance(this); // } // // @Override // public Configuration getConfiguration() { // return configuration; // } // // @Override // public void close() { // executor.close(); // } // // @Override // public void rollback() { // executor.rollback(); // } // } // Path: src/main/java/org/easyarch/slardar/mapping/MapperProxy.java import org.easyarch.slardar.annotation.sql.Mapper; import org.easyarch.slardar.cache.InterfaceCache; import org.easyarch.slardar.cache.factory.InterfaceCacheFactory; import org.easyarch.slardar.session.impl.MapperDBSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-24 * 下午8:17 * description: */ public class MapperProxy<T> implements InvocationHandler { private MapperDBSession session; private Class<T> interfaceClass;
private InterfaceCache interfaceCache;
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/mapping/MapperProxy.java
// Path: src/main/java/org/easyarch/slardar/cache/InterfaceCache.java // public class InterfaceCache implements Cache<Class,ClassItem>{ // // private volatile Cache<Class,ClassItem> cache; // // public InterfaceCache(Cache<Class,ClassItem> cache){ // this.cache = cache; // } // // @Override // public ClassItem get(Class key) { // return cache.get(key); // } // // @Override // public void set(Class key, ClassItem value) { // if (value == null){ // return; // } // cache.set(key,value); // } // // @Override // public ClassItem remove(Class key) { // return cache.remove(key); // } // // @Override // public boolean isHit(Class key) { // return cache.isHit(key); // } // // @Override // public void clear() { // cache.clear(); // } // } // // Path: src/main/java/org/easyarch/slardar/cache/factory/InterfaceCacheFactory.java // public class InterfaceCacheFactory extends AbstractCacheFactory<InterfaceCache> { // // private static InterfaceCacheFactory interfaceCacheFactory; // // private volatile InterfaceCache interfaceCache; // // public static InterfaceCacheFactory getInstance() { // synchronized (InterfaceCacheFactory.class){ // if (interfaceCacheFactory == null){ // synchronized (InterfaceCacheFactory.class){ // interfaceCacheFactory = new InterfaceCacheFactory(); // } // } // } // return interfaceCacheFactory; // } // // private InterfaceCacheFactory(){ // // } // @Override // public InterfaceCache createCache(CacheEntity entity) { // if (interfaceCache == null){ // if (entity != null &&entity.isEnable()){ // switch (entity.getMode()){ // case FIFO: // interfaceCache = new InterfaceCache(new FIFOCache<>(entity.getSize())); // return interfaceCache; // case LRU: // interfaceCache = new InterfaceCache(new LRUCache<>(entity.getSize())); // return interfaceCache; // case TIMEOUT: // interfaceCache = new InterfaceCache(new TimeOutCache<>(entity.getSize())); // return interfaceCache; // default: // interfaceCache = new InterfaceCache(new DefaultCache<>()); // return interfaceCache; // } // } // interfaceCache = new InterfaceCache(new DefaultCache<>()); // } // return interfaceCache; // } // } // // Path: src/main/java/org/easyarch/slardar/session/impl/MapperDBSession.java // public class MapperDBSession extends DBSessionAdapter { // // private ProxyCacheFactory factory; // // private Configuration configuration; // // private AbstractExecutor executor; // // public MapperDBSession(Configuration configuration, AbstractExecutor executor) { // this.executor = executor; // this.configuration = configuration; // factory = ProxyCacheFactory.getInstance(); // } // // @Override // public <T> T selectOne(String sql, Class<T> clazz, Object... parameters) { // return executor.query(sql,new BeanResultSetHadler<T>(clazz),parameters); // } // // @Override // public <E> List<E> selectList(String sql, Class<E> clazz, Object... parameters) { // List<E> list = executor.query(sql, new BeanListResultSetHadler<>(clazz), parameters); // return list; // } // // @Override // public int selectCount(String sql, Object... parameters) { // return executor.query(sql, new BaseTypeResultSetHandler<>(Integer.class), parameters); // } // // @Override // public List<Map<String, Object>> selectMap(String sql, Object... parameters) { // List<Map<String, Object>> list = executor.query(sql, new MapResultHandler(), parameters); // return list; // } // // @Override // public int update(String sql, Object... parameter) { // return executor.alter(sql, parameter); // } // // @Override // public int delete(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public int insert(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public <T> T getMapper(Class<T> clazz) { // ProxyCache proxyCache = factory.createCache(configuration.getCacheEntity()); // if (proxyCache.isHit(clazz)){ // return (T) proxyCache.get(clazz); // } // MapperProxyFactory<T> mapperProxyFactory = new MapperProxyFactory(configuration,clazz); // return mapperProxyFactory.newInstance(this); // } // // @Override // public Configuration getConfiguration() { // return configuration; // } // // @Override // public void close() { // executor.close(); // } // // @Override // public void rollback() { // executor.rollback(); // } // }
import org.easyarch.slardar.annotation.sql.Mapper; import org.easyarch.slardar.cache.InterfaceCache; import org.easyarch.slardar.cache.factory.InterfaceCacheFactory; import org.easyarch.slardar.session.impl.MapperDBSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-24 * 下午8:17 * description: */ public class MapperProxy<T> implements InvocationHandler { private MapperDBSession session; private Class<T> interfaceClass; private InterfaceCache interfaceCache; public MapperProxy(MapperDBSession session, Class<T> interfaceClass){ this.session = session; this.interfaceClass = interfaceClass;
// Path: src/main/java/org/easyarch/slardar/cache/InterfaceCache.java // public class InterfaceCache implements Cache<Class,ClassItem>{ // // private volatile Cache<Class,ClassItem> cache; // // public InterfaceCache(Cache<Class,ClassItem> cache){ // this.cache = cache; // } // // @Override // public ClassItem get(Class key) { // return cache.get(key); // } // // @Override // public void set(Class key, ClassItem value) { // if (value == null){ // return; // } // cache.set(key,value); // } // // @Override // public ClassItem remove(Class key) { // return cache.remove(key); // } // // @Override // public boolean isHit(Class key) { // return cache.isHit(key); // } // // @Override // public void clear() { // cache.clear(); // } // } // // Path: src/main/java/org/easyarch/slardar/cache/factory/InterfaceCacheFactory.java // public class InterfaceCacheFactory extends AbstractCacheFactory<InterfaceCache> { // // private static InterfaceCacheFactory interfaceCacheFactory; // // private volatile InterfaceCache interfaceCache; // // public static InterfaceCacheFactory getInstance() { // synchronized (InterfaceCacheFactory.class){ // if (interfaceCacheFactory == null){ // synchronized (InterfaceCacheFactory.class){ // interfaceCacheFactory = new InterfaceCacheFactory(); // } // } // } // return interfaceCacheFactory; // } // // private InterfaceCacheFactory(){ // // } // @Override // public InterfaceCache createCache(CacheEntity entity) { // if (interfaceCache == null){ // if (entity != null &&entity.isEnable()){ // switch (entity.getMode()){ // case FIFO: // interfaceCache = new InterfaceCache(new FIFOCache<>(entity.getSize())); // return interfaceCache; // case LRU: // interfaceCache = new InterfaceCache(new LRUCache<>(entity.getSize())); // return interfaceCache; // case TIMEOUT: // interfaceCache = new InterfaceCache(new TimeOutCache<>(entity.getSize())); // return interfaceCache; // default: // interfaceCache = new InterfaceCache(new DefaultCache<>()); // return interfaceCache; // } // } // interfaceCache = new InterfaceCache(new DefaultCache<>()); // } // return interfaceCache; // } // } // // Path: src/main/java/org/easyarch/slardar/session/impl/MapperDBSession.java // public class MapperDBSession extends DBSessionAdapter { // // private ProxyCacheFactory factory; // // private Configuration configuration; // // private AbstractExecutor executor; // // public MapperDBSession(Configuration configuration, AbstractExecutor executor) { // this.executor = executor; // this.configuration = configuration; // factory = ProxyCacheFactory.getInstance(); // } // // @Override // public <T> T selectOne(String sql, Class<T> clazz, Object... parameters) { // return executor.query(sql,new BeanResultSetHadler<T>(clazz),parameters); // } // // @Override // public <E> List<E> selectList(String sql, Class<E> clazz, Object... parameters) { // List<E> list = executor.query(sql, new BeanListResultSetHadler<>(clazz), parameters); // return list; // } // // @Override // public int selectCount(String sql, Object... parameters) { // return executor.query(sql, new BaseTypeResultSetHandler<>(Integer.class), parameters); // } // // @Override // public List<Map<String, Object>> selectMap(String sql, Object... parameters) { // List<Map<String, Object>> list = executor.query(sql, new MapResultHandler(), parameters); // return list; // } // // @Override // public int update(String sql, Object... parameter) { // return executor.alter(sql, parameter); // } // // @Override // public int delete(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public int insert(String sql, Object... parameter) { // return update(sql, parameter); // } // // @Override // public <T> T getMapper(Class<T> clazz) { // ProxyCache proxyCache = factory.createCache(configuration.getCacheEntity()); // if (proxyCache.isHit(clazz)){ // return (T) proxyCache.get(clazz); // } // MapperProxyFactory<T> mapperProxyFactory = new MapperProxyFactory(configuration,clazz); // return mapperProxyFactory.newInstance(this); // } // // @Override // public Configuration getConfiguration() { // return configuration; // } // // @Override // public void close() { // executor.close(); // } // // @Override // public void rollback() { // executor.rollback(); // } // } // Path: src/main/java/org/easyarch/slardar/mapping/MapperProxy.java import org.easyarch.slardar.annotation.sql.Mapper; import org.easyarch.slardar.cache.InterfaceCache; import org.easyarch.slardar.cache.factory.InterfaceCacheFactory; import org.easyarch.slardar.session.impl.MapperDBSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; package org.easyarch.slardar.mapping; /** * Description : * Created by xingtianyu on 17-1-24 * 下午8:17 * description: */ public class MapperProxy<T> implements InvocationHandler { private MapperDBSession session; private Class<T> interfaceClass; private InterfaceCache interfaceCache; public MapperProxy(MapperDBSession session, Class<T> interfaceClass){ this.session = session; this.interfaceClass = interfaceClass;
this.interfaceCache = InterfaceCacheFactory.getInstance()
rpgmakervx/slardar
src/main/java/org/easyarch/test/controlle/SessionController.java
// Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // }
import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService;
package org.easyarch.test.controlle; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:39 * description: */ public class SessionController { public static void main(String[] args) {
// Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // } // Path: src/main/java/org/easyarch/test/controlle/SessionController.java import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; package org.easyarch.test.controlle; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:39 * description: */ public class SessionController { public static void main(String[] args) {
UserService service = new UserService();
rpgmakervx/slardar
src/main/java/org/easyarch/test/controlle/SessionController.java
// Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // }
import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService;
package org.easyarch.test.controlle; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:39 * description: */ public class SessionController { public static void main(String[] args) { UserService service = new UserService();
// Path: src/main/java/org/easyarch/test/pojo/User.java // @Table(tableName = "user") // public class User { // // @Column(name = "client_id") // private String clientId; // // @Column(name = "username") // private String userName; // // @Column(name = "password") // private String password; // // @Column(name = "phone") // private String phone; // // public String getClientId() { // return clientId; // } // // public void setClientId(String clientId) { // this.clientId = clientId == null ? null : clientId.trim(); // } // // 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 == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // @Override // public String toString() { // return "User{" + // "clientId='" + clientId + '\'' + // ", userName='" + userName + '\'' + // ", password='" + password + '\'' + // ", phone='" + phone + '\'' + // '}'; // } // } // // Path: src/main/java/org/easyarch/test/service/UserService.java // public class UserService { // // private UserMapper mapper; // // private DBSession session; // private DBSession defaultSession; // // public UserService(){ // try { // DBSessionFactory sessionFactory = new DBSessionFactoryBuilder().build( // ResourcesUtil.getResourceAsStream("/config.xml")); // session = sessionFactory.newDelegateSession(); // defaultSession = sessionFactory.newDefaultSession(); // mapper = session.getMapper(UserMapper.class); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public int getUserCount(User user){ // return mapper.getCount(user); // } // // public User getUser(String id){ // return mapper.findById(id); // } // // public User fetchUser(String id){ // Parameter param = new Parameter("id",id); // return defaultSession.selectOne(UserMapper.class.getName()+"@"+"findById",User.class,param); // } // public List<User> getUsers(User user){ // return mapper.findByUser(user); // } // public List<User> getUsers(Query query){ // return mapper.findByQuery(query); // } // // public List<User> fetchUsers(User user){ // return defaultSession.selectList(UserMapper.class.getName()+"@"+"findByUser" // ,User.class,ParamUtil.create(user)); // } // // public void saveUser(User user){ // mapper.insert(user); // } // public void insertUser(User user){ // defaultSession.insert(UserMapper.class.getName()+"@"+"insert", ParamUtil.create(user)); // } // // public void update(User user){ // mapper.update(user); // } // // public List<User> searchUsers(User user){ // return session.selectList("select * from user where client_id = ?" // ,User.class,user.getClientId()); // } // // public void deleteById(String id){ // mapper.deleteById(id); // } // // } // Path: src/main/java/org/easyarch/test/controlle/SessionController.java import org.easyarch.test.pojo.User; import org.easyarch.test.service.UserService; package org.easyarch.test.controlle; /** * Description : * Created by xingtianyu on 17-2-12 * 下午10:39 * description: */ public class SessionController { public static void main(String[] args) { UserService service = new UserService();
User user = service.getUser("123567");
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/parser/ParamParser.java
// Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String KEY = "$"; // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String POINT = ".";
import static org.easyarch.slardar.parser.Token.KEY; import static org.easyarch.slardar.parser.Token.POINT;
package org.easyarch.slardar.parser; /** * Description : * Created by code4j on 17-1-19 * 上午10:00 * description: */ public class ParamParser extends ParserAdapter { private String []paramTokens; @Override public void parse(String src) {
// Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String KEY = "$"; // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String POINT = "."; // Path: src/main/java/org/easyarch/slardar/parser/ParamParser.java import static org.easyarch.slardar.parser.Token.KEY; import static org.easyarch.slardar.parser.Token.POINT; package org.easyarch.slardar.parser; /** * Description : * Created by code4j on 17-1-19 * 上午10:00 * description: */ public class ParamParser extends ParserAdapter { private String []paramTokens; @Override public void parse(String src) {
int beginIndex = KEY.length();
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/parser/ParamParser.java
// Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String KEY = "$"; // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String POINT = ".";
import static org.easyarch.slardar.parser.Token.KEY; import static org.easyarch.slardar.parser.Token.POINT;
package org.easyarch.slardar.parser; /** * Description : * Created by code4j on 17-1-19 * 上午10:00 * description: */ public class ParamParser extends ParserAdapter { private String []paramTokens; @Override public void parse(String src) { int beginIndex = KEY.length(); String word = src.substring(beginIndex, src.length() - beginIndex);
// Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String KEY = "$"; // // Path: src/main/java/org/easyarch/slardar/parser/Token.java // public static final String POINT = "."; // Path: src/main/java/org/easyarch/slardar/parser/ParamParser.java import static org.easyarch.slardar.parser.Token.KEY; import static org.easyarch.slardar.parser.Token.POINT; package org.easyarch.slardar.parser; /** * Description : * Created by code4j on 17-1-19 * 上午10:00 * description: */ public class ParamParser extends ParserAdapter { private String []paramTokens; @Override public void parse(String src) { int beginIndex = KEY.length(); String word = src.substring(beginIndex, src.length() - beginIndex);
paramTokens = word.split(POINT);
dries007/TFCSeedMaker
src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerRiverMix.java
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // // Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // }
import net.dries007.tfc.seedmaker.datatypes.Biome; import static net.dries007.tfc.seedmaker.datatypes.Biome.*;
return index < array.length && index >= 0; } @Override public Layer initWorldGenSeed(final long seed) { biomePatternGeneratorChain.initWorldGenSeed(seed); riverPatternGeneratorChain.initWorldGenSeed(seed); return super.initWorldGenSeed(seed); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] layerBiomes = biomePatternGeneratorChain.getInts(x, y, sizeX, sizeY); final int[] layerRivers = riverPatternGeneratorChain.getInts(x, y, sizeX, sizeY); final int[] layerOut = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { final int index = xx + yy * sizeX; final int b = layerBiomes[index]; final int xn = index - 1; final int xp = index + 1; final int yn = index - sizeY; final int yp = index + sizeY;
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // // Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // Path: src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerRiverMix.java import net.dries007.tfc.seedmaker.datatypes.Biome; import static net.dries007.tfc.seedmaker.datatypes.Biome.*; return index < array.length && index >= 0; } @Override public Layer initWorldGenSeed(final long seed) { biomePatternGeneratorChain.initWorldGenSeed(seed); riverPatternGeneratorChain.initWorldGenSeed(seed); return super.initWorldGenSeed(seed); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] layerBiomes = biomePatternGeneratorChain.getInts(x, y, sizeX, sizeY); final int[] layerRivers = riverPatternGeneratorChain.getInts(x, y, sizeX, sizeY); final int[] layerOut = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { final int index = xx + yy * sizeX; final int b = layerBiomes[index]; final int xn = index - 1; final int xp = index + 1; final int yn = index - sizeY; final int yp = index + sizeY;
if (Biome.isOceanicBiome(b)) layerOut[index] = b;
dries007/TFCSeedMaker
src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerAddIsland.java
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // }
import net.dries007.tfc.seedmaker.datatypes.Biome;
package net.dries007.tfc.seedmaker.genlayers; public class LayerAddIsland extends Layer { public LayerAddIsland(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int sizeX_2 = sizeX + 2; final int sizeY_2 = sizeY + 2; final int[] ints = parent.getInts(x - 1, y - 1, sizeX_2, sizeY_2); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { final int dl = ints[xx + yy * sizeX_2]; // down left final int dr = ints[xx + 2 + yy * sizeX_2]; // down right final int ul = ints[xx + (yy + 2) * sizeX_2]; // up left final int ur = ints[xx + 2 + (yy + 2) * sizeX_2]; // up right final int us = ints[xx + 1 + (yy + 1) * sizeX_2]; // us initChunkSeed(xx + x, yy + y);
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // Path: src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerAddIsland.java import net.dries007.tfc.seedmaker.datatypes.Biome; package net.dries007.tfc.seedmaker.genlayers; public class LayerAddIsland extends Layer { public LayerAddIsland(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int sizeX_2 = sizeX + 2; final int sizeY_2 = sizeY + 2; final int[] ints = parent.getInts(x - 1, y - 1, sizeX_2, sizeY_2); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { final int dl = ints[xx + yy * sizeX_2]; // down left final int dr = ints[xx + 2 + yy * sizeX_2]; // down right final int ul = ints[xx + (yy + 2) * sizeX_2]; // up left final int ur = ints[xx + 2 + (yy + 2) * sizeX_2]; // up right final int us = ints[xx + 1 + (yy + 1) * sizeX_2]; // us initChunkSeed(xx + x, yy + y);
if (us == Biome.OCEAN.id && (dl != Biome.OCEAN.id || dr != Biome.OCEAN.id || ul != Biome.OCEAN.id || ur != Biome.OCEAN.id)) // We are OCEAN and any of our neighbours is not
dries007/TFCSeedMaker
src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerRiverInit.java
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // }
import net.dries007.tfc.seedmaker.datatypes.Biome;
package net.dries007.tfc.seedmaker.genlayers; public class LayerRiverInit extends Layer { public LayerRiverInit(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] ints = parent.getInts(x, y, sizeX, sizeY); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { initChunkSeed(xx + x, yy + y); final int index = xx + yy * sizeX; final int id = ints[index];
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // Path: src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerRiverInit.java import net.dries007.tfc.seedmaker.datatypes.Biome; package net.dries007.tfc.seedmaker.genlayers; public class LayerRiverInit extends Layer { public LayerRiverInit(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] ints = parent.getInts(x, y, sizeX, sizeY); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { initChunkSeed(xx + x, yy + y); final int index = xx + yy * sizeX; final int id = ints[index];
out[index] = !Biome.isOceanicBiome(id) && !Biome.isMountainBiome(id) ? 1 : 0;
dries007/TFCSeedMaker
src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerLakes.java
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // }
import net.dries007.tfc.seedmaker.datatypes.Biome; import static net.dries007.tfc.seedmaker.datatypes.Biome.LAKE;
package net.dries007.tfc.seedmaker.genlayers; public class LayerLakes extends Layer { public LayerLakes(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] ints = parent.getInts(x - 1, y - 1, sizeX + 2, sizeY + 2); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { initChunkSeed(xx + x, yy + y); final int us = ints[xx + 1 + (yy + 1) * (sizeX + 2)]; final int idD = ints[xx + 1 + (yy) * (sizeX + 2)]; // down final int idR = ints[xx + 2 + (yy + 1) * (sizeX + 2)]; // right final int idL = ints[xx + (yy + 1) * (sizeX + 2)]; // left final int idU = ints[xx + 1 + (yy + 2) * (sizeX + 2)]; // up
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Biome.java // public enum Biome // { // OCEAN(0, new Color(0x3232C8)), // RIVER(1, new Color(0x2B8CBA)), // BEACH(2, new Color(0xC7A03B)), // GRAVEL_BEACH(3, new Color(0x7E7450)), // HIGH_HILLS(4, new Color(0x920072)), // PLAINS(5, new Color(0x346B25)), // SWAMPLAND(6, new Color(0x099200)), // HIGH_HILLS_EDGE(7, new Color(0x92567C)), // ROLLING_HILLS(8, new Color(0x734B92)), // MOUNTAINS(9, new Color(0x920000)), // MOUNTAINS_EDGE(10, new Color(0x924A4C)), // HIGH_PLAINS(11, new Color(0x225031)), // DEEP_OCEAN(12, new Color(0x000080)), // LAKE(13, new Color(0x5D8C8D)); // // public static final List<Biome> ALLOWEDBIOMES = Arrays.asList(OCEAN, HIGH_HILLS, PLAINS, SWAMPLAND, ROLLING_HILLS, MOUNTAINS, HIGH_PLAINS); // public static final int[] COLORS = new int[values().length]; // // static // { // for (Biome biome : values()) COLORS[biome.id] = biome.color.getRGB(); // } // // public final int id; // public final Color color; // // Biome(final int id, final Color color) // { // this.id = id; // this.color = color; // } // // public static boolean isOceanicBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id; // } // // public static boolean isWaterBiome(int id) // { // return id == OCEAN.id || id == DEEP_OCEAN.id || id == LAKE.id || id == RIVER.id; // } // // public static boolean isMountainBiome(int id) // { // return id == MOUNTAINS.id || id == MOUNTAINS_EDGE.id; // } // // public static boolean isBeachBiome(int id) // { // return id == BEACH.id || id == GRAVEL_BEACH.id; // } // } // Path: src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerLakes.java import net.dries007.tfc.seedmaker.datatypes.Biome; import static net.dries007.tfc.seedmaker.datatypes.Biome.LAKE; package net.dries007.tfc.seedmaker.genlayers; public class LayerLakes extends Layer { public LayerLakes(final long seed, final Layer parent) { super(seed, parent); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] ints = parent.getInts(x - 1, y - 1, sizeX + 2, sizeY + 2); final int[] out = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { initChunkSeed(xx + x, yy + y); final int us = ints[xx + 1 + (yy + 1) * (sizeX + 2)]; final int idD = ints[xx + 1 + (yy) * (sizeX + 2)]; // down final int idR = ints[xx + 2 + (yy + 1) * (sizeX + 2)]; // right final int idL = ints[xx + (yy + 1) * (sizeX + 2)]; // left final int idU = ints[xx + 1 + (yy + 2) * (sizeX + 2)]; // up
if (Biome.isOceanicBiome(us))
dries007/TFCSeedMaker
src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerDrainageInit.java
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Drainage.java // public enum Drainage // { // DRAINAGE_NONE(0), // DRAINAGE_VERY_POOR(1), // DRAINAGE_POOR(2), // DRAINAGE_NORMAL(3), // DRAINAGE_GOOD(4), // DRAINAGE_VERY_GOOD(5); // // public static final int MIN = DRAINAGE_NONE.id; // public static final int MAX = DRAINAGE_VERY_GOOD.id; // // public final int id; // // Drainage(final int id) // { // this.id = id; // } // }
import net.dries007.tfc.seedmaker.datatypes.Drainage;
package net.dries007.tfc.seedmaker.genlayers; public class LayerDrainageInit extends Layer { public LayerDrainageInit(final long seed) { super(seed); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] outs = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { this.initChunkSeed(x + xx, y + yy);
// Path: src/main/java/net/dries007/tfc/seedmaker/datatypes/Drainage.java // public enum Drainage // { // DRAINAGE_NONE(0), // DRAINAGE_VERY_POOR(1), // DRAINAGE_POOR(2), // DRAINAGE_NORMAL(3), // DRAINAGE_GOOD(4), // DRAINAGE_VERY_GOOD(5); // // public static final int MIN = DRAINAGE_NONE.id; // public static final int MAX = DRAINAGE_VERY_GOOD.id; // // public final int id; // // Drainage(final int id) // { // this.id = id; // } // } // Path: src/main/java/net/dries007/tfc/seedmaker/genlayers/LayerDrainageInit.java import net.dries007.tfc.seedmaker.datatypes.Drainage; package net.dries007.tfc.seedmaker.genlayers; public class LayerDrainageInit extends Layer { public LayerDrainageInit(final long seed) { super(seed); } @Override public int[] getInts(final int x, final int y, final int sizeX, final int sizeY) { final int[] outs = new int[sizeX * sizeY]; for (int yy = 0; yy < sizeY; ++yy) { for (int xx = 0; xx < sizeX; ++xx) { this.initChunkSeed(x + xx, y + yy);
outs[xx + yy * sizeX] = Drainage.MIN + this.nextInt(5);