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
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleLocalNoResultRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/request/LocalRequest.java // public abstract class LocalRequest<T> extends BallRequest<T> { // // protected LocalRequest() { // super(-1, null, null); // } // // protected LocalRequest(SingleResponseListener<T> responseListener) { // super(-1, null, responseListener, null); // } // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return performLocal(); // } // // @Override // public void saveLocalResponse(T response) { // // } // }; // } // // public abstract T performLocal(); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // }
import com.siu.android.volleyball.request.LocalRequest; import com.siu.android.volleyball.samples.util.ScenarioUtils;
package com.siu.android.volleyball.samples.volley.request; /** * Sample local request * The local request that returns nothing */ public class SampleLocalNoResultRequest extends LocalRequest<Void> { public SampleLocalNoResultRequest() { super(); } @Override public Void performLocal() { // perform your task outside of UI thread here
// Path: library/src/main/java/com/siu/android/volleyball/request/LocalRequest.java // public abstract class LocalRequest<T> extends BallRequest<T> { // // protected LocalRequest() { // super(-1, null, null); // } // // protected LocalRequest(SingleResponseListener<T> responseListener) { // super(-1, null, responseListener, null); // } // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return performLocal(); // } // // @Override // public void saveLocalResponse(T response) { // // } // }; // } // // public abstract T performLocal(); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleLocalNoResultRequest.java import com.siu.android.volleyball.request.LocalRequest; import com.siu.android.volleyball.samples.util.ScenarioUtils; package com.siu.android.volleyball.samples.volley.request; /** * Sample local request * The local request that returns nothing */ public class SampleLocalNoResultRequest extends LocalRequest<Void> { public SampleLocalNoResultRequest() { super(); } @Override public Void performLocal() { // perform your task outside of UI thread here
ScenarioUtils.waitSeveralSeconds(2);
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/BallRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/local/LocalRequestProcessor.java // public interface LocalRequestProcessor<T> { // // public abstract T getLocalResponse(); // // public abstract void saveLocalResponse(T response); // // // } // // Path: library/src/main/java/com/siu/android/volleyball/network/NetworkRequestProcessor.java // public interface NetworkRequestProcessor<T> { // // public abstract BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // }
import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.local.LocalRequestProcessor; import com.siu.android.volleyball.network.NetworkRequestProcessor; import com.siu.android.volleyball.response.ResponseListener;
package com.siu.android.volleyball; /** * Created by lukas on 8/29/13. */ public abstract class BallRequest<T> extends Request<T> { /* Private fields from Request class */ protected static final long SLOW_REQUEST_THRESHOLD_MS = 3000; protected final BallMarkerLog mEventLog = BallMarkerLog.ENABLED ? new BallMarkerLog() : null; protected long mRequestBirthTime = 0; protected BallRequestQueue mRequestQueue; /* Additionnal logic from Ball */ protected LocalRequestProcessor<T> mLocalRequestProcessor; protected NetworkRequestProcessor<T> mNetworkRequestProcessor; protected ResponseListener mResponseListener; /** * Error from final response, stored and used later if intermediate response is still to be delivered: * If intermediate response is delivered after with no response, deliver the final error */ private VolleyError mFinalResponseError; protected boolean mFinalResponseDelivered = false; /** * Intermediate response of the request has been delivered. * <p/> * Several use cases: * - In the executor delivery to consider only the 1st intermediate request and ignore the 2nd one. * - REMOVED FOR NOW, NOT VOLATILE -- In the network dispatcher to return identical response in case of 304 not modified response * and if a valid intermediate response was returned. Must be volatile because it can apply between * local and network thread. */ protected boolean mIntermediateResponseDelivered = false; /** * Request is finished and no more response should be delivered * Volatile because it is used to determine if a marker should be added to the log, * and value need to be synchronized between all worker threads */ protected volatile boolean mFinished = false; private boolean mLocalIntermediateResponseDelivered = false; private boolean mCacheIntermediateResponseDelivered = false; private boolean mIntermediateResponseDeliveredWithSuccess = false; protected BallRequest(int method, String url, Response.ErrorListener errorListener) { super(method, url, errorListener); if (shouldProcessLocal()) { mLocalRequestProcessor = createLocalRequestProcessor(); if (mLocalRequestProcessor == null) {
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/local/LocalRequestProcessor.java // public interface LocalRequestProcessor<T> { // // public abstract T getLocalResponse(); // // public abstract void saveLocalResponse(T response); // // // } // // Path: library/src/main/java/com/siu/android/volleyball/network/NetworkRequestProcessor.java // public interface NetworkRequestProcessor<T> { // // public abstract BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // Path: library/src/main/java/com/siu/android/volleyball/BallRequest.java import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.local.LocalRequestProcessor; import com.siu.android.volleyball.network.NetworkRequestProcessor; import com.siu.android.volleyball.response.ResponseListener; package com.siu.android.volleyball; /** * Created by lukas on 8/29/13. */ public abstract class BallRequest<T> extends Request<T> { /* Private fields from Request class */ protected static final long SLOW_REQUEST_THRESHOLD_MS = 3000; protected final BallMarkerLog mEventLog = BallMarkerLog.ENABLED ? new BallMarkerLog() : null; protected long mRequestBirthTime = 0; protected BallRequestQueue mRequestQueue; /* Additionnal logic from Ball */ protected LocalRequestProcessor<T> mLocalRequestProcessor; protected NetworkRequestProcessor<T> mNetworkRequestProcessor; protected ResponseListener mResponseListener; /** * Error from final response, stored and used later if intermediate response is still to be delivered: * If intermediate response is delivered after with no response, deliver the final error */ private VolleyError mFinalResponseError; protected boolean mFinalResponseDelivered = false; /** * Intermediate response of the request has been delivered. * <p/> * Several use cases: * - In the executor delivery to consider only the 1st intermediate request and ignore the 2nd one. * - REMOVED FOR NOW, NOT VOLATILE -- In the network dispatcher to return identical response in case of 304 not modified response * and if a valid intermediate response was returned. Must be volatile because it can apply between * local and network thread. */ protected boolean mIntermediateResponseDelivered = false; /** * Request is finished and no more response should be delivered * Volatile because it is used to determine if a marker should be added to the log, * and value need to be synchronized between all worker threads */ protected volatile boolean mFinished = false; private boolean mLocalIntermediateResponseDelivered = false; private boolean mCacheIntermediateResponseDelivered = false; private boolean mIntermediateResponseDeliveredWithSuccess = false; protected BallRequest(int method, String url, Response.ErrorListener errorListener) { super(method, url, errorListener); if (shouldProcessLocal()) { mLocalRequestProcessor = createLocalRequestProcessor(); if (mLocalRequestProcessor == null) {
throw new BallException("Request should process local but local request processor is not provided");
nickyangjun/EasyEmoji
app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiInterceptor.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/Target.java // public interface Target { // int getIcon(); // String getEmoji(); // }
import android.text.Spannable; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.Target; import java.util.regex.Matcher; import java.util.regex.Pattern;
package org.nicky.easyemoji.lovedEmoji; /** * Created by nickyang on 2017/4/5. */ public class LovedEmojiInterceptor implements EmojiInterceptor { @Override
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/Target.java // public interface Target { // int getIcon(); // String getEmoji(); // } // Path: app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiInterceptor.java import android.text.Spannable; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.Target; import java.util.regex.Matcher; import java.util.regex.Pattern; package org.nicky.easyemoji.lovedEmoji; /** * Created by nickyang on 2017/4/5. */ public class LovedEmojiInterceptor implements EmojiInterceptor { @Override
public Target intercept(Spannable text, int startIndex) {
nickyangjun/EasyEmoji
app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // }
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List;
package org.nicky.easyemoji.lovedEmoji; /** * Created by nickyang on 2017/4/5. */ public class LovedEmojiStyle implements EmojiStyle { LovedEmojicons emojicons; public LovedEmojiStyle() { emojicons = new LovedEmojicons(); } @Override public String getStyleName() { return "loved"; } @Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // } // Path: app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List; package org.nicky.easyemoji.lovedEmoji; /** * Created by nickyang on 2017/4/5. */ public class LovedEmojiStyle implements EmojiStyle { LovedEmojicons emojicons; public LovedEmojiStyle() { emojicons = new LovedEmojicons(); } @Override public String getStyleName() { return "loved"; } @Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override
public EmojiFragment getCustomFragment(int index) {
nickyangjun/EasyEmoji
app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // }
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List;
@Override public String getStyleName() { return "loved"; } @Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override public EmojiFragment getCustomFragment(int index) { return new LovedEmojiFragment<>(); } @Override
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // } // Path: app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List; @Override public String getStyleName() { return "loved"; } @Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override public EmojiFragment getCustomFragment(int index) { return new LovedEmojiFragment<>(); } @Override
public PageEmojiStyle getPagerData(int index) {
nickyangjun/EasyEmoji
app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // }
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List;
@Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override public EmojiFragment getCustomFragment(int index) { return new LovedEmojiFragment<>(); } @Override public PageEmojiStyle getPagerData(int index) { return new LovedPageEmojiStyle(); } @Override
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiInterceptor.java // public interface EmojiInterceptor { // Target intercept( Spannable text,int startIndex); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java // public interface EmojiStyle<T extends Parcelable> { // /** // * 名称tag, 必须唯一 // */ // String getStyleName(); // // /** // * 底部tab的图标 // */ // int getStyleIcon(); // // /** // * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, // * tab 被选中时会调用view的 selected 事件 // */ // View getStyleIconView(Context context); // // /** // * 所有emoji的数据源 // */ // List<T> getEmojiData(); // // /** // * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 // * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 // * // * @param index // * @return // */ // EmojiFragment getCustomFragment(int index); // // /** // * 一个显示页面的数据源 // * // * @param index // * @return // */ // PageEmojiStyle getPagerData(int index); // // /** // * 文本拦截事件, 用于处理自定义表情 // * // * @return // */ // EmojiInterceptor getEmojiInterceptor(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // } // Path: app/src/main/java/org/nicky/easyemoji/lovedEmoji/LovedEmojiStyle.java import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import org.nicky.easyemoji.R; import org.nicky.libeasyemoji.emoji.EmojiFragment; import org.nicky.libeasyemoji.emoji.interfaces.EmojiInterceptor; import org.nicky.libeasyemoji.emoji.interfaces.EmojiStyle; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; import java.util.List; @Override public int getStyleIcon() { return R.drawable.sg001; } @Override public View getStyleIconView(Context context) { ImageButton image = new ImageButton(context); image.setImageResource(R.drawable.sg003); image.setBackgroundResource(R.drawable.love_emojicon); image.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); return image; } @Override public List getEmojiData() { return emojicons.getEmojis(); } @Override public EmojiFragment getCustomFragment(int index) { return new LovedEmojiFragment<>(); } @Override public PageEmojiStyle getPagerData(int index) { return new LovedPageEmojiStyle(); } @Override
public EmojiInterceptor getEmojiInterceptor() {
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyleChangeListener.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiStyleWrapper.java // public class EmojiStyleWrapper<T extends Parcelable> implements ViewTab{ // private View tabItemView; // private EmojiStyle style; // private boolean isSelected; // /** // * 表情的所有分页 // */ // private List<PageEmojiStyle> pagerDataList; // //如果当前style被选中,curDisplayPageIndex >= 0 , 表示当前显示页在style中的索引 // private int curDisplayPageIndex = -1; // // public EmojiStyleWrapper(EmojiStyle style){ // this.style = style; // setup(); // } // // private void setup(){ // int index = 0; // int allDataCounts = this.style.getEmojiData().size(); // int itemCounts = 0; // if(pagerDataList == null){ // pagerDataList = new ArrayList<>(10); // }else { // pagerDataList.clear(); // } // for(int i=0;i< allDataCounts;){ // PageEmojiStyle pager = this.style.getPagerData(index); // if(pager != null){ // pagerDataList.add(pager); // int count = pager.getExceptItemCount(); // itemCounts += count; // if(itemCounts < allDataCounts){ // index++; // pager.setData(new ArrayList(this.style.getEmojiData().subList(i,i+count))); // }else { // pager.setData(new ArrayList(this.style.getEmojiData().subList(i,allDataCounts))); // break; // } // i += count; // } // } // } // // public EmojiStyle getEmojiStyle(){ // return style; // } // // public int getPagerCounts(){ // return pagerDataList.size(); // } // // /** // * // * @param index 此EmojiStyleWrapper中的pager下标,从0开始 // * @return // */ // public EmojiFragment getFragment(int index){ // if(index >= getPagerCounts()){ // return null; // } // EmojiFragment fragment = this.style.getCustomFragment(index); // fragment.setEmojiData(pagerDataList.get(index)); // return fragment; // } // // public String getStyleName(){ // return style.getStyleName(); // } // // @Override // public String getViewType() { // return hashCode()+""; // } // // public boolean isSelected() { // return isSelected; // } // // @Override // public int type() { // return ViewTab.T_EMOJI; // } // // /** // * 底部tab的图标View,tab 被选中时会调用view的 selected 事件 // */ // @Override // public View getTabView(Context context) { // if(tabItemView != null) return tabItemView; // tabItemView = style.getStyleIconView(context); // if(tabItemView == null){ // ImageButton imageView = new ImageButton(context); // imageView.setLayoutParams(new ViewGroup.LayoutParams(EmojiUtil.dip2px(context, 40), ViewGroup.LayoutParams.MATCH_PARENT)); // imageView.setBackgroundColor(Color.WHITE); // int resourceId = style.getStyleIcon(); // if (resourceId > 0) { // imageView.setImageResource(resourceId); // } // tabItemView = imageView; // } // return tabItemView; // } // // @Override // public void setTabSelected(boolean selected) { // tabItemView.setSelected(selected); // } // // public void setSelected(boolean selected) { // isSelected = selected; // if(!isSelected){ // curDisplayPageIndex = -1; // }else { // curDisplayPageIndex = 0; // } // } // // public void setCurDisplayPageIndex(int displayPageIndex){ // curDisplayPageIndex = displayPageIndex; // } // // public int getCurDisplayPageIndex() { // if(!isSelected){ // return -1; // } // return curDisplayPageIndex; // } // // @Override // public boolean equals(Object o) { // if(o instanceof EmojiStyleWrapper){ // EmojiStyleWrapper wrapper = (EmojiStyleWrapper) o; // return wrapper.getStyleName().equals(getStyleName()); // } // return false; // } // }
import android.support.annotation.Nullable; import org.nicky.libeasyemoji.emoji.EmojiStyleWrapper;
package org.nicky.libeasyemoji.emoji.interfaces; /** * Created by nickyang on 2017/4/1. */ public interface EmojiStyleChangeListener { enum TYPE{ ADD, DELETE, UPDATE }
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiStyleWrapper.java // public class EmojiStyleWrapper<T extends Parcelable> implements ViewTab{ // private View tabItemView; // private EmojiStyle style; // private boolean isSelected; // /** // * 表情的所有分页 // */ // private List<PageEmojiStyle> pagerDataList; // //如果当前style被选中,curDisplayPageIndex >= 0 , 表示当前显示页在style中的索引 // private int curDisplayPageIndex = -1; // // public EmojiStyleWrapper(EmojiStyle style){ // this.style = style; // setup(); // } // // private void setup(){ // int index = 0; // int allDataCounts = this.style.getEmojiData().size(); // int itemCounts = 0; // if(pagerDataList == null){ // pagerDataList = new ArrayList<>(10); // }else { // pagerDataList.clear(); // } // for(int i=0;i< allDataCounts;){ // PageEmojiStyle pager = this.style.getPagerData(index); // if(pager != null){ // pagerDataList.add(pager); // int count = pager.getExceptItemCount(); // itemCounts += count; // if(itemCounts < allDataCounts){ // index++; // pager.setData(new ArrayList(this.style.getEmojiData().subList(i,i+count))); // }else { // pager.setData(new ArrayList(this.style.getEmojiData().subList(i,allDataCounts))); // break; // } // i += count; // } // } // } // // public EmojiStyle getEmojiStyle(){ // return style; // } // // public int getPagerCounts(){ // return pagerDataList.size(); // } // // /** // * // * @param index 此EmojiStyleWrapper中的pager下标,从0开始 // * @return // */ // public EmojiFragment getFragment(int index){ // if(index >= getPagerCounts()){ // return null; // } // EmojiFragment fragment = this.style.getCustomFragment(index); // fragment.setEmojiData(pagerDataList.get(index)); // return fragment; // } // // public String getStyleName(){ // return style.getStyleName(); // } // // @Override // public String getViewType() { // return hashCode()+""; // } // // public boolean isSelected() { // return isSelected; // } // // @Override // public int type() { // return ViewTab.T_EMOJI; // } // // /** // * 底部tab的图标View,tab 被选中时会调用view的 selected 事件 // */ // @Override // public View getTabView(Context context) { // if(tabItemView != null) return tabItemView; // tabItemView = style.getStyleIconView(context); // if(tabItemView == null){ // ImageButton imageView = new ImageButton(context); // imageView.setLayoutParams(new ViewGroup.LayoutParams(EmojiUtil.dip2px(context, 40), ViewGroup.LayoutParams.MATCH_PARENT)); // imageView.setBackgroundColor(Color.WHITE); // int resourceId = style.getStyleIcon(); // if (resourceId > 0) { // imageView.setImageResource(resourceId); // } // tabItemView = imageView; // } // return tabItemView; // } // // @Override // public void setTabSelected(boolean selected) { // tabItemView.setSelected(selected); // } // // public void setSelected(boolean selected) { // isSelected = selected; // if(!isSelected){ // curDisplayPageIndex = -1; // }else { // curDisplayPageIndex = 0; // } // } // // public void setCurDisplayPageIndex(int displayPageIndex){ // curDisplayPageIndex = displayPageIndex; // } // // public int getCurDisplayPageIndex() { // if(!isSelected){ // return -1; // } // return curDisplayPageIndex; // } // // @Override // public boolean equals(Object o) { // if(o instanceof EmojiStyleWrapper){ // EmojiStyleWrapper wrapper = (EmojiStyleWrapper) o; // return wrapper.getStyleName().equals(getStyleName()); // } // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyleChangeListener.java import android.support.annotation.Nullable; import org.nicky.libeasyemoji.emoji.EmojiStyleWrapper; package org.nicky.libeasyemoji.emoji.interfaces; /** * Created by nickyang on 2017/4/1. */ public interface EmojiStyleChangeListener { enum TYPE{ ADD, DELETE, UPDATE }
void update(TYPE type, @Nullable EmojiStyleWrapper styleWrapper, int selectedPage);
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // }
import android.content.Context; import android.os.Parcelable; import android.view.View; import org.nicky.libeasyemoji.emoji.EmojiFragment; import java.util.List;
package org.nicky.libeasyemoji.emoji.interfaces; /** * Created by nickyang on 2017/4/1. */ public interface EmojiStyle<T extends Parcelable> { /** * 名称tag, 必须唯一 */ String getStyleName(); /** * 底部tab的图标 */ int getStyleIcon(); /** * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, * tab 被选中时会调用view的 selected 事件 */ View getStyleIconView(Context context); /** * 所有emoji的数据源 */ List<T> getEmojiData(); /** * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 * * @param index * @return */
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java // public abstract class EmojiFragment<T extends Parcelable> extends Fragment { // // protected OnEmojiconClickedListener mOnEmojiconClickedListener; // // protected Bundle saveState = new Bundle(); // // final public void setEmojiData(PageEmojiStyle<T> emojiData){ // saveState.putParcelable("emojiData",emojiData); // setData(emojiData); // } // // public abstract void setData(PageEmojiStyle<T> emojiData); // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // restoreData(savedInstanceState); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putBundle("saveState",saveState); // super.onSaveInstanceState(outState); // } // // @Override // public void onViewStateRestored(@Nullable Bundle savedInstanceState) { // super.onViewStateRestored(savedInstanceState); // restoreData(savedInstanceState); // } // // private void restoreData(Bundle savedInstanceState){ // if(savedInstanceState!=null && saveState.getParcelable("emojiData") == null){ // Bundle data = (Bundle) savedInstanceState.get("saveState"); // if(data != null&& data.getParcelable("emojiData")!=null){ // setEmojiData((PageEmojiStyle) data.getParcelable("emojiData")); // } // } // } // // public void setOnEmojiconClickedListener(OnEmojiconClickedListener listener){ // mOnEmojiconClickedListener = listener; // } // // public interface OnEmojiconClickedListener { // void onEmojiconClicked(String emojiCode); // void onBackspaceClicked(); // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/EmojiStyle.java import android.content.Context; import android.os.Parcelable; import android.view.View; import org.nicky.libeasyemoji.emoji.EmojiFragment; import java.util.List; package org.nicky.libeasyemoji.emoji.interfaces; /** * Created by nickyang on 2017/4/1. */ public interface EmojiStyle<T extends Parcelable> { /** * 名称tag, 必须唯一 */ String getStyleName(); /** * 底部tab的图标 */ int getStyleIcon(); /** * 底部tab的图标, 如果不为空,优先使用, 如果为空则使用 getStyleIcon() 返回的图标, * tab 被选中时会调用view的 selected 事件 */ View getStyleIconView(Context context); /** * 所有emoji的数据源 */ List<T> getEmojiData(); /** * 自定义的emoji显示页面, 一个 EmojiFragment 页面对应 一个 PageEmojiStyle 对象 * EmojiFragment 为展示页面, PageEmojiStyle 为一个页面的数据源 * * @param index * @return */
EmojiFragment getCustomFragment(int index);
nickyangjun/EasyEmoji
app/src/main/java/org/nicky/easyemoji/image/ImageLoader.java
// Path: app/src/main/java/org/nicky/easyemoji/image/transform/GlideCircleTransform.java // public class GlideCircleTransform extends BitmapTransformation { // public GlideCircleTransform(Context context) { // super(context); // } // // @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return circleCrop(pool, toTransform); // } // // private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // // TODO this could be acquired from the pool too // Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); // // Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // return result; // } // // @Override public String getId() { // return getClass().getName(); // } // } // // Path: app/src/main/java/org/nicky/easyemoji/image/transform/GlideRoundTransform.java // public class GlideRoundTransform extends BitmapTransformation { // // private static float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, 4); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private static Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override public String getId() { // return getClass().getName() + Math.round(radius); // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.bumptech.glide.GenericRequestBuilder; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.target.Target; import org.nicky.easyemoji.image.transform.GlideCircleTransform; import org.nicky.easyemoji.image.transform.GlideRoundTransform;
req.placeholder(defaultIcon); } req.into(new BitmapImageViewTarget(imageView) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { super.onResourceReady(resource, glideAnimation); if (listener != null) { listener.onLoadCompleted(uri, imageView, resource); } } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); if (listener != null) { listener.onLoadFailed(uri, imageView); } } }); } /** * 重载方法 加载展示圆形图片 * @param round 调用方传布尔值即视为要加载圆形图片 */ public void displayImage(Context context, String uri, ImageView view , int defaultIcon, boolean round) { Glide.with(context) .load(uri) .diskCacheStrategy(mDiskCacheStrategy)
// Path: app/src/main/java/org/nicky/easyemoji/image/transform/GlideCircleTransform.java // public class GlideCircleTransform extends BitmapTransformation { // public GlideCircleTransform(Context context) { // super(context); // } // // @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return circleCrop(pool, toTransform); // } // // private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // // TODO this could be acquired from the pool too // Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); // // Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // return result; // } // // @Override public String getId() { // return getClass().getName(); // } // } // // Path: app/src/main/java/org/nicky/easyemoji/image/transform/GlideRoundTransform.java // public class GlideRoundTransform extends BitmapTransformation { // // private static float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, 4); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private static Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override public String getId() { // return getClass().getName() + Math.round(radius); // } // } // Path: app/src/main/java/org/nicky/easyemoji/image/ImageLoader.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.bumptech.glide.GenericRequestBuilder; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.target.Target; import org.nicky.easyemoji.image.transform.GlideCircleTransform; import org.nicky.easyemoji.image.transform.GlideRoundTransform; req.placeholder(defaultIcon); } req.into(new BitmapImageViewTarget(imageView) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { super.onResourceReady(resource, glideAnimation); if (listener != null) { listener.onLoadCompleted(uri, imageView, resource); } } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); if (listener != null) { listener.onLoadFailed(uri, imageView); } } }); } /** * 重载方法 加载展示圆形图片 * @param round 调用方传布尔值即视为要加载圆形图片 */ public void displayImage(Context context, String uri, ImageView view , int defaultIcon, boolean round) { Glide.with(context) .load(uri) .diskCacheStrategy(mDiskCacheStrategy)
.transform(new GlideCircleTransform(context))
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // }
import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle;
package org.nicky.libeasyemoji.emoji; /** * Created by nickyang on 2017/4/1. */ public abstract class EmojiFragment<T extends Parcelable> extends Fragment { protected OnEmojiconClickedListener mOnEmojiconClickedListener; protected Bundle saveState = new Bundle();
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/PageEmojiStyle.java // public interface PageEmojiStyle<T extends Parcelable> extends Parcelable{ // int getExceptItemCount(); // void setData(List<T> data); // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/EmojiFragment.java import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import org.nicky.libeasyemoji.emoji.interfaces.PageEmojiStyle; package org.nicky.libeasyemoji.emoji; /** * Created by nickyang on 2017/4/1. */ public abstract class EmojiFragment<T extends Parcelable> extends Fragment { protected OnEmojiconClickedListener mOnEmojiconClickedListener; protected Bundle saveState = new Bundle();
final public void setEmojiData(PageEmojiStyle<T> emojiData){
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class IMEPanelLayout extends FrameLayout implements IPanelLayout { private static final String TAG = IMEPanelLayout.class.getSimpleName(); private boolean mIsHide = false;
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class IMEPanelLayout extends FrameLayout implements IPanelLayout { private static final String TAG = IMEPanelLayout.class.getSimpleName(); private boolean mIsHide = false;
IKeyboardManager mKeyboardManager;
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
} @Override public void setVisibility(int visibility) { if (filterSetVisibility(visibility)) { return; } super.setVisibility(visibility); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if(mOnPanelListener == null){ return; } if(visibility == VISIBLE && isVisible()){ mOnPanelListener.onPanelDisplay(true); }else { mOnPanelListener.onPanelDisplay(false); } } @Override public IMEPanelLayout getPanel() { return this; } @Override public void changeHeight(int panelHeight) {
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; } @Override public void setVisibility(int visibility) { if (filterSetVisibility(visibility)) { return; } super.setVisibility(visibility); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if(mOnPanelListener == null){ return; } if(visibility == VISIBLE && isVisible()){ mOnPanelListener.onPanelDisplay(true); }else { mOnPanelListener.onPanelDisplay(false); } } @Override public IMEPanelLayout getPanel() { return this; } @Override public void changeHeight(int panelHeight) {
ViewUtil.refreshHeight(this,panelHeight);
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
super.onVisibilityChanged(changedView, visibility); if(mOnPanelListener == null){ return; } if(visibility == VISIBLE && isVisible()){ mOnPanelListener.onPanelDisplay(true); }else { mOnPanelListener.onPanelDisplay(false); } } @Override public IMEPanelLayout getPanel() { return this; } @Override public void changeHeight(int panelHeight) { ViewUtil.refreshHeight(this,panelHeight); } @Override public void openPanel() { setVisibility(VISIBLE); } @Override public void closePanel() { setVisibility(GONE); }
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/OnPanelListener.java // public interface OnPanelListener { // void onPanelDisplay(boolean isShowing); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/IMEPanelLayout.java import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.widget.FrameLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.interfaces.OnPanelListener; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; super.onVisibilityChanged(changedView, visibility); if(mOnPanelListener == null){ return; } if(visibility == VISIBLE && isVisible()){ mOnPanelListener.onPanelDisplay(true); }else { mOnPanelListener.onPanelDisplay(false); } } @Override public IMEPanelLayout getPanel() { return this; } @Override public void changeHeight(int panelHeight) { ViewUtil.refreshHeight(this,panelHeight); } @Override public void openPanel() { setVisibility(VISIBLE); } @Override public void closePanel() { setVisibility(GONE); }
private OnPanelListener mOnPanelListener;
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus;
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus;
private IKeyboardManager mKeyboardManager;
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager;
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager;
IPanelLayout mPanelManager;
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager; IPanelLayout mPanelManager; public RootLayoutChangeHandler(final View imeLayout, IPanelLayout panelManager, IKeyboardManager keyboardManager){ mIMELayoutView = imeLayout;
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager; IPanelLayout mPanelManager; public RootLayoutChangeHandler(final View imeLayout, IPanelLayout panelManager, IKeyboardManager keyboardManager){ mIMELayoutView = imeLayout;
this.mStatusBarHeight = StatusBarHeightUtil.getStatusBarHeight(mIMELayoutView.getContext());
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // }
import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil;
package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager; IPanelLayout mPanelManager; public RootLayoutChangeHandler(final View imeLayout, IPanelLayout panelManager, IKeyboardManager keyboardManager){ mIMELayoutView = imeLayout; this.mStatusBarHeight = StatusBarHeightUtil.getStatusBarHeight(mIMELayoutView.getContext());
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IKeyboardManager.java // public interface IKeyboardManager { // boolean isKeyboardShowing(); // void setKeyboardShowing(boolean isShowing); // void openKeyboard(View view); // void closeKeyboard(View view); // void closeKeyboard(Activity activity); // ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelLayout target, OnKeyboardListener listener); // void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/interfaces/IPanelLayout.java // public interface IPanelLayout { // IMEPanelLayout getPanel(); // void changeHeight(int panelHeight); // int getHeight(); // void openPanel(); // void closePanel(); // void addOnPanelListener(OnPanelListener listener); // boolean isVisible(); // void setHide(); // void handleShow(); // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/StatusBarHeightUtil.java // public class StatusBarHeightUtil { // private static boolean INIT = false; // private static int STATUS_BAR_HEIGHT = 50; // // private final static String STATUS_BAR_DEF_PACKAGE = "android"; // private final static String STATUS_BAR_DEF_TYPE = "dimen"; // private final static String STATUS_BAR_NAME = "status_bar_height"; // // public static synchronized int getStatusBarHeight(final Context context) { // if (!INIT) { // int resourceId = context.getResources(). // getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE); // if (resourceId > 0) { // STATUS_BAR_HEIGHT = context.getResources().getDimensionPixelSize(resourceId); // INIT = true; // } // } // // return STATUS_BAR_HEIGHT; // } // } // // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/utils/ViewUtil.java // public class ViewUtil { // // public static boolean refreshHeight(final View view, final int aimHeight) { // if (view.isInEditMode()) { // return false; // } // // if (view.getHeight() == aimHeight) { // return false; // } // // if (Math.abs(view.getHeight() - aimHeight) == // StatusBarHeightUtil.getStatusBarHeight(view.getContext())) { // return false; // } // // final int validPanelHeight = KeyboardManagerImpl.getValidPanelHeight(view.getContext()); // ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); // if (layoutParams == null) { // layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // validPanelHeight); // view.setLayoutParams(layoutParams); // } else { // layoutParams.height = validPanelHeight; // view.requestLayout(); // } // // return true; // } // // public static boolean isFullScreen(final Activity activity) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public static boolean isTranslucentStatus(final Activity activity) { // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // return (activity.getWindow().getAttributes().flags & // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0; // } // return false; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public static boolean isFitsSystemWindows(final Activity activity){ // //noinspection SimplifiableIfStatement // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0). // getFitsSystemWindows(); // } // // return false; // } // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/EasyInput/RootLayoutChangeHandler.java import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import org.nicky.libeasyemoji.EasyInput.interfaces.IKeyboardManager; import org.nicky.libeasyemoji.EasyInput.interfaces.IPanelLayout; import org.nicky.libeasyemoji.EasyInput.utils.StatusBarHeightUtil; import org.nicky.libeasyemoji.EasyInput.utils.ViewUtil; package org.nicky.libeasyemoji.EasyInput; /** * Created by nickyang on 2017/3/22. */ public class RootLayoutChangeHandler { private final View mIMELayoutView; private int mOldHeight = -1; private final int mStatusBarHeight; private final boolean mIsTranslucentStatus; private IKeyboardManager mKeyboardManager; IPanelLayout mPanelManager; public RootLayoutChangeHandler(final View imeLayout, IPanelLayout panelManager, IKeyboardManager keyboardManager){ mIMELayoutView = imeLayout; this.mStatusBarHeight = StatusBarHeightUtil.getStatusBarHeight(mIMELayoutView.getContext());
this.mIsTranslucentStatus = ViewUtil.isTranslucentStatus((Activity) mIMELayoutView.getContext());
nickyangjun/EasyEmoji
libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/BottomStyleManager.java
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/ViewTab.java // public interface ViewTab { // int T_EMOJI = 0; //有表情页的Type // int T_VIEW = 1; //没有表情页的,自定义可点击view // // int type(); // // /** // * 底部tab的图标View,tab 被选中时会调用view的 selected 事件 // */ // View getTabView(Context context); // // void setTabSelected(boolean selected); // // /** // * 用于 recyclerView 的 viewType, 必须唯一, // * 这里返回的String类型必须可以转为int类型, 这里用String类型是用于与position区分, 因为ViewTab会存入LinkHaspMap集合里 // * // * @return // */ // String getViewType(); // // }
import android.content.Context; import android.view.ViewGroup; import org.nicky.libeasyemoji.emoji.interfaces.ViewTab;
package org.nicky.libeasyemoji.emoji; /** * Created by nickyang on 2017/9/18. * <p> * 底部的 tab item 管理,包括表情和自定义添加的按钮, 注意 自定义添加的 item 按钮只能添加到最后 */ public class BottomStyleManager { private EmojiStyleWrapperManager styleWrapperManager; private Context context; public BottomStyleManager(Context context, EmojiStyleWrapperManager styleWrapperManager) { this.context = context; this.styleWrapperManager = styleWrapperManager; }
// Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/interfaces/ViewTab.java // public interface ViewTab { // int T_EMOJI = 0; //有表情页的Type // int T_VIEW = 1; //没有表情页的,自定义可点击view // // int type(); // // /** // * 底部tab的图标View,tab 被选中时会调用view的 selected 事件 // */ // View getTabView(Context context); // // void setTabSelected(boolean selected); // // /** // * 用于 recyclerView 的 viewType, 必须唯一, // * 这里返回的String类型必须可以转为int类型, 这里用String类型是用于与position区分, 因为ViewTab会存入LinkHaspMap集合里 // * // * @return // */ // String getViewType(); // // } // Path: libeasyemoji/src/main/java/org/nicky/libeasyemoji/emoji/BottomStyleManager.java import android.content.Context; import android.view.ViewGroup; import org.nicky.libeasyemoji.emoji.interfaces.ViewTab; package org.nicky.libeasyemoji.emoji; /** * Created by nickyang on 2017/9/18. * <p> * 底部的 tab item 管理,包括表情和自定义添加的按钮, 注意 自定义添加的 item 按钮只能添加到最后 */ public class BottomStyleManager { private EmojiStyleWrapperManager styleWrapperManager; private Context context; public BottomStyleManager(Context context, EmojiStyleWrapperManager styleWrapperManager) { this.context = context; this.styleWrapperManager = styleWrapperManager; }
ViewTab onCreateViewHolder(ViewGroup parent, int viewType) {
pangliang/MirServer-Netty
GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/engine/MagicEngine.java
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdMagic.java // @Entity // public class StdMagic implements Parcelable { // // public static final int NAME_BYTE_SIZE = 12; // // @Id // @GeneratedValue // public int id; // // public int magicId; // public String name; // public short effectType; // public short effect; // public short spell; // public short power; // public short maxPower; // public short upSpell; // public short upPower; // public short upMaxPower; // public Job job; // public int delay; // public String scriptName; // // @Override // public void readPacket(ByteBuf in) throws WrongFormatException { // // } // // @Override // public void writePacket(ByteBuf out) { // out.writeShort(id); // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > NAME_BYTE_SIZE ? NAME_BYTE_SIZE : nameBytes.length); // out.writeBytes(new byte[NAME_BYTE_SIZE - nameBytes.length]); // // out.writeByte(effectType); // out.writeByte(effect); // out.writeByte(0); // out.writeShort(spell); // out.writeShort(power); // out.writeBytes(new byte[]{(byte) 11, (byte) 12, (byte) 13, (byte) 14}); // out.writeShort(0); // // // 各技能等级最高修炼点 // out.writeInt(10000); // out.writeInt(20000); // out.writeInt(30000); // out.writeInt(40000); // // out.writeByte(2); // // out.writeByte(job.ordinal()); // out.writeShort(id); // out.writeInt(delay); // // out.writeByte(upSpell); // out.writeByte(upPower); // out.writeShort(maxPower); // out.writeByte(upMaxPower); // // nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > 18 ? 18 : nameBytes.length); // out.writeBytes(new byte[18 - nameBytes.length]); // } // }
import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.gameserver.entities.StdMagic; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.zhaoxiaodan.mirserver.gameserver.engine; public class MagicEngine { private static Map<String, StdMagic> magicNames = new HashMap<>(); public synchronized static void reload() throws Exception {
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdMagic.java // @Entity // public class StdMagic implements Parcelable { // // public static final int NAME_BYTE_SIZE = 12; // // @Id // @GeneratedValue // public int id; // // public int magicId; // public String name; // public short effectType; // public short effect; // public short spell; // public short power; // public short maxPower; // public short upSpell; // public short upPower; // public short upMaxPower; // public Job job; // public int delay; // public String scriptName; // // @Override // public void readPacket(ByteBuf in) throws WrongFormatException { // // } // // @Override // public void writePacket(ByteBuf out) { // out.writeShort(id); // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > NAME_BYTE_SIZE ? NAME_BYTE_SIZE : nameBytes.length); // out.writeBytes(new byte[NAME_BYTE_SIZE - nameBytes.length]); // // out.writeByte(effectType); // out.writeByte(effect); // out.writeByte(0); // out.writeShort(spell); // out.writeShort(power); // out.writeBytes(new byte[]{(byte) 11, (byte) 12, (byte) 13, (byte) 14}); // out.writeShort(0); // // // 各技能等级最高修炼点 // out.writeInt(10000); // out.writeInt(20000); // out.writeInt(30000); // out.writeInt(40000); // // out.writeByte(2); // // out.writeByte(job.ordinal()); // out.writeShort(id); // out.writeInt(delay); // // out.writeByte(upSpell); // out.writeByte(upPower); // out.writeShort(maxPower); // out.writeByte(upMaxPower); // // nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > 18 ? 18 : nameBytes.length); // out.writeBytes(new byte[18 - nameBytes.length]); // } // } // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/engine/MagicEngine.java import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.gameserver.entities.StdMagic; import java.util.HashMap; import java.util.List; import java.util.Map; package com.zhaoxiaodan.mirserver.gameserver.engine; public class MagicEngine { private static Map<String, StdMagic> magicNames = new HashMap<>(); public synchronized static void reload() throws Exception {
List<StdMagic> list = DB.query(StdMagic.class);
pangliang/MirServer-Netty
Tools/src/main/java/com/zhaoxiaodan/mirserver/tools/ImportDB.java
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // }
import com.zhaoxiaodan.mirserver.db.DB; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
package com.zhaoxiaodan.mirserver.tools; public class ImportDB { public Map<String, String> tables = new HashMap<String, String>() { { put("SERVERINFO", "数据文件/MIR2_PUBLIC_SERVERINFO.csv"); put("STDITEM", "数据文件/MIR2_PUBLIC_STDITEM.csv"); put("STDMONSTER", "数据文件/MIR2_PUBLIC_STDMONSTER.csv"); put("STDMAGIC", "数据文件/MIR2_PUBLIC_STDMAGIC.csv"); } }; /** * 因为Hibernate创建的表的字段顺序问题, 利用反射导入原DBC数据库导出的文件 * * @throws Exception */ public void importAll() { try {
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // Path: Tools/src/main/java/com/zhaoxiaodan/mirserver/tools/ImportDB.java import com.zhaoxiaodan.mirserver.db.DB; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; package com.zhaoxiaodan.mirserver.tools; public class ImportDB { public Map<String, String> tables = new HashMap<String, String>() { { put("SERVERINFO", "数据文件/MIR2_PUBLIC_SERVERINFO.csv"); put("STDITEM", "数据文件/MIR2_PUBLIC_STDITEM.csv"); put("STDMONSTER", "数据文件/MIR2_PUBLIC_STDMONSTER.csv"); put("STDMAGIC", "数据文件/MIR2_PUBLIC_STDMAGIC.csv"); } }; /** * 因为Hibernate创建的表的字段顺序问题, 利用反射导入原DBC数据库导出的文件 * * @throws Exception */ public void importAll() { try {
DB.init();
pangliang/MirServer-Netty
GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdItem.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/types/ItemAttr.java // @Embeddable // public class ItemAttr implements Parcelable, Cloneable { // // public static final int NAME_BYTE_SIZE = 14; // // public String name; // public byte stdMode; // public short shape; // public byte weight; // public byte anicount; // public byte source; // public byte reserved; // public byte needIdentify; // public short looks; // /** // * 耐久度, 客户端显示 int(duraMax/1000) 的值 // */ // public int duraMax; // public short reserved1; // public short AC; // public short AC2; // public short MAC; // public short MAC2; // public short DC; // public short DC2; // public short MC; // public short MC2; // public short SC; // public short SC2; // public int need; // public int needLevel; // public int price; // public int stock; // public String description; // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // // } // // public ItemAttr clone() { // try { // return (ItemAttr) super.clone(); // } catch (CloneNotSupportedException e) { // return null; // } // } // // public void writePacket(ByteBuf out) { // oldVersion(out); // } // // public void newVersion(ByteBuf out) { // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > NAME_BYTE_SIZE ? NAME_BYTE_SIZE : nameBytes.length); // // out.writeBytes(new byte[NAME_BYTE_SIZE - nameBytes.length]); // // out.writeByte(stdMode); // out.writeByte(shape); // out.writeByte(weight); // out.writeByte(anicount); // out.writeByte(source); // out.writeByte(reserved); // out.writeByte(needIdentify); // out.writeShort(looks); // out.writeShort(duraMax); // // out.writeShort(reserved1); // // out.writeInt(NumUtil.makeLong(AC, AC2)); // out.writeInt(NumUtil.makeLong(MAC, MAC2)); // out.writeInt(NumUtil.makeLong(DC, DC2)); // out.writeInt(NumUtil.makeLong(MC, MC2)); // out.writeInt(NumUtil.makeLong(SC, SC2)); // // out.writeByte(need); // out.writeByte(needLevel); // out.writeShort(0); // out.writeInt(price); // out.writeInt(stock); // } // // private void oldVersion(ByteBuf out) { // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes); // // out.writeBytes(new byte[14 - nameBytes.length]); // // out.writeByte(stdMode); // out.writeByte(shape); // out.writeByte(weight); // out.writeByte(anicount); // out.writeByte(source); // out.writeByte(reserved); // out.writeByte(needIdentify); // out.writeShort(looks); // out.writeShort(duraMax); // // out.writeShort(NumUtil.makeWord((byte) AC, (byte) AC2)); // out.writeShort(NumUtil.makeWord((byte) MAC, (byte) MAC2)); // out.writeShort(NumUtil.makeWord((byte) DC, (byte) DC2)); // out.writeShort(NumUtil.makeWord((byte) MC, (byte) MC2)); // out.writeShort(NumUtil.makeWord((byte) SC, (byte) SC2)); // out.writeByte(need); // out.writeByte(needLevel); // out.writeShort(0); // out.writeInt(price); // } // }
import com.zhaoxiaodan.mirserver.gameserver.types.ItemAttr; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
package com.zhaoxiaodan.mirserver.gameserver.entities; @Entity public class StdItem { @Id @GeneratedValue public int id;
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/types/ItemAttr.java // @Embeddable // public class ItemAttr implements Parcelable, Cloneable { // // public static final int NAME_BYTE_SIZE = 14; // // public String name; // public byte stdMode; // public short shape; // public byte weight; // public byte anicount; // public byte source; // public byte reserved; // public byte needIdentify; // public short looks; // /** // * 耐久度, 客户端显示 int(duraMax/1000) 的值 // */ // public int duraMax; // public short reserved1; // public short AC; // public short AC2; // public short MAC; // public short MAC2; // public short DC; // public short DC2; // public short MC; // public short MC2; // public short SC; // public short SC2; // public int need; // public int needLevel; // public int price; // public int stock; // public String description; // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // // } // // public ItemAttr clone() { // try { // return (ItemAttr) super.clone(); // } catch (CloneNotSupportedException e) { // return null; // } // } // // public void writePacket(ByteBuf out) { // oldVersion(out); // } // // public void newVersion(ByteBuf out) { // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes, 0, nameBytes.length > NAME_BYTE_SIZE ? NAME_BYTE_SIZE : nameBytes.length); // // out.writeBytes(new byte[NAME_BYTE_SIZE - nameBytes.length]); // // out.writeByte(stdMode); // out.writeByte(shape); // out.writeByte(weight); // out.writeByte(anicount); // out.writeByte(source); // out.writeByte(reserved); // out.writeByte(needIdentify); // out.writeShort(looks); // out.writeShort(duraMax); // // out.writeShort(reserved1); // // out.writeInt(NumUtil.makeLong(AC, AC2)); // out.writeInt(NumUtil.makeLong(MAC, MAC2)); // out.writeInt(NumUtil.makeLong(DC, DC2)); // out.writeInt(NumUtil.makeLong(MC, MC2)); // out.writeInt(NumUtil.makeLong(SC, SC2)); // // out.writeByte(need); // out.writeByte(needLevel); // out.writeShort(0); // out.writeInt(price); // out.writeInt(stock); // } // // private void oldVersion(ByteBuf out) { // byte[] nameBytes = name.getBytes(); // out.writeByte(nameBytes.length); // out.writeBytes(nameBytes); // // out.writeBytes(new byte[14 - nameBytes.length]); // // out.writeByte(stdMode); // out.writeByte(shape); // out.writeByte(weight); // out.writeByte(anicount); // out.writeByte(source); // out.writeByte(reserved); // out.writeByte(needIdentify); // out.writeShort(looks); // out.writeShort(duraMax); // // out.writeShort(NumUtil.makeWord((byte) AC, (byte) AC2)); // out.writeShort(NumUtil.makeWord((byte) MAC, (byte) MAC2)); // out.writeShort(NumUtil.makeWord((byte) DC, (byte) DC2)); // out.writeShort(NumUtil.makeWord((byte) MC, (byte) MC2)); // out.writeShort(NumUtil.makeWord((byte) SC, (byte) SC2)); // out.writeByte(need); // out.writeByte(needLevel); // out.writeShort(0); // out.writeInt(price); // } // } // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdItem.java import com.zhaoxiaodan.mirserver.gameserver.types.ItemAttr; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; package com.zhaoxiaodan.mirserver.gameserver.entities; @Entity public class StdItem { @Id @GeneratedValue public int id;
public ItemAttr attr;
pangliang/MirServer-Netty
LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/UserHandler.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket;
package com.zhaoxiaodan.mirserver.loginserver.handlers; public abstract class UserHandler extends Handler { public final void onPacket(ClientPacket packet) throws Exception {
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/UserHandler.java import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; package com.zhaoxiaodan.mirserver.loginserver.handlers; public abstract class UserHandler extends Handler { public final void onPacket(ClientPacket packet) throws Exception {
User user = (User) session.get("user");
pangliang/MirServer-Netty
GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/Config.java
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // }
import com.zhaoxiaodan.mirserver.db.DB; import javax.persistence.Entity; import javax.persistence.Table; import java.util.List;
package com.zhaoxiaodan.mirserver.gameserver.entities; public class Config { /** * 用户动作间隔, 防止加速 */ public static int PLAYER_ACTION_INTERVAL_TIME = 200; public static int OBJECT_SPEED_BASE = 3000; public static String GAME_GOLD_NAME = "游戏金币"; public static String GAME_POINT_NAME = "游戏点数"; public static int DEFAULT_VIEW_DISTANCE = 5; public static int EXP_MULTIPLE = 10; public static int MONSTER_DROP_RATE_BASE = 10000; public static int MONSTER_BONES_DISAPPEAR_TIME = 10 * 1000; public static int ENGINE_TICK_INTERVAL_TIME = 1000; public static int PLAYER_CHECK_PICKUP_ITEM_INTERVAL_TIME = 1000; public static int DROP_ITEM_PROTECT_TIME = 30 * 1000; public static int DROP_ITEM_LIFE_TIME = 3 * 60 * 1000; public static int COMPOSE_REQURE_NUMBER = 3; public static int COMPOSE_REQURE_GOLD = 10000; @Entity @Table(name = "Config") public static class ConfigEntity { public String key; public Object value; } public static void reload() throws Exception {
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/Config.java import com.zhaoxiaodan.mirserver.db.DB; import javax.persistence.Entity; import javax.persistence.Table; import java.util.List; package com.zhaoxiaodan.mirserver.gameserver.entities; public class Config { /** * 用户动作间隔, 防止加速 */ public static int PLAYER_ACTION_INTERVAL_TIME = 200; public static int OBJECT_SPEED_BASE = 3000; public static String GAME_GOLD_NAME = "游戏金币"; public static String GAME_POINT_NAME = "游戏点数"; public static int DEFAULT_VIEW_DISTANCE = 5; public static int EXP_MULTIPLE = 10; public static int MONSTER_DROP_RATE_BASE = 10000; public static int MONSTER_BONES_DISAPPEAR_TIME = 10 * 1000; public static int ENGINE_TICK_INTERVAL_TIME = 1000; public static int PLAYER_CHECK_PICKUP_ITEM_INTERVAL_TIME = 1000; public static int DROP_ITEM_PROTECT_TIME = 30 * 1000; public static int DROP_ITEM_LIFE_TIME = 3 * 60 * 1000; public static int COMPOSE_REQURE_NUMBER = 3; public static int COMPOSE_REQURE_GOLD = 10000; @Entity @Table(name = "Config") public static class ConfigEntity { public String key; public Object value; } public static void reload() throws Exception {
List configEntityList = DB.query(ConfigEntity.class);
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ServerPacket.java // public class ServerPacket extends Packet { // // public ServerPacket() { // super(); // } // // public ServerPacket(int recog, Protocol protocol, short p1, short p2, short p3) { // super(recog, protocol, p1, p2, p3); // } // // public ServerPacket(int recog, Protocol protocol) { // this(recog, protocol, (short) 0, (short) 0, (short) 0); // } // // public ServerPacket(Protocol protocol) { // super(protocol); // } // }
import com.zhaoxiaodan.mirserver.network.packets.ServerPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.zhaoxiaodan.mirserver.network; public class Session { private static Logger logger = LogManager.getLogger(Session.class); private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); private final ChannelHandlerContext socket; private Session(ChannelHandlerContext ctx){ this.socket = ctx; } public void remove() { logger.debug("remove session for {}", socket.toString()); sessions.remove(socket.channel().remoteAddress().toString()); }
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ServerPacket.java // public class ServerPacket extends Packet { // // public ServerPacket() { // super(); // } // // public ServerPacket(int recog, Protocol protocol, short p1, short p2, short p3) { // super(recog, protocol, p1, p2, p3); // } // // public ServerPacket(int recog, Protocol protocol) { // this(recog, protocol, (short) 0, (short) 0, (short) 0); // } // // public ServerPacket(Protocol protocol) { // super(protocol); // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java import com.zhaoxiaodan.mirserver.network.packets.ServerPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.zhaoxiaodan.mirserver.network; public class Session { private static Logger logger = LogManager.getLogger(Session.class); private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); private final ChannelHandlerContext socket; private Session(ChannelHandlerContext ctx){ this.socket = ctx; } public void remove() { logger.debug("remove session for {}", socket.toString()); sessions.remove(socket.channel().remoteAddress().toString()); }
public void sendPacket(ServerPacket msg){
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/PacketDispatcher.java
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.*;
package com.zhaoxiaodan.mirserver.network; public class PacketDispatcher extends ChannelHandlerAdapter { //handler处理器所在的包名 private final String handlerPackageName; public PacketDispatcher(String handlerPackageName) { this.handlerPackageName = handlerPackageName; } @Override public void channelRead(ChannelHandlerContext ctx, Object pakcet) throws Exception {
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/PacketDispatcher.java import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.*; package com.zhaoxiaodan.mirserver.network; public class PacketDispatcher extends ChannelHandlerAdapter { //handler处理器所在的包名 private final String handlerPackageName; public PacketDispatcher(String handlerPackageName) { this.handlerPackageName = handlerPackageName; } @Override public void channelRead(ChannelHandlerContext ctx, Object pakcet) throws Exception {
if (!(pakcet instanceof ClientPacket)) {
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/encoder/ClientPacketBit6Encoder.java
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Bit6Coder.java // public class Bit6Coder { // public static byte[] encoder6BitBuf(byte[] src) { // int len = src.length; // int destLen = (len/3)*4+10; // byte[] dest = new byte[destLen]; // int destPos = 0, resetCount = 0; // byte chMade = 0, chRest = 0; // // for (int i = 0; i < len ; i++) { // if (destPos >= destLen) // break; // // chMade = (byte) ((chRest | ((src[i] & 0xff) >> (2 + resetCount))) & 0x3f); // chRest = (byte) ((((src[i] & 0xff) << (8 - (2 + resetCount))) >> 2) & 0x3f); // // resetCount += 2; // if(resetCount < 6) // { // dest[destPos++] = (byte)(chMade + 0x3c); // }else{ // if(destPos < destLen - 1) // { // dest[destPos++] = (byte)(chMade + 0x3c); // dest[destPos++] = (byte)(chRest + 0x3c); // }else { // dest[destPos++] = (byte)(chMade + 0x3c); // } // // resetCount = 0; // chRest = 0; // } // } // if(resetCount > 0 ) // dest[destPos++] = (byte)(chRest + 0x3c); // // dest[destPos] = 0; // return Arrays.copyOfRange(dest,0,destPos); // // } // // public static byte[] decode6BitBuf(byte[] src) { // final byte[] Decode6BitMask = {(byte) 0xfc, (byte) 0xf8, (byte) 0xf0, (byte) 0xe0, (byte) 0xc0}; // // int len = src.length; // byte[] dest = new byte[len*3/4]; // // int destPos = 0; // int bitPos = 2; // int madeBit = 0; // // byte ch = 0, chCode = 0, tmp = 0; // // for (int i = 0; i < len; i++) { // if ((src[i] - 0x3c) >= 0) { // ch = (byte) (src[i] - 0x3c); // } else { // destPos = 0; // break; // } // // if (destPos >= dest.length) // break; // // if (madeBit + 6 >= 8) { // chCode = (byte) (tmp | ((ch & 0x3f) >> (6 - bitPos))); // dest[destPos++] = chCode; // // madeBit = 0; // if (bitPos < 6) { // bitPos += 2; // } else { // bitPos = 2; // continue; // } // } // // tmp = (byte) ((ch << bitPos) & Decode6BitMask[bitPos - 2]); // // madeBit += 8 - bitPos; // } // // return dest; // // } // }
import com.zhaoxiaodan.mirserver.network.Bit6Coder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import java.util.List;
package com.zhaoxiaodan.mirserver.network.encoder; public class ClientPacketBit6Encoder extends MessageToMessageEncoder<ByteBuf> { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeByte('#'); // 加上 头分割符 buf.writeByte(in.readByte()); byte[] body = new byte[in.readableBytes()]; in.readBytes(body);
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Bit6Coder.java // public class Bit6Coder { // public static byte[] encoder6BitBuf(byte[] src) { // int len = src.length; // int destLen = (len/3)*4+10; // byte[] dest = new byte[destLen]; // int destPos = 0, resetCount = 0; // byte chMade = 0, chRest = 0; // // for (int i = 0; i < len ; i++) { // if (destPos >= destLen) // break; // // chMade = (byte) ((chRest | ((src[i] & 0xff) >> (2 + resetCount))) & 0x3f); // chRest = (byte) ((((src[i] & 0xff) << (8 - (2 + resetCount))) >> 2) & 0x3f); // // resetCount += 2; // if(resetCount < 6) // { // dest[destPos++] = (byte)(chMade + 0x3c); // }else{ // if(destPos < destLen - 1) // { // dest[destPos++] = (byte)(chMade + 0x3c); // dest[destPos++] = (byte)(chRest + 0x3c); // }else { // dest[destPos++] = (byte)(chMade + 0x3c); // } // // resetCount = 0; // chRest = 0; // } // } // if(resetCount > 0 ) // dest[destPos++] = (byte)(chRest + 0x3c); // // dest[destPos] = 0; // return Arrays.copyOfRange(dest,0,destPos); // // } // // public static byte[] decode6BitBuf(byte[] src) { // final byte[] Decode6BitMask = {(byte) 0xfc, (byte) 0xf8, (byte) 0xf0, (byte) 0xe0, (byte) 0xc0}; // // int len = src.length; // byte[] dest = new byte[len*3/4]; // // int destPos = 0; // int bitPos = 2; // int madeBit = 0; // // byte ch = 0, chCode = 0, tmp = 0; // // for (int i = 0; i < len; i++) { // if ((src[i] - 0x3c) >= 0) { // ch = (byte) (src[i] - 0x3c); // } else { // destPos = 0; // break; // } // // if (destPos >= dest.length) // break; // // if (madeBit + 6 >= 8) { // chCode = (byte) (tmp | ((ch & 0x3f) >> (6 - bitPos))); // dest[destPos++] = chCode; // // madeBit = 0; // if (bitPos < 6) { // bitPos += 2; // } else { // bitPos = 2; // continue; // } // } // // tmp = (byte) ((ch << bitPos) & Decode6BitMask[bitPos - 2]); // // madeBit += 8 - bitPos; // } // // return dest; // // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/encoder/ClientPacketBit6Encoder.java import com.zhaoxiaodan.mirserver.network.Bit6Coder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import java.util.List; package com.zhaoxiaodan.mirserver.network.encoder; public class ClientPacketBit6Encoder extends MessageToMessageEncoder<ByteBuf> { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeByte('#'); // 加上 头分割符 buf.writeByte(in.readByte()); byte[] body = new byte[in.readableBytes()]; in.readBytes(body);
buf.writeBytes(Bit6Coder.encoder6BitBuf(body));
pangliang/MirServer-Netty
GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdMagic.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/types/Job.java // public enum Job { // /** // * 战士 // */ // Warrior, // /** // * 法师 // */ // Wizard, // /** // * 道士 // */ // Taoist, // /** // * 英雄 // */ // Hero // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/Parcelable.java // public interface Parcelable { // // public void readPacket(ByteBuf in) throws WrongFormatException; // // public void writePacket(ByteBuf out); // // public class WrongFormatException extends Exception { // // public WrongFormatException() { // // } // // public WrongFormatException(String msg) { // super(msg); // } // } // }
import com.zhaoxiaodan.mirserver.gameserver.types.Job; import com.zhaoxiaodan.mirserver.network.packets.Parcelable; import io.netty.buffer.ByteBuf; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
package com.zhaoxiaodan.mirserver.gameserver.entities; @Entity public class StdMagic implements Parcelable { public static final int NAME_BYTE_SIZE = 12; @Id @GeneratedValue public int id; public int magicId; public String name; public short effectType; public short effect; public short spell; public short power; public short maxPower; public short upSpell; public short upPower; public short upMaxPower;
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/types/Job.java // public enum Job { // /** // * 战士 // */ // Warrior, // /** // * 法师 // */ // Wizard, // /** // * 道士 // */ // Taoist, // /** // * 英雄 // */ // Hero // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/Parcelable.java // public interface Parcelable { // // public void readPacket(ByteBuf in) throws WrongFormatException; // // public void writePacket(ByteBuf out); // // public class WrongFormatException extends Exception { // // public WrongFormatException() { // // } // // public WrongFormatException(String msg) { // super(msg); // } // } // } // Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/StdMagic.java import com.zhaoxiaodan.mirserver.gameserver.types.Job; import com.zhaoxiaodan.mirserver.network.packets.Parcelable; import io.netty.buffer.ByteBuf; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; package com.zhaoxiaodan.mirserver.gameserver.entities; @Entity public class StdMagic implements Parcelable { public static final int NAME_BYTE_SIZE = 12; @Id @GeneratedValue public int id; public int magicId; public String name; public short effectType; public short effect; public short spell; public short power; public short maxPower; public short upSpell; public short upPower; public short upMaxPower;
public Job job;
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.resource.transaction.spi.TransactionStatus;
package com.zhaoxiaodan.mirserver.network; public abstract class Handler { protected Logger logger = LogManager.getLogger(this.getClass().getName()); protected Session session;
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.resource.transaction.spi.TransactionStatus; package com.zhaoxiaodan.mirserver.network; public abstract class Handler { protected Logger logger = LogManager.getLogger(this.getClass().getName()); protected Session session;
protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception {
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.resource.transaction.spi.TransactionStatus;
package com.zhaoxiaodan.mirserver.network; public abstract class Handler { protected Logger logger = LogManager.getLogger(this.getClass().getName()); protected Session session; protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { session = Session.getSession(ctx); if(null == session){ logger.debug("new session for {}",ctx); session = Session.create(ctx); }
// Path: DB/src/main/java/com/zhaoxiaodan/mirserver/db/DB.java // public class DB { // // private static SessionFactory ourSessionFactory; // private static ServiceRegistry serviceRegistry; // // public static void init() throws Exception { // Configuration configuration = new Configuration(); // configuration.configure(); // // serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // ourSessionFactory = configuration.buildSessionFactory(); // } // // public static Session getSession() { // return ourSessionFactory.getCurrentSession(); // } // // public static void save(Object object) { // getSession().save(object); // } // // public static void update(Object object) { // getSession().update(object); // } // // public static void delete(Object object) { // getSession().delete(object); // } // // public static List query(Class clazz, SimpleExpression... simpleExpressions) { // Criteria criteria = getSession().createCriteria(clazz); // for (SimpleExpression simpleExpression : simpleExpressions) { // criteria.add(simpleExpression); // } // List result = criteria.list(); // return result; // } // // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java import com.zhaoxiaodan.mirserver.db.DB; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.resource.transaction.spi.TransactionStatus; package com.zhaoxiaodan.mirserver.network; public abstract class Handler { protected Logger logger = LogManager.getLogger(this.getClass().getName()); protected Session session; protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { session = Session.getSession(ctx); if(null == session){ logger.debug("new session for {}",ctx); session = Session.create(ctx); }
DB.getSession().getTransaction().begin();
pangliang/MirServer-Netty
Core/src/main/java/com/zhaoxiaodan/mirserver/network/decoder/ClientPacketBit6Decoder.java
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Bit6Coder.java // public class Bit6Coder { // public static byte[] encoder6BitBuf(byte[] src) { // int len = src.length; // int destLen = (len/3)*4+10; // byte[] dest = new byte[destLen]; // int destPos = 0, resetCount = 0; // byte chMade = 0, chRest = 0; // // for (int i = 0; i < len ; i++) { // if (destPos >= destLen) // break; // // chMade = (byte) ((chRest | ((src[i] & 0xff) >> (2 + resetCount))) & 0x3f); // chRest = (byte) ((((src[i] & 0xff) << (8 - (2 + resetCount))) >> 2) & 0x3f); // // resetCount += 2; // if(resetCount < 6) // { // dest[destPos++] = (byte)(chMade + 0x3c); // }else{ // if(destPos < destLen - 1) // { // dest[destPos++] = (byte)(chMade + 0x3c); // dest[destPos++] = (byte)(chRest + 0x3c); // }else { // dest[destPos++] = (byte)(chMade + 0x3c); // } // // resetCount = 0; // chRest = 0; // } // } // if(resetCount > 0 ) // dest[destPos++] = (byte)(chRest + 0x3c); // // dest[destPos] = 0; // return Arrays.copyOfRange(dest,0,destPos); // // } // // public static byte[] decode6BitBuf(byte[] src) { // final byte[] Decode6BitMask = {(byte) 0xfc, (byte) 0xf8, (byte) 0xf0, (byte) 0xe0, (byte) 0xc0}; // // int len = src.length; // byte[] dest = new byte[len*3/4]; // // int destPos = 0; // int bitPos = 2; // int madeBit = 0; // // byte ch = 0, chCode = 0, tmp = 0; // // for (int i = 0; i < len; i++) { // if ((src[i] - 0x3c) >= 0) { // ch = (byte) (src[i] - 0x3c); // } else { // destPos = 0; // break; // } // // if (destPos >= dest.length) // break; // // if (madeBit + 6 >= 8) { // chCode = (byte) (tmp | ((ch & 0x3f) >> (6 - bitPos))); // dest[destPos++] = chCode; // // madeBit = 0; // if (bitPos < 6) { // bitPos += 2; // } else { // bitPos = 2; // continue; // } // } // // tmp = (byte) ((ch << bitPos) & Decode6BitMask[bitPos - 2]); // // madeBit += 8 - bitPos; // } // // return dest; // // } // }
import com.zhaoxiaodan.mirserver.network.Bit6Coder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import java.util.List;
package com.zhaoxiaodan.mirserver.network.decoder; /** * 解密, request有cmdIndex , response没有 */ public class ClientPacketBit6Decoder extends MessageToMessageDecoder<ByteBuf> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = Unpooled.buffer(); in.readByte(); // # , 在这里就去掉 头尾 buf.writeByte(in.readByte()); //cmdIndex byte[] bodyBytes = new byte[in.readableBytes() - 1]; in.readBytes(bodyBytes);
// Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Bit6Coder.java // public class Bit6Coder { // public static byte[] encoder6BitBuf(byte[] src) { // int len = src.length; // int destLen = (len/3)*4+10; // byte[] dest = new byte[destLen]; // int destPos = 0, resetCount = 0; // byte chMade = 0, chRest = 0; // // for (int i = 0; i < len ; i++) { // if (destPos >= destLen) // break; // // chMade = (byte) ((chRest | ((src[i] & 0xff) >> (2 + resetCount))) & 0x3f); // chRest = (byte) ((((src[i] & 0xff) << (8 - (2 + resetCount))) >> 2) & 0x3f); // // resetCount += 2; // if(resetCount < 6) // { // dest[destPos++] = (byte)(chMade + 0x3c); // }else{ // if(destPos < destLen - 1) // { // dest[destPos++] = (byte)(chMade + 0x3c); // dest[destPos++] = (byte)(chRest + 0x3c); // }else { // dest[destPos++] = (byte)(chMade + 0x3c); // } // // resetCount = 0; // chRest = 0; // } // } // if(resetCount > 0 ) // dest[destPos++] = (byte)(chRest + 0x3c); // // dest[destPos] = 0; // return Arrays.copyOfRange(dest,0,destPos); // // } // // public static byte[] decode6BitBuf(byte[] src) { // final byte[] Decode6BitMask = {(byte) 0xfc, (byte) 0xf8, (byte) 0xf0, (byte) 0xe0, (byte) 0xc0}; // // int len = src.length; // byte[] dest = new byte[len*3/4]; // // int destPos = 0; // int bitPos = 2; // int madeBit = 0; // // byte ch = 0, chCode = 0, tmp = 0; // // for (int i = 0; i < len; i++) { // if ((src[i] - 0x3c) >= 0) { // ch = (byte) (src[i] - 0x3c); // } else { // destPos = 0; // break; // } // // if (destPos >= dest.length) // break; // // if (madeBit + 6 >= 8) { // chCode = (byte) (tmp | ((ch & 0x3f) >> (6 - bitPos))); // dest[destPos++] = chCode; // // madeBit = 0; // if (bitPos < 6) { // bitPos += 2; // } else { // bitPos = 2; // continue; // } // } // // tmp = (byte) ((ch << bitPos) & Decode6BitMask[bitPos - 2]); // // madeBit += 8 - bitPos; // } // // return dest; // // } // } // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/decoder/ClientPacketBit6Decoder.java import com.zhaoxiaodan.mirserver.network.Bit6Coder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import java.util.List; package com.zhaoxiaodan.mirserver.network.decoder; /** * 解密, request有cmdIndex , response没有 */ public class ClientPacketBit6Decoder extends MessageToMessageDecoder<ByteBuf> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = Unpooled.buffer(); in.readByte(); // # , 在这里就去掉 头尾 buf.writeByte(in.readByte()); //cmdIndex byte[] bodyBytes = new byte[in.readableBytes() - 1]; in.readBytes(bodyBytes);
buf.writeBytes(Bit6Coder.decode6BitBuf(bodyBytes));
pangliang/MirServer-Netty
LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket;
package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override
public void onPacket(ClientPacket packet) throws Exception {
pangliang/MirServer-Netty
LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket;
package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override public void onPacket(ClientPacket packet) throws Exception { } @Override public void onDisconnect() throws Exception {
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override public void onPacket(ClientPacket packet) throws Exception { } @Override public void onDisconnect() throws Exception {
User user = (User) session.get("user");
pangliang/MirServer-Netty
LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // }
import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket;
package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override public void onPacket(ClientPacket packet) throws Exception { } @Override public void onDisconnect() throws Exception { User user = (User) session.get("user"); if(null != user){
// Path: GameServer/src/main/java/com/zhaoxiaodan/mirserver/gameserver/entities/User.java // @Entity // public class User { // // @Id // @GeneratedValue // public int id; // // @Column(unique = true) // public String loginId; // public String password; // public String username; // public Date lastLoginTime; // @OneToOne(fetch = FetchType.EAGER) // @JoinColumn(name = "selectServerId") // public ServerInfo selectServer; // public byte certification; // // @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) // public List<Player> players; // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Handler.java // public abstract class Handler { // protected Logger logger = LogManager.getLogger(this.getClass().getName()); // protected Session session; // // protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception { // session = Session.getSession(ctx); // if(null == session){ // logger.debug("new session for {}",ctx); // session = Session.create(ctx); // } // DB.getSession().getTransaction().begin(); // try{ // onPacket(packet); // if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE)) // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // logger.error("onPacket error, {}", packet.protocol , e); // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // // } // // protected void onDisconnect(ChannelHandlerContext ctx) throws Exception{ // session = Session.getSession(ctx); // if(null == session){ // logger.error("session already remove for {}",ctx); // return; // } // // session.remove(); // DB.getSession().getTransaction().begin(); // try{ // onDisconnect(); // DB.getSession().getTransaction().commit(); // }catch(Exception e){ // if(DB.getSession().isOpen()) // DB.getSession().getTransaction().rollback(); // } // } // // public abstract void onPacket(ClientPacket packet) throws Exception; // public void onDisconnect() throws Exception{ // logger.error("overwrite it !!"); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/Session.java // public class Session { // // private static Logger logger = LogManager.getLogger(Session.class); // private static final Map<String, Session> sessions = new ConcurrentHashMap<String, Session>(); // // private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); // private final ChannelHandlerContext socket; // // private Session(ChannelHandlerContext ctx){ // this.socket = ctx; // } // // public void remove() { // logger.debug("remove session for {}", socket.toString()); // sessions.remove(socket.channel().remoteAddress().toString()); // } // // public void sendPacket(ServerPacket msg){ // socket.writeAndFlush(msg); // } // // public void put(String key, Object value) { // values.put(key, value); // } // // public Object get(String key) { // return values.get(key); // } // // public static Session getSession(ChannelHandlerContext ctx) { // return sessions.get(ctx.channel().remoteAddress().toString()); // } // // public static Session create(ChannelHandlerContext ctx) { // logger.debug("create session for {}", ctx.toString()); // Session session = new Session(ctx); // sessions.put(ctx.channel().remoteAddress().toString(), session); // return session; // } // // public static int size() { // return sessions.size(); // } // // public String toString(){ // return socket.toString(); // } // } // // Path: Core/src/main/java/com/zhaoxiaodan/mirserver/network/packets/ClientPacket.java // public class ClientPacket extends Packet { // // public byte cmdIndex; // #号后面紧跟的序号, 响应包的序号要跟请求一直 // // public ClientPacket() {} // // public ClientPacket(Protocol pid, byte cmdIndex) { // super(0, pid, (short) 0, (short) 0, (short) 0); // this.cmdIndex = cmdIndex; // } // // @Override // public void readPacket(ByteBuf in) throws Parcelable.WrongFormatException { // cmdIndex = in.readByte(); // cmdIndex = (byte) (cmdIndex - '0'); // super.readPacket(in); // } // // @Override // public void writePacket(ByteBuf out) { // out.writeByte(cmdIndex + '0'); // super.writePacket(out); // } // } // Path: LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/handlers/DisconnectHandler.java import com.zhaoxiaodan.mirserver.gameserver.entities.User; import com.zhaoxiaodan.mirserver.network.Handler; import com.zhaoxiaodan.mirserver.network.Session; import com.zhaoxiaodan.mirserver.network.packets.ClientPacket; package com.zhaoxiaodan.mirserver.loginserver.handlers; public class DisconnectHandler extends Handler { @Override public void onPacket(ClientPacket packet) throws Exception { } @Override public void onDisconnect() throws Exception { User user = (User) session.get("user"); if(null != user){
logger.info("user {} disconnect, online count : {}" ,user.loginId, Session.size());
perwendel/spark
src/test/java/spark/RedirectTest.java
// Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static final Redirect redirect = getInstance().redirect;
import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.get; import static spark.Spark.redirect;
/* * Copyright 2016 - Per Wendel * * 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 spark; /** * Tests the redirect utility methods in {@link spark.Redirect} */ public class RedirectTest { private static final String REDIRECTED = "Redirected"; private static SparkTestUtil testUtil; @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); testUtil.setFollowRedirectStrategy(301, 302); // don't set the others to be able to verify affect of Redirect.Status
// Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static final Redirect redirect = getInstance().redirect; // Path: src/test/java/spark/RedirectTest.java import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.get; import static spark.Spark.redirect; /* * Copyright 2016 - Per Wendel * * 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 spark; /** * Tests the redirect utility methods in {@link spark.Redirect} */ public class RedirectTest { private static final String REDIRECTED = "Redirected"; private static SparkTestUtil testUtil; @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); testUtil.setFollowRedirectStrategy(301, 302); // don't set the others to be able to verify affect of Redirect.Status
get("/hello", (request, response) -> REDIRECTED);
perwendel/spark
src/test/java/spark/RedirectTest.java
// Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static final Redirect redirect = getInstance().redirect;
import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.get; import static spark.Spark.redirect;
/* * Copyright 2016 - Per Wendel * * 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 spark; /** * Tests the redirect utility methods in {@link spark.Redirect} */ public class RedirectTest { private static final String REDIRECTED = "Redirected"; private static SparkTestUtil testUtil; @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); testUtil.setFollowRedirectStrategy(301, 302); // don't set the others to be able to verify affect of Redirect.Status get("/hello", (request, response) -> REDIRECTED);
// Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static final Redirect redirect = getInstance().redirect; // Path: src/test/java/spark/RedirectTest.java import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.get; import static spark.Spark.redirect; /* * Copyright 2016 - Per Wendel * * 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 spark; /** * Tests the redirect utility methods in {@link spark.Redirect} */ public class RedirectTest { private static final String REDIRECTED = "Redirected"; private static SparkTestUtil testUtil; @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); testUtil.setFollowRedirectStrategy(301, 302); // don't set the others to be able to verify affect of Redirect.Status get("/hello", (request, response) -> REDIRECTED);
redirect.get("/hi", "/hello");
perwendel/spark
src/test/java/spark/UnmapTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // }
import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap;
package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception {
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // } // Path: src/test/java/spark/UnmapTest.java import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap; package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception {
get("/tobeunmapped", (q, a) -> "tobeunmapped");
perwendel/spark
src/test/java/spark/UnmapTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // }
import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap;
package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception { get("/tobeunmapped", (q, a) -> "tobeunmapped");
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // } // Path: src/test/java/spark/UnmapTest.java import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap; package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception { get("/tobeunmapped", (q, a) -> "tobeunmapped");
awaitInitialization();
perwendel/spark
src/test/java/spark/UnmapTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // }
import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap;
package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception { get("/tobeunmapped", (q, a) -> "tobeunmapped"); awaitInitialization(); SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/tobeunmapped", null); Assert.assertEquals(200, response.status); Assert.assertEquals("tobeunmapped", response.body);
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // // Path: src/main/java/spark/Spark.java // public static boolean unmap(String path) { // return getInstance().unmap(path); // } // Path: src/test/java/spark/UnmapTest.java import org.junit.Assert; import org.junit.Test; import spark.util.SparkTestUtil; import static spark.Spark.awaitInitialization; import static spark.Spark.get; import static spark.Spark.unmap; package spark; public class UnmapTest { SparkTestUtil testUtil = new SparkTestUtil(4567); @Test public void testUnmap() throws Exception { get("/tobeunmapped", (q, a) -> "tobeunmapped"); awaitInitialization(); SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/tobeunmapped", null); Assert.assertEquals(200, response.status); Assert.assertEquals("tobeunmapped", response.body);
unmap("/tobeunmapped");
perwendel/spark
src/test/java/spark/BodyAvailabilityTest.java
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post;
package spark; public class BodyAvailabilityTest { private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class); private static final String BODY_CONTENT = "the body content"; private static SparkTestUtil testUtil; private final int HTTP_OK = 200; private static String beforeBody = null; private static String routeBody = null; private static String afterBody = null; @AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null;
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // } // Path: src/test/java/spark/BodyAvailabilityTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post; package spark; public class BodyAvailabilityTest { private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class); private static final String BODY_CONTENT = "the body content"; private static SparkTestUtil testUtil; private final int HTTP_OK = 200; private static String beforeBody = null; private static String routeBody = null; private static String afterBody = null; @AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null;
before("/hello", (req, res) -> {
perwendel/spark
src/test/java/spark/BodyAvailabilityTest.java
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post;
package spark; public class BodyAvailabilityTest { private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class); private static final String BODY_CONTENT = "the body content"; private static SparkTestUtil testUtil; private final int HTTP_OK = 200; private static String beforeBody = null; private static String routeBody = null; private static String afterBody = null; @AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null; before("/hello", (req, res) -> { LOGGER.debug("before-req.body() = " + req.body()); beforeBody = req.body(); });
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // } // Path: src/test/java/spark/BodyAvailabilityTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post; package spark; public class BodyAvailabilityTest { private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class); private static final String BODY_CONTENT = "the body content"; private static SparkTestUtil testUtil; private final int HTTP_OK = 200; private static String beforeBody = null; private static String routeBody = null; private static String afterBody = null; @AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null; before("/hello", (req, res) -> { LOGGER.debug("before-req.body() = " + req.body()); beforeBody = req.body(); });
post("/hello", (req, res) -> {
perwendel/spark
src/test/java/spark/BodyAvailabilityTest.java
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post;
@AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null; before("/hello", (req, res) -> { LOGGER.debug("before-req.body() = " + req.body()); beforeBody = req.body(); }); post("/hello", (req, res) -> { LOGGER.debug("get-req.body() = " + req.body()); routeBody = req.body(); return req.body(); });
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void post(String path, Route route) { // getInstance().post(path, route); // } // Path: src/test/java/spark/BodyAvailabilityTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Spark.after; import static spark.Spark.before; import static spark.Spark.post; @AfterClass public static void tearDown() { Spark.stop(); beforeBody = null; routeBody = null; afterBody = null; } @BeforeClass public static void setup() { LOGGER.debug("setup()"); testUtil = new SparkTestUtil(4567); beforeBody = null; routeBody = null; afterBody = null; before("/hello", (req, res) -> { LOGGER.debug("before-req.body() = " + req.body()); beforeBody = req.body(); }); post("/hello", (req, res) -> { LOGGER.debug("get-req.body() = " + req.body()); routeBody = req.body(); return req.body(); });
after("/hello", (req, res) -> {
perwendel/spark
src/test/java/spark/examples/filter/FilterExampleAttributes.java
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // }
import static spark.Spark.after; import static spark.Spark.get; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2011- Per Wendel * * 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 spark.examples.filter; /** * Example showing the use of attributes * * @author Per Wendel */ public class FilterExampleAttributes { private static final Logger LOGGER = LoggerFactory.getLogger(FilterExampleAttributes.class); public static void main(String[] args) {
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // Path: src/test/java/spark/examples/filter/FilterExampleAttributes.java import static spark.Spark.after; import static spark.Spark.get; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2011- Per Wendel * * 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 spark.examples.filter; /** * Example showing the use of attributes * * @author Per Wendel */ public class FilterExampleAttributes { private static final Logger LOGGER = LoggerFactory.getLogger(FilterExampleAttributes.class); public static void main(String[] args) {
get("/hi", (request, response) -> {
perwendel/spark
src/test/java/spark/examples/filter/FilterExampleAttributes.java
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // }
import static spark.Spark.after; import static spark.Spark.get; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2011- Per Wendel * * 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 spark.examples.filter; /** * Example showing the use of attributes * * @author Per Wendel */ public class FilterExampleAttributes { private static final Logger LOGGER = LoggerFactory.getLogger(FilterExampleAttributes.class); public static void main(String[] args) { get("/hi", (request, response) -> { request.attribute("foo", "bar"); return null; });
// Path: src/main/java/spark/Spark.java // public static void after(String path, Filter filter) { // getInstance().after(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void get(final String path, final Route route) { // getInstance().get(path, route); // } // Path: src/test/java/spark/examples/filter/FilterExampleAttributes.java import static spark.Spark.after; import static spark.Spark.get; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2011- Per Wendel * * 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 spark.examples.filter; /** * Example showing the use of attributes * * @author Per Wendel */ public class FilterExampleAttributes { private static final Logger LOGGER = LoggerFactory.getLogger(FilterExampleAttributes.class); public static void main(String[] args) { get("/hi", (request, response) -> { request.attribute("foo", "bar"); return null; });
after("/hi", (request, response) -> {
perwendel/spark
src/main/java/spark/Spark.java
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // }
import spark.routematch.RouteMatch; import java.util.List; import java.util.function.Consumer; import static spark.Service.ignite;
/* * Copyright 2011- Per Wendel * * 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 spark; /** * The main building block of a Spark application is a set of routes. A route is * made up of three simple pieces: * <ul> * <li>A verb (get, post, put, delete, head, trace, connect, options)</li> * <li>A path (/hello, /users/:name)</li> * <li>A callback (request, response)</li> * </ul> * Example: * get("/hello", (request, response) -&#62; { * return "Hello World!"; * }); * The public methods and fields in this class should be statically imported for the semantic to make sense. * Ie. one should use: * 'post("/books")' without the prefix 'Spark.' * * @author Per Wendel */ public class Spark { // Hide constructor protected Spark() { } /** * Initializes singleton. */ private static class SingletonHolder {
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // } // Path: src/main/java/spark/Spark.java import spark.routematch.RouteMatch; import java.util.List; import java.util.function.Consumer; import static spark.Service.ignite; /* * Copyright 2011- Per Wendel * * 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 spark; /** * The main building block of a Spark application is a set of routes. A route is * made up of three simple pieces: * <ul> * <li>A verb (get, post, put, delete, head, trace, connect, options)</li> * <li>A path (/hello, /users/:name)</li> * <li>A callback (request, response)</li> * </ul> * Example: * get("/hello", (request, response) -&#62; { * return "Hello World!"; * }); * The public methods and fields in this class should be statically imported for the semantic to make sense. * Ie. one should use: * 'post("/books")' without the prefix 'Spark.' * * @author Per Wendel */ public class Spark { // Hide constructor protected Spark() { } /** * Initializes singleton. */ private static class SingletonHolder {
private static final Service INSTANCE = ignite();
perwendel/spark
src/main/java/spark/Spark.java
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // }
import spark.routematch.RouteMatch; import java.util.List; import java.util.function.Consumer; import static spark.Service.ignite;
/** * Sets Spark to NOT trust Forwarded, X-Forwarded-Host, X-Forwarded-Server, X-Forwarded-For, X-Forwarded-Proto, X-Proxied-Https headers * as defined at https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/server/ForwardedRequestCustomizer.html */ public static void untrustForwardHeaders() { getInstance().untrustForwardHeaders(); } /** * Initializes the Spark server. SHOULD just be used when using the Websockets functionality. */ public static void init() { getInstance().init(); } /** * Constructs a ModelAndView with the provided model and view name * * @param model the model * @param viewName the view name * @return the model and view */ public static ModelAndView modelAndView(Object model, String viewName) { return new ModelAndView(model, viewName); } /** * @return All routes available */
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // } // Path: src/main/java/spark/Spark.java import spark.routematch.RouteMatch; import java.util.List; import java.util.function.Consumer; import static spark.Service.ignite; /** * Sets Spark to NOT trust Forwarded, X-Forwarded-Host, X-Forwarded-Server, X-Forwarded-For, X-Forwarded-Proto, X-Proxied-Https headers * as defined at https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/server/ForwardedRequestCustomizer.html */ public static void untrustForwardHeaders() { getInstance().untrustForwardHeaders(); } /** * Initializes the Spark server. SHOULD just be used when using the Websockets functionality. */ public static void init() { getInstance().init(); } /** * Constructs a ModelAndView with the provided model and view name * * @param model the model * @param viewName the view name * @return the model and view */ public static ModelAndView modelAndView(Object model, String viewName) { return new ModelAndView(model, viewName); } /** * @return All routes available */
public static List<RouteMatch> routes() {
perwendel/spark
src/test/java/spark/ServicePortIntegrationTest.java
// Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Service.ignite;
package spark; /** * Created by Tom on 08/02/2017. */ public class ServicePortIntegrationTest { private static Service service; private static final Logger LOGGER = LoggerFactory.getLogger(ServicePortIntegrationTest.class); @BeforeClass public static void setUpClass() throws Exception {
// Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // } // Path: src/test/java/spark/ServicePortIntegrationTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.util.SparkTestUtil; import static spark.Service.ignite; package spark; /** * Created by Tom on 08/02/2017. */ public class ServicePortIntegrationTest { private static Service service; private static final Logger LOGGER = LoggerFactory.getLogger(ServicePortIntegrationTest.class); @BeforeClass public static void setUpClass() throws Exception {
service = ignite();
perwendel/spark
src/test/java/spark/FilterTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // }
import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop;
package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() {
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // } // Path: src/test/java/spark/FilterTest.java import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop; package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() {
stop();
perwendel/spark
src/test/java/spark/FilterTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // }
import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop;
package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() { stop(); } @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567);
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // } // Path: src/test/java/spark/FilterTest.java import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop; package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() { stop(); } @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567);
before("/justfilter", (q, a) -> System.out.println("Filter matched"));
perwendel/spark
src/test/java/spark/FilterTest.java
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // }
import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop;
package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() { stop(); } @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); before("/justfilter", (q, a) -> System.out.println("Filter matched"));
// Path: src/main/java/spark/Spark.java // public static void awaitInitialization() { // getInstance().awaitInitialization(); // } // // Path: src/main/java/spark/Spark.java // public static void before(String path, Filter filter) { // getInstance().before(path, filter); // } // // Path: src/main/java/spark/Spark.java // public static void stop() { // getInstance().stop(); // } // Path: src/test/java/spark/FilterTest.java import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.util.SparkTestUtil; import spark.util.SparkTestUtil.UrlResponse; import static spark.Spark.awaitInitialization; import static spark.Spark.before; import static spark.Spark.stop; package spark; public class FilterTest { static SparkTestUtil testUtil; @AfterClass public static void tearDown() { stop(); } @BeforeClass public static void setup() throws IOException { testUtil = new SparkTestUtil(4567); before("/justfilter", (q, a) -> System.out.println("Filter matched"));
awaitInitialization();
perwendel/spark
src/main/java/spark/route/SimpleRouteMatcher.java
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // }
import java.util.List; import spark.routematch.RouteMatch;
/* * Copyright 2011- Per Wendel * * 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 spark.route; /** * Kept just for not breaking API. * * @deprecated see {@link spark.route.Routes} */ public class SimpleRouteMatcher extends Routes { /** * @param route the route * @param acceptType the accept type * @param target the target * @deprecated */ public void parseValidateAddRoute(String route, String acceptType, Object target) { add(route, acceptType, target); } /** * @param httpMethod the HttpMethod * @param path the path * @param acceptType the accept type * @return the RouteMatch object * @deprecated */
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // Path: src/main/java/spark/route/SimpleRouteMatcher.java import java.util.List; import spark.routematch.RouteMatch; /* * Copyright 2011- Per Wendel * * 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 spark.route; /** * Kept just for not breaking API. * * @deprecated see {@link spark.route.Routes} */ public class SimpleRouteMatcher extends Routes { /** * @param route the route * @param acceptType the accept type * @param target the target * @deprecated */ public void parseValidateAddRoute(String route, String acceptType, Object target) { add(route, acceptType, target); } /** * @param httpMethod the HttpMethod * @param path the path * @param acceptType the accept type * @return the RouteMatch object * @deprecated */
public RouteMatch findTargetForRequestedRoute(HttpMethod httpMethod, String path, String acceptType) {
perwendel/spark
src/main/java/spark/embeddedserver/jetty/SocketConnectorFactory.java
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // }
import java.util.concurrent.TimeUnit; import org.eclipse.jetty.server.ForwardedRequestCustomizer; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import spark.ssl.SslStores; import spark.utils.Assert;
/* * Copyright 2015 - Per Wendel * * 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 spark.embeddedserver.jetty; /** * Creates socket connectors. */ public class SocketConnectorFactory { /** * Creates an ordinary, non-secured Jetty server jetty. * * @param server Jetty server * @param host host * @param port port * @return - a server jetty */ public static ServerConnector createSocketConnector(Server server, String host, int port, boolean trustForwardHeaders) { Assert.notNull(server, "'server' must not be null"); Assert.notNull(host, "'host' must not be null"); HttpConnectionFactory httpConnectionFactory = createHttpConnectionFactory(trustForwardHeaders); ServerConnector connector = new ServerConnector(server, httpConnectionFactory); initializeConnector(connector, host, port); return connector; } /** * Creates a ssl jetty socket jetty. Keystore required, truststore * optional. If truststore not specified keystore will be reused. * * @param server Jetty server * @param sslStores the security sslStores. * @param host host * @param port port * @return a ssl socket jetty */ public static ServerConnector createSecureSocketConnector(Server server, String host, int port,
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // } // Path: src/main/java/spark/embeddedserver/jetty/SocketConnectorFactory.java import java.util.concurrent.TimeUnit; import org.eclipse.jetty.server.ForwardedRequestCustomizer; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import spark.ssl.SslStores; import spark.utils.Assert; /* * Copyright 2015 - Per Wendel * * 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 spark.embeddedserver.jetty; /** * Creates socket connectors. */ public class SocketConnectorFactory { /** * Creates an ordinary, non-secured Jetty server jetty. * * @param server Jetty server * @param host host * @param port port * @return - a server jetty */ public static ServerConnector createSocketConnector(Server server, String host, int port, boolean trustForwardHeaders) { Assert.notNull(server, "'server' must not be null"); Assert.notNull(host, "'host' must not be null"); HttpConnectionFactory httpConnectionFactory = createHttpConnectionFactory(trustForwardHeaders); ServerConnector connector = new ServerConnector(server, httpConnectionFactory); initializeConnector(connector, host, port); return connector; } /** * Creates a ssl jetty socket jetty. Keystore required, truststore * optional. If truststore not specified keystore will be reused. * * @param server Jetty server * @param sslStores the security sslStores. * @param host host * @param port port * @return a ssl socket jetty */ public static ServerConnector createSecureSocketConnector(Server server, String host, int port,
SslStores sslStores,
perwendel/spark
src/test/java/spark/MultipleServicesTest.java
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.route.HttpMethod; import spark.routematch.RouteMatch; import spark.util.SparkTestUtil; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static spark.Service.ignite;
} @Test public void testGetUniqueForSecondWithFirst() throws Exception { SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/uniqueforsecond", null); Assert.assertEquals(404, response.status); } @Test public void testGetUniqueForSecondWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/uniqueforsecond", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Bompton", response.body); } @Test public void testStaticFileCssStyleCssWithFirst() throws Exception { SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(404, response.status); } @Test public void testStaticFileCssStyleCssWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Content of css file", response.body); } @Test public void testGetAllRoutesFromBothServices(){
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // } // Path: src/test/java/spark/MultipleServicesTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.route.HttpMethod; import spark.routematch.RouteMatch; import spark.util.SparkTestUtil; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static spark.Service.ignite; } @Test public void testGetUniqueForSecondWithFirst() throws Exception { SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/uniqueforsecond", null); Assert.assertEquals(404, response.status); } @Test public void testGetUniqueForSecondWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/uniqueforsecond", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Bompton", response.body); } @Test public void testStaticFileCssStyleCssWithFirst() throws Exception { SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(404, response.status); } @Test public void testStaticFileCssStyleCssWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Content of css file", response.body); } @Test public void testGetAllRoutesFromBothServices(){
for(RouteMatch routeMatch : first.routes()){
perwendel/spark
src/test/java/spark/MultipleServicesTest.java
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // }
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.route.HttpMethod; import spark.routematch.RouteMatch; import spark.util.SparkTestUtil; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static spark.Service.ignite;
@Test public void testStaticFileCssStyleCssWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Content of css file", response.body); } @Test public void testGetAllRoutesFromBothServices(){ for(RouteMatch routeMatch : first.routes()){ Assert.assertEquals(routeMatch.getAcceptType(), "*/*"); Assert.assertEquals(routeMatch.getHttpMethod(), HttpMethod.get); Assert.assertEquals(routeMatch.getMatchUri(), "/hello"); Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES"); Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class)); } for(RouteMatch routeMatch : second.routes()){ Assert.assertEquals(routeMatch.getAcceptType(), "*/*"); Assert.assertThat(routeMatch.getHttpMethod(), instanceOf(HttpMethod.class)); boolean isUriOnList = ("/hello/hi/uniqueforsecond").contains(routeMatch.getMatchUri()); Assert.assertTrue(isUriOnList); Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES"); Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class)); } } private static Service igniteFirstService() {
// Path: src/main/java/spark/routematch/RouteMatch.java // public class RouteMatch { // // private Object target; // private String matchUri; // private String requestURI; // private String acceptType; // private HttpMethod httpMethod; // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType) { // this(target, matchUri, requestUri, acceptType, null); // } // // public RouteMatch(Object target, String matchUri, String requestUri, String acceptType, HttpMethod httpMethod) { // super(); // this.target = target; // this.matchUri = matchUri; // this.requestURI = requestUri; // this.acceptType = acceptType; // this.httpMethod = httpMethod; // } // // /** // * @return the accept type // */ // public HttpMethod getHttpMethod() { // return httpMethod; // } // // /** // * @return the accept type // */ // public String getAcceptType() { // return acceptType; // } // // /** // * @return the target // */ // public Object getTarget() { // return target; // } // // // /** // * @return the matchUri // */ // public String getMatchUri() { // return matchUri; // } // // // /** // * @return the requestUri // */ // public String getRequestURI() { // return requestURI; // } // // // } // // Path: src/main/java/spark/Service.java // public static Service ignite() { // return new Service(); // } // Path: src/test/java/spark/MultipleServicesTest.java import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import spark.route.HttpMethod; import spark.routematch.RouteMatch; import spark.util.SparkTestUtil; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static spark.Service.ignite; @Test public void testStaticFileCssStyleCssWithSecond() throws Exception { SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/css/style.css", null); Assert.assertEquals(200, response.status); Assert.assertEquals("Content of css file", response.body); } @Test public void testGetAllRoutesFromBothServices(){ for(RouteMatch routeMatch : first.routes()){ Assert.assertEquals(routeMatch.getAcceptType(), "*/*"); Assert.assertEquals(routeMatch.getHttpMethod(), HttpMethod.get); Assert.assertEquals(routeMatch.getMatchUri(), "/hello"); Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES"); Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class)); } for(RouteMatch routeMatch : second.routes()){ Assert.assertEquals(routeMatch.getAcceptType(), "*/*"); Assert.assertThat(routeMatch.getHttpMethod(), instanceOf(HttpMethod.class)); boolean isUriOnList = ("/hello/hi/uniqueforsecond").contains(routeMatch.getMatchUri()); Assert.assertTrue(isUriOnList); Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES"); Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class)); } } private static Service igniteFirstService() {
Service http = ignite(); // I give the variable the name 'http' for the code to make sense when adding routes.
perwendel/spark
src/main/java/spark/embeddedserver/EmbeddedServer.java
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // }
import java.util.Map; import java.util.Optional; import spark.embeddedserver.jetty.websocket.WebSocketHandlerWrapper; import spark.ssl.SslStores;
/* * Copyright 2016 - Per Wendel * * 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 spark.embeddedserver; /** * Represents an embedded server that can be used in Spark. (this is currently Jetty by default). */ public interface EmbeddedServer { /** * Ignites the embedded server, listening on the specified port, running SSL secured with the specified keystore * and truststore. If truststore is null, keystore is reused. * * @param host The address to listen on * @param port - the port * @param sslStores - The SSL sslStores. * @param maxThreads - max nbr of threads. * @param minThreads - min nbr of threads. * @return The port number the server was launched on. */ int ignite(String host, int port,
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // } // Path: src/main/java/spark/embeddedserver/EmbeddedServer.java import java.util.Map; import java.util.Optional; import spark.embeddedserver.jetty.websocket.WebSocketHandlerWrapper; import spark.ssl.SslStores; /* * Copyright 2016 - Per Wendel * * 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 spark.embeddedserver; /** * Represents an embedded server that can be used in Spark. (this is currently Jetty by default). */ public interface EmbeddedServer { /** * Ignites the embedded server, listening on the specified port, running SSL secured with the specified keystore * and truststore. If truststore is null, keystore is reused. * * @param host The address to listen on * @param port - the port * @param sslStores - The SSL sslStores. * @param maxThreads - max nbr of threads. * @param minThreads - min nbr of threads. * @return The port number the server was launched on. */ int ignite(String host, int port,
SslStores sslStores,
perwendel/spark
src/test/java/spark/embeddedserver/jetty/SocketConnectorFactoryTest.java
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // }
import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import spark.ssl.SslStores; import java.util.Map; import static org.junit.Assert.*;
assertEquals("'host' must not be null", ex.getMessage()); } } @Test public void testCreateSecureSocketConnector_whenSslStoresIsNull() { Server server = new Server(); try { SocketConnectorFactory.createSecureSocketConnector(server, "localhost", 80, null, true); fail("SocketConnector creation should have thrown an IllegalArgumentException"); } catch(IllegalArgumentException ex) { assertEquals("'sslStores' must not be null", ex.getMessage()); } } @Test @PrepareForTest({ServerConnector.class}) public void testCreateSecureSocketConnector() throws Exception { final String host = "localhost"; final int port = 8888; final String keystoreFile = "keystoreFile.jks"; final String keystorePassword = "keystorePassword"; final String truststoreFile = "truststoreFile.jks"; final String trustStorePassword = "trustStorePassword";
// Path: src/main/java/spark/ssl/SslStores.java // public class SslStores { // // protected String keystoreFile; // protected String keystorePassword; // protected String certAlias; // protected String truststoreFile; // protected String truststorePassword; // protected boolean needsClientCert; // // /** // * Creates a Stores instance. // * // * @param keystoreFile the keystoreFile // * @param keystorePassword the keystorePassword // * @param truststoreFile the truststoreFile // * @param truststorePassword the truststorePassword // * @return the SslStores instance. // */ // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); // } // // public static SslStores create(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // // return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); // } // // private SslStores(String keystoreFile, // String keystorePassword, // String certAlias, // String truststoreFile, // String truststorePassword, // boolean needsClientCert) { // this.keystoreFile = keystoreFile; // this.keystorePassword = keystorePassword; // this.certAlias = certAlias; // this.truststoreFile = truststoreFile; // this.truststorePassword = truststorePassword; // this.needsClientCert = needsClientCert; // } // // /** // * @return keystoreFile // */ // public String keystoreFile() { // return keystoreFile; // } // // /** // * @return keystorePassword // */ // public String keystorePassword() { // return keystorePassword; // } // // /** // * @return certAlias // */ // public String certAlias() { // return certAlias; // } // // /** // * @return trustStoreFile // */ // public String trustStoreFile() { // return truststoreFile; // } // // /** // * @return trustStorePassword // */ // public String trustStorePassword() { // return truststorePassword; // } // // /** // * @return needsClientCert // */ // public boolean needsClientCert() { // return needsClientCert; // } // } // Path: src/test/java/spark/embeddedserver/jetty/SocketConnectorFactoryTest.java import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import spark.ssl.SslStores; import java.util.Map; import static org.junit.Assert.*; assertEquals("'host' must not be null", ex.getMessage()); } } @Test public void testCreateSecureSocketConnector_whenSslStoresIsNull() { Server server = new Server(); try { SocketConnectorFactory.createSecureSocketConnector(server, "localhost", 80, null, true); fail("SocketConnector creation should have thrown an IllegalArgumentException"); } catch(IllegalArgumentException ex) { assertEquals("'sslStores' must not be null", ex.getMessage()); } } @Test @PrepareForTest({ServerConnector.class}) public void testCreateSecureSocketConnector() throws Exception { final String host = "localhost"; final int port = 8888; final String keystoreFile = "keystoreFile.jks"; final String keystorePassword = "keystorePassword"; final String truststoreFile = "truststoreFile.jks"; final String trustStorePassword = "trustStorePassword";
SslStores sslStores = SslStores.create(keystoreFile, keystorePassword, truststoreFile, trustStorePassword);
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/service/JsonPathParser.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/JsonParameter.java // public class JsonParameter implements Serializable { // private String envVarName; // private String jsonPath; // // public JsonParameter(String envVarName, String jsonPath) { // this.envVarName = envVarName; // this.jsonPath = jsonPath; // } // // public String getEnvVarName() { // return envVarName; // } // // public String getJsonPath() { // return jsonPath; // } // // public void setEnvVarName(String envVarName) { // this.envVarName = envVarName; // } // // public void setJsonPath(String jsonPath) { // this.jsonPath = jsonPath; // } // // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LogUtils.java // public class LogUtils { // public static String getStackTrace(Throwable t){ // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // String stackTrace = sw.toString(); // pw.close(); // try{ // sw.close(); // }catch(Exception ignored){ // } // return stackTrace; // } // }
import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPathException; import com.xti.jenkins.plugin.awslambda.invoke.JsonParameter; import com.xti.jenkins.plugin.awslambda.util.LogUtils; import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.xti.jenkins.plugin.awslambda.service; public class JsonPathParser { private List<JsonParameter> jsonParameters; private JenkinsLogger logger; public JsonPathParser(List<JsonParameter> jsonParameters, JenkinsLogger logger) { this.jsonParameters = jsonParameters; this.logger = logger; } public Map<String, String> parse(String payload){ Map<String, String> result = new HashMap<String, String>(); if(StringUtils.isNotEmpty(payload)) { DocumentContext documentContext = JsonPath.parse(payload); for (JsonParameter jsonParameter : jsonParameters) { if (StringUtils.isEmpty(jsonParameter.getJsonPath())) { result.put(jsonParameter.getEnvVarName(), payload); } else { try { result.put(jsonParameter.getEnvVarName(), documentContext.read(jsonParameter.getJsonPath()).toString()); } catch (JsonPathException jpe) { logger.log("Error while parsing path %s for environment variable %s.%nStacktrace:%n%s%n",
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/JsonParameter.java // public class JsonParameter implements Serializable { // private String envVarName; // private String jsonPath; // // public JsonParameter(String envVarName, String jsonPath) { // this.envVarName = envVarName; // this.jsonPath = jsonPath; // } // // public String getEnvVarName() { // return envVarName; // } // // public String getJsonPath() { // return jsonPath; // } // // public void setEnvVarName(String envVarName) { // this.envVarName = envVarName; // } // // public void setJsonPath(String jsonPath) { // this.jsonPath = jsonPath; // } // // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LogUtils.java // public class LogUtils { // public static String getStackTrace(Throwable t){ // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // String stackTrace = sw.toString(); // pw.close(); // try{ // sw.close(); // }catch(Exception ignored){ // } // return stackTrace; // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/JsonPathParser.java import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPathException; import com.xti.jenkins.plugin.awslambda.invoke.JsonParameter; import com.xti.jenkins.plugin.awslambda.util.LogUtils; import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map; package com.xti.jenkins.plugin.awslambda.service; public class JsonPathParser { private List<JsonParameter> jsonParameters; private JenkinsLogger logger; public JsonPathParser(List<JsonParameter> jsonParameters, JenkinsLogger logger) { this.jsonParameters = jsonParameters; this.logger = logger; } public Map<String, String> parse(String payload){ Map<String, String> result = new HashMap<String, String>(); if(StringUtils.isNotEmpty(payload)) { DocumentContext documentContext = JsonPath.parse(payload); for (JsonParameter jsonParameter : jsonParameters) { if (StringUtils.isEmpty(jsonParameter.getJsonPath())) { result.put(jsonParameter.getEnvVarName(), payload); } else { try { result.put(jsonParameter.getEnvVarName(), documentContext.read(jsonParameter.getJsonPath()).toString()); } catch (JsonPathException jpe) { logger.log("Error while parsing path %s for environment variable %s.%nStacktrace:%n%s%n",
jsonParameter.getJsonPath(), jsonParameter.getEnvVarName(), LogUtils.getStackTrace(jpe));
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepTest.java
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Launcher; import hudson.model.*; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when;
package com.xti.jenkins.plugin.awslambda.upload; @RunWith(MockitoJUnitRunner.class) public class LambdaUploadBuildStepTest { @Rule public JenkinsRule j = new JenkinsRule();
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepTest.java import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Launcher; import hudson.model.*; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; package com.xti.jenkins.plugin.awslambda.upload; @RunWith(MockitoJUnitRunner.class) public class LambdaUploadBuildStepTest { @Rule public JenkinsRule j = new JenkinsRule();
private TestUtil testUtil = new TestUtil();
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepTest.java
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Launcher; import hudson.model.*; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when;
package com.xti.jenkins.plugin.awslambda.upload; @RunWith(MockitoJUnitRunner.class) public class LambdaUploadBuildStepTest { @Rule public JenkinsRule j = new JenkinsRule(); private TestUtil testUtil = new TestUtil(); @Test @Ignore public void testHtml() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "ziplocation", "description", "function", "handler", "1024", "role", "nodejs", "30", "full", false, null, false, "", ""); FreeStyleProject p = j.createFreeStyleProject(); LambdaUploadBuildStep before = new LambdaUploadBuildStep(variables); p.getBuildersList().add(before); j.submit(j.createWebClient().getPage(p,"configure").getFormByName("config")); LambdaUploadBuildStep after = p.getBuildersList().get(LambdaUploadBuildStep.class); assertEquals(before, after); } @Mock private LambdaUploadBuildStepVariables original; @Mock
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepTest.java import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Launcher; import hudson.model.*; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; package com.xti.jenkins.plugin.awslambda.upload; @RunWith(MockitoJUnitRunner.class) public class LambdaUploadBuildStepTest { @Rule public JenkinsRule j = new JenkinsRule(); private TestUtil testUtil = new TestUtil(); @Test @Ignore public void testHtml() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "ziplocation", "description", "function", "handler", "1024", "role", "nodejs", "30", "full", false, null, false, "", ""); FreeStyleProject p = j.createFreeStyleProject(); LambdaUploadBuildStep before = new LambdaUploadBuildStep(variables); p.getBuildersList().add(before); j.submit(j.createWebClient().getPage(p,"configure").getFormByName("config")); LambdaUploadBuildStep after = p.getBuildersList().get(LambdaUploadBuildStep.class); assertEquals(before, after); } @Mock private LambdaUploadBuildStepVariables original; @Mock
private LambdaClientConfig clientConfig;
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
LambdaInvokeBuildStepVariables expected = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("$ENV_SECRET}"), "eu-west-1", "FUNCTION", "{\"payload\":\"vhello\"}", true, null); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionName(), clone.getFunctionName()); assertEquals(expected.getPayload(), clone.getPayload()); assertEquals(expected.getSynchronous(), clone.getSynchronous()); } @Test public void testGetInvokeConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, jsonParameterVariables); InvokeConfig invokeConfig = variables.getInvokeConfig(); assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName()); assertEquals(variables.getPayload(), invokeConfig.getPayload()); assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous()); assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName()); assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetLambdaClientConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, jsonParameterVariables);
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariablesTest.java import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; LambdaInvokeBuildStepVariables expected = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("$ENV_SECRET}"), "eu-west-1", "FUNCTION", "{\"payload\":\"vhello\"}", true, null); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionName(), clone.getFunctionName()); assertEquals(expected.getPayload(), clone.getPayload()); assertEquals(expected.getSynchronous(), clone.getSynchronous()); } @Test public void testGetInvokeConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, jsonParameterVariables); InvokeConfig invokeConfig = variables.getInvokeConfig(); assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName()); assertEquals(variables.getPayload(), invokeConfig.getPayload()); assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous()); assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName()); assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetLambdaClientConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, jsonParameterVariables);
LambdaClientConfig clientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.util.LogTaskListener; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when;
package com.xti.jenkins.plugin.awslambda.invoke; @RunWith(MockitoJUnitRunner.class) public class LambdaInvokeBuildStepTest { private static final Logger LOGGER = Logger.getLogger(LambdaInvokeBuildStepTest.class.getName()); @Rule public JenkinsRule j = new JenkinsRule(); @Ignore @Test public void testHtml() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("KEY", "value")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables); FreeStyleProject p = j.createFreeStyleProject(); LambdaInvokeBuildStep before = new LambdaInvokeBuildStep(variables); p.getBuildersList().add(before); j.submit(j.createWebClient().getPage(p, "configure").getFormByName("config")); LambdaInvokeBuildStep after = p.getBuildersList().get(LambdaInvokeBuildStep.class); assertEquals(before, after); } @Mock private LambdaInvokeBuildStepVariables original; @Mock
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepTest.java import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.util.LogTaskListener; import hudson.util.Secret; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; package com.xti.jenkins.plugin.awslambda.invoke; @RunWith(MockitoJUnitRunner.class) public class LambdaInvokeBuildStepTest { private static final Logger LOGGER = Logger.getLogger(LambdaInvokeBuildStepTest.class.getName()); @Rule public JenkinsRule j = new JenkinsRule(); @Ignore @Test public void testHtml() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("KEY", "value")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables); FreeStyleProject p = j.createFreeStyleProject(); LambdaInvokeBuildStep before = new LambdaInvokeBuildStep(variables); p.getBuildersList().add(before); j.submit(j.createWebClient().getPage(p, "configure").getFormByName("config")); LambdaInvokeBuildStep after = p.getBuildersList().get(LambdaInvokeBuildStep.class); assertEquals(before, after); } @Mock private LambdaInvokeBuildStepVariables original; @Mock
private LambdaClientConfig clientConfig;
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); assertEquals(variables.getEnvironmentConfiguration().getKmsArn(), uploadConfig.getKmsArn()); assertEquals(variables.getEnvironmentConfiguration().getEnvironment().get(0).getValue(), uploadConfig.getEnvironmentVariables().get("key")); } @Test public void testGetUploadConfigNullTimeoutAndMemory() throws Exception { LambdaUploadVariables variables = new LambdaUploadVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", null, "ROLE", "RUNTIME", "", true, false, "full", null, false, "subnet1, subnet2", "secgroup"); DeployConfig uploadConfig = variables.getUploadConfig(); assertEquals(variables.getArtifactLocation(), uploadConfig.getArtifactLocation()); assertEquals(variables.getDescription(), uploadConfig.getDescription()); assertNull(uploadConfig.getMemorySize()); assertNull(uploadConfig.getTimeout()); assertEquals(variables.getHandler(), uploadConfig.getHandler()); assertEquals(variables.getRuntime(), uploadConfig.getRuntime()); assertEquals(variables.getFunctionName(), uploadConfig.getFunctionName()); assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaUploadVariables variables = new LambdaUploadVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", true, false, "full", null, false, "subnet1, subnet2", "secgroup"); variables.expandVariables(new EnvVars());
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadVariablesTest.java import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); assertEquals(variables.getEnvironmentConfiguration().getKmsArn(), uploadConfig.getKmsArn()); assertEquals(variables.getEnvironmentConfiguration().getEnvironment().get(0).getValue(), uploadConfig.getEnvironmentVariables().get("key")); } @Test public void testGetUploadConfigNullTimeoutAndMemory() throws Exception { LambdaUploadVariables variables = new LambdaUploadVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", null, "ROLE", "RUNTIME", "", true, false, "full", null, false, "subnet1, subnet2", "secgroup"); DeployConfig uploadConfig = variables.getUploadConfig(); assertEquals(variables.getArtifactLocation(), uploadConfig.getArtifactLocation()); assertEquals(variables.getDescription(), uploadConfig.getDescription()); assertNull(uploadConfig.getMemorySize()); assertNull(uploadConfig.getTimeout()); assertEquals(variables.getHandler(), uploadConfig.getHandler()); assertEquals(variables.getRuntime(), uploadConfig.getRuntime()); assertEquals(variables.getFunctionName(), uploadConfig.getFunctionName()); assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaUploadVariables variables = new LambdaUploadVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", true, false, "full", null, false, "subnet1, subnet2", "secgroup"); variables.expandVariables(new EnvVars());
LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); assertEquals(variables.getEnvironmentConfiguration().getKmsArn(), uploadConfig.getKmsArn()); assertEquals(variables.getEnvironmentConfiguration().getEnvironment().get(0).getValue(), uploadConfig.getEnvironmentVariables().get("key")); } @Test public void testGetUploadConfigNullTimeoutAndMemory() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", null, "ROLE", "RUNTIME", "", "full", false, null, false, "subnet1, subnet2", "secgroup"); DeployConfig uploadConfig = variables.getUploadConfig(); assertEquals(variables.getArtifactLocation(), uploadConfig.getArtifactLocation()); assertEquals(variables.getDescription(), uploadConfig.getDescription()); assertNull(uploadConfig.getMemorySize()); assertNull(uploadConfig.getTimeout()); assertEquals(variables.getHandler(), uploadConfig.getHandler()); assertEquals(variables.getRuntime(), uploadConfig.getRuntime()); assertEquals(variables.getFunctionName(), uploadConfig.getFunctionName()); assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", "full", false, null, false, "subnet1, subnet2", "secgroup"); variables.expandVariables(new EnvVars());
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/upload/LambdaUploadBuildStepVariablesTest.java import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); assertEquals(variables.getEnvironmentConfiguration().getKmsArn(), uploadConfig.getKmsArn()); assertEquals(variables.getEnvironmentConfiguration().getEnvironment().get(0).getValue(), uploadConfig.getEnvironmentVariables().get("key")); } @Test public void testGetUploadConfigNullTimeoutAndMemory() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", null, "ROLE", "RUNTIME", "", "full", false, null, false, "subnet1, subnet2", "secgroup"); DeployConfig uploadConfig = variables.getUploadConfig(); assertEquals(variables.getArtifactLocation(), uploadConfig.getArtifactLocation()); assertEquals(variables.getDescription(), uploadConfig.getDescription()); assertNull(uploadConfig.getMemorySize()); assertNull(uploadConfig.getTimeout()); assertEquals(variables.getHandler(), uploadConfig.getHandler()); assertEquals(variables.getRuntime(), uploadConfig.getRuntime()); assertEquals(variables.getFunctionName(), uploadConfig.getFunctionName()); assertEquals(variables.getRole(), uploadConfig.getRole()); assertEquals(variables.getUpdateMode(), uploadConfig.getUpdateMode()); assertEquals(Arrays.asList("subnet1", "subnet2"), uploadConfig.getSubnets()); assertEquals(Collections.singletonList("secgroup"), uploadConfig.getSecurityGroups()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaUploadBuildStepVariables variables = new LambdaUploadBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FILE", "description DESCRIPTION", "FUNCTION", "HANDLER", "1024", "ROLE", "RUNTIME", "30", "full", false, null, false, "subnet1, subnet2", "secgroup"); variables.expandVariables(new EnvVars());
LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
public String getFunctionName() { return functionName; } public String getEventSourceArn() { return eventSourceArn; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public LambdaEventSourceBuildStepVariables getClone() { LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables = new LambdaEventSourceBuildStepVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceBuildStepVariables.setFunctionAlias(functionAlias); return lambdaEventSourceBuildStepVariables; } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStepVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; public String getFunctionName() { return functionName; } public String getEventSourceArn() { return eventSourceArn; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public LambdaEventSourceBuildStepVariables getClone() { LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables = new LambdaEventSourceBuildStepVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceBuildStepVariables.setFunctionAlias(functionAlias); return lambdaEventSourceBuildStepVariables; } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); }
public LambdaClientConfig getLambdaClientConfig(){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
} public String getEventSourceArn() { return eventSourceArn; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public LambdaEventSourceBuildStepVariables getClone() { LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables = new LambdaEventSourceBuildStepVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceBuildStepVariables.setFunctionAlias(functionAlias); return lambdaEventSourceBuildStepVariables; } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStepVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; } public String getEventSourceArn() { return eventSourceArn; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public LambdaEventSourceBuildStepVariables getClone() { LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables = new LambdaEventSourceBuildStepVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceBuildStepVariables.setFunctionAlias(functionAlias); return lambdaEventSourceBuildStepVariables; } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
envVars.put("ENV_REGION", "eu-west-1"); envVars.put("ENV_ARN", "ARN"); envVars.put("ENV_ALIAS", "ALIAS"); envVars.put("ENV_VERSIONDESCRIPTION", "DESCRIPTION"); clone.expandVariables(envVars); LambdaPublishVariables expected = new LambdaPublishVariables(false, "ID", Secret.fromString("$ENV_SECRET}}"), "eu-west-1", "ARN", "ALIAS", "description DESCRIPTION"); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionARN(), clone.getFunctionARN()); assertEquals(expected.getFunctionAlias(), clone.getFunctionAlias()); assertEquals(expected.getVersionDescription(), clone.getVersionDescription()); } @Test public void testGetPublishConfig() throws Exception { LambdaPublishVariables variables = new LambdaPublishVariables("eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); PublishConfig publishConfig = variables.getPublishConfig(); assertEquals(variables.getFunctionAlias(), publishConfig.getFunctionAlias()); assertEquals(variables.getFunctionARN(), publishConfig.getFunctionARN()); assertEquals(variables.getVersionDescription(), publishConfig.getVersionDescription()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaPublishVariables variables = new LambdaPublishVariables(false, "KEY", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); variables.expandVariables(new EnvVars());
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishVariablesTest.java import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; envVars.put("ENV_REGION", "eu-west-1"); envVars.put("ENV_ARN", "ARN"); envVars.put("ENV_ALIAS", "ALIAS"); envVars.put("ENV_VERSIONDESCRIPTION", "DESCRIPTION"); clone.expandVariables(envVars); LambdaPublishVariables expected = new LambdaPublishVariables(false, "ID", Secret.fromString("$ENV_SECRET}}"), "eu-west-1", "ARN", "ALIAS", "description DESCRIPTION"); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionARN(), clone.getFunctionARN()); assertEquals(expected.getFunctionAlias(), clone.getFunctionAlias()); assertEquals(expected.getVersionDescription(), clone.getVersionDescription()); } @Test public void testGetPublishConfig() throws Exception { LambdaPublishVariables variables = new LambdaPublishVariables("eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); PublishConfig publishConfig = variables.getPublishConfig(); assertEquals(variables.getFunctionAlias(), publishConfig.getFunctionAlias()); assertEquals(variables.getFunctionARN(), publishConfig.getFunctionARN()); assertEquals(variables.getVersionDescription(), publishConfig.getVersionDescription()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaPublishVariables variables = new LambdaPublishVariables(false, "KEY", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); variables.expandVariables(new EnvVars());
LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/service/LambdaClientConfigTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail;
package com.xti.jenkins.plugin.awslambda.service; public class LambdaClientConfigTest { @Test public void testGetClient() throws Exception {
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/service/LambdaClientConfigTest.java import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; package com.xti.jenkins.plugin.awslambda.service; public class LambdaClientConfigTest { @Test public void testGetClient() throws Exception {
LambdaClientConfig lambdaClientConfig = new LambdaClientConfig("abc", "def", "eu-west-1", JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/service/LambdaClientConfigTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail;
package com.xti.jenkins.plugin.awslambda.service; public class LambdaClientConfigTest { @Test public void testGetClient() throws Exception {
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/service/LambdaClientConfigTest.java import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; package com.xti.jenkins.plugin.awslambda.service; public class LambdaClientConfigTest { @Test public void testGetClient() throws Exception {
LambdaClientConfig lambdaClientConfig = new LambdaClientConfig("abc", "def", "eu-west-1", JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStep.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/EventSourceCallable.java // public class EventSourceCallable implements Callable<Boolean, RuntimeException> { // // private TaskListener listener; // private EventSourceConfig eventSourceConfig; // private LambdaClientConfig clientConfig; // // public EventSourceCallable(TaskListener listener, EventSourceConfig eventSourceConfig, LambdaClientConfig clientConfig) { // this.listener = listener; // this.eventSourceConfig = eventSourceConfig; // this.clientConfig = clientConfig; // } // // @Override // public Boolean call() throws RuntimeException { // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaDeployService service = new LambdaDeployService(clientConfig.getClient(), logger); // EventSourceBuilder builder = new EventSourceBuilder(service, logger); // // return builder.createEventSource(eventSourceConfig); // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.callable.EventSourceCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException;
package com.xti.jenkins.plugin.awslambda.eventsource; /** * Created by anthonyikeda on 25/11/2015. * */ public class LambdaEventSourceBuildStep extends Builder implements SimpleBuildStep { private LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables; @DataBoundConstructor public LambdaEventSourceBuildStep(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables) { this.lambdaEventSourceBuildStepVariables = lambdaEventSourceBuildStepVariables; } public LambdaEventSourceBuildStepVariables getLambdaEventSourceBuildStepVariables() { return this.lambdaEventSourceBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaEventSourceBuildStepVariables, run, launcher, listener); } public void perform(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaEventSourceBuildStepVariables executionVariables = lambdaEventSourceBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); EventSourceConfig eventSourceConfig = executionVariables.getEventSourceConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/EventSourceCallable.java // public class EventSourceCallable implements Callable<Boolean, RuntimeException> { // // private TaskListener listener; // private EventSourceConfig eventSourceConfig; // private LambdaClientConfig clientConfig; // // public EventSourceCallable(TaskListener listener, EventSourceConfig eventSourceConfig, LambdaClientConfig clientConfig) { // this.listener = listener; // this.eventSourceConfig = eventSourceConfig; // this.clientConfig = clientConfig; // } // // @Override // public Boolean call() throws RuntimeException { // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaDeployService service = new LambdaDeployService(clientConfig.getClient(), logger); // EventSourceBuilder builder = new EventSourceBuilder(service, logger); // // return builder.createEventSource(eventSourceConfig); // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStep.java import com.xti.jenkins.plugin.awslambda.callable.EventSourceCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException; package com.xti.jenkins.plugin.awslambda.eventsource; /** * Created by anthonyikeda on 25/11/2015. * */ public class LambdaEventSourceBuildStep extends Builder implements SimpleBuildStep { private LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables; @DataBoundConstructor public LambdaEventSourceBuildStep(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables) { this.lambdaEventSourceBuildStepVariables = lambdaEventSourceBuildStepVariables; } public LambdaEventSourceBuildStepVariables getLambdaEventSourceBuildStepVariables() { return this.lambdaEventSourceBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaEventSourceBuildStepVariables, run, launcher, listener); } public void perform(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaEventSourceBuildStepVariables executionVariables = lambdaEventSourceBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); EventSourceConfig eventSourceConfig = executionVariables.getEventSourceConfig();
LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStep.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/EventSourceCallable.java // public class EventSourceCallable implements Callable<Boolean, RuntimeException> { // // private TaskListener listener; // private EventSourceConfig eventSourceConfig; // private LambdaClientConfig clientConfig; // // public EventSourceCallable(TaskListener listener, EventSourceConfig eventSourceConfig, LambdaClientConfig clientConfig) { // this.listener = listener; // this.eventSourceConfig = eventSourceConfig; // this.clientConfig = clientConfig; // } // // @Override // public Boolean call() throws RuntimeException { // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaDeployService service = new LambdaDeployService(clientConfig.getClient(), logger); // EventSourceBuilder builder = new EventSourceBuilder(service, logger); // // return builder.createEventSource(eventSourceConfig); // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.callable.EventSourceCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException;
package com.xti.jenkins.plugin.awslambda.eventsource; /** * Created by anthonyikeda on 25/11/2015. * */ public class LambdaEventSourceBuildStep extends Builder implements SimpleBuildStep { private LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables; @DataBoundConstructor public LambdaEventSourceBuildStep(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables) { this.lambdaEventSourceBuildStepVariables = lambdaEventSourceBuildStepVariables; } public LambdaEventSourceBuildStepVariables getLambdaEventSourceBuildStepVariables() { return this.lambdaEventSourceBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaEventSourceBuildStepVariables, run, launcher, listener); } public void perform(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaEventSourceBuildStepVariables executionVariables = lambdaEventSourceBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); EventSourceConfig eventSourceConfig = executionVariables.getEventSourceConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/EventSourceCallable.java // public class EventSourceCallable implements Callable<Boolean, RuntimeException> { // // private TaskListener listener; // private EventSourceConfig eventSourceConfig; // private LambdaClientConfig clientConfig; // // public EventSourceCallable(TaskListener listener, EventSourceConfig eventSourceConfig, LambdaClientConfig clientConfig) { // this.listener = listener; // this.eventSourceConfig = eventSourceConfig; // this.clientConfig = clientConfig; // } // // @Override // public Boolean call() throws RuntimeException { // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaDeployService service = new LambdaDeployService(clientConfig.getClient(), logger); // EventSourceBuilder builder = new EventSourceBuilder(service, logger); // // return builder.createEventSource(eventSourceConfig); // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceBuildStep.java import com.xti.jenkins.plugin.awslambda.callable.EventSourceCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException; package com.xti.jenkins.plugin.awslambda.eventsource; /** * Created by anthonyikeda on 25/11/2015. * */ public class LambdaEventSourceBuildStep extends Builder implements SimpleBuildStep { private LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables; @DataBoundConstructor public LambdaEventSourceBuildStep(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables) { this.lambdaEventSourceBuildStepVariables = lambdaEventSourceBuildStepVariables; } public LambdaEventSourceBuildStepVariables getLambdaEventSourceBuildStepVariables() { return this.lambdaEventSourceBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaEventSourceBuildStepVariables, run, launcher, listener); } public void perform(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaEventSourceBuildStepVariables executionVariables = lambdaEventSourceBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); EventSourceConfig eventSourceConfig = executionVariables.getEventSourceConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
EventSourceCallable eventSourceCallable = new EventSourceCallable(listener, eventSourceConfig, clientConfig);
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/PublishConfig.java // public class PublishConfig implements Serializable { // // private static final long serialVersionUID = 1L; // // private String functionAlias; // private String functionARN; // private String versionDescription; // // public PublishConfig(String functionAlias, String functionARN, String versionDescription){ // this.functionAlias = functionAlias; // this.functionARN = functionARN; // this.versionDescription = versionDescription; // } // // public void setFunctionAlias(String alias) { // this.functionAlias = alias; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public void setFunctionARN(String functionARN){ // this.functionARN = functionARN; // } // // public String getFunctionARN(){ // return this.functionARN; // } // // public String getVersionDescription() { // return this.versionDescription; // } // // public void setVersionDescription(String versionDescription){ // this.versionDescription = versionDescription; // } // }
import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.publish.PublishConfig;
package com.xti.jenkins.plugin.awslambda.service; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/PublishConfig.java // public class PublishConfig implements Serializable { // // private static final long serialVersionUID = 1L; // // private String functionAlias; // private String functionARN; // private String versionDescription; // // public PublishConfig(String functionAlias, String functionARN, String versionDescription){ // this.functionAlias = functionAlias; // this.functionARN = functionARN; // this.versionDescription = versionDescription; // } // // public void setFunctionAlias(String alias) { // this.functionAlias = alias; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public void setFunctionARN(String functionARN){ // this.functionARN = functionARN; // } // // public String getFunctionARN(){ // return this.functionARN; // } // // public String getVersionDescription() { // return this.versionDescription; // } // // public void setVersionDescription(String versionDescription){ // this.versionDescription = versionDescription; // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.publish.PublishConfig; package com.xti.jenkins.plugin.awslambda.service; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
public LambdaPublishServiceResponse publishLambda(PublishConfig config){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/PublishConfig.java // public class PublishConfig implements Serializable { // // private static final long serialVersionUID = 1L; // // private String functionAlias; // private String functionARN; // private String versionDescription; // // public PublishConfig(String functionAlias, String functionARN, String versionDescription){ // this.functionAlias = functionAlias; // this.functionARN = functionARN; // this.versionDescription = versionDescription; // } // // public void setFunctionAlias(String alias) { // this.functionAlias = alias; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public void setFunctionARN(String functionARN){ // this.functionARN = functionARN; // } // // public String getFunctionARN(){ // return this.functionARN; // } // // public String getVersionDescription() { // return this.versionDescription; // } // // public void setVersionDescription(String versionDescription){ // this.versionDescription = versionDescription; // } // }
import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.publish.PublishConfig;
package com.xti.jenkins.plugin.awslambda.service; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/PublishConfig.java // public class PublishConfig implements Serializable { // // private static final long serialVersionUID = 1L; // // private String functionAlias; // private String functionARN; // private String versionDescription; // // public PublishConfig(String functionAlias, String functionARN, String versionDescription){ // this.functionAlias = functionAlias; // this.functionARN = functionARN; // this.versionDescription = versionDescription; // } // // public void setFunctionAlias(String alias) { // this.functionAlias = alias; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public void setFunctionARN(String functionARN){ // this.functionARN = functionARN; // } // // public String getFunctionARN(){ // return this.functionARN; // } // // public String getVersionDescription() { // return this.versionDescription; // } // // public void setVersionDescription(String versionDescription){ // this.versionDescription = versionDescription; // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.*; import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.publish.PublishConfig; package com.xti.jenkins.plugin.awslambda.service; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; }
public LambdaPublishServiceResponse publishLambda(PublishConfig config){
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionName(), clone.getFunctionName()); assertEquals(expected.getPayload(), clone.getPayload()); assertEquals(expected.getSynchronous(), clone.getSynchronous()); assertEquals(expected.getSuccessOnly(), clone.getSuccessOnly()); assertEquals(expected.getJsonParameters().get(0).getEnvVarName(), clone.getJsonParameters().get(0).getEnvVarName()); assertEquals(expected.getJsonParameters().get(0).getJsonPath(), clone.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetInvokeConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeVariables variables = new LambdaInvokeVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, true, jsonParameterVariables); InvokeConfig invokeConfig = variables.getInvokeConfig(); assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName()); assertEquals(variables.getPayload(), invokeConfig.getPayload()); assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous()); assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName()); assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetLambdaClientConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeVariables variables = new LambdaInvokeVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, true, jsonParameterVariables);
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariablesTest.java import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionName(), clone.getFunctionName()); assertEquals(expected.getPayload(), clone.getPayload()); assertEquals(expected.getSynchronous(), clone.getSynchronous()); assertEquals(expected.getSuccessOnly(), clone.getSuccessOnly()); assertEquals(expected.getJsonParameters().get(0).getEnvVarName(), clone.getJsonParameters().get(0).getEnvVarName()); assertEquals(expected.getJsonParameters().get(0).getJsonPath(), clone.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetInvokeConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeVariables variables = new LambdaInvokeVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, true, jsonParameterVariables); InvokeConfig invokeConfig = variables.getInvokeConfig(); assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName()); assertEquals(variables.getPayload(), invokeConfig.getPayload()); assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous()); assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName()); assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath()); } @Test public void testGetLambdaClientConfig() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path")); LambdaInvokeVariables variables = new LambdaInvokeVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, true, jsonParameterVariables);
LambdaClientConfig clientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeBuildStepVariables getClone(){ LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables = new LambdaInvokeBuildStepVariables(awsRegion, functionName, synchronous); lambdaInvokeBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeBuildStepVariables.setPayload(payload); lambdaInvokeBuildStepVariables.setJsonParameters(jsonParameters); return lambdaInvokeBuildStepVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariables.java import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeBuildStepVariables getClone(){ LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables = new LambdaInvokeBuildStepVariables(awsRegion, functionName, synchronous); lambdaInvokeBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeBuildStepVariables.setPayload(payload); lambdaInvokeBuildStepVariables.setJsonParameters(jsonParameters); return lambdaInvokeBuildStepVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
} } public LambdaInvokeBuildStepVariables getClone(){ LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables = new LambdaInvokeBuildStepVariables(awsRegion, functionName, synchronous); lambdaInvokeBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeBuildStepVariables.setPayload(payload); lambdaInvokeBuildStepVariables.setJsonParameters(jsonParameters); return lambdaInvokeBuildStepVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } @Extension // This indicates to Jenkins that this is an implementation of an extension point.
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeBuildStepVariables.java import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; } } public LambdaInvokeBuildStepVariables getClone(){ LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables = new LambdaInvokeBuildStepVariables(awsRegion, functionName, synchronous); lambdaInvokeBuildStepVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeBuildStepVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeBuildStepVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeBuildStepVariables.setPayload(payload); lambdaInvokeBuildStepVariables.setJsonParameters(jsonParameters); return lambdaInvokeBuildStepVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } @Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static class DescriptorImpl extends AWSLambdaDescriptor<LambdaInvokeBuildStepVariables> {
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
public String getFunctionName() { return functionName; } public String getEventSourceArn() { return eventSourceArn; } public boolean getSuccessOnly() { return successOnly; } @DataBoundSetter public void setSuccessOnly(boolean successOnly) { this.successOnly = successOnly; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; public String getFunctionName() { return functionName; } public String getEventSourceArn() { return eventSourceArn; } public boolean getSuccessOnly() { return successOnly; } @DataBoundSetter public void setSuccessOnly(boolean successOnly) { this.successOnly = successOnly; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); }
public LambdaClientConfig getLambdaClientConfig(){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
} public String getEventSourceArn() { return eventSourceArn; } public boolean getSuccessOnly() { return successOnly; } @DataBoundSetter public void setSuccessOnly(boolean successOnly) { this.successOnly = successOnly; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; } public String getEventSourceArn() { return eventSourceArn; } public boolean getSuccessOnly() { return successOnly; } @DataBoundSetter public void setSuccessOnly(boolean successOnly) { this.successOnly = successOnly; } public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } public LambdaEventSourceVariables getClone() { LambdaEventSourceVariables lambdaEventSourceVariables = new LambdaEventSourceVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceVariables.setFunctionAlias(functionAlias); lambdaEventSourceVariables.setSuccessOnly(successOnly); return lambdaEventSourceVariables; } @Extension
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/eventsource/LambdaEventSourceVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); functionAlias = ExpansionUtils.expand(functionAlias, env); eventSourceArn = ExpansionUtils.expand(eventSourceArn, env); } public EventSourceConfig getEventSourceConfig() { return new EventSourceConfig(functionName, functionAlias, eventSourceArn); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } public LambdaEventSourceVariables getClone() { LambdaEventSourceVariables lambdaEventSourceVariables = new LambdaEventSourceVariables(awsRegion, functionName, eventSourceArn); lambdaEventSourceVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaEventSourceVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaEventSourceVariables.setAwsSecretKey(awsSecretKey); lambdaEventSourceVariables.setFunctionAlias(functionAlias); lambdaEventSourceVariables.setSuccessOnly(successOnly); return lambdaEventSourceVariables; } @Extension
public static class DescriptorImpl extends AWSLambdaDescriptor<LambdaEventSourceVariables> {
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List;
package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishPublisher extends Notifier { List<LambdaPublishVariables> lambdaPublishVariablesList = new ArrayList<>(); @DataBoundConstructor public LambdaPublishPublisher(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List; package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishPublisher extends Notifier { List<LambdaPublishVariables> lambdaPublishVariablesList = new ArrayList<>(); @DataBoundConstructor public LambdaPublishPublisher(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig();
LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List;
package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishPublisher extends Notifier { List<LambdaPublishVariables> lambdaPublishVariablesList = new ArrayList<>(); @DataBoundConstructor public LambdaPublishPublisher(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List; package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishPublisher extends Notifier { List<LambdaPublishVariables> lambdaPublishVariablesList = new ArrayList<>(); @DataBoundConstructor public LambdaPublishPublisher(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig);
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List;
public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig(); PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig);
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishServiceResponse.java // public class LambdaPublishServiceResponse { // private String functionVersion; // private String functionAlias; // private boolean success; // // public LambdaPublishServiceResponse(String functionVersion, String functionAlias, boolean success){ // this.functionAlias = functionAlias; // this.functionVersion = functionVersion; // this.success = success; // } // // public String getFunctionVersion(){ // return this.functionVersion; // } // // public String getFunctionAlias(){ // return this.functionAlias; // } // // public boolean getSuccess(){ // return this.success; // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishPublisher.java import com.xti.jenkins.plugin.awslambda.publish.LambdaPublishServiceResponse; import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.List; public List<LambdaPublishVariables> getLambdaPublishVariablesList() { return lambdaPublishVariablesList; } public void setLambdaPublishVariablesList(List<LambdaPublishVariables> lambdaPublishVariablesList) { this.lambdaPublishVariablesList = lambdaPublishVariablesList; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { boolean returnValue = true; if(lambdaPublishVariablesList != null) { for(LambdaPublishVariables variables : lambdaPublishVariablesList) { returnValue = returnValue && perform(variables, build, launcher, listener); } } return returnValue; } public boolean perform(LambdaPublishVariables variables, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { try { LambdaPublishVariables executionVariables = variables.getClone(); executionVariables.expandVariables(build.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig(); PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig);
LambdaPublishServiceResponse lambdaRepsonse = launcher.getChannel().call(publishCallable);
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java // public class LambdaPublishService { // private AWSLambdaClient client; // private JenkinsLogger logger; // // public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { // this.client = client; // this.logger = logger; // } // // public LambdaPublishServiceResponse publishLambda(PublishConfig config){ // // GetAliasRequest getAliasRequest = new GetAliasRequest() // .withName(config.getFunctionAlias()) // .withFunctionName(config.getFunctionARN()); // // logger.log("Lambda function alias existence check:%n%s%n%s%n", config.getFunctionARN(), config.getFunctionAlias()); // try { // GetAliasResult functionResult = client.getAlias(getAliasRequest); // logger.log("Lambda function alias exists:%n%s%n", functionResult.toString()); // } catch (ResourceNotFoundException rnfe) { // return new LambdaPublishServiceResponse("", "", false); // } // // logger.log("Publishing new version"); // // PublishVersionRequest publishVersionRequest = new PublishVersionRequest().withFunctionName(config.getFunctionARN()).withDescription(config.getVersionDescription()); // PublishVersionResult publishVersionResult = client.publishVersion(publishVersionRequest); // // logger.log(publishVersionResult.toString()); // // logger.log("Updating alias"); // // UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest().withName(config.getFunctionAlias()); // updateAliasRequest.setFunctionName(config.getFunctionARN()); // updateAliasRequest.setDescription(config.getVersionDescription()); // updateAliasRequest.setFunctionVersion(publishVersionResult.getVersion()); // // UpdateAliasResult updateAliasResult = client.updateAlias(updateAliasRequest); // // logger.log(updateAliasResult.toString()); // // return new LambdaPublishServiceResponse(publishVersionResult.getVersion(), updateAliasResult.getName(), true); // } // // }
import com.xti.jenkins.plugin.awslambda.service.JenkinsLogger; import com.xti.jenkins.plugin.awslambda.service.LambdaPublishService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.xti.jenkins.plugin.awslambda.publish; /** * Created by Magnus Sulland on 4/08/2016. */ @RunWith(MockitoJUnitRunner.class) public class LambdaPublishTest { @Mock
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaPublishService.java // public class LambdaPublishService { // private AWSLambdaClient client; // private JenkinsLogger logger; // // public LambdaPublishService(AWSLambdaClient client, JenkinsLogger logger) { // this.client = client; // this.logger = logger; // } // // public LambdaPublishServiceResponse publishLambda(PublishConfig config){ // // GetAliasRequest getAliasRequest = new GetAliasRequest() // .withName(config.getFunctionAlias()) // .withFunctionName(config.getFunctionARN()); // // logger.log("Lambda function alias existence check:%n%s%n%s%n", config.getFunctionARN(), config.getFunctionAlias()); // try { // GetAliasResult functionResult = client.getAlias(getAliasRequest); // logger.log("Lambda function alias exists:%n%s%n", functionResult.toString()); // } catch (ResourceNotFoundException rnfe) { // return new LambdaPublishServiceResponse("", "", false); // } // // logger.log("Publishing new version"); // // PublishVersionRequest publishVersionRequest = new PublishVersionRequest().withFunctionName(config.getFunctionARN()).withDescription(config.getVersionDescription()); // PublishVersionResult publishVersionResult = client.publishVersion(publishVersionRequest); // // logger.log(publishVersionResult.toString()); // // logger.log("Updating alias"); // // UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest().withName(config.getFunctionAlias()); // updateAliasRequest.setFunctionName(config.getFunctionARN()); // updateAliasRequest.setDescription(config.getVersionDescription()); // updateAliasRequest.setFunctionVersion(publishVersionResult.getVersion()); // // UpdateAliasResult updateAliasResult = client.updateAlias(updateAliasRequest); // // logger.log(updateAliasResult.toString()); // // return new LambdaPublishServiceResponse(publishVersionResult.getVersion(), updateAliasResult.getName(), true); // } // // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishTest.java import com.xti.jenkins.plugin.awslambda.service.JenkinsLogger; import com.xti.jenkins.plugin.awslambda.service.LambdaPublishService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.xti.jenkins.plugin.awslambda.publish; /** * Created by Magnus Sulland on 4/08/2016. */ @RunWith(MockitoJUnitRunner.class) public class LambdaPublishTest { @Mock
private LambdaPublishService service;
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaInvokeService.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/InvokeConfig.java // public class InvokeConfig implements Serializable { // private String functionName; // private String payload; // private boolean synchronous; // private List<JsonParameter> jsonParameters; // // public InvokeConfig(String functionName, String payload, boolean synchronous, List<JsonParameter> jsonParameters) { // this.functionName = functionName; // this.payload = payload; // this.synchronous = synchronous; // this.jsonParameters = jsonParameters; // } // // public String getFunctionName() { // return functionName; // } // // public void setFunctionName(String functionName) { // this.functionName = functionName; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public boolean isSynchronous() { // return synchronous; // } // // public void setSynchronous(boolean synchronous) { // this.synchronous = synchronous; // } // // public List<JsonParameter> getJsonParameters() { // return jsonParameters; // } // // public void setJsonParameters(List<JsonParameter> jsonParameters) { // this.jsonParameters = jsonParameters; // } // }
import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.InvocationType; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult; import com.amazonaws.services.lambda.model.LogType; import com.amazonaws.util.Base64; import com.xti.jenkins.plugin.awslambda.exception.LambdaInvokeException; import com.xti.jenkins.plugin.awslambda.invoke.InvokeConfig; import org.apache.commons.lang.StringUtils; import java.nio.charset.Charset;
package com.xti.jenkins.plugin.awslambda.service; public class LambdaInvokeService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaInvokeService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; } /** * Synchronously or asynchronously invokes an AWS Lambda function. * If synchronously invoked, the AWS Lambda log is collected and the response payload is returned * @param invokeConfig AWS Lambda invocation configuration * @return response payload */
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/InvokeConfig.java // public class InvokeConfig implements Serializable { // private String functionName; // private String payload; // private boolean synchronous; // private List<JsonParameter> jsonParameters; // // public InvokeConfig(String functionName, String payload, boolean synchronous, List<JsonParameter> jsonParameters) { // this.functionName = functionName; // this.payload = payload; // this.synchronous = synchronous; // this.jsonParameters = jsonParameters; // } // // public String getFunctionName() { // return functionName; // } // // public void setFunctionName(String functionName) { // this.functionName = functionName; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public boolean isSynchronous() { // return synchronous; // } // // public void setSynchronous(boolean synchronous) { // this.synchronous = synchronous; // } // // public List<JsonParameter> getJsonParameters() { // return jsonParameters; // } // // public void setJsonParameters(List<JsonParameter> jsonParameters) { // this.jsonParameters = jsonParameters; // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/LambdaInvokeService.java import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.InvocationType; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult; import com.amazonaws.services.lambda.model.LogType; import com.amazonaws.util.Base64; import com.xti.jenkins.plugin.awslambda.exception.LambdaInvokeException; import com.xti.jenkins.plugin.awslambda.invoke.InvokeConfig; import org.apache.commons.lang.StringUtils; import java.nio.charset.Charset; package com.xti.jenkins.plugin.awslambda.service; public class LambdaInvokeService { private AWSLambdaClient client; private JenkinsLogger logger; public LambdaInvokeService(AWSLambdaClient client, JenkinsLogger logger) { this.client = client; this.logger = logger; } /** * Synchronously or asynchronously invokes an AWS Lambda function. * If synchronously invoked, the AWS Lambda log is collected and the response payload is returned * @param invokeConfig AWS Lambda invocation configuration * @return response payload */
public String invokeLambdaFunction(InvokeConfig invokeConfig) throws LambdaInvokeException {
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); }
public LambdaClientConfig getLambdaClientConfig(){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } } public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig;
} public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } @Extension // This indicates to Jenkins that this is an implementation of an extension point.
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/invoke/LambdaInvokeVariables.java import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.List; import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; } public LambdaInvokeVariables getClone(){ LambdaInvokeVariables lambdaInvokeVariables = new LambdaInvokeVariables(awsRegion, functionName, synchronous); lambdaInvokeVariables.setUseInstanceCredentials(useInstanceCredentials); lambdaInvokeVariables.setAwsAccessKeyId(awsAccessKeyId); lambdaInvokeVariables.setAwsSecretKey(awsSecretKey); lambdaInvokeVariables.setPayload(payload); lambdaInvokeVariables.setSuccessOnly(successOnly); lambdaInvokeVariables.setJsonParameters(jsonParameters); return lambdaInvokeVariables; } public InvokeConfig getInvokeConfig(){ List<JsonParameter> jsonParameters = new ArrayList<JsonParameter>(); for (JsonParameterVariables jsonParameterVariables : getJsonParameters()) { jsonParameters.add(jsonParameterVariables.buildJsonParameter()); } return new InvokeConfig(functionName, payload, synchronous, jsonParameters); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){ return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig()); } else { return new LambdaClientConfig(awsAccessKeyId, clearTextAwsSecretKey, awsRegion, JenkinsProxy.getConfig()); } } @Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static class DescriptorImpl extends AWSLambdaDescriptor<LambdaInvokeVariables> {
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariablesTest.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
envVars.put("ENV_REGION", "eu-west-1"); envVars.put("ENV_ARN", "ARN"); envVars.put("ENV_ALIAS", "ALIAS"); envVars.put("ENV_VERSIONDESCRIPTION", "DESCRIPTION"); clone.expandVariables(envVars); LambdaPublishBuildStepVariables expected = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("$ENV_SECRET}}"), "eu-west-1", "ARN", "ALIAS", "description DESCRIPTION"); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionARN(), clone.getFunctionARN()); assertEquals(expected.getFunctionAlias(), clone.getFunctionAlias()); assertEquals(expected.getVersionDescription(), clone.getVersionDescription()); } @Test public void testGetPublishConfig() throws Exception { LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); PublishConfig publishConfig = variables.getPublishConfig(); assertEquals(variables.getFunctionARN(), publishConfig.getFunctionARN()); assertEquals(variables.getVersionDescription(), publishConfig.getVersionDescription()); assertEquals(variables.getFunctionAlias(), publishConfig.getFunctionAlias()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); variables.expandVariables(new EnvVars());
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariablesTest.java import com.amazonaws.services.lambda.AWSLambda; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.util.Secret; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; envVars.put("ENV_REGION", "eu-west-1"); envVars.put("ENV_ARN", "ARN"); envVars.put("ENV_ALIAS", "ALIAS"); envVars.put("ENV_VERSIONDESCRIPTION", "DESCRIPTION"); clone.expandVariables(envVars); LambdaPublishBuildStepVariables expected = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("$ENV_SECRET}}"), "eu-west-1", "ARN", "ALIAS", "description DESCRIPTION"); assertEquals(expected.getAwsAccessKeyId(), clone.getAwsAccessKeyId()); assertEquals(expected.getAwsSecretKey(), clone.getAwsSecretKey()); assertEquals(expected.getAwsRegion(), clone.getAwsRegion()); assertEquals(expected.getFunctionARN(), clone.getFunctionARN()); assertEquals(expected.getFunctionAlias(), clone.getFunctionAlias()); assertEquals(expected.getVersionDescription(), clone.getVersionDescription()); } @Test public void testGetPublishConfig() throws Exception { LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); PublishConfig publishConfig = variables.getPublishConfig(); assertEquals(variables.getFunctionARN(), publishConfig.getFunctionARN()); assertEquals(variables.getVersionDescription(), publishConfig.getVersionDescription()); assertEquals(variables.getFunctionAlias(), publishConfig.getFunctionAlias()); } @Test public void testGetLambdaClientConfig() throws Exception { LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); variables.expandVariables(new EnvVars());
LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStep.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException;
package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishBuildStep extends Builder implements SimpleBuildStep { private LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables; @DataBoundConstructor public LambdaPublishBuildStep(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables) { this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } public LambdaPublishBuildStepVariables getLambdaPublishBuildStepVariables() { return this.lambdaPublishBuildStepVariables; } public void setLambdaPublishBuildStepVariables(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables){ this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaPublishBuildStepVariables, run, launcher, listener); } public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStep.java import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException; package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishBuildStep extends Builder implements SimpleBuildStep { private LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables; @DataBoundConstructor public LambdaPublishBuildStep(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables) { this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } public LambdaPublishBuildStepVariables getLambdaPublishBuildStepVariables() { return this.lambdaPublishBuildStepVariables; } public void setLambdaPublishBuildStepVariables(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables){ this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaPublishBuildStepVariables, run, launcher, listener); } public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig();
LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStep.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException;
package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishBuildStep extends Builder implements SimpleBuildStep { private LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables; @DataBoundConstructor public LambdaPublishBuildStep(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables) { this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } public LambdaPublishBuildStepVariables getLambdaPublishBuildStepVariables() { return this.lambdaPublishBuildStepVariables; } public void setLambdaPublishBuildStepVariables(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables){ this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaPublishBuildStepVariables, run, launcher, listener); } public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/callable/PublishCallable.java // public class PublishCallable implements Callable<LambdaPublishServiceResponse, RuntimeException> { // // private TaskListener listener; // private PublishConfig publishConfig; // private LambdaClientConfig clientConfig; // // public PublishCallable(TaskListener listener, PublishConfig publishConfig, LambdaClientConfig lambdaClientConfig) { // this.listener = listener; // this.publishConfig = publishConfig; // this.clientConfig = lambdaClientConfig; // } // // @Override // public LambdaPublishServiceResponse call() throws RuntimeException { // // JenkinsLogger logger = new JenkinsLogger(listener.getLogger()); // LambdaPublishService service = new LambdaPublishService(clientConfig.getClient(), logger); // // try { // LambdaPublisher publishPublisher = new LambdaPublisher(service, logger); // return publishPublisher.publish(publishConfig); // } catch (IOException | InterruptedException e) { // throw new RuntimeException(e); // } // } // // @Override // public void checkRoles(RoleChecker roleChecker) throws SecurityException { // //ignore for now // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStep.java import com.xti.jenkins.plugin.awslambda.callable.PublishCallable; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.Nonnull; import java.io.IOException; package com.xti.jenkins.plugin.awslambda.publish; /** * Project: aws-lambda * Created by Magnus Sulland on 26/07/2016. */ public class LambdaPublishBuildStep extends Builder implements SimpleBuildStep { private LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables; @DataBoundConstructor public LambdaPublishBuildStep(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables) { this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } public LambdaPublishBuildStepVariables getLambdaPublishBuildStepVariables() { return this.lambdaPublishBuildStepVariables; } public void setLambdaPublishBuildStepVariables(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables){ this.lambdaPublishBuildStepVariables = lambdaPublishBuildStepVariables; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { perform(lambdaPublishBuildStepVariables, run, launcher, listener); } public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig);
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipperTest.java
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // }
import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleProject; import hudson.util.OneShotEvent; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipFile; import static org.junit.Assert.*;
package com.xti.jenkins.plugin.awslambda.service; public class WorkSpaceZipperTest { @Rule public JenkinsRule j = new JenkinsRule();
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipperTest.java import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleProject; import hudson.util.OneShotEvent; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipFile; import static org.junit.Assert.*; package com.xti.jenkins.plugin.awslambda.service; public class WorkSpaceZipperTest { @Rule public JenkinsRule j = new JenkinsRule();
private TestUtil testUtil = new TestUtil();
XT-i/aws-lambda-jenkins-plugin
src/test/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipperTest.java
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // }
import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleProject; import hudson.util.OneShotEvent; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipFile; import static org.junit.Assert.*;
} }); p.scheduleBuild2(0); buildEnded.block(); JenkinsLogger logger = new JenkinsLogger(System.out); WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger); File zip = workSpaceZipper.getZip("echo"); assertTrue(zip.exists()); assertTrue(zip.getAbsolutePath().contains("awslambda-")); ZipFile zipFile = new ZipFile(zip); assertNotNull(zipFile); assertNotNull(zipFile.getEntry("index.js")); } @Test public void testGetZipFileNotExists() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.scheduleBuild2(0).get(); JenkinsLogger logger = new JenkinsLogger(System.out); WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger); try { workSpaceZipper.getZip("echo.zip"); fail("Expected LambdaDeployException.");
// Path: src/test/java/com/xti/jenkins/plugin/awslambda/TestUtil.java // public class TestUtil { // public File getResource(String resourcePath){ // ClassLoader classLoader = getClass().getClassLoader(); // URL resource = classLoader.getResource(resourcePath); // if(resource != null){ // try { // File tempEcho = File.createTempFile("aws-lambda-plugin", "echo.zip"); // FileUtils.copyFile(new File(resource.getFile()), tempEcho); // tempEcho.deleteOnExit(); // return tempEcho; // } catch (IOException e) { // throw new IllegalStateException("Could not load " + resourcePath); // } // // } else { // throw new IllegalStateException("Could not load " + resourcePath); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/test/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipperTest.java import com.xti.jenkins.plugin.awslambda.TestUtil; import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleProject; import hudson.util.OneShotEvent; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipFile; import static org.junit.Assert.*; } }); p.scheduleBuild2(0); buildEnded.block(); JenkinsLogger logger = new JenkinsLogger(System.out); WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger); File zip = workSpaceZipper.getZip("echo"); assertTrue(zip.exists()); assertTrue(zip.getAbsolutePath().contains("awslambda-")); ZipFile zipFile = new ZipFile(zip); assertNotNull(zipFile); assertNotNull(zipFile.getEntry("index.js")); } @Test public void testGetZipFileNotExists() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.scheduleBuild2(0).get(); JenkinsLogger logger = new JenkinsLogger(System.out); WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger); try { workSpaceZipper.getZip("echo.zip"); fail("Expected LambdaDeployException.");
} catch (LambdaDeployException lde){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipper.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // }
import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.FilePath; import hudson.util.DirScanner; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;
package com.xti.jenkins.plugin.awslambda.service; public class WorkSpaceZipper { private FilePath workSpace; private JenkinsLogger logger; public WorkSpaceZipper(FilePath workSpace, JenkinsLogger logger) { this.workSpace = workSpace; this.logger = logger; } public File getZip(String artifactLocation) throws IOException, InterruptedException { FilePath artifactFilePath = null; if(StringUtils.isNotEmpty(artifactLocation)) { artifactFilePath = new FilePath(workSpace, artifactLocation); } File zipFile = null; if(artifactFilePath != null){ zipFile = getArtifactZip(artifactFilePath); } return zipFile; } private File getArtifactZip(FilePath artifactLocation) throws IOException, InterruptedException { File resultFile = File.createTempFile("awslambda-", ".zip"); if (!artifactLocation.isDirectory()) { if(artifactLocation.exists()) { logger.log("Copying zip file"); artifactLocation.copyTo(new FileOutputStream(resultFile)); } else {
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/exception/LambdaDeployException.java // public class LambdaDeployException extends AWSLambdaPluginException { // // public LambdaDeployException(String message) { // super(message); // } // // public LambdaDeployException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/service/WorkSpaceZipper.java import com.xti.jenkins.plugin.awslambda.exception.LambdaDeployException; import hudson.FilePath; import hudson.util.DirScanner; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; package com.xti.jenkins.plugin.awslambda.service; public class WorkSpaceZipper { private FilePath workSpace; private JenkinsLogger logger; public WorkSpaceZipper(FilePath workSpace, JenkinsLogger logger) { this.workSpace = workSpace; this.logger = logger; } public File getZip(String artifactLocation) throws IOException, InterruptedException { FilePath artifactFilePath = null; if(StringUtils.isNotEmpty(artifactLocation)) { artifactFilePath = new FilePath(workSpace, artifactLocation); } File zipFile = null; if(artifactFilePath != null){ zipFile = getArtifactZip(artifactFilePath); } return zipFile; } private File getArtifactZip(FilePath artifactLocation) throws IOException, InterruptedException { File resultFile = File.createTempFile("awslambda-", ".zip"); if (!artifactLocation.isDirectory()) { if(artifactLocation.exists()) { logger.log("Copying zip file"); artifactLocation.copyTo(new FileOutputStream(resultFile)); } else {
throw new LambdaDeployException("Could not find zipfile or folder.");
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
} public String getAwsSecretKey() { return this.awsSecretKey; } public String getAwsRegion() { return this.awsRegion; } public String getFunctionARN() { return this.functionARN; } public String getFunctionAlias() { return this.functionAlias; } public String getVersionDescription() { return this.versionDescription; } public void setVersionDescription(String versionDescription){ this.versionDescription = versionDescription; } public PublishConfig getPublishConfig() { return new PublishConfig(this.functionAlias, this.functionARN, this.versionDescription); }
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; } public String getAwsSecretKey() { return this.awsSecretKey; } public String getAwsRegion() { return this.awsRegion; } public String getFunctionARN() { return this.functionARN; } public String getFunctionAlias() { return this.functionAlias; } public String getVersionDescription() { return this.versionDescription; } public void setVersionDescription(String versionDescription){ this.versionDescription = versionDescription; } public PublishConfig getPublishConfig() { return new PublishConfig(this.functionAlias, this.functionARN, this.versionDescription); }
public LambdaClientConfig getLambdaClientConfig(){
XT-i/aws-lambda-jenkins-plugin
src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariables.java
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // }
import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
public String getAwsSecretKey() { return this.awsSecretKey; } public String getAwsRegion() { return this.awsRegion; } public String getFunctionARN() { return this.functionARN; } public String getFunctionAlias() { return this.functionAlias; } public String getVersionDescription() { return this.versionDescription; } public void setVersionDescription(String versionDescription){ this.versionDescription = versionDescription; } public PublishConfig getPublishConfig() { return new PublishConfig(this.functionAlias, this.functionARN, this.versionDescription); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
// Path: src/main/java/com/xti/jenkins/plugin/awslambda/AWSLambdaDescriptor.java // public abstract class AWSLambdaDescriptor<T extends Describable<T>> extends Descriptor<T> { // // //awsAccessKeyId field // public FormValidation doCheckAwsAccessKeyId(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Access Key Id."); // } else { // return FormValidation.ok(); // } // } // // //awsSecretKey field // public FormValidation doCheckAwsSecretKey(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Secret Id."); // } else { // return FormValidation.ok(); // } // } // // //awsRegion field // public FormValidation doCheckAwsRegion(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Region."); // } else { // return FormValidation.ok(); // } // } // // //functionName field // public FormValidation doCheckFunctionName(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function name."); // } else { // return FormValidation.ok(); // } // } // // //functionARN field // public FormValidation doCheckFunctionARN(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda function ARN."); // } else { // return FormValidation.ok(); // } // } // // //functionAlias field // public FormValidation doCheckFunctionAlias(@QueryParameter String value) { // if(StringUtils.isEmpty(value)){ // return FormValidation.error("Please fill in AWS Lambda alias name."); // } else { // return FormValidation.ok(); // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/JenkinsProxy.java // public class JenkinsProxy { // public static ProxyConfiguration getConfig(){ // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // return instance.proxy; // } else { // return null; // } // } // } // // Path: src/main/java/com/xti/jenkins/plugin/awslambda/util/LambdaClientConfig.java // public class LambdaClientConfig implements Serializable { // private String region; // private String accessKeyId; // private String secretKey; // private Boolean useDefaultAWSCredentials; // private ProxyConfiguration proxyConfiguration; // // public LambdaClientConfig(String region, ProxyConfiguration proxyConfiguration){ // this.region = region; // this.useDefaultAWSCredentials = true; // this.proxyConfiguration = proxyConfiguration; // } // // public LambdaClientConfig(String accessKeyId, String secretKey, String region, ProxyConfiguration proxyConfiguration) { // this.region = region; // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // this.useDefaultAWSCredentials = false; // this.proxyConfiguration = proxyConfiguration; // } // // public AWSLambdaClient getClient() { // if(useDefaultAWSCredentials){ // return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } else { // return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration()) // .withRegion(Region.getRegion(Regions.fromName(region))); // } // } // // private ClientConfiguration getClientConfiguration() { // /* // Jenkins instance = Jenkins.getInstance(); // // if (instance != null) { // ProxyConfiguration proxy = instance.proxy; // */ // ClientConfiguration config = new ClientConfiguration(); // // if (proxyConfiguration != null) { // config.setProxyHost(proxyConfiguration.name); // config.setProxyPort(proxyConfiguration.port); // if (proxyConfiguration.getUserName() != null) { // config.setProxyUsername(proxyConfiguration.getUserName()); // config.setProxyPassword(proxyConfiguration.getPassword()); // } // if (proxyConfiguration.noProxyHost != null) { // config.setNonProxyHosts(proxyConfiguration.noProxyHost); // } // } // // return config; // // } // } // Path: src/main/java/com/xti/jenkins/plugin/awslambda/publish/LambdaPublishBuildStepVariables.java import com.xti.jenkins.plugin.awslambda.AWSLambdaDescriptor; import com.xti.jenkins.plugin.awslambda.util.ExpansionUtils; import com.xti.jenkins.plugin.awslambda.util.JenkinsProxy; import com.xti.jenkins.plugin.awslambda.util.LambdaClientConfig; import hudson.EnvVars; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; public String getAwsSecretKey() { return this.awsSecretKey; } public String getAwsRegion() { return this.awsRegion; } public String getFunctionARN() { return this.functionARN; } public String getFunctionAlias() { return this.functionAlias; } public String getVersionDescription() { return this.versionDescription; } public void setVersionDescription(String versionDescription){ this.versionDescription = versionDescription; } public PublishConfig getPublishConfig() { return new PublishConfig(this.functionAlias, this.functionARN, this.versionDescription); } public LambdaClientConfig getLambdaClientConfig(){ if(useInstanceCredentials){
return new LambdaClientConfig(awsRegion, JenkinsProxy.getConfig());
openbakery/timetracker
src/main/java/org/openbakery/timetracker/web/timesheet/DayEntryListView.java
// Path: src/main/java/org/openbakery/timetracker/util/DateHelper.java // public class DateHelper { // // private static final Logger log = LoggerFactory.getLogger(DateHelper.class); // // TODO move resource bundle // public static final String TIME_PATTERN = "HH:mm"; // public static final String DATE_PATTERN = "dd.MM.yyyy"; // public static final String DATE_PATTERN_WITH_DAYNAME = "EEE dd.MM.yyyy"; // private static final int INTERVAL = 15; // // public static Date setTimeForDate(Date currentDay, Date currentTime) { // DateTime currentDate = new DateTime(currentDay.getTime()); // MutableDateTime dateTime = new MutableDateTime(currentTime); // dateTime.setYear(currentDate.getYear()); // dateTime.setMonthOfYear(currentDate.getMonthOfYear()); // dateTime.setDayOfYear(currentDate.getDayOfYear()); // return dateTime.toDate(); // } // // // public static DateTime trimDateTime(DateTime dateTime) { // log.debug("before trim: {}", dateTime); // // MutableDateTime mutableDateTime = dateTime.toMutableDateTime(); // mutableDateTime.setMinuteOfHour((mutableDateTime.getMinuteOfHour() / INTERVAL) * INTERVAL); // mutableDateTime.setSecondOfMinute(0); // mutableDateTime.setMillisOfSecond(0); // dateTime = mutableDateTime.toDateTime(); // // log.debug("after trim: {}", dateTime); // return dateTime; // // } // // public static Date trimDateTime(Date date) { // return trimDateTime(new DateTime(date.getTime())).toDate(); // } // } // // Path: src/main/java/org/openbakery/timetracker/util/DurationHelper.java // public class DurationHelper { // // private static Logger log = LoggerFactory.getLogger(DurationHelper.class); // // // public static Duration calculateDurationSum(List<TimeEntry> timeEntryList) { // Duration sum = Duration.ZERO; // // for (TimeEntry entry : timeEntryList) { // sum = sum.plus(entry.getDuration()); // log.debug("add {}, sum {}", entry.getDuration(), sum); // } // return sum; // } // // public static String toTimeString(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + "," + period.getMinutes()*100/60; // } // // public static double toTime(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + period.getMinutes()/60.0; // } // // }
import org.apache.commons.lang.time.DateUtils; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.openbakery.timetracker.util.DateHelper; import org.openbakery.timetracker.util.DurationHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List;
package org.openbakery.timetracker.web.timesheet; /** * Created with IntelliJ IDEA. * User: rene * Date: 25.02.13 * Time: 17:00 * To change this template use File | Settings | File Templates. */ public class DayEntryListView extends ListView<DayEntry> { private static final long serialVersionUID = 1L;
// Path: src/main/java/org/openbakery/timetracker/util/DateHelper.java // public class DateHelper { // // private static final Logger log = LoggerFactory.getLogger(DateHelper.class); // // TODO move resource bundle // public static final String TIME_PATTERN = "HH:mm"; // public static final String DATE_PATTERN = "dd.MM.yyyy"; // public static final String DATE_PATTERN_WITH_DAYNAME = "EEE dd.MM.yyyy"; // private static final int INTERVAL = 15; // // public static Date setTimeForDate(Date currentDay, Date currentTime) { // DateTime currentDate = new DateTime(currentDay.getTime()); // MutableDateTime dateTime = new MutableDateTime(currentTime); // dateTime.setYear(currentDate.getYear()); // dateTime.setMonthOfYear(currentDate.getMonthOfYear()); // dateTime.setDayOfYear(currentDate.getDayOfYear()); // return dateTime.toDate(); // } // // // public static DateTime trimDateTime(DateTime dateTime) { // log.debug("before trim: {}", dateTime); // // MutableDateTime mutableDateTime = dateTime.toMutableDateTime(); // mutableDateTime.setMinuteOfHour((mutableDateTime.getMinuteOfHour() / INTERVAL) * INTERVAL); // mutableDateTime.setSecondOfMinute(0); // mutableDateTime.setMillisOfSecond(0); // dateTime = mutableDateTime.toDateTime(); // // log.debug("after trim: {}", dateTime); // return dateTime; // // } // // public static Date trimDateTime(Date date) { // return trimDateTime(new DateTime(date.getTime())).toDate(); // } // } // // Path: src/main/java/org/openbakery/timetracker/util/DurationHelper.java // public class DurationHelper { // // private static Logger log = LoggerFactory.getLogger(DurationHelper.class); // // // public static Duration calculateDurationSum(List<TimeEntry> timeEntryList) { // Duration sum = Duration.ZERO; // // for (TimeEntry entry : timeEntryList) { // sum = sum.plus(entry.getDuration()); // log.debug("add {}, sum {}", entry.getDuration(), sum); // } // return sum; // } // // public static String toTimeString(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + "," + period.getMinutes()*100/60; // } // // public static double toTime(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + period.getMinutes()/60.0; // } // // } // Path: src/main/java/org/openbakery/timetracker/web/timesheet/DayEntryListView.java import org.apache.commons.lang.time.DateUtils; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.openbakery.timetracker.util.DateHelper; import org.openbakery.timetracker.util.DurationHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; package org.openbakery.timetracker.web.timesheet; /** * Created with IntelliJ IDEA. * User: rene * Date: 25.02.13 * Time: 17:00 * To change this template use File | Settings | File Templates. */ public class DayEntryListView extends ListView<DayEntry> { private static final long serialVersionUID = 1L;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DateHelper.DATE_PATTERN_WITH_DAYNAME);
openbakery/timetracker
src/main/java/org/openbakery/timetracker/web/timesheet/DayEntryListView.java
// Path: src/main/java/org/openbakery/timetracker/util/DateHelper.java // public class DateHelper { // // private static final Logger log = LoggerFactory.getLogger(DateHelper.class); // // TODO move resource bundle // public static final String TIME_PATTERN = "HH:mm"; // public static final String DATE_PATTERN = "dd.MM.yyyy"; // public static final String DATE_PATTERN_WITH_DAYNAME = "EEE dd.MM.yyyy"; // private static final int INTERVAL = 15; // // public static Date setTimeForDate(Date currentDay, Date currentTime) { // DateTime currentDate = new DateTime(currentDay.getTime()); // MutableDateTime dateTime = new MutableDateTime(currentTime); // dateTime.setYear(currentDate.getYear()); // dateTime.setMonthOfYear(currentDate.getMonthOfYear()); // dateTime.setDayOfYear(currentDate.getDayOfYear()); // return dateTime.toDate(); // } // // // public static DateTime trimDateTime(DateTime dateTime) { // log.debug("before trim: {}", dateTime); // // MutableDateTime mutableDateTime = dateTime.toMutableDateTime(); // mutableDateTime.setMinuteOfHour((mutableDateTime.getMinuteOfHour() / INTERVAL) * INTERVAL); // mutableDateTime.setSecondOfMinute(0); // mutableDateTime.setMillisOfSecond(0); // dateTime = mutableDateTime.toDateTime(); // // log.debug("after trim: {}", dateTime); // return dateTime; // // } // // public static Date trimDateTime(Date date) { // return trimDateTime(new DateTime(date.getTime())).toDate(); // } // } // // Path: src/main/java/org/openbakery/timetracker/util/DurationHelper.java // public class DurationHelper { // // private static Logger log = LoggerFactory.getLogger(DurationHelper.class); // // // public static Duration calculateDurationSum(List<TimeEntry> timeEntryList) { // Duration sum = Duration.ZERO; // // for (TimeEntry entry : timeEntryList) { // sum = sum.plus(entry.getDuration()); // log.debug("add {}, sum {}", entry.getDuration(), sum); // } // return sum; // } // // public static String toTimeString(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + "," + period.getMinutes()*100/60; // } // // public static double toTime(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + period.getMinutes()/60.0; // } // // }
import org.apache.commons.lang.time.DateUtils; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.openbakery.timetracker.util.DateHelper; import org.openbakery.timetracker.util.DurationHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List;
package org.openbakery.timetracker.web.timesheet; /** * Created with IntelliJ IDEA. * User: rene * Date: 25.02.13 * Time: 17:00 * To change this template use File | Settings | File Templates. */ public class DayEntryListView extends ListView<DayEntry> { private static final long serialVersionUID = 1L; private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DateHelper.DATE_PATTERN_WITH_DAYNAME); public DayEntryListView(String id, List<DayEntry> dayEntryList) { super(id, dayEntryList); } @Override protected void populateItem(ListItem<DayEntry> item) { DayEntry dayEntry = item.getModelObject(); String dayString = dateFormat.format(dayEntry.getDate()); if (DateUtils.isSameDay(dayEntry.getDate(), new Date())) { dayString += "&nbsp;&nbsp;&nbsp;<span class=\"label label-important\">Today</span>"; } Label dayLabel = new Label("day", dayString); dayLabel.setEscapeModelStrings(false); item.add(dayLabel);
// Path: src/main/java/org/openbakery/timetracker/util/DateHelper.java // public class DateHelper { // // private static final Logger log = LoggerFactory.getLogger(DateHelper.class); // // TODO move resource bundle // public static final String TIME_PATTERN = "HH:mm"; // public static final String DATE_PATTERN = "dd.MM.yyyy"; // public static final String DATE_PATTERN_WITH_DAYNAME = "EEE dd.MM.yyyy"; // private static final int INTERVAL = 15; // // public static Date setTimeForDate(Date currentDay, Date currentTime) { // DateTime currentDate = new DateTime(currentDay.getTime()); // MutableDateTime dateTime = new MutableDateTime(currentTime); // dateTime.setYear(currentDate.getYear()); // dateTime.setMonthOfYear(currentDate.getMonthOfYear()); // dateTime.setDayOfYear(currentDate.getDayOfYear()); // return dateTime.toDate(); // } // // // public static DateTime trimDateTime(DateTime dateTime) { // log.debug("before trim: {}", dateTime); // // MutableDateTime mutableDateTime = dateTime.toMutableDateTime(); // mutableDateTime.setMinuteOfHour((mutableDateTime.getMinuteOfHour() / INTERVAL) * INTERVAL); // mutableDateTime.setSecondOfMinute(0); // mutableDateTime.setMillisOfSecond(0); // dateTime = mutableDateTime.toDateTime(); // // log.debug("after trim: {}", dateTime); // return dateTime; // // } // // public static Date trimDateTime(Date date) { // return trimDateTime(new DateTime(date.getTime())).toDate(); // } // } // // Path: src/main/java/org/openbakery/timetracker/util/DurationHelper.java // public class DurationHelper { // // private static Logger log = LoggerFactory.getLogger(DurationHelper.class); // // // public static Duration calculateDurationSum(List<TimeEntry> timeEntryList) { // Duration sum = Duration.ZERO; // // for (TimeEntry entry : timeEntryList) { // sum = sum.plus(entry.getDuration()); // log.debug("add {}, sum {}", entry.getDuration(), sum); // } // return sum; // } // // public static String toTimeString(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + "," + period.getMinutes()*100/60; // } // // public static double toTime(Duration duration) { // Period period = duration.toPeriod(); // return period.getHours() + period.getMinutes()/60.0; // } // // } // Path: src/main/java/org/openbakery/timetracker/web/timesheet/DayEntryListView.java import org.apache.commons.lang.time.DateUtils; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.openbakery.timetracker.util.DateHelper; import org.openbakery.timetracker.util.DurationHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; package org.openbakery.timetracker.web.timesheet; /** * Created with IntelliJ IDEA. * User: rene * Date: 25.02.13 * Time: 17:00 * To change this template use File | Settings | File Templates. */ public class DayEntryListView extends ListView<DayEntry> { private static final long serialVersionUID = 1L; private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DateHelper.DATE_PATTERN_WITH_DAYNAME); public DayEntryListView(String id, List<DayEntry> dayEntryList) { super(id, dayEntryList); } @Override protected void populateItem(ListItem<DayEntry> item) { DayEntry dayEntry = item.getModelObject(); String dayString = dateFormat.format(dayEntry.getDate()); if (DateUtils.isSameDay(dayEntry.getDate(), new Date())) { dayString += "&nbsp;&nbsp;&nbsp;<span class=\"label label-important\">Today</span>"; } Label dayLabel = new Label("day", dayString); dayLabel.setEscapeModelStrings(false); item.add(dayLabel);
item.add(new Label("sumDuration", DurationHelper.toTimeString(DurationHelper.calculateDurationSum(dayEntry.getTimeEntryList()))));
openbakery/timetracker
src/main/java/org/openbakery/timetracker/annotation/RequireRole.java
// Path: src/main/java/org/openbakery/timetracker/data/Role.java // public enum Role { // // USER, ADMINISTRATOR; // }
import org.openbakery.timetracker.data.Role; import java.lang.annotation.*;
package org.openbakery.timetracker.annotation; /** * User: rene * Date: 04.05.11 */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface RequireRole {
// Path: src/main/java/org/openbakery/timetracker/data/Role.java // public enum Role { // // USER, ADMINISTRATOR; // } // Path: src/main/java/org/openbakery/timetracker/annotation/RequireRole.java import org.openbakery.timetracker.data.Role; import java.lang.annotation.*; package org.openbakery.timetracker.annotation; /** * User: rene * Date: 04.05.11 */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface RequireRole {
public Role value();
openbakery/timetracker
src/main/java/org/openbakery/timetracker/web/LogoutPage.java
// Path: src/main/java/org/openbakery/timetracker/service/UserService.java // public interface UserService { // public User login(String username, String password) throws LoginFailedException; // public void logoff(User user); // public void store(User user); // public void delete(User user); // public List<User> getAllUsers(); // public List<User> getAllActiveUsers(); // // }
import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.service.UserService;
package org.openbakery.timetracker.web; public class LogoutPage extends TimeTrackerPage { @SpringBean
// Path: src/main/java/org/openbakery/timetracker/service/UserService.java // public interface UserService { // public User login(String username, String password) throws LoginFailedException; // public void logoff(User user); // public void store(User user); // public void delete(User user); // public List<User> getAllUsers(); // public List<User> getAllActiveUsers(); // // } // Path: src/main/java/org/openbakery/timetracker/web/LogoutPage.java import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.service.UserService; package org.openbakery.timetracker.web; public class LogoutPage extends TimeTrackerPage { @SpringBean
private UserService userService;
openbakery/timetracker
src/main/java/org/openbakery/timetracker/web/project/SaveButton.java
// Path: src/main/java/org/openbakery/timetracker/data/Project.java // @Entity // @Table(name = "project") // public class Project implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue // private int id; // // @Column(name = "name") // private String name; // // @Column(name = "description") // private String description; // // @ManyToOne // @JoinColumn(name = "customer_id") // private Customer customer; // // // @Column(name = "issueTrackerURL") // private String issueTrackerURL; // // @Column(name = "disabled") // private boolean disabled; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Customer getCustomer() { // return customer; // } // // public void setCustomer(Customer customer) { // this.customer = customer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isDisabled() { // return disabled; // } // // public void setDisabled(boolean disabled) { // this.disabled = disabled; // } // // public String getIssueTrackerURL() { // return issueTrackerURL; // } // // public void setIssueTrackerURL(String issueTrackerURL) { // this.issueTrackerURL = issueTrackerURL; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Project project = (Project) o; // // if (disabled != project.disabled) return false; // if (id != project.id) return false; // if (customer != null ? !customer.equals(project.customer) : project.customer != null) return false; // if (description != null ? !description.equals(project.description) : project.description != null) return false; // if (issueTrackerURL != null ? !issueTrackerURL.equals(project.issueTrackerURL) : project.issueTrackerURL != null) // return false; // if (name != null ? !name.equals(project.name) : project.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // result = 31 * result + (customer != null ? customer.hashCode() : 0); // result = 31 * result + (issueTrackerURL != null ? issueTrackerURL.hashCode() : 0); // result = 31 * result + (disabled ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "Project{" + // "id=" + id + // ", name='" + name + '\'' + // ", description='" + description + '\'' + // ", customer=" + customer + // ", issueTrackerURL='" + issueTrackerURL + '\'' + // ", disabled=" + disabled + // '}'; // } // } // // Path: src/main/java/org/openbakery/timetracker/service/ProjectService.java // public class ProjectService { // private static Logger log = LoggerFactory.getLogger(ProjectService.class); // // // @Autowired // private Persistence persistence; // // public List<Project> getAllProjects() throws PersistenceException { // return persistence.query("Select project from Project as project", Project.class); // } // // public List<Project> getAllActiveProjects() throws PersistenceException { // return persistence.query("Select project from Project as project WHERE project.disabled = false", Project.class); // } // // public void delete(Project modelObject) { // persistence.delete(modelObject); // } // // public void store(Project modelObject) { // persistence.store(modelObject); // } // // public List<Project> getProjectByCustomer(Customer customer) { // log.debug("get projects for customer {}", customer); // ImmutableMap<String, Object> parameters = new ImmutableMap.Builder<String, Object>() // .put("customer", customer).build(); // // List<Project> result = // persistence.query("SELECT project from Project as project WHERE project.customer = :customer AND project.disabled = false", // parameters, Project.class); // // log.debug("found projects {}", result); // // return result; // } // }
import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.data.Project; import org.openbakery.timetracker.service.ProjectService;
package org.openbakery.timetracker.web.project; public class SaveButton extends Button { private static final long serialVersionUID = 1L; @SpringBean
// Path: src/main/java/org/openbakery/timetracker/data/Project.java // @Entity // @Table(name = "project") // public class Project implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue // private int id; // // @Column(name = "name") // private String name; // // @Column(name = "description") // private String description; // // @ManyToOne // @JoinColumn(name = "customer_id") // private Customer customer; // // // @Column(name = "issueTrackerURL") // private String issueTrackerURL; // // @Column(name = "disabled") // private boolean disabled; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Customer getCustomer() { // return customer; // } // // public void setCustomer(Customer customer) { // this.customer = customer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isDisabled() { // return disabled; // } // // public void setDisabled(boolean disabled) { // this.disabled = disabled; // } // // public String getIssueTrackerURL() { // return issueTrackerURL; // } // // public void setIssueTrackerURL(String issueTrackerURL) { // this.issueTrackerURL = issueTrackerURL; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Project project = (Project) o; // // if (disabled != project.disabled) return false; // if (id != project.id) return false; // if (customer != null ? !customer.equals(project.customer) : project.customer != null) return false; // if (description != null ? !description.equals(project.description) : project.description != null) return false; // if (issueTrackerURL != null ? !issueTrackerURL.equals(project.issueTrackerURL) : project.issueTrackerURL != null) // return false; // if (name != null ? !name.equals(project.name) : project.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // result = 31 * result + (customer != null ? customer.hashCode() : 0); // result = 31 * result + (issueTrackerURL != null ? issueTrackerURL.hashCode() : 0); // result = 31 * result + (disabled ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "Project{" + // "id=" + id + // ", name='" + name + '\'' + // ", description='" + description + '\'' + // ", customer=" + customer + // ", issueTrackerURL='" + issueTrackerURL + '\'' + // ", disabled=" + disabled + // '}'; // } // } // // Path: src/main/java/org/openbakery/timetracker/service/ProjectService.java // public class ProjectService { // private static Logger log = LoggerFactory.getLogger(ProjectService.class); // // // @Autowired // private Persistence persistence; // // public List<Project> getAllProjects() throws PersistenceException { // return persistence.query("Select project from Project as project", Project.class); // } // // public List<Project> getAllActiveProjects() throws PersistenceException { // return persistence.query("Select project from Project as project WHERE project.disabled = false", Project.class); // } // // public void delete(Project modelObject) { // persistence.delete(modelObject); // } // // public void store(Project modelObject) { // persistence.store(modelObject); // } // // public List<Project> getProjectByCustomer(Customer customer) { // log.debug("get projects for customer {}", customer); // ImmutableMap<String, Object> parameters = new ImmutableMap.Builder<String, Object>() // .put("customer", customer).build(); // // List<Project> result = // persistence.query("SELECT project from Project as project WHERE project.customer = :customer AND project.disabled = false", // parameters, Project.class); // // log.debug("found projects {}", result); // // return result; // } // } // Path: src/main/java/org/openbakery/timetracker/web/project/SaveButton.java import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.data.Project; import org.openbakery.timetracker.service.ProjectService; package org.openbakery.timetracker.web.project; public class SaveButton extends Button { private static final long serialVersionUID = 1L; @SpringBean
private ProjectService projectService;
openbakery/timetracker
src/main/java/org/openbakery/timetracker/web/project/SaveButton.java
// Path: src/main/java/org/openbakery/timetracker/data/Project.java // @Entity // @Table(name = "project") // public class Project implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue // private int id; // // @Column(name = "name") // private String name; // // @Column(name = "description") // private String description; // // @ManyToOne // @JoinColumn(name = "customer_id") // private Customer customer; // // // @Column(name = "issueTrackerURL") // private String issueTrackerURL; // // @Column(name = "disabled") // private boolean disabled; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Customer getCustomer() { // return customer; // } // // public void setCustomer(Customer customer) { // this.customer = customer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isDisabled() { // return disabled; // } // // public void setDisabled(boolean disabled) { // this.disabled = disabled; // } // // public String getIssueTrackerURL() { // return issueTrackerURL; // } // // public void setIssueTrackerURL(String issueTrackerURL) { // this.issueTrackerURL = issueTrackerURL; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Project project = (Project) o; // // if (disabled != project.disabled) return false; // if (id != project.id) return false; // if (customer != null ? !customer.equals(project.customer) : project.customer != null) return false; // if (description != null ? !description.equals(project.description) : project.description != null) return false; // if (issueTrackerURL != null ? !issueTrackerURL.equals(project.issueTrackerURL) : project.issueTrackerURL != null) // return false; // if (name != null ? !name.equals(project.name) : project.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // result = 31 * result + (customer != null ? customer.hashCode() : 0); // result = 31 * result + (issueTrackerURL != null ? issueTrackerURL.hashCode() : 0); // result = 31 * result + (disabled ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "Project{" + // "id=" + id + // ", name='" + name + '\'' + // ", description='" + description + '\'' + // ", customer=" + customer + // ", issueTrackerURL='" + issueTrackerURL + '\'' + // ", disabled=" + disabled + // '}'; // } // } // // Path: src/main/java/org/openbakery/timetracker/service/ProjectService.java // public class ProjectService { // private static Logger log = LoggerFactory.getLogger(ProjectService.class); // // // @Autowired // private Persistence persistence; // // public List<Project> getAllProjects() throws PersistenceException { // return persistence.query("Select project from Project as project", Project.class); // } // // public List<Project> getAllActiveProjects() throws PersistenceException { // return persistence.query("Select project from Project as project WHERE project.disabled = false", Project.class); // } // // public void delete(Project modelObject) { // persistence.delete(modelObject); // } // // public void store(Project modelObject) { // persistence.store(modelObject); // } // // public List<Project> getProjectByCustomer(Customer customer) { // log.debug("get projects for customer {}", customer); // ImmutableMap<String, Object> parameters = new ImmutableMap.Builder<String, Object>() // .put("customer", customer).build(); // // List<Project> result = // persistence.query("SELECT project from Project as project WHERE project.customer = :customer AND project.disabled = false", // parameters, Project.class); // // log.debug("found projects {}", result); // // return result; // } // }
import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.data.Project; import org.openbakery.timetracker.service.ProjectService;
package org.openbakery.timetracker.web.project; public class SaveButton extends Button { private static final long serialVersionUID = 1L; @SpringBean private ProjectService projectService;
// Path: src/main/java/org/openbakery/timetracker/data/Project.java // @Entity // @Table(name = "project") // public class Project implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // @GeneratedValue // private int id; // // @Column(name = "name") // private String name; // // @Column(name = "description") // private String description; // // @ManyToOne // @JoinColumn(name = "customer_id") // private Customer customer; // // // @Column(name = "issueTrackerURL") // private String issueTrackerURL; // // @Column(name = "disabled") // private boolean disabled; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Customer getCustomer() { // return customer; // } // // public void setCustomer(Customer customer) { // this.customer = customer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isDisabled() { // return disabled; // } // // public void setDisabled(boolean disabled) { // this.disabled = disabled; // } // // public String getIssueTrackerURL() { // return issueTrackerURL; // } // // public void setIssueTrackerURL(String issueTrackerURL) { // this.issueTrackerURL = issueTrackerURL; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Project project = (Project) o; // // if (disabled != project.disabled) return false; // if (id != project.id) return false; // if (customer != null ? !customer.equals(project.customer) : project.customer != null) return false; // if (description != null ? !description.equals(project.description) : project.description != null) return false; // if (issueTrackerURL != null ? !issueTrackerURL.equals(project.issueTrackerURL) : project.issueTrackerURL != null) // return false; // if (name != null ? !name.equals(project.name) : project.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // result = 31 * result + (customer != null ? customer.hashCode() : 0); // result = 31 * result + (issueTrackerURL != null ? issueTrackerURL.hashCode() : 0); // result = 31 * result + (disabled ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "Project{" + // "id=" + id + // ", name='" + name + '\'' + // ", description='" + description + '\'' + // ", customer=" + customer + // ", issueTrackerURL='" + issueTrackerURL + '\'' + // ", disabled=" + disabled + // '}'; // } // } // // Path: src/main/java/org/openbakery/timetracker/service/ProjectService.java // public class ProjectService { // private static Logger log = LoggerFactory.getLogger(ProjectService.class); // // // @Autowired // private Persistence persistence; // // public List<Project> getAllProjects() throws PersistenceException { // return persistence.query("Select project from Project as project", Project.class); // } // // public List<Project> getAllActiveProjects() throws PersistenceException { // return persistence.query("Select project from Project as project WHERE project.disabled = false", Project.class); // } // // public void delete(Project modelObject) { // persistence.delete(modelObject); // } // // public void store(Project modelObject) { // persistence.store(modelObject); // } // // public List<Project> getProjectByCustomer(Customer customer) { // log.debug("get projects for customer {}", customer); // ImmutableMap<String, Object> parameters = new ImmutableMap.Builder<String, Object>() // .put("customer", customer).build(); // // List<Project> result = // persistence.query("SELECT project from Project as project WHERE project.customer = :customer AND project.disabled = false", // parameters, Project.class); // // log.debug("found projects {}", result); // // return result; // } // } // Path: src/main/java/org/openbakery/timetracker/web/project/SaveButton.java import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.spring.injection.annot.SpringBean; import org.openbakery.timetracker.data.Project; import org.openbakery.timetracker.service.ProjectService; package org.openbakery.timetracker.web.project; public class SaveButton extends Button { private static final long serialVersionUID = 1L; @SpringBean private ProjectService projectService;
private Project project;
openbakery/timetracker
src/main/test/org/openbakery/timetracker/TestWebApplication.java
// Path: src/main/java/org/openbakery/timetracker/web/TimeTrackerSession.java // public class TimeTrackerSession extends WebSession { // // private static Logger log = LoggerFactory.getLogger(TimeTrackerSession.class); // // private static final long serialVersionUID = 1L; // // private User user; // private DateTime currentDate; // private Project lastStoredProject; // // public TimeTrackerSession(Request request) { // super(request); // user = new User(); // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // // public List<MenuItem> getMenuItems() { // // return ((TimeTrackerWebApplication) getApplication()).getMenuItems(); // } // // public DateTime getCurrentDate() { // if (currentDate == null) { // currentDate = DateHelper.trimDateTime(new DateTime()); // } // return currentDate; // } // // // public void setCurrentDate(DateTime currentDate) { // this.currentDate = DateHelper.trimDateTime(currentDate); // } // // public Project getLastStoredProject() { // return lastStoredProject; // } // // public void setLastStoredProject(Project lastStoredProject) { // this.lastStoredProject = lastStoredProject; // } // // }
import org.apache.wicket.Session; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.openbakery.timetracker.web.TimeTrackerSession;
package org.openbakery.timetracker; public class TestWebApplication extends WebApplication { private Class<? extends WebPage> webpage; public TestWebApplication(Class<? extends WebPage> webpage) { this.webpage = webpage; } @Override public Class<? extends WebPage> getHomePage() { return webpage; } @Override public Session newSession(Request request, Response response) {
// Path: src/main/java/org/openbakery/timetracker/web/TimeTrackerSession.java // public class TimeTrackerSession extends WebSession { // // private static Logger log = LoggerFactory.getLogger(TimeTrackerSession.class); // // private static final long serialVersionUID = 1L; // // private User user; // private DateTime currentDate; // private Project lastStoredProject; // // public TimeTrackerSession(Request request) { // super(request); // user = new User(); // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // // public List<MenuItem> getMenuItems() { // // return ((TimeTrackerWebApplication) getApplication()).getMenuItems(); // } // // public DateTime getCurrentDate() { // if (currentDate == null) { // currentDate = DateHelper.trimDateTime(new DateTime()); // } // return currentDate; // } // // // public void setCurrentDate(DateTime currentDate) { // this.currentDate = DateHelper.trimDateTime(currentDate); // } // // public Project getLastStoredProject() { // return lastStoredProject; // } // // public void setLastStoredProject(Project lastStoredProject) { // this.lastStoredProject = lastStoredProject; // } // // } // Path: src/main/test/org/openbakery/timetracker/TestWebApplication.java import org.apache.wicket.Session; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.openbakery.timetracker.web.TimeTrackerSession; package org.openbakery.timetracker; public class TestWebApplication extends WebApplication { private Class<? extends WebPage> webpage; public TestWebApplication(Class<? extends WebPage> webpage) { this.webpage = webpage; } @Override public Class<? extends WebPage> getHomePage() { return webpage; } @Override public Session newSession(Request request, Response response) {
return new TimeTrackerSession(request);