text stringlengths 10 2.72M |
|---|
package com.worldchip.bbp.bbpawmanager.cn.view;
import java.io.File;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.worldchip.bbp.bbpawmanager.cn.R;
import com.worldchip.bbp.bbpawmanager.cn.activity.InformationActivity;
import com.worldchip.bbp.bbpawmanager.cn.model.Information;
import com.worldchip.bbp.bbpawmanager.cn.utils.Common;
import com.worldchip.bbp.bbpawmanager.cn.utils.NetworkUtils;
import com.worldchip.bbp.bbpawmanager.cn.utils.ScaleAnimEffect;
import com.worldchip.bbp.bbpawmanager.cn.utils.Utils;
public class DownloadView implements OnClickListener{
private Context mContext;
//private RoundProgress roundProgressBar;
private ImageView closeButton;
private ImageView installButton;
private ImageView cancelButton;
private ImageView startButton;
private ImageView mRoundProgress;
private TextView downloadProgress;
private TextView mDownloadTitle;
private Handler mCallback;
private String downloadUrl;
public static final int DOWNLOAD_CLOSE = 200;
public static final int DOWNLOAD_CANCEL = 201;
public static final int DOWNLOAD_INSTALL = 202;
public static final int DOWNLOAD_START = 203;
public static final int DOWNLOAD_PAUSE = 204;
public static final int DOWNLOAD_CONTINUE = 205;
public static final int CLOSE_DOWNLOAD_VIEW = 206;
public DownloadState mDownloadState = DownloadState.STOP;
public boolean isAlready = false;
private RotateAnimation mRoundProgressAnim = null;
private String mCompleteFile="";
private GlobalAlertDialog mNoticeDialog = null;
private Information mDownloadInfo = null;
private ScaleAnimEffect mAnimEffect = new ScaleAnimEffect();
private static float big_x = 1.08F;
private static float big_y = 1.08F;
public enum DownloadState
{
STOP, PAUSE, DOWNLOADING
}
public DownloadView(Context context, Handler callback,Information info) {
this.mContext = context;
this.mCallback = callback;
this.mDownloadInfo = info;
if (info != null) {
this.downloadUrl = info.getDownloadUrl();
}
}
public View creatDownloadView() {
View downloadView = LayoutInflater.from(mContext).inflate(R.layout.app_update_layout, null);
if (downloadView == null) {
return null;
}
//roundProgressBar = (RoundProgress) downloadView.findViewById(R.id.progress);
closeButton = (ImageView) downloadView.findViewById(R.id.dowmload_close_btn);
installButton = (ImageView) downloadView.findViewById(R.id.install_btn);
installButton.setVisibility(View.GONE);
cancelButton = (ImageView) downloadView.findViewById(R.id.dowmload_cancel_btn);
startButton = (ImageView) downloadView.findViewById(R.id.start_download_btn);
mRoundProgress = (ImageView) downloadView.findViewById(R.id.round_progress);
downloadProgress = (TextView) downloadView.findViewById(R.id.download_progress);
mDownloadTitle = (TextView) downloadView.findViewById(R.id.download_title);
mDownloadTitle.setSelected(true);
closeButton.setOnClickListener(this);
installButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
startButton.setOnClickListener(this);
return downloadView;
}
/*public RoundProgress getRoundProgressBar() {
return roundProgressBar;
}
public void setRoundProgressBar(RoundProgress roundProgressBar) {
this.roundProgressBar = roundProgressBar;
}*/
public ImageView getCloseButton() {
return closeButton;
}
public void setCloseButton(ImageView closeButton) {
this.closeButton = closeButton;
}
public ImageView getInstallButton() {
return installButton;
}
public void setInstallButton(ImageView installButton) {
this.installButton = installButton;
}
public ImageView getCancelButton() {
return cancelButton;
}
public void setCancelButton(ImageView cancelButton) {
this.cancelButton = cancelButton;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadTitle(String title) {
if (mDownloadTitle != null) {
mDownloadTitle.setText(title);
}
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
startAnimEffect(view);
/*switch (view.getId()) {
case R.id.dowmload_close_btn:
if (mDownloadState == DownloadState.DOWNLOADING){
showBackgroundDownloadDialog();
} else {
if (mCallback != null) {
mCallback.sendEmptyMessage(DOWNLOAD_CLOSE);
}
}
break;
case R.id.install_btn:
installAPK(mCompleteFile);
if (mDownloadInfo != null) {
Common.replyStateToServer(mDownloadInfo, Utils.REPLY_STATE_INSTALLED);
}
break;
case R.id.dowmload_cancel_btn:
if (mDownloadState == DownloadState.DOWNLOADING) {
showCancelDownloadDialog();
} else {
mCallback.sendEmptyMessage(CLOSE_DOWNLOAD_VIEW);
}
break;
case R.id.start_download_btn:
if (mCallback != null) {
if (mDownloadState == DownloadState.STOP
|| mDownloadState == DownloadState.PAUSE) {
mDownloadState = DownloadState.DOWNLOADING;
startButton.setBackgroundResource(R.drawable.ic_pause_btn);
startRoundProgressAnim();
if (!isAlready) {
mCallback.sendEmptyMessage(DOWNLOAD_START);
isAlready = true;
} else {
mCallback.sendEmptyMessage(DOWNLOAD_CONTINUE);
}
} else {
mDownloadState = DownloadState.PAUSE;
startButton.setBackgroundResource(R.drawable.ic_start_btn);
mCallback.sendEmptyMessage(DOWNLOAD_PAUSE);
stopRoundProgressAnim();
}
}
break;
}*/
}
public TextView getDownloadProgress() {
return downloadProgress;
}
public void setDownloadProgress(TextView downloadProgress) {
this.downloadProgress = downloadProgress;
}
@SuppressLint("DefaultLocale")
public void onDownloadComplete(String downloadFile) {
mCompleteFile = downloadFile;
if (startButton != null) {
startButton.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(downloadFile) &&
downloadFile.toLowerCase().endsWith(".apk")) {
if (installButton != null) {
installButton.setVisibility(View.VISIBLE);
}
}
if(downloadProgress != null) {
downloadProgress.setText("100%");
}
mDownloadState = DownloadState.STOP;
isAlready = false;
if (mDownloadInfo != null) {
Common.replyStateToServer(mDownloadInfo, Utils.REPLY_STATE_DOWNLOADED);
}
}
public void startRoundProgressAnim() {
if (mRoundProgress != null) {
if (mRoundProgressAnim == null) {
mRoundProgressAnim = new RotateAnimation(0f, 720f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mRoundProgressAnim.setInterpolator(new LinearInterpolator());
mRoundProgressAnim.setDuration(1500);
mRoundProgressAnim.setRepeatCount(Integer.MAX_VALUE);
mRoundProgressAnim.setFillAfter(true);
}
stopRoundProgressAnim();
mRoundProgress.startAnimation(mRoundProgressAnim);
}
}
public void stopRoundProgressAnim() {
if (mRoundProgressAnim != null) {
if (mRoundProgressAnim.hasStarted()) {
if (mRoundProgress != null) {
mRoundProgress.clearAnimation();
}
}
}
}
public void onUpdateStartBtn() {
if (mDownloadState == DownloadState.STOP) {
Log.e("lee", "dowmload view onUpdateStartBtn ----- ");
if (startButton != null) {
startButton.setBackgroundResource(R.drawable.ic_pause_btn);
}
mDownloadState = DownloadState.DOWNLOADING;
isAlready = true;
startRoundProgressAnim();
}
}
public void onStopDownload() {
if (startButton != null) {
startButton.setBackgroundResource(R.drawable.ic_start_btn);
}
mDownloadState = DownloadState.STOP;
isAlready = false;
stopRoundProgressAnim();
}
public void cancelReset() {
mDownloadState = DownloadState.PAUSE;
isAlready = false;
if (downloadProgress != null) {
downloadProgress.setText("");
}
if (startButton != null) {
startButton.setBackgroundResource(R.drawable.ic_start_btn);
}
stopRoundProgressAnim();
Log.e("lee", "dowmload view reset ----- ");
}
private void installAPK(String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(filePath)),
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}
private void showBackgroundDownloadDialog() {
String message = mContext.getResources().getString(R.string.global_background_download_msg);
showDialog(message,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {//确定
if (mCallback != null) {
mCallback.sendEmptyMessage(DOWNLOAD_CLOSE);
}
dialog.dismiss();
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {//取消
// TODO Auto-generated method stub
}
});
}
private void showCancelDownloadDialog() {
String fileName = NetworkUtils.getFileNameFromUrl(downloadUrl);
String message = mContext.getResources().getString(R.string.download_cancel_text_format, fileName);
showDialog(message,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {//确定
cancelReset();
if (mCallback != null) {
mCallback.sendEmptyMessage(DOWNLOAD_CANCEL);
isAlready = false;
}
dialog.dismiss();
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {//取消
// TODO Auto-generated method stub
}
});
}
private void showDialog(String message, DialogInterface.OnClickListener positiveButtonOnClickListener,
DialogInterface.OnClickListener negativeButtonOnClickListener) {
if (mNoticeDialog != null) {
if (mNoticeDialog.isShowing()) {
mNoticeDialog.dismiss();
}
mNoticeDialog = null;
}
mNoticeDialog = new GlobalAlertDialog.Builder(mContext)
.setTitle(mContext.getResources().getString(R.string.global_title_text))
.setMessage(message)
.setCancelable(true)
.setNegativeButton(mContext.getResources().getString(R.string.no_text), negativeButtonOnClickListener)
.setPositiveButton(mContext.getResources().getString(R.string.yes_text), positiveButtonOnClickListener)
.create(-1);
mNoticeDialog.show();
}
public DownloadState getDownloadState() {
return mDownloadState;
}
private void startAnimEffect(final View view) {
mAnimEffect.setAttributs(1.0F, big_x, 1.0F, big_y, 200);
Animation anim = mAnimEffect.createAnimation();
anim.setFillBefore(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.dowmload_close_btn:
if (mDownloadState == DownloadState.DOWNLOADING){
showBackgroundDownloadDialog();
} else {
if (mCallback != null) {
mCallback.sendEmptyMessage(DOWNLOAD_CLOSE);
}
}
break;
case R.id.install_btn:
installAPK(mCompleteFile);
if (mDownloadInfo != null) {
Common.replyStateToServer(mDownloadInfo, Utils.REPLY_STATE_INSTALLED);
}
break;
case R.id.dowmload_cancel_btn:
if (mDownloadState == DownloadState.DOWNLOADING) {
showCancelDownloadDialog();
} else {
mCallback.sendEmptyMessage(CLOSE_DOWNLOAD_VIEW);
}
break;
case R.id.start_download_btn:
if (mCallback != null) {
if (mDownloadState == DownloadState.STOP
|| mDownloadState == DownloadState.PAUSE) {
mDownloadState = DownloadState.DOWNLOADING;
startButton.setBackgroundResource(R.drawable.ic_pause_btn);
startRoundProgressAnim();
if (!isAlready) {
mCallback.sendEmptyMessage(DOWNLOAD_START);
isAlready = true;
} else {
mCallback.sendEmptyMessage(DOWNLOAD_CONTINUE);
}
} else {
mDownloadState = DownloadState.PAUSE;
startButton.setBackgroundResource(R.drawable.ic_start_btn);
mCallback.sendEmptyMessage(DOWNLOAD_PAUSE);
stopRoundProgressAnim();
}
}
break;
}
}
});
view.startAnimation(anim);
}
}
|
package com.rednovo.ace.widget.live;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.rednovo.ace.AceApplication;
import com.rednovo.ace.R;
import com.rednovo.ace.common.CacheUserInfoUtils;
import com.rednovo.ace.common.GiftUtils;
import com.rednovo.ace.common.Globle;
import com.rednovo.ace.common.LiveInfoUtils;
import com.rednovo.ace.core.session.SendUtils;
import com.rednovo.ace.data.UserInfoUtils;
import com.rednovo.ace.data.cell.MsgLog;
import com.rednovo.ace.data.events.BaseEvent;
import com.rednovo.ace.data.events.ChatMessage;
import com.rednovo.ace.data.events.CommonGiftAnimEvent;
import com.rednovo.ace.data.events.EnterRoomEvent;
import com.rednovo.ace.data.events.KeyBoardEvent;
import com.rednovo.ace.data.events.KickOutEvent;
import com.rednovo.ace.data.events.ReciveGiftInfo;
import com.rednovo.ace.data.events.RoomBroadcastEvent;
import com.rednovo.ace.data.events.SendGiftResponse;
import com.rednovo.ace.net.api.ReqRelationApi;
import com.rednovo.ace.net.api.ReqRoomApi;
import com.rednovo.ace.net.api.ReqUserApi;
import com.rednovo.ace.net.parser.AudienceResult;
import com.rednovo.ace.net.parser.BaseResult;
import com.rednovo.ace.net.parser.GiftListResult;
import com.rednovo.ace.net.parser.UserInfoResult;
import com.rednovo.ace.net.request.RequestCallback;
import com.rednovo.ace.ui.activity.ACEWebActivity;
import com.rednovo.ace.view.dialog.SimpleLoginDialog;
import com.rednovo.ace.widget.gift.CommonGiftView;
import com.rednovo.ace.widget.live.gift.GiftDialog;
import com.rednovo.ace.widget.parise.VoteSurface;
import com.rednovo.libs.common.KeyBoardUtils;
import com.rednovo.libs.common.ShowUtils;
import com.rednovo.libs.net.fresco.FrescoEngine;
import com.rednovo.libs.widget.emoji.ExpressionPanel;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
/**
* 直播间视频上层的view
*/
public class LiveView extends RelativeLayout implements GalleryAdapter.OnItemClickLitener, View.OnClickListener, DialogInterface.OnDismissListener, SimpleUserInfoDialog.OnNoLoginListener, RoomChatAdapter.OnChatItemClickLitener, AbsListView.OnScrollListener {
private static final int MSG_ENTER_ROOM = 0x05;
private static final int MSG_FOLLOW_NOTICE = 0x06;
private static final int FOLLOW_TIME = 60 * 1000;
private EditText et;
private ImageView ivEmoji, ivChat, ivGift, ivShare, ivClose, ivCamera, ivWarmClose;
private TextView tvSend, tvAudience, tvCollect, tvAnchorName, tvEnterRoom, tvWarm, tvTicketNum;
private CheckBox cbVoice, cbFlicker, cbSkincare;
private LinearLayout llTop, llWarm, llFollow;
private RelativeLayout rlInput, rlBtns, rlAnchor, rlVoice, rlFlicker;
// 横向头像列表
private RecyclerView hrView;
// 聊天list
private ListView listView;
private RoomChatAdapter roomChatAdapter;
private List<MsgLog> chatDatas = new ArrayList<MsgLog>();
private GalleryAdapter mAdapter;
private List<AudienceResult.MemberListEntity> mDatas = new ArrayList<AudienceResult.MemberListEntity>();
private ExpressionPanel vEmoji;
private SimpleDraweeView ivAnchor;
private GiftDialog giftDialog;
private SimpleUserInfoDialog infoDialog;
private ShareDialog shareDialog;
private boolean isAnchor;
private boolean isKeyBoardVisible;
private View giftLayout;
private VoteSurface vsPariseView;
private boolean needEmoji;
private PanelLayout mPanelRoot;
private OnClickListener onClickListener;
private CommonGiftView commonGiftView1;
private CommonGiftView commonGiftView2;
private boolean isScrolling;
private SimpleLoginDialog simpleLoginDialog = null;
private LinkedHashMap<String, List<ReciveGiftInfo>> receiveGiftMsgMap = new LinkedHashMap<String, List<ReciveGiftInfo>>();
private int count = 0;
private static MessageHandler mMessageHandler;
private static long lastEnterTime;
private boolean isFirstShowGiftDialog = true;
private long lastClickTime;
@Override
public void loginNotice() {
showLoginDilaog();
}
@Override
public void followNotice() {
mMessageHandler.removeMessages(MSG_FOLLOW_NOTICE);
llFollow.setVisibility(View.GONE);
}
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
switch (i) {
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
isScrolling = false;
break;
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
isScrolling = true;
break;
}
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
private static class MessageHandler extends Handler {
WeakReference<LiveView> mActivityReference;
MessageHandler(LiveView view) {
mActivityReference = new WeakReference<LiveView>(view);
}
@Override
public void handleMessage(android.os.Message msg) {
final LiveView view = mActivityReference.get();
if (view != null) {
switch (msg.what) {
case MSG_ENTER_ROOM:
view.clearEnterRoom();
break;
case MSG_FOLLOW_NOTICE:
view.clearFollowNotice();
break;
default:
break;
}
}
}
}
public void clearEnterRoom() {
tvEnterRoom.setText("");
}
public void clearFollowNotice() {
llFollow.setVisibility(View.GONE);
}
public void setIsAnchor(boolean isAnchor) {
this.isAnchor = isAnchor;
if (isAnchor) {
ivGift.setVisibility(View.GONE);
ivShare.setVisibility(View.GONE);
rlVoice.setVisibility(View.VISIBLE);
ivCamera.setVisibility(View.VISIBLE);
rlFlicker.setVisibility(View.VISIBLE);
cbSkincare.setVisibility(View.VISIBLE);
//放大聊天区域
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = (int) getContext().getResources().getDimension(R.dimen.chat_anchor_height);
tvEnterRoom.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
roomChatAdapter.setTextSize(18);
RelativeLayout.LayoutParams giftLayoutParams = (LayoutParams) giftLayout.getLayoutParams();
giftLayoutParams.bottomMargin = ShowUtils.dip2px(getContext(), 50);
giftLayoutParams.addRule(RelativeLayout.ABOVE, R.id.tv_enter_room);
} else {
//不是主播,请求是否已经关注
requestRelation(LiveInfoUtils.getStartId());
}
}
public void setOnClickListener(OnClickListener mOnClickListener) {
this.onClickListener = mOnClickListener;
if (onClickListener != null) {
cbVoice.setOnClickListener(onClickListener);
ivCamera.setOnClickListener(onClickListener);
cbFlicker.setOnClickListener(onClickListener);
cbSkincare.setOnClickListener(onClickListener);
}
}
public LiveView(Context context) {
super(context);
initView(context);
}
public LiveView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public LiveView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
inflate(context, R.layout.layout_live_view, this);
mMessageHandler = new MessageHandler(this);
et = (EditText) findViewById(R.id.et);
ivChat = (ImageView) findViewById(R.id.iv_chat);
ivGift = (ImageView) findViewById(R.id.iv_gift);
ivShare = (ImageView) findViewById(R.id.iv_share);
ivClose = (ImageView) findViewById(R.id.iv_close);
ivEmoji = (ImageView) findViewById(R.id.iv_emoji);
ivWarmClose = (ImageView) findViewById(R.id.iv_close_warm);
cbVoice = (CheckBox) findViewById(R.id.cb_voice);
ivCamera = (ImageView) findViewById(R.id.iv_camera);
cbFlicker = (CheckBox) findViewById(R.id.cb_flicker);
cbSkincare = (CheckBox) findViewById(R.id.cb_skincare);
ivAnchor = (SimpleDraweeView) findViewById(R.id.iv_anchor);
tvSend = (TextView) findViewById(R.id.tv_send);
tvWarm = (TextView) findViewById(R.id.tv_warm);
tvSend.setEnabled(false);
tvAudience = (TextView) findViewById(R.id.tv_audience);
tvCollect = (TextView) findViewById(R.id.tv_collect);
tvAnchorName = (TextView) findViewById(R.id.tv_anchorName);
tvEnterRoom = (TextView) findViewById(R.id.tv_enter_room);
tvTicketNum = (TextView) findViewById(R.id.tv_ticket_num);
rlBtns = (RelativeLayout) findViewById(R.id.rl_btns);
llTop = (LinearLayout) findViewById(R.id.ll_top);
llWarm = (LinearLayout) findViewById(R.id.ll_warm);
llFollow = (LinearLayout) findViewById(R.id.ll_follow);
rlInput = (RelativeLayout) findViewById(R.id.rl_input);
rlVoice = (RelativeLayout) findViewById(R.id.rl_voice);
rlFlicker = (RelativeLayout) findViewById(R.id.rl_flicker);
rlAnchor = (RelativeLayout) findViewById(R.id.rl_anchor);
hrView = (RecyclerView) findViewById(R.id.h_recyclerview);
mPanelRoot = (PanelLayout) findViewById(R.id.panel_root);
vEmoji = (ExpressionPanel) findViewById(R.id.view_emoji);
vEmoji.setTextView(et, false, tvSend);
vEmoji.setMaxLength(50);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
hrView.setLayoutManager(linearLayoutManager);
mAdapter = new GalleryAdapter(getContext(), mDatas);
hrView.setAdapter(mAdapter);
mAdapter.setOnItemClickLitener(this);
listView = (ListView) findViewById(R.id.list_view);
roomChatAdapter = new RoomChatAdapter(getContext(), 0, chatDatas);
listView.setAdapter(roomChatAdapter);
roomChatAdapter.setOnChatItemClickLitener(this);
listView.setOnTouchListener(new MyOnTouch());
listView.setOnScrollListener(this);
ivChat.setOnClickListener(this);
ivEmoji.setOnClickListener(this);
tvSend.setOnClickListener(this);
ivGift.setOnClickListener(this);
ivShare.setOnClickListener(this);
ivClose.setOnClickListener(this);
rlAnchor.setOnClickListener(this);
ivCamera.setOnClickListener(this);
et.setOnClickListener(this);
ivWarmClose.setOnClickListener(this);
llFollow.setOnClickListener(this);
giftLayout = findViewById(R.id.ll_gift_layout);
commonGiftView1 = (CommonGiftView) findViewById(R.id.gift_anim_layout_one);
commonGiftView2 = (CommonGiftView) findViewById(R.id.gift_anim_layout_two);
vsPariseView = (VoteSurface) findViewById(R.id.vs_parise_view);
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// int giftId = 12;
// int giftCnt = 1;
// Random random = new Random();
// for(int i = 0; i < 100; i++) {
// ReciveGiftInfo giftInfo = new ReciveGiftInfo(Globle.KEY_EVENT_RECEIVE_GIFT);
// giftInfo.setSenderName("送礼" + (4705 + (i % 2)));
// giftInfo.setSenderId((4705) + "");
// giftId = random.nextInt(2) == 1 ? 17:12;
// giftInfo.setGiftId(giftId + "");
// giftInfo.setReceiverId("4233");
// giftInfo.setReceiverName("接受礼物人");
// giftInfo.setGiftCnt(giftCnt++);
//
// GiftListResult.GiftListEntity giftEntity = GiftUtils.getGiftById(giftId + ""); // 17完美 8香蕉
// if(giftEntity != null) {
// giftInfo.setGiftUrl(giftEntity.getPic());
// giftInfo.setGiftName(giftEntity.getName());
//
// EventBus.getDefault().post(giftInfo);
// }else {
// ShowUtils.showToast("礼物信息缓存为空");
// }
// giftInfo.setGiftId("18");
// giftInfo.setId(Globle.KEY_EVENT_RECEIVE_SPECIAL_GIFT);
// EventBus.getDefault().post(giftInfo);
// }
// }
// }, 2000);
addTips();
}
private void addTips() {
if (!TextUtils.isEmpty(CacheUserInfoUtils.getShowTips())) {
MsgLog msgLog = new MsgLog();
msgLog.msgType = MsgLog.TYPE_TIPS;
msgLog.msgContent = CacheUserInfoUtils.getShowTips();
addMsg(msgLog);
}
}
/**
* 主播信息
*/
public void initAnChorData() {
ivAnchor.getHierarchy().setPlaceholderImage(R.drawable.head_online);
ivAnchor.getHierarchy().setFailureImage(AceApplication.getApplication().getResources().getDrawable(R.drawable.head_offline));
if (isAnchor) {
FrescoEngine.setSimpleDraweeView(ivAnchor, UserInfoUtils.getUserInfo().getProfile(), ImageRequest.ImageType.SMALL);
tvAnchorName.setText(UserInfoUtils.getUserInfo().getNickName());
tvAudience.setText("0");
tvCollect.setText("0");
} else {
FrescoEngine.setSimpleDraweeView(ivAnchor, LiveInfoUtils.getProFile(), ImageRequest.ImageType.SMALL);
tvAnchorName.setText(LiveInfoUtils.getNickName());
tvAudience.setText(TextUtils.isEmpty(LiveInfoUtils.getAudienceCnt()) ? "0" : LiveInfoUtils.getAudienceCnt());
tvCollect.setText("0");
}
getAudience();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
EventBus.getDefault().register(this);
//关闭房间定时刷新观众
// AlarmUtil.alarm(30, RefreshAudienceReceiver.class);
}
@Override
protected void onDetachedFromWindow() {
// AlarmUtil.alarm(-1, RefreshAudienceReceiver.class);
EventBus.getDefault().unregister(this);
if (mMessageHandler != null) {
mMessageHandler.removeCallbacksAndMessages(null);
mMessageHandler = null;
}
// GiftDialog.onActivityDestory();
commonGiftView1.setAnimatorFlag(false);
commonGiftView2.setAnimatorFlag(false);
vsPariseView = null;
super.onDetachedFromWindow();
}
@Override
public void onChatItemClick(MsgLog msgLog) {
hideKeyBoard();
int msgType = msgLog.getMsgType();
if (msgType != MsgLog.TYPE_TIPS && msgType != MsgLog.TYPE_SYSTEM)
showUserInfoDialog(msgLog.getSendNumber());
}
@Override
public void onLinkClick(String url) {
if (!TextUtils.isEmpty(url) && !isAnchor) {
Intent intent = new Intent(getContext(), ACEWebActivity.class);
intent.putExtra("url", url);
getContext().startActivity(intent);
}
}
@Override
public void onItemClick(View view, int position) {
AudienceResult.MemberListEntity memberListEntity = mAdapter.getmDatas().get(position);
showUserInfoDialog(memberListEntity.getUserId());
}
/**
* 个人信息弹窗
*
* @param id
*/
private void showUserInfoDialog(String id) {
if (multiClick()) return;
if (!TextUtils.isEmpty(id)) {
if (id.equals("-1")) {
return;
}
// infoDialog = SimpleUserInfoDialog.getSimpleUserInfoDialog(getContext(), 0);
if (infoDialog == null) {
infoDialog = new SimpleUserInfoDialog(getContext(), 0);
infoDialog.setOnNoLoginListener(this);
if (isAnchor) {
infoDialog.setIsAnchor(isAnchor);
}
}
infoDialog.setUserId(id);
infoDialog.show();
}
}
/**
* 防止连续点击
*
* @return
*/
private boolean multiClick() {
if (System.currentTimeMillis() - lastClickTime < 800) {
return true;
}
lastClickTime = System.currentTimeMillis();
return false;
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.iv_chat:
if (multiClick()) return;
if (UserInfoUtils.isAlreadyLogin()) {
KeyBoardUtils.openKeybord(et, getContext());
et.requestFocus();
} else {
showLoginDilaog();
}
break;
case R.id.iv_emoji:
if (mPanelRoot.getVisibility() == View.VISIBLE) {
KeyBoardUtils.openKeybord(et, getContext());
// hideKeyBoard();
} else {
needEmoji = true;
KeyBoardUtils.closeKeybord(et, getContext());
mPanelRoot.setVisibility(View.VISIBLE);
}
break;
case R.id.tv_send:
String content = et.getText().toString().trim();
if (!TextUtils.isEmpty(content)) {
sendMsg(content);
et.setText("");
// hideKeyBoard();
}
break;
case R.id.iv_gift:
if (multiClick()) return;
if (!UserInfoUtils.isAlreadyLogin()) {
showLoginDilaog();
return;
}
if (giftDialog == null) {
List<GiftListResult.GiftListEntity> giftList = GiftUtils.getGiftList();
if (giftList != null && giftList.size() != 0) {
// if (isFirstShowGiftDialog)
// GiftDialog.onActivityDestory();
// giftDialog = GiftDialog.getGiftDialog(getContext(), 0);
if (giftDialog == null) {
giftDialog = new GiftDialog(getContext(), 0);
giftDialog.setOnDismissListener(this);
}
giftDialog.show();
if (isFirstShowGiftDialog) {
giftDialog.setGifts(giftList);
tvEnterRoom.setAlpha(0);
listView.setAlpha(0);
rlBtns.setAlpha(0);
isFirstShowGiftDialog = false;
}
} else {
}
} else {
giftDialog.show();
tvEnterRoom.setAlpha(0);
listView.setAlpha(0);
rlBtns.setAlpha(0);
}
break;
case R.id.iv_share:
if (multiClick()) return;
shareDialog = ShareDialog.getShareDialog((Activity) getContext(), 0);
shareDialog.setOnDismissListener(this);
shareDialog.setShare(isAnchor);
rlBtns.setAlpha(0);
shareDialog.show();
break;
case R.id.iv_close:
EventBus.getDefault().post(new BaseEvent(Globle.KEY_ONCLICK_LIVE_FINISH));
break;
case R.id.rl_anchor:
String startId;
if (isAnchor) {
startId = UserInfoUtils.getUserInfo().getUserId();
} else {
startId = LiveInfoUtils.getStartId();
}
showUserInfoDialog(startId);
break;
case R.id.et:
KeyBoardUtils.openKeybord(et, getContext());
break;
case R.id.iv_close_warm:
llWarm.setVisibility(View.GONE);
break;
case R.id.ll_follow:
ReqRelationApi.reqSubscibe(getContext(), UserInfoUtils.getUserInfo().getUserId(), LiveInfoUtils.getStartId(), new RequestCallback<BaseResult>() {
@Override
public void onRequestSuccess(BaseResult object) {
}
@Override
public void onRequestFailure(BaseResult error) {
}
});
llFollow.setVisibility(View.GONE);
mMessageHandler.removeMessages(MSG_FOLLOW_NOTICE);
break;
default:
break;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (!isAnchor && !(mPanelRoot.getVisibility() == View.VISIBLE || isKeyBoardVisible)) {
vsPariseView.click();
String userId = "";
if (UserInfoUtils.isAlreadyLogin()) {
userId = UserInfoUtils.getUserInfo().getUserId();
}
SendUtils.sendParise(LiveInfoUtils.getShowId(), userId, "1");
}
hideKeyBoard();
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return super.onTouchEvent(event);
}
/**
* 键盘弹出和收回
*
* @param event
*/
@Subscribe(threadMode = ThreadMode.MainThread)
public void onKeyBoardEvent(KeyBoardEvent event) {
boolean show = event.isShow();
isKeyBoardVisible = show;
if (show) {
rlBtns.setVisibility(View.GONE);
rlInput.setVisibility(View.VISIBLE);
if (llTop.getVisibility() == View.VISIBLE)
hideTop(true);
} else {
if (needEmoji) {
needEmoji = false;
return;
}
rlInput.setVisibility(View.GONE);
rlBtns.setVisibility(View.VISIBLE);
if (llTop.getVisibility() != View.VISIBLE) {
hideTop(false);
}
}
}
/**
* 顶部布局
*
* @param hide :true,隐藏;false,显示
*/
private void hideTop(boolean hide) {
llTop.clearAnimation();
if (hide) {
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_out_from_top);
llTop.setVisibility(View.GONE);
llTop.startAnimation(animation);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(giftLayout.getLayoutParams());
params.bottomMargin = ShowUtils.dip2px(getContext(), 10);
params.addRule(RelativeLayout.ABOVE, R.id.tv_enter_room);
giftLayout.setLayoutParams(params);
giftLayout.requestLayout();
if (isAnchor) {
ViewGroup.LayoutParams params1 = listView.getLayoutParams();
params1.height = (int) getContext().getResources().getDimension(R.dimen.chat_audience_height);
}
} else {
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_in_from_top);
llTop.setVisibility(View.VISIBLE);
llTop.startAnimation(animation);
if (isAnchor) {
ViewGroup.LayoutParams params1 = listView.getLayoutParams();
params1.height = (int) getContext().getResources().getDimension(R.dimen.chat_anchor_height);
RelativeLayout.LayoutParams params = (LayoutParams) giftLayout.getLayoutParams();
params.bottomMargin = ShowUtils.dip2px(getContext(), 50);
params.addRule(RelativeLayout.ABOVE, R.id.tv_enter_room);
giftLayout.setLayoutParams(params);
giftLayout.requestLayout();
} else {
RelativeLayout.LayoutParams params = (LayoutParams) giftLayout.getLayoutParams();
params.bottomMargin = ShowUtils.dip2px(getContext(), 160);
params.addRule(RelativeLayout.ABOVE, R.id.tv_enter_room);
giftLayout.setLayoutParams(params);
giftLayout.requestLayout();
}
}
}
/**
* 收到socket消息
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.MainThread)
public void onReceiveMsg(BaseEvent msg) {
switch (msg.id) {
case Globle.KEY_EVENT_CHAT:
MsgLog msgLog = ((ChatMessage) msg).mMsgLog;
addMsg(msgLog);
break;
case Globle.KEY_RECEIVE_WARN:
MsgLog warn = ((ChatMessage) msg).mMsgLog;
if (!TextUtils.isEmpty(warn.getMsgContent())) {
tvWarm.setText(warn.getMsgContent());
llWarm.setVisibility(View.VISIBLE);
}
break;
case Globle.KEY_EVENT_ROOM_BROADCAST:
RoomBroadcastEvent roomBroadcastEvent = (RoomBroadcastEvent) msg;
if (Integer.parseInt(roomBroadcastEvent.getSupportCnt()) > 0) {
vsPariseView.add(Integer.parseInt(roomBroadcastEvent.getSupportCnt()));
}
tvAudience.setText(roomBroadcastEvent.getMemberCnt());
tvCollect.setText(roomBroadcastEvent.getTotalSupportCnt());
String income = roomBroadcastEvent.getIncome();
if (!TextUtils.isEmpty(income))
tvTicketNum.setText(income);
break;
case Globle.KEY_EVENT_RECEIVE_GIFT:
ReciveGiftInfo receiveGiftInfo = (ReciveGiftInfo) msg;
synchronized (this) {
String mapKey = receiveGiftInfo.getSenderId() + receiveGiftInfo.getGiftId();
List<ReciveGiftInfo> temp = receiveGiftMsgMap.get(mapKey);
if (temp == null) {
List<ReciveGiftInfo> reciveGiftInfoList = new ArrayList<ReciveGiftInfo>(2);
reciveGiftInfoList.add(receiveGiftInfo);
receiveGiftMsgMap.put(mapKey, reciveGiftInfoList);
} else {
temp.add(receiveGiftInfo);
}
}
// 礼物2号跑道空闲,并且当前礼物与礼物1跑道上的(发送人+礼物)不统一,发送执行动画消息
if (!commonGiftView2.isRunning() && !commonGiftView1.compareTo(receiveGiftInfo.getSenderId() + receiveGiftInfo.getGiftId())) {
CommonGiftAnimEvent animFinishEvent = new CommonGiftAnimEvent();
animFinishEvent.id = Globle.KEY_EVENT_GIFT_FINISH;
animFinishEvent.giftViewTag = 2;
EventBus.getDefault().post(animFinishEvent);
// 礼物1号跑道空闲,并且当前礼物与礼物2跑道上的(发送人+礼物)不统一,发送执行动画消息
} else if (!commonGiftView1.isRunning() && !commonGiftView2.compareTo(receiveGiftInfo.getSenderId() + receiveGiftInfo.getGiftId())) {
CommonGiftAnimEvent animFinishEvent = new CommonGiftAnimEvent();
animFinishEvent.id = Globle.KEY_EVENT_GIFT_FINISH;
animFinishEvent.giftViewTag = 1;
EventBus.getDefault().post(animFinishEvent);
// 礼物1跑道正被占用,当前礼物消息的(发送人+礼物)与跑道上的一致,设置收到新消息标记
} else if (commonGiftView1.compareTo(receiveGiftInfo.getSenderId() + receiveGiftInfo.getGiftId())) {
commonGiftView1.hasReceivedNewMsg(true);
// 礼物2跑道正被占用,当前礼物消息的(发送人+礼物)与跑道上的一致,设置收到新消息标记
} else if (commonGiftView2.compareTo(receiveGiftInfo.getSenderId() + receiveGiftInfo.getGiftId())) {
commonGiftView2.hasReceivedNewMsg(true);
}
break;
case Globle.KEY_EVENT_GIFT_FINISH:
CommonGiftAnimEvent giftAnimEvent = (CommonGiftAnimEvent) msg;
synchronized (this) {
if (receiveGiftMsgMap.size() > 0) {
if (giftAnimEvent.giftViewTag == 2) {
Iterator<String> iterator = receiveGiftMsgMap.keySet().iterator();
String mapKey = iterator.next();
// 选择将要执行的礼物与另一个跑道上的礼物不是同一个人发的同一种礼物
while (commonGiftView1.isRunning() && commonGiftView1.compareTo(mapKey)) {
if (iterator.hasNext()) {
mapKey = iterator.next();
} else {
mapKey = null;
break;
}
}
if (mapKey != null && (commonGiftView2.compareTo(mapKey) || commonGiftView2.compareTo(""))) {
commonGiftView2.startAnimation(mapKey, receiveGiftMsgMap.remove(mapKey));
} else if (commonGiftView2.getViewStatus() == CommonGiftView.GIFTVIEWPAUSE) {
commonGiftView2.stopAnimation();
}
} else if (giftAnimEvent.giftViewTag == 1) {
Iterator iterator = receiveGiftMsgMap.keySet().iterator();
String mapKey = (String) iterator.next();
while (commonGiftView2.isRunning() && commonGiftView2.compareTo(mapKey)) {
if (iterator.hasNext()) {
mapKey = (String) iterator.next();
} else {
mapKey = null;
break;
}
}
if (mapKey != null && (commonGiftView1.compareTo(mapKey) || commonGiftView1.compareTo(""))) {
commonGiftView1.startAnimation(mapKey, receiveGiftMsgMap.remove(mapKey));
} else if (commonGiftView1.getViewStatus() == CommonGiftView.GIFTVIEWPAUSE) {
commonGiftView1.stopAnimation();
}
}
} else {
if (giftAnimEvent.giftViewTag == 1 && commonGiftView1.isRunning()) {
commonGiftView1.stopAnimation();
} else if (giftAnimEvent.giftViewTag == 2 && commonGiftView2.isRunning()) {
commonGiftView2.stopAnimation();
}
}
}
break;
case Globle.KEY_ENTER_ROOM_MSG:
//进场
EnterRoomEvent event = (EnterRoomEvent) msg;
// if(!TextUtils.isEmpty(event.getUserId()) && UserInfoUtils.isAlreadyLogin() && isAnchor && UserInfoUtils.getUserInfo().getUserId().equals(event.getUserId())){
// //主播自己进场
// return;
// }
if (!TextUtils.isEmpty(event.getUserId()) && !event.getUserId().equals("-1")) {
tvEnterRoom.setText(getContext().getString(R.string.welcome_erter_room, event.getNickName()));
if (mMessageHandler == null)
mMessageHandler = new MessageHandler(this);
mMessageHandler.removeMessages(MSG_ENTER_ROOM);
lastEnterTime = System.currentTimeMillis();
mMessageHandler.sendEmptyMessageDelayed(MSG_ENTER_ROOM, 5000);
}
AudienceResult.MemberListEntity audience = new AudienceResult.MemberListEntity();
audience.setSex(event.getSex());
audience.setProfile(event.getProfile());
audience.setUserId(event.getUserId());
mAdapter.addData(audience);
break;
case Globle.KEY_KICKOUT_MSG:
//踢人
KickOutEvent kick = (KickOutEvent) msg;
if (kick.isResponse() && kick.isSuccess()) {
// ShowUtils.showToast(getContext().getString(R.string.tv_kick_success));
} else if (!kick.isResponse() && UserInfoUtils.isAlreadyLogin()) {
String userId = kick.getUserId();
if (!TextUtils.isEmpty(userId) && userId.equals(UserInfoUtils.getUserInfo().getUserId())) {
ShowUtils.showToast(getContext().getString(R.string.kick_out_msg));
ivClose.performClick();
}
}
break;
case Globle.KEY_ALARM_REQUEST_AUDIENCE:
// getAudience();
break;
case Globle.SEND_GIFT_RESPONSE:
if (giftDialog != null && giftDialog.isShowing()) {
SendGiftResponse response = (SendGiftResponse) msg;
giftDialog.setBalance(response);
}
break;
case Globle.KEY_EVENT_RECEIVE__GIFT_FORCHAT:
ReciveGiftInfo giftChatMsg = (ReciveGiftInfo) msg;
//生成聊天消息
MsgLog giftMsg = new MsgLog();
giftMsg.setChatMode(MsgLog.CHAT_MODE_GROUP);
giftMsg.setMsgType(MsgLog.TYPE_GIFT);
giftMsg.setMsgContent(getContext().getString(R.string.gift_msg, giftChatMsg.getGiftName()));
giftMsg.setSendNumber(giftChatMsg.getSenderId());
giftMsg.setNickName(giftChatMsg.getSenderName());
addMsg(giftMsg);
break;
default:
break;
}
}
public List<ReciveGiftInfo> getData(String userId) {
synchronized (this) {
Iterator<String> iterator = receiveGiftMsgMap.keySet().iterator();
if (iterator.hasNext()) {
if (userId.equals(iterator.next())) {
return receiveGiftMsgMap.remove(userId);
}
}
return null;
}
}
private void addMsg(MsgLog msgLog) {
roomChatAdapter.addData(msgLog, true);
listView.postDelayed(new Runnable() {
@Override
public void run() {
if (!isScrolling)
listView.smoothScrollToPosition(roomChatAdapter.getCount() - 1);
}
}, 100);
}
@Override
public void onDismiss(DialogInterface dialog) {
Animation move = AnimationUtils.loadAnimation(getContext(), R.anim.anim_in_from_bottom);
rlBtns.clearAnimation();
rlBtns.setAlpha(1);
rlBtns.startAnimation(move);
if (dialog.getClass().equals(GiftDialog.class)) {
Animation alpha = AnimationUtils.loadAnimation(getContext(), R.anim.anim_alpha_in);
listView.clearAnimation();
listView.setAlpha(1);
listView.startAnimation(alpha);
tvEnterRoom.clearAnimation();
tvEnterRoom.setAlpha(1);
tvEnterRoom.startAnimation(alpha);
}
}
class MyOnTouch implements OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
hideKeyBoard();
break;
default:
break;
}
return false;
}
}
/**
* 隐藏键盘和表情
*/
public void hideKeyBoard() {
if (mPanelRoot.getVisibility() == View.VISIBLE) {
mPanelRoot.setVisibility(View.GONE);
hideTop(false);
} else {
KeyBoardUtils.closeKeybord(et, getContext());
}
rlInput.setVisibility(View.GONE);
rlBtns.setVisibility(View.VISIBLE);
}
/**
* 用于观众接到主播下播通知时,隐藏所有弹出框
*/
public void hideDialog() {
if (infoDialog != null && infoDialog.isShowing()) {
infoDialog.dismiss();
}
if (shareDialog != null && shareDialog.isShowing()) {
shareDialog.dismiss();
}
if (giftDialog != null && giftDialog.isShowing()) {
giftDialog.dismiss();
}
if (simpleLoginDialog != null && simpleLoginDialog.isShowing()) {
simpleLoginDialog.dismiss();
}
hideKeyBoard();
}
public boolean canGoBack() {
if (mPanelRoot.getVisibility() == View.VISIBLE || isKeyBoardVisible) {
hideKeyBoard();
return true;
}
return false;
}
public boolean isMuteChecked() {
return cbVoice.isChecked();
}
public void setFlashswitch(boolean enabled) {
if (enabled) {
rlFlicker.setVisibility(View.VISIBLE);
cbFlicker.setChecked(false);
} else {
rlFlicker.setVisibility(View.GONE);
}
}
/**
* 获取观众列表
*/
private void getAudience() {
String id;
if (isAnchor) {
id = UserInfoUtils.getUserInfo().getUserId();
} else {
id = LiveInfoUtils.getShowId();
}
ReqRoomApi.reqAudienceList((Activity) getContext(), id, "1", "1000", new RequestCallback<AudienceResult>() {
@Override
public void onRequestSuccess(AudienceResult object) {
List<AudienceResult.MemberListEntity> memberList = object.getMemberList();
int size = Math.min(1000, memberList.size());
ArrayList<AudienceResult.MemberListEntity> memberListEntities = new ArrayList<AudienceResult.MemberListEntity>();
memberListEntities.addAll(memberList.subList(0, size));
Collections.reverse(memberListEntities);
AudienceResult.MemberListEntity omit = new AudienceResult.MemberListEntity();
omit.setUserId("-1");
omit.setProfile("res://" + getContext().getPackageName() + "/" + R.drawable.omit);
memberListEntities.add(omit);
mAdapter.setmDatas(memberListEntities);
tvAudience.setText(object.getMemberSize());
tvCollect.setText(object.getSupportCnt());
}
@Override
public void onRequestFailure(AudienceResult error) {
}
});
}
private void sendMsg(String content) {
UserInfoResult.UserEntity user = UserInfoUtils.getUserInfo();
String showId = "";
if (isAnchor) {
showId = user.getUserId();
} else {
showId = LiveInfoUtils.getShowId();
}
MsgLog msgLog = new MsgLog();
msgLog.sendNumber = user.getUserId();
msgLog.showId = showId;
msgLog.nickName = user.getNickName();
msgLog.msgContent = content;
msgLog.chatMode = MsgLog.CHAT_MODE_GROUP;
msgLog.msgType = MsgLog.TYPE_TXT_MSG;
addMsg(msgLog);
SendUtils.sendMessage(msgLog);
}
public void showLoginDilaog() {
if (simpleLoginDialog == null) {
simpleLoginDialog = new SimpleLoginDialog(getContext());
}
simpleLoginDialog.show();
}
public EditText getEditView() {
return et;
}
public void destroyPariseView() {
vsPariseView.destroyHolder();
}
/**
* 请求是否关注了主播
*
* @param startId
*/
private void requestRelation(String startId) {
if (UserInfoUtils.isAlreadyLogin() && !TextUtils.isEmpty(startId)) {
String userId = UserInfoUtils.getUserInfo().getUserId();
ReqUserApi.requestUserInfo(this, startId, userId, new RequestCallback<UserInfoResult>() {
@Override
public void onRequestSuccess(UserInfoResult object) {
if (object != null) {
String relatoin = object.getUser().getExtendData().getRelatoin();
if (!TextUtils.isEmpty(relatoin) && relatoin.equals("1")) {
//已经关注
} else {
llFollow.setVisibility(View.VISIBLE);
mMessageHandler.sendEmptyMessageDelayed(MSG_FOLLOW_NOTICE, FOLLOW_TIME);
}
}
}
@Override
public void onRequestFailure(UserInfoResult error) {
}
});
}
}
public CheckBox getCheckBox(int id) {
CheckBox cb = null;
switch (id) {
case R.id.cb_voice:
cb = cbVoice;
break;
case R.id.cb_flicker:
cb = cbFlicker;
break;
case R.id.cb_skincare:
cb = cbSkincare;
break;
}
return cb;
}
public void clearSpecialEffects() {
vsPariseView.stopDraw();
receiveGiftMsgMap.clear();
commonGiftView1.setAnimatorFlag(false);
commonGiftView2.setAnimatorFlag(false);
}
}
|
package basic;
public class Loop5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x;
for(int i=1;i<=3;i++)
{
x=97;
for(int j=2;j>=i;j--)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print((char)x);
x++;
}
for(int d=1;d<=i-1;d++)
{
x=x-2;
System.out.print((char)x);
x++;
}
System.out.println();
}
for(int s=1;s<=2;s++)
{
x=97;
for(int l=1;l<=s;l++)
{
System.out.print(" ");
}
for(int m=2;m>=s;m--)
{
System.out.print((char)x);
x++;
}
for(int n=2;n>s;n--)
{
x=97;
System.out.print((char)x);
}
System.out.println();
}
}
}
|
package com.bukkit.Duendek86.tiredman;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.*;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
/**
* TiredMan 0.5
* Copyright (C) 2011 Duendek86 <mendezpoli86@gmail.com>, Fran <franrv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* tiredmanBlockListener.java
*
* Comprueba si el usuario esta moviendose dentro de agua profunda y calcula.
* si tiene suficiente energia o si comienza a ahogarse.
*
* @author Duendek86 <mendezpoli86@gmail.com>
* @author Fran <franrv@gmail.com>
*/
public class tiredmanBlockListener extends BlockListener {
private final TiredMan plugin;
public tiredmanBlockListener(final TiredMan instance) {
plugin = instance;
}
//put all Block related code here
@Override
public void onBlockDamage(BlockDamageEvent event){
Integer fatigatrue = Integer.parseInt((String) Config.getConfiguracion().get("landfatigue"));
if (fatigatrue == 1){
Player player = event.getPlayer();
PlayerStatus status = new PlayerStatus(player);
String njugador = player.getName();
if (Config.getConfiguracion().contains(njugador)){
return;
}
Integer cansancio = Config.basedatoscansado.get(njugador);
status.aumentarcansancio(cansancio, 15);
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event){
Integer fatigatrue = Integer.parseInt((String) Config.getConfiguracion().get("landfatigue"));
if (fatigatrue == 1){
Player player = event.getPlayer();
PlayerStatus status = new PlayerStatus(player);
String njugador = player.getName();
for (int i = 0; i<Config.getUsersunafected().size(); i++){
if (njugador.equalsIgnoreCase((String) Config.getUsersunafected().get(i))){
return;
}
}
Integer cansancio = Config.basedatoscansado.get(njugador);
status.aumentarcansancio(cansancio, 8);
}
}
} |
package Operacional;
import java.util.List;
public interface TicketDao {
public boolean salvarTicket(Ticket ls);
}
|
package com.fest.pecfestBackend.request;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@AllArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@NoArgsConstructor
public class ResetPasswordRequest {
@NotNull
private Long userId;
@NotBlank
private String password;
@NotNull
private String verificationCode;
}
|
import java.io.*;
/**
* Created by VSZM on 2014-08-02.
*/
class EIGHTS {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] lastThreeDigits = new int[]{192,442,692,942};
int caseCount = Integer.parseInt(br.readLine());
while (caseCount-- > 0){
long k =Long.parseLong(br.readLine());
long result = lastThreeDigits[(int)( (k-1) % 4)] + 1000 * ((k-1)/4);
bw.write(Long.toString(result));
bw.newLine();
}
bw.flush();
}
}
|
package comUtil;
public class HexStringUtil {
public static HexStringUtil getInstance() {
return new HexStringUtil();
}
public String bytesToHexString(byte[] bArray) {
StringBuffer stringBuffer = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
stringBuffer.append(0);
stringBuffer.append(sTemp.toUpperCase());
}
return stringBuffer.toString();
}
public byte[] hexStringToByte(String hex) {
int len = 0;
//判断字符串的长度是否是两位
if (hex.length() >= 2) {
//判断字符喜欢是否是偶数
len = (hex.length() / 2);
if (hex.length() % 2 == 1) {
hex = "0" + hex;
len = len + 1;
}
} else {
hex = "0" + hex;
len = 1;
}
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static int toByte(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
}
|
package com.gmail.filoghost.holographicdisplays.nms.interfaces.entity;
public interface NMSArmorStand extends NMSNameable {
}
|
package net.cpollet.es.database;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DefaultConnectionFactory implements ConnectionFactory {
private final DataSource dataSource;
public DefaultConnectionFactory(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
/**
* Class containing a register field where the user can enter credentials and
* submit.
*
* @author Emil
*/
public class Register {
private User newUser;
private String filled = "";
/**
* Takes the Window to know where to place the register pop-up and then
* creates the window will all required fields.
*
* @param owner
*/
public Register(Window owner) {
final Stage dialog = new Stage();
dialog.setTitle("Enter Information: ");
dialog.initOwner(owner);
dialog.initStyle(StageStyle.UTILITY);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.setX(owner.getX() + owner.getWidth());
dialog.setY(owner.getY());
final TextField usernameField = new TextField();
final PasswordField passField = new PasswordField();
final PasswordField pass2Field = new PasswordField();
final TextField userField = new TextField();
final TextField surnameField = new TextField();
final TextField ssnField = new TextField();
final TextField emailField = new TextField();
final Button submitButton = new Button("Submit");
final Label usernameL = new Label("Username:");
final Label passwordL = new Label("Password");
final Label password2L = new Label("Password Again");
final Label userL = new Label("First name");
final Label surnameL = new Label("Surname");
final Label ssnL = new Label("Social security number");
final Label emailL = new Label("Email");
submitButton.setDefaultButton(true);
submitButton.setOnAction(new EventHandler<ActionEvent>() {
/**
* The button has a function that closes the window if no field is
* empty and passwords match empty and the passwords match. And sets a new User and the confirms everything is filled.
*
* @param t ActionEvent
*/
@Override
public void handle(ActionEvent t) {
if (userField.getText().isEmpty() || passField.getText().isEmpty() || pass2Field.getText().isEmpty() || usernameField.getText().isEmpty() || surnameField.getText().isEmpty() || emailField.getText().isEmpty() || ssnField.getText().isEmpty()) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText("Missing credentials warning:");
alert.setContentText("Please fill in all the forms!");
alert.showAndWait();
} else {
if (passField.getText().equals(pass2Field.getText())) {
newUser = new User(usernameField.getText(), passField.getText(), userField.getText(), surnameField.getText(), ssnField.getText(), emailField.getText());
filled = "done";
dialog.close();
} else {
passField.setText("");
pass2Field.setText("");
pass2Field.setPromptText("Paswords do not match");
passField.setPromptText("Paswords do not match");
}
}
}
});
usernameField.setMinHeight(TextField.USE_PREF_SIZE);
usernameField.setPromptText("Username");
passField.setMinHeight(TextField.USE_PREF_SIZE);
passField.setPromptText("Password");
pass2Field.setMinHeight(TextField.USE_PREF_SIZE);
pass2Field.setPromptText("Password");
userField.setMinHeight(TextField.USE_PREF_SIZE);
userField.setPromptText("First name");
surnameField.setMinHeight(TextField.USE_PREF_SIZE);
surnameField.setPromptText("Surname");
ssnField.setMinHeight(TextField.USE_PREF_SIZE);
ssnField.setPromptText("Social security number");
emailField.setMinHeight(TextField.USE_PREF_SIZE);
emailField.setPromptText("Email");
final VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER_RIGHT);
layout.setStyle("-fx-background-color: azure; -fx-padding: 10;");
layout.getChildren().setAll(
usernameL,
usernameField,
passwordL,
passField,
password2L,
pass2Field,
userL,
userField,
surnameL,
surnameField,
ssnL,
ssnField,
emailL,
emailField,
submitButton
);
dialog.setScene(new Scene(layout));
dialog.showAndWait();
}
/**
* Returns the user created from the entered credentials.
*
* @return user from entered credentials
*/
public User getUser() {
return newUser;
}
/**
* Returns a string confirming the user has been registered.
*
* @return string confirming registration
*/
public String getFilled() {
return filled;
}
}
|
package com.bharath.trainings.servlets.preinit;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class PreInitServlet
*/
public class PreInitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() {
System.out.println("Inside the init method");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("From the pre init servlet");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// TODO Auto-generated method stub
}
}
|
package com.xwolf.eop.common.pojo;
import com.alibaba.fastjson.JSONArray;
import lombok.Data;
/**
* @author wolf
* @date 2016-12-26 11:47
* @since V1.0.0
*/
@Data
public class NavMenus {
private String id;
private String text;
private String icon;
private String url;
private JSONArray children;
}
|
package org.maven;
import java.util.List;
import java.awt.print.Book;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Excel {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",
"C:\\Vaishu\\eclipse-workspace\\MavenDay1\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.automationtesting.in/Register.html");
WebElement click = driver.findElement(By.id("countries"));
click.click();
Select s = new Select(click);
List<WebElement> l = s.getOptions();
int p = l.size();
File file = new File("C:\\Vaishu\\eclipse-workspace\\MavenDay1\\Access1\\Book7.xlsx");
FileInputStream stream = new FileInputStream(file);
Workbook book = new XSSFWorkbook(stream);
Sheet sheet = book.createSheet("Abi5");
Row createRow = null;
Cell createCell = null;
for (int i = 0; i < p; i++) {
String options = l.get(i).getText();
System.out.println(options);
createRow = sheet.createRow(i);
createCell = createRow.createCell(1);
createCell.setCellValue(options);
}
FileOutputStream stream1 = new FileOutputStream(file);
book.write(stream1);
driver.quit();
}
}
|
package com.example.motionlayout;
import android.app.Activity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ArrayList<ActivityItem> mActivityData;
private ActivityAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager
(2, StaggeredGridLayoutManager.VERTICAL));
mActivityData = new ArrayList<>();
mAdapter = new ActivityAdapter(this, mActivityData);
mRecyclerView.setAdapter(mAdapter);
initializeData();
}
private void initializeData() {
String[] activityNames = getResources()
.getStringArray(R.array.activities_names);
}
} |
package com.gxtc.huchuan.ui.mine.personalhomepage.more;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.CircleHomeBean;
import com.gxtc.huchuan.bean.DealListBean;
import com.gxtc.huchuan.bean.HomePageChatInfo;
import com.gxtc.huchuan.bean.NewsBean;
import com.gxtc.huchuan.bean.ThumbsupVosBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.List;
/**
* Describe:
* Created by ALing on 2017/4/10 .
*/
public class PersonalHomePageMoreContract {
public interface View extends BaseUserView<PersonalHomePageMoreContract.Presenter> {
void showHomePageGroupInfoList(List<CircleHomeBean> list);
void showDZSuccess(int id);
void showSelfNewsList(List<NewsBean> list);
void showUserNewsList(List<NewsBean> list);
void showSelfChatInfoList(List<HomePageChatInfo> list);
void showUserChatInfoList(List<HomePageChatInfo> list);
void showSelfDealList(List<DealListBean> list);
void showUserDealList(List<DealListBean> list);
void showLoadMoreNewsList(List<NewsBean> list);
void showLoadMoreChatInfoList(List<HomePageChatInfo> list);
void showLoadMoreHomePageGroupInfoList(List<CircleHomeBean> list);
void showLoadMoreDealList(List<DealListBean> list);
/**
* 没有更多数据
*/
void showNoMore();
}
public interface Presenter extends BasePresenter {
void getHomePageGroupInfoList(String userCode,boolean isRefresh);
void dianZan(int id);
void getSelfNewsList(boolean isRefresh);
void getUserNewsList(String userCode,boolean isRefresh);
void getSelfChatInfoList(boolean isRefresh);
void getUserChatInfoList(String userCode,boolean isRefresh);
void getSelfDealList(boolean isRefresh);
void getUserDealList(String userCode,boolean isRefresh);
void loadMrore(String type, String userCode);
}
public interface Source extends BaseSource {
//动态主页
void getHomePageGroupInfoList(ApiCallBack<List<CircleHomeBean>> callBack, String userCode,String token, String start);
//动态点赞
void dianZan(String token, int id, ApiCallBack<ThumbsupVosBean> callBack);
//获取自己个人主页的新闻列表接口
void getSelfNewsList(ApiCallBack<List<NewsBean>> callBack, String token, String start);
//获取用户个人主页的新闻列表接口
void getUserNewsList(ApiCallBack<List<NewsBean>> callBack, String userCode, String start);
//获取自己个人主页的直播课程列表接口
void getSelfChatInfoList(ApiCallBack<List<HomePageChatInfo>> callBack, String token, String start);
//获取用户个人主页的直播课程列表接口
void getUserChatInfoList(ApiCallBack<List<HomePageChatInfo>> callBack, String userCode, String start);
//获取自己个人主页的交易列表接口
void getSelfDealList(ApiCallBack<List<DealListBean>> callBack, String token, String start);
//获取用户个人主页的交易列表接口
void getUserDealList(ApiCallBack<List<DealListBean>> callBack, String userCode, String start);
}
}
|
package com.khakaton.mafia.interfaces;
public interface GroupGame {
public void start();
public void play();
public void doCycle();
}
|
package com.testAutomationCoach.amazon;
public class HomePage {
Imagen logoAmazon;
TextField campoBusqueda;
Button lupitaBusquda;
Link devolucionesPedidos;
Imagen[] articuloSugerido;
public void buscarProducto(String nombreProducto) {
campoBusqueda.ingresarTexto(nombreProducto);
lupitaBusquda.click();
}
public void clickDevoluciones() {
devolucionesPedidos.click();
}
public void seleccionarArticulo(String nombreArticulo) {
//buscar en todas las imagenes, una que tenga tooltip igual al nombreArticulo
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.client;
import java.io.IOException;
import java.net.URI;
import org.springframework.http.HttpMethod;
/**
* Wrapper for a {@link ClientHttpRequestFactory} that buffers
* all outgoing and incoming streams in memory.
*
* <p>Using this wrapper allows for multiple reads of the
* {@linkplain ClientHttpResponse#getBody() response body}.
*
* @author Arjen Poutsma
* @since 3.1
*/
public class BufferingClientHttpRequestFactory extends AbstractClientHttpRequestFactoryWrapper {
/**
* Create a buffering wrapper for the given {@link ClientHttpRequestFactory}.
* @param requestFactory the target request factory to wrap
*/
public BufferingClientHttpRequestFactory(ClientHttpRequestFactory requestFactory) {
super(requestFactory);
}
@Override
protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory)
throws IOException {
ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
if (shouldBuffer(uri, httpMethod)) {
return new BufferingClientHttpRequestWrapper(request);
}
else {
return request;
}
}
/**
* Indicates whether the request/response exchange for the given URI and method
* should be buffered in memory.
* <p>The default implementation returns {@code true} for all URIs and methods.
* Subclasses can override this method to change this behavior.
* @param uri the URI
* @param httpMethod the method
* @return {@code true} if the exchange should be buffered; {@code false} otherwise
*/
protected boolean shouldBuffer(URI uri, HttpMethod httpMethod) {
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hu.unideb.inf.modell;
import hu.unideb.inf.entity.Course;
import hu.unideb.inf.entity.Note;
import hu.unideb.inf.entity.User;
import hu.unideb.inf.util.JpaEduDAO;
import hu.unideb.inf.util.EduDAO;
import java.time.LocalDate;
/**
*
* @author pixel
*/
public class Simulation {
private User student1, student2, teacher1, admin1;
private Note note1, note2;
private Course subject;
private static Simulation instance = null;
public static synchronized Simulation getInstance() {
if (instance == null) {
instance = new Simulation();
}
return instance;
}
public User getStudent1() {
return student1;
}
public User getStudent2() {
return student2;
}
public User getTeacher1() {
return teacher1;
}
public User getAdmin1() {
return admin1;
}
public Course getSubject() {
return subject;
}
private Simulation() { //privát láthatóságú konstruktor!
student1 = new User(User.userType.STUDENT, "ElekVokOztCso", "János", "Kocsis", LocalDate.parse("1999-04-04"), "jonnyyespapa@malbox.unideb.hu", "jelszó123");
student2 = new User(User.userType.STUDENT, "Tesztellek", "Elek", "Teszt", LocalDate.parse("1998-12-03"), "szamonkerlek@malbox.unideb.hu", "TESZT123");
teacher1 = new User(User.userType.TEACHER, "EzAlma", "Péter", "Alma", LocalDate.parse("1981-07-06"), "ezalma@malbox.unideb.hu", "jelszó123");
admin1 = new User(User.userType.ADMIN, "admin", "Jenő", "Menő", LocalDate.parse("1977-07-07"), "nagyonadmin@malbox.unideb.hu", "admin123");
note1 = new Note("Jegyzet1", "Ez egy jegyzet.");
note2 = new Note("Jegyzet2");
note2.setValue("Ez egy másik jegyzet.");
subject = new Course("SzoftDev", "123");
//Save the users
try (EduDAO uDAO = new JpaEduDAO<User>()) {
uDAO.save(student1);
uDAO.save(student2);
uDAO.save(teacher1);
uDAO.save(admin1);
}
// //Add the users to the course
// subject.addUser(student2);
// subject.addUser(teacher1);
// subject.setResponsible(teacher1);
// try (EduDAO cDAO = new JpaEduDAO<Course>()) {
// cDAO.save(subject);
// }
// try (EduDAO cDAO = new JpaEduDAO<Course>()){
// cDAO.update(subject);
// }
//Add the course to the users
var subject2 = new Course("Menő", "123");
student1.addCourse(subject);
student2.addCourse(subject);
teacher1.addCourse(subject);
teacher1.addCourse(subject2);
subject.setResponsible(teacher1);
subject2.setResponsible(teacher1);
try (EduDAO cDAO = new JpaEduDAO<Course>()) {
cDAO.save(subject);
cDAO.save(subject2);
}
try (EduDAO uDAO = new JpaEduDAO<User>()) {
uDAO.update(student1);
uDAO.update(student2);
uDAO.update(teacher1);
}
//Add the notes to the course
subject.addNote(note1);
subject.addNote(note2);
try (EduDAO nDAO = new JpaEduDAO<Note>()) {
nDAO.save(note1);
nDAO.save(note2);
}
try (EduDAO uDAO = new JpaEduDAO<Course>()) {
uDAO.update(subject);
}
}
}
|
package dados;
import java.util.List;
import negocios.beans.Funcionario;
public interface IRepositorioFuncionario {
public boolean inserir(Funcionario funcionario);
public boolean alterar(Funcionario novoFuncionario);
public Funcionario buscar(int codigo);
public boolean remover(int codigo);
public boolean funcionarioContem(Funcionario funcionario);
public boolean existe(int codigo);
public abstract List<Funcionario> listar();
void salvarArquivo();
}
|
/*
* The MIT License (MIT)
* Copyright © 2012 Remo Koch, http://rko.mit-license.org/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the “Software”), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.rko.uzh.mailsys.facade.cli;
import io.rko.uzh.mailsys.base.Category;
import io.rko.uzh.mailsys.base.IMessageSource;
import io.rko.uzh.mailsys.ctrl.Mailbox;
import io.rko.uzh.mailsys.ctrl.Mailsystem;
import io.rko.uzh.mailsys.model.Mail;
import io.rko.uzh.mailsys.version.PackageVersion;
public class MailsystemMain {
public static void main(String[] pArgs) {
System.out.println(String.format("%s started successfully.", PackageVersion.getPackageVersion()));
Mailsystem msys = new Mailsystem();
Mailbox mbox1 = new Mailbox("Mailbox 1");
Mailbox mbox2 = new Mailbox("Mailbox 2");
Mailbox mbox3 = new Mailbox("Mailbox 3");
msys.subscribe(Category.IT, mbox1);
msys.subscribe(Category.MISC, mbox1);
msys.subscribe(Category.MISC, mbox2);
msys.subscribe(Category.BUSINESS, mbox3);
IMessageSource mail;
// Mail that should not get through
System.out.println();
System.out.println("Mail 1 ------------");
mail = new Mail("hello@test.ch", "Whatever", "Message shouldn't get through");
msys.receive(mail);
// Mail to MISC
System.out.println();
System.out.println("Mail 2 ------------");
mail = new Mail("hello@rko.io", "Whatever", "New message");
msys.receive(mail);
// Mail to MISC
System.out.println();
System.out.println("Mail 3 ------------");
mail = new Mail("hello@somecompany.com", "[STUFF] Good news", "This is some boring news stuff");
msys.receive(mail);
// Mail that should not get through -> spam
System.out.println();
System.out.println("Mail 4 ------------");
mail = new Mail("hello@somecompany.com", "[IT] It's spam", "tHizz m3ss4ge is sPAm!!");
msys.receive(mail);
System.out.println();
System.out.println("Mail 5 ------------");
mail = new Mail("hello@somecompany.com", "[business] this is a business mail", "We have<br> html tags <b>here!</b>");
msys.receive(mail);
System.out.println();
System.out.println("Mail 6 ------------");
mail = new Mail("mi6@somecompany.com", "[secret] eyes only!", "TROLL!");
msys.receive(mail);
System.out.println();
System.out.println("Mail 7 ------------");
mail = new Mail("derp@somecompany.com", "[news] derpina cheated on you!", "hehehehe!");
msys.receive(mail);
System.out.println();
System.out.println("-------------------");
System.out.println();
System.out.println("All done, shutting down.");
System.exit(0);
}
}
|
package com.karya.service;
import java.util.List;
import com.karya.model.AccountsPayable001MB;
public interface IAccountsPayableService {
public List<AccountsPayable001MB> accountspayablelist();
public void addaccountspayable(AccountsPayable001MB accountspayablemb);
public AccountsPayable001MB getAccountsPayable(int id);
public void deleteaccountspayable(int id);
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.api;
import java.util.Map;
import java.util.Set;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.types.basic.NotificationChannel;
/**
* Management and usage of notifications subsystem (email, sms, ...)
* @author K. Benedyczak
*/
public interface NotificationsManagement
{
/**
* @return set with names of all available notification facilities (implementations). E.g. email
* sender can be a facility.
*/
public Set<String> getNotificationFacilities() throws EngineException;
/**
* Creates a new channel for a given facility. E.g. a new email facility configured to use a concrete
* SMTP server.
* @param toAdd
*/
public void addNotificationChannel(NotificationChannel toAdd) throws EngineException;
/**
* Removes a specified channel.
* @param channelName
* @throws EngineException
*/
public void removeNotificationChannel(String channelName) throws EngineException;
/**
* Changes configuration of an existing notification channel.
* @param channelName
* @param newConfiguration
* @throws EngineException
*/
public void updateNotificationChannel(String channelName, String newConfiguration) throws EngineException;
/**
*
* @return map of available notification channels.
* @throws EngineException
*/
public Map<String, NotificationChannel> getNotificationChannels() throws EngineException;
}
|
package cn.v5cn.v5cms.service.impl;
import cn.v5cn.v5cms.dao.CommentsDao;
import cn.v5cn.v5cms.entity.Comments;
import cn.v5cn.v5cms.service.CommentsService;
import cn.v5cn.v5cms.util.PropertyUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.util.List;
/**
* Created by ZXF-PC1 on 2015/7/28.
*/
@Service("commentsService")
public class CommentsServiceImpl implements CommentsService {
@Autowired
private CommentsDao commentsDao;
@Override
public Page<Comments> findCommentsPageable(final Comments comment, Integer currPage) {
int pageSize = Integer.valueOf(PropertyUtils.getValue("page.size").or("0"));
if(currPage == null || currPage < 1) currPage = 1;
return commentsDao.findAll(new Specification<Comments>(){
@Override
public Predicate toPredicate(Root<Comments> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> ps = Lists.newArrayList();
if(comment.getCommentContent() !=null && !"".equals(comment.getCommentContent())){
Path<String> commentContent = root.get("commentContent");
Path<String> reply = root.get("reply");
ps.add(criteriaBuilder.like(commentContent, "%" + comment.getCommentContent() + "%"));
ps.add(criteriaBuilder.like(reply, "%" + comment.getCommentContent() + "%"));
}
//criteriaBuilder.conjunction(); 创建一个AND
//criteriaBuilder.disjunction(); 创建一个OR
return ps.size() == 0 ? criteriaBuilder.conjunction():criteriaBuilder.or(ps.toArray(new Predicate[ps.size()]));
}
},new PageRequest(currPage-1,pageSize,new Sort(Sort.Direction.DESC,"commentDate")));
}
}
|
package boisson;
import decorateurr.Chocolat;
import decorateurr.Vanille;
public class Main {
public static void main(String[] args) {
Boisson boisson= new Expresso();
System.out.println(boisson.getDescription());
System.out.println("prix : "+boisson.cout());
System.out.println("----------------------");
boisson= new Chocolat( new Vanille(boisson));
System.out.println(boisson.getDescription());
System.out.println("prix : "+boisson.cout());
}
}
|
package com.ayt.dataprovider;
import org.apache.log4j.Logger;
import org.springframework.boot.test.context.SpringBootTest;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.util.Map;
/**
* @Auther: ayt
* @Date: 2018/8/19 23:37
* @Description: Don't worry ,just try
*/
@Listeners
@SpringBootTest
public class DataProvider1Test {
private static Logger logger=Logger.getLogger(DataProvider1Test.class);
@Test(dataProvider = "create",dataProviderClass = DataProvider1.class)
public void testDataCreat(int x,int y,int z,boolean expected){
logger.info(x+y+z);
logger.info(expected);
}
@Test(dataProvider = "create",dataProviderClass = DataProvider1.class)
public void testDataCreat1(Object[][] objects){
// logger.info(x+y+z);
// logger.info(expected);
for (int i=0;i<objects.length;i++){
for (int j = 0; j <objects[i].length ; j++) {
logger.info(objects[i][j]);
}
}
}
@Test(dataProvider = "create1",dataProviderClass = DataProvider1.class)
public void two (int x){
logger.info(x);
}
@Test(dataProvider = "create2",dataProviderClass = DataProvider1.class)
public void randow(Integer n){
logger.info(n);
}
}
|
public class Giocatori {
private String nome;
private double punteggio;
private int eta;
private String ruolo;
public Giocatori(String nome,int eta){
this.nome=nome.substring(0, 1).toUpperCase() + nome.substring(1).toLowerCase();
if (eta<10 || eta>50){
this.eta=20;
}else{
this.eta=eta;
}
}
public Giocatori(String nome,int eta,int punteggio,String ruolo){
this.nome=nome.substring(0, 1).toUpperCase() + nome.substring(1).toLowerCase();
if (eta<10 || eta>50){
this.eta=23;
}else{
this.eta=eta;
}
if(punteggio<40 || punteggio>100){
this.punteggio=70;
}else{
this.punteggio=punteggio;
}
ruolo=ruolo.toUpperCase();
this.ruolo=ruolo;
}
public String getNome(){
return nome;
}
public double getPunteggo(){
return punteggio;
}
public int getEta(){
return eta;
}
public String getRuolo(){
return ruolo;
}
public void setEta(int eta) {
this.eta = eta+1;
}
public void setPunteggo(double nuovoPunteggio){
if(nuovoPunteggio<40 && nuovoPunteggio>100){
nuovoPunteggio=40;
}
this.punteggio=nuovoPunteggio;
}
public String toString(){
return "\n nome :" + nome + " " + " \n punteggio : " + punteggio + " " + "\n eta : " + eta + " " + "\n ruolo:" + ruolo + "\n";
}
}
|
package com.lotbyte.inter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
/**
* @author lp
* @Date 2019/3/28 18:13
* @Version 1.0
*/
@FunctionalInterface
public interface ResultSetFunction<T> {
/**
* 执行结果集处理
*/
public ResultSet execute(PreparedStatement ps) throws Exception;
}
|
package nl.tue.win.dbt.tests;
import nl.tue.win.dbt.data.LabeledGraph;
import nl.tue.win.dbt.data.LabeledHistoryGraph;
import nl.tue.win.dbt.parsers.DatasetParser;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Objects;
public class ReadTime<V, E, L> {
private final String filename;
private final DatasetParser<V, E, L> parser;
private long startRead;
private long endRead;
private long startWrite;
private long endWrite;
private final LabeledHistoryGraph<LabeledGraph<V, E, L>, V, E, L> lhg;
public ReadTime(String filename, DatasetParser<V, E, L> parser) {
Objects.requireNonNull(filename);
Objects.requireNonNull(parser);
this.filename = filename;
this.parser = parser;
this.startRead= System.currentTimeMillis();
this.lhg = this.parser.convertToHistoryGraph(this.filename);
this.endRead = System.currentTimeMillis();
this.startWrite = System.currentTimeMillis();
// this.writeToFile("data/lhg.ser");
this.endWrite = System.currentTimeMillis();
}
public String getFilename() {
return this.filename;
}
public DatasetParser<V, E, L> getParser() {
return this.parser;
}
public long getStartRead() {
return this.startRead;
}
public long getEndRead() {
return this.endRead;
}
public long getStartWrite() {
return this.startWrite;
}
public long getEndWrite() {
return this.endWrite;
}
public LabeledHistoryGraph<LabeledGraph<V, E, L>, V, E, L> getLhg() {
return this.lhg;
}
public long calculateReadDelta() {
return this.endRead - this.startRead;
}
public long calculateWriteDelta() {
return this.endWrite - this.startWrite;
}
private void writeToFile(String filename) {
try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) {
out.writeObject(this.lhg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package ToyStore;
//(c) A+ Computer Science
//www.apluscompsci.com
//Name -
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class ToyStoreRunner
{
public static void main( String args[] )
{
ToyStore store= new ToyStore();
store.loadToys("Bat Sorry Sorry Sorry Bat Baseball Ball");
store.loadToys("Sorry Bat Ball");
System.out.println(store.toString());
System.out.println(store.getThatToy("Baseball").toString());
System.out.println(store.getMostFrequentToy());
store.sortToysByCount();
System.out.println(store.toString());
}
} |
package com.gk.service.impl;
import java.util.LinkedHashMap;
public class FilterChainDefinitionMapMapBuilder {
public LinkedHashMap<String, String> buildFilterChainDefinitionMap(){
LinkedHashMap<String, String> map = new LinkedHashMap<>();
//访问数据表
map.put("/signIn.jsp", "anon");
map.put("/signUp.jsp", "anon");
map.put("/css/*", "anon");
map.put("/js/*", "anon");
map.put("/images/*", "anon");
map.put("/loginAndLogout", "anon");
map.put("/userlogin","anon");
map.put("/getCode","anon");
map.put("/eeteacher","anon");
map.put("/isHasAccount", "anon");
map.put("/isTrueCode","anon");
map.put("/logout", "logout");
/*map.put("/shiro/logout", "logout");
map.put("/user.jsp", "authc,roles[user]");
map.put("/admin.jsp", "authc,roles[admin]");
map.put("/list.jsp","user");*/
map.put("/**", "authc");
return map;
}
}
|
package com.proyectogrado.alternativahorario.alternativahorario.negocio;
import com.proyectogrado.alternativahorario.entidades.Clase;
import com.proyectogrado.alternativahorario.entidades.Horario;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author Steven
*/
@Local
public interface AdministracionHorarioLocal {
List<Horario> getHorarios();
List<Horario> getHorariosPorClase(Clase clase);
boolean eliminarHorario(Horario horario);
List<Horario> eliminarHorarios(List<Horario> horarios);
boolean agregarHorario(Horario horario);
}
|
package ru.silentflame.karaf.commands;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.console.OsgiCommandSupport;
//import org.apache.karaf.shell.console.OsgiCommandSupport;
@Command(
scope = "silentflame",
name = "say",
description = "Just test command")
public class TestCommand extends OsgiCommandSupport {
public TestCommand() {
}
@Override
protected Object doExecute() throws Exception {
System.out.println("Good night");
return null;
}
}
|
package org.dimigo.library;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.utils.StringBuilder;
import net.dermetfan.gdx.physics.box2d.PositionController;
import org.dimigo.vaiohazard.Device.Components;
import org.dimigo.vaiohazard.Device.VaioProblem;
import org.dimigo.vaiohazard.GameResource;
import org.dimigo.vaiohazard.Object.Customer;
import org.dimigo.vaiohazard.Object.PixelizedDialog;
import org.dimigo.vaiohazard.Object.RepairOrder;
import org.dimigo.vaiohazard.Object.ServiceCenter;
import org.dimigo.vaiohazard.conversation.Conversation;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by juwoong on 15. 11. 10..
*/
public class DialogGenerator {
private static BitmapFont textFont, titleFont;
private static Window.WindowStyle windowStyle;
private static TextButton.TextButtonStyle textButtonStyle;
private static RightCheckBox.CheckBoxStyle checkBoxStyle;
private static SelectBox.SelectBoxStyle selectBoxStyle;
private static Label.LabelStyle labelStyle;
private static Label.LabelStyle bigLabelStyle;
private Conversation conv;
private boolean isInspected = false;
static {
textFont = new BitmapFont(Gdx.files.internal("resources/font/font.fnt"));
titleFont = new BitmapFont(Gdx.files.internal("resources/font/font_big.fnt"));
windowStyle = new Window.WindowStyle();
windowStyle.titleFont = titleFont;
//이거 동적으로
windowStyle.titleFontColor = Color.NAVY;
//
windowStyle.background = new NinePatchDrawable(GameResource.getInstance().getPatch("dialog_background"));
textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.up = GameResource.getInstance().getDrawable("dialog_button");
textButtonStyle.over = GameResource.getInstance().getDrawable("dialog_button_hover");
textButtonStyle.down = GameResource.getInstance().getDrawable("dialog_button_pressed");
textButtonStyle.font = textFont;
textButtonStyle.fontColor = Color.BLACK;
checkBoxStyle = new RightCheckBox.CheckBoxStyle();
checkBoxStyle.checkboxOff = GameResource.getInstance().getDrawable("checkbox");
checkBoxStyle.checkboxOn = GameResource.getInstance().getDrawable("checkbox_checked");
checkBoxStyle.checkboxOver = GameResource.getInstance().getDrawable("checkbox_hover");
checkBoxStyle.font = new BitmapFont(Gdx.files.internal("resources/font/font_big.fnt"));
checkBoxStyle.fontColor = Color.BLACK;
selectBoxStyle = new SelectBox.SelectBoxStyle();
selectBoxStyle.background = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.backgroundOpen = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.backgroundOver = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.listStyle = new List.ListStyle(
new BitmapFont(Gdx.files.internal("resources/font/font.fnt")),
Color.RED, Color.BLACK, GameResource.getInstance().getDrawable("dialog_button_hover"));
selectBoxStyle.scrollStyle = new ScrollPane.ScrollPaneStyle();
selectBoxStyle.scrollStyle.background = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.scrollStyle.corner = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.scrollStyle.hScroll = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.scrollStyle.hScrollKnob = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.scrollStyle.vScroll = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.scrollStyle.vScrollKnob = GameResource.getInstance().getDrawable("LightGreen");
selectBoxStyle.font = new BitmapFont(Gdx.files.internal("resources/font/font.fnt"));
selectBoxStyle.fontColor = Color.BLACK;
labelStyle = new Label.LabelStyle(textFont, Color.BLACK);
bigLabelStyle = new Label.LabelStyle(titleFont, Color.BLACK);
}
public DialogGenerator(Conversation conv) {
this.conv = conv;
}
public PixelizedDialog getDialog(String title, String content) {
PixelizedDialog dialog = new PixelizedDialog(title, windowStyle, conv);
dialog.text(content, labelStyle);
return dialog;
}
public PixelizedDialog getInspectLoading(String title, ServiceCenter.InspectResult inspectResults) {
PixelizedDialog dialog = new PixelizedDialog(title, windowStyle, conv);
final ServiceCenter.InspectResult inspectResult = inspectResults;
//Label inspect = new Label("조사중", bigLabelStyle);
Label inspect = new Label("조사 중", bigLabelStyle){
@Override
public void act(float deltaTime) {
super.act(deltaTime);
if(isInspected == false) {
SequenceAction seq = new SequenceAction();
for(VaioProblem.Trouble troubles : inspectResult.impairs.keySet()) {
SequenceAction fadeInOutStep = new SequenceAction();
final VaioProblem.Trouble trouble = troubles;
int blinkNum = (new Random()).nextInt(5) + 2;
float inOutDuration = 1.4f;
for(int i=0; i<=blinkNum; i++) {
fadeInOutStep.addAction(Actions.fadeIn(inOutDuration));
final int index = i;
if(i==blinkNum || i==blinkNum-1) {
fadeInOutStep.addAction(new Action() {
@Override
public boolean act(float delta) {
String str = trouble.name() + "이/가 " + inspectResult.impairs.get(trouble).name() + "한 Feeling이군!";
setText(str);
return true;
}
});
} else {
fadeInOutStep.addAction(new Action() {
@Override
public boolean act(float delta) {
StringBuilder builder = new StringBuilder();
builder.append("조사 중 ");
for(int j=0; j<index; j++) {
builder.append(". ");
}
setText(builder);
return true;
}
});
}
fadeInOutStep.addAction(Actions.fadeOut(inOutDuration));
}
seq.addAction(fadeInOutStep);
}
addAction(seq);
isInspected = true;
}
}
};
//원래다이얼로그에서 컨텐트 테이블은 왼쪽부터 글쓰는 곳이라 padLeft들어가 있는데 이건 아니니까 오른쪽으로 옮기깅!
dialog.getContentTable().add(inspect).expandX().center().padRight(50).padTop(40);
dialog.button("볼장은 다봤깅!", null, textButtonStyle);
return dialog;
}
public PixelizedDialog getImpairSelect(String title, ServiceCenter.InspectResult inspectResult) {
PixelizedDialog dialog = new PixelizedDialog(title, windowStyle, conv);
Table contentTable = dialog.getContentTable();
contentTable.top().padTop(77);
Map<VaioProblem.Trouble, VaioProblem.Critical> selectResult = new HashMap<VaioProblem.Trouble, VaioProblem.Critical>();
ImpairSelector selector = new ImpairSelector(selectBoxStyle);
contentTable.add(new Actor());
for(String troubleString : VaioProblem.TroubleStrings) {
contentTable.add(new Label(troubleString, labelStyle));
}
contentTable.row().padTop(12);
contentTable.add(new Label("조사 결과 :", labelStyle));
for(VaioProblem.Trouble trouble : VaioProblem.Trouble.getList()) {
if(Rand.get(ServiceCenter.getInstance().getInspectSkill()))
contentTable.add(new Label(inspectResult.impairs.get(trouble).name(), labelStyle));
else
contentTable.add(new Label("아몰랑:)", labelStyle));
}
contentTable.row().padTop(12);
contentTable.add(new Label("구라 치기 :", labelStyle));
for(Object selectBox : selector.getSelectBoxes()) {
if (selectBox instanceof SelectBox) {
contentTable.add((SelectBox)selectBox).maxWidth(80).maxHeight(20).width(75).padLeft(5).height(20);
}
}
dialog.button("이걸로 구라치기 ->", selector, textButtonStyle);
return dialog;
}
public PixelizedDialog getBillDialog(RepairOrder order) {
PixelizedDialog dialog = new PixelizedDialog(order.getOrderer().getName(), windowStyle, conv);
Table contentTable = dialog.getContentTable();
contentTable.padTop(20);
contentTable.add(new Label(order.getOrderer().getName() + " 호갱님", bigLabelStyle));
contentTable.row().padTop(8);
contentTable.add(new Label("문제점 :", labelStyle));
for(String troubleString : VaioProblem.TroubleStrings) {
contentTable.add(new Label(troubleString, labelStyle)).padLeft(2);
}
contentTable.row().padTop(3);
contentTable.add(new Label("심각성 :", labelStyle));
for(VaioProblem.Trouble trouble : VaioProblem.Trouble.getList()) {
contentTable.add(new Label(order.getDetail().get(trouble).name(), labelStyle)).padLeft(2);
}
contentTable.row().padTop(3);
contentTable.add(new Label(order.getAppointmentMonth() + "월" + order.getAppointmentDate() + "일에 방문", labelStyle));
contentTable.row().padTop(3);
contentTable.add(new Label(order.getReward() + "원 개이득", labelStyle));
dialog.button("호갱 주문 리스트에 넣기 ㄱㄱ->", null, textButtonStyle);
return dialog;
}
public TextButton.TextButtonStyle getTextButtonStyle() { return textButtonStyle; }
public SelectBox.SelectBoxStyle getSelectBoxStyle() { return selectBoxStyle; }
/*public PixelizedDialog getComponetsSelect(String title) {
PixelizedDialog dialog = new PixelizedDialog(title, windowStyle);
Table table = dialog.getButtonTable();
table.padBottom(80).left();
RightCheckBox zeroIndexCheck = new RightCheckBox(Components.deviceStrings[0], checkBoxStyle);
table.add(zeroIndexCheck).left();
zeroIndexCheck.getImageCell().expandX().right();
//zeroIndexCheck.setDebug(true);
table.setDebug(true);
for(int i=1; i<Components.deviceStrings.length; i++) {
RightCheckBox check = new RightCheckBox(Components.deviceStrings[i], checkBoxStyle);
check.getImageCell().padLeft(10);
if(i % 2 == 0) {
table.row().padTop(20);
table.add(check).left();
} else {
table.add(check).left().padLeft(20);
}
//check.setDebug(true);
check.getImageCell().expandX().right();
}
TextButton.TextButtonStyle newStyle = new TextButton.TextButtonStyle(textButtonStyle);
newStyle.fontColor = Color.PINK;
dialog.button("위 재료가 필요하다고 구라치기 ㄱㄱ -->", true, newStyle);
dialog.getButtonTable().getCells().get(dialog.getButtonTable().getCells().size - 1).padLeft(20);
return dialog;
}*/
} |
package com.base.danmaku;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.base.host.AppLogic;
import com.base.host.HostApplication;
import com.facebook.fresco.FrescoImageHelper;
import com.facebook.fresco.FrescoParam;
import com.heihei.model.User;
import com.wmlives.heihei.R;
public class DanmakuTextItemView extends DanmakuItemView {
private TextView tv_danmaku;
private TextView tv_nickanme;
private ImageView danmaku_icon;
public DanmakuTextItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
tv_nickanme = (TextView) findViewById(R.id.danmaku_nickname);
tv_danmaku = (TextView) findViewById(R.id.danmaku_text);
danmaku_icon = (ImageView) findViewById(R.id.danmaku_icon);
};
@Override
public void refreshView() {
if (item.gender == User.FEMALE) {
tv_nickanme.setTextColor(getResources().getColor(R.color.hh_color_female));
} else {
tv_nickanme.setTextColor(getResources().getColor(R.color.hh_color_male));
}
tv_nickanme.setText(item.userName);
tv_danmaku.setText(item.text);
if (item.giftId != -1) {
danmaku_icon.setVisibility(View.VISIBLE);
FrescoParam param = new FrescoParam(AppLogic.gifts.get(item.giftId));
FrescoImageHelper.getImage(param, danmaku_icon);
}else {
danmaku_icon.setVisibility(View.GONE);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
|
package kxg.searchaf.url.neiman_cat;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import kxg.searchaf.url.Constant;
import kxg.searchaf.util.ProxyUtli;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.MetaTag;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;
import org.json.JSONObject;
public class ParserNeimanPage {
public NeimanPage page;
public HashMap<Long, NeimanProduct> allprolist;
public NeimanProduct product;
public ParserNeimanPage(NeimanPage page,
HashMap<Long, NeimanProduct> allprolist) {
this.page = page;
this.allprolist = allprolist;
};
public void checkprice() throws Exception {
// System.out.println("checking Neiman url [" + page.url + "]");
URL url = new URL(page.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(Constant.connect_timeout);
urlConnection.connect();
InputStream is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s;
StringBuilder result = new StringBuilder();
while (((s = reader.readLine()) != null)) {
result.append(s);
}
// System.out.println("result= " + result.toString());
is.close();
JSONObject jsonObj = new JSONObject(result.toString())
.getJSONObject("GenericSearchResp");
String productResults = jsonObj.getString("productResults");
// System.out.println("productResults= " + productResults);
Parser parser = new Parser(productResults.toString());
// Parser parser = new Parser(urlConnection);
parser.setEncoding(Constant.ENCODE);
NodeClassFilter span_filter = new NodeClassFilter(Span.class);
NodeClassFilter div_filter = new NodeClassFilter(Div.class);
NodeClassFilter meta_filter = new NodeClassFilter(MetaTag.class);
OrFilter filters = new OrFilter();
filters.setPredicates(new NodeFilter[] { // span_filter, meta_filter,
div_filter });
NodeList list = parser.extractAllNodesThatMatch(filters);
for (int i = 0; i < list.size(); i++) {
Node tag = list.elementAt(i);
if (tag instanceof Div) {
Div d = (Div) tag;
String divclass = d.getAttribute("class");
if ("product".equalsIgnoreCase(divclass)
|| "product start".equalsIgnoreCase(divclass)) {
product = new NeimanProduct();
String id = d.getAttribute("id");
product.productid = Long.valueOf(id.substring(4,
id.length() - 7));
product.tagcontext = processHTML(tag);
getName(d);
if (allprolist.get(product.productid) == null) {
allprolist.put(product.productid, product);
// System.out.println(product);
}
}
// else if ("qv-tip".equalsIgnoreCase(divclass)) {
// System.out.println(d.getAttribute("product_id"));
// product.productid = Integer.valueOf(d.getAttribute(
// "product_id").substring(4));
// if (allprolist.get(product.productid) == null) {
// allprolist.put(product.productid, product);
// System.out.println(product);
// }
// }
// parsePriceWithDiv(tag);
}
}
}
private String processHTML(Node node) {
//String html = node.toHtml();
String html = node.getChildren().elementAt(3).toHtml();
// html = html + node.getChildren().elementAt(5).toHtml();
// html = html + node.getChildren().elementAt(9).toHtml();
// if (node.getChildren().size() > 11) {
// html = html + node.getChildren().elementAt(11).toHtml();
// }
html = html
.replaceAll("<a href=\"/p",
"<a href=\"http://www.neimanmarcus.com/p");
// html = html.replaceAll("//anf", "http://anf");
// String htmldivswatches = node.getChildren().elementAt(11).toHtml();
// htmldivswatches = htmldivswatches.replace("//anf", "http://anf");
//<div class="productImageContainer"> <a href="/p/Johnny-Was-Collection-Miliana-Embroidered-Georgette-Blouse/prod154410143_cat46520736__/;jsessionid=515190121FE79278BD9FB71515481871?icid=&searchType=EndecaDrivenCat&rte=%252Fcategory.service%253FitemId%253Dcat46520736%2526pageSize%253D120%2526No%253D0%2526refinements%253D&eItemId=prod152910204&cmCat=product" class="prodImgLink"> <img onerror="this.src='/images/shim.gif'" title="T5T9W Johnny Was Collection Miliana Embroidered Georgette Blouse" class="productImage" style="" src="http://images.neimanmarcus.com/ca/1/products/mi/NMT5T9W_mi.jpg" alt="" id="prod152910204"></img> <script>nm.thumbnails.addToggleImage('prod152910204', 'http://images.neimanmarcus.com/ca/1/products/mi/NMT5T9W_mi.jpg', 'http://images.neimanmarcus.com/ca/1/products/ai/NM-43ZY_ai.jpg')</script> </a> </div>
return html;
}
private void getName(Node node) throws Exception {
NodeList childList = node.getChildren();
List<String> productvalue = new ArrayList<String>();
processNodeList(childList, productvalue);
// System.out.println(productvalue);
// System.out.print(productvalue.get(2) + " " + productvalue.get(3));
product.name = productvalue.get(2) + " " + productvalue.get(3);
boolean foundListprice = false;
for (int i = 4; i < productvalue.size(); i++) {
String a = productvalue.get(i).trim();
if (a.startsWith("$")) {
if (foundListprice) {
// it's price
product.price = getprice(a);
} else {
// it's list price
product.listprice = getprice(a);
product.price = product.listprice;
foundListprice = true;
}
}
}
product.realdiscount = Math.round(product.price / product.listprice
* 100) / 100f;
// if (!foundListprice) {
// System.out.println(productvalue);
// }
}
private float getprice(String priceStr) throws Exception {
priceStr = priceStr.replace(" ", "");
float returnvalue = 0;
try {
// listprice= $80
returnvalue = Float.parseFloat(priceStr.substring(1));
} catch (NumberFormatException ex) {
// listprice= $80-$90
returnvalue = Float.parseFloat(priceStr.substring(1,
priceStr.indexOf("-")));
}
return returnvalue;
}
private void processNodeList(NodeList list, List<String> valueList) {
// 迭代开始
SimpleNodeIterator iterator = list.elements();
while (iterator.hasMoreNodes()) {
Node node = iterator.nextNode();
// 得到该节点的子节点列表
NodeList childList = node.getChildren();
// 孩子节点为空,说明是值节点
if (null == childList) {
// 得到值节点的值
String result = node.toPlainTextString().trim();
// 若包含关键字,则简单打印出来文本
// System.out.println(result);
if (result != null && !"".equals(result))
valueList.add(result);
} // end if
// 孩子节点不为空,继续迭代该孩子节点
else {
processNodeList(childList, valueList);
}// end else
}// end wile
}
}
|
package com.share.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "des_inform")
public class Inform implements java.io.Serializable {
private static final long serialVersionUID = -5892444078860463333L;
@Id
@GeneratedValue
private Integer id;
@Column(name = "title", length = 255)
private String title;
@Column(name = "content", length = 2000)
private String content;
@Column(name = "times", length = 255)
private String times;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getTimes() {
return this.times;
}
public void setTimes(String times) {
this.times = times;
}
} |
package autoInterfaces;
import java.util.List;
/*Interface for AutocompleteProvider*/
public interface AutocompleteProvider {
public List<Candidate> getWords(String fragment);
public void train(String passage);
public String toString(List<Candidate> lst);
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.example.sys.mq;
import javax.jms.ConnectionFactory;
import javax.jms.Topic;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
@Configuration
@EnableJms
public class ActiveMQConfig {
public ActiveMQConfig() {
}
@Bean
public ActiveMQQueue queue() {
return new ActiveMQQueue("ds_vedio_web_1");
}
@Bean
public JmsListenerContainerFactory jmsTopicListenerContainerFactory(ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(true);
return factory;
}
@Bean
public Topic topic() {
return new ActiveMQTopic("ds_vedio_web_1");
}
}
|
package series04chess;
public class Game {
static Chess runningGame;
public static void main(String[] args) {
runningGame = new Chess();
}
}
|
package actions.compte;
import modele.exceptions.ExceptionConnexion.ExceptionLoginDejaConnecte;
import modele.exceptions.ExceptionConnexion.ExceptionLoginDejaPris;
import modele.exceptions.ExceptionConnexion.ExceptionLoginNonExistant;
import modele.exceptions.ExceptionConnexion.ExceptionMdpInccorect;
/**
* Created by alucard on 22/11/2016.
*/
public class LoginAction extends EnvironementCommunCompte{
public String execute() throws ExceptionLoginDejaPris {
try {
this.getMaFacade().connexion(this.getPseudo(),this.getPassword());
} catch (ExceptionLoginDejaConnecte exceptionLoginDejaConnecte) {
addActionError(getText("dejaConnecte"));
return "login";
} catch (ExceptionLoginNonExistant exceptionLoginNonExistant) {
addActionError(getText("errors.pseudoInexistant"));
return "login";
} catch (ExceptionMdpInccorect exceptionMdpInccorect) {
addActionError(getText("errors.mdpInccorect"));
return "login";
}
this.getSessionMap().put("pseudo", this.getPseudo());
return SUCCESS;
}
@org.apache.struts2.interceptor.validation.SkipValidation
public String home(){
return SUCCESS;
}
}
|
package com.minecraftabnormals.allurement.core;
import com.google.common.collect.Lists;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.ConfigValue;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
@EventBusSubscriber(modid = Allurement.MOD_ID)
public class AllurementConfig {
public static class Common {
public final ConfigValue<Boolean> enchantableHorseArmor;
public final ConfigValue<Boolean> enchantedHorseArmorGenerates;
public final ConfigValue<List<String>> unenchantedHorseArmorLootTables;
public final ConfigValue<Boolean> baneOfArthropodsBreaksCobwebsFaster;
public final ConfigValue<Boolean> featherFallingPreventsTrampling;
public final ConfigValue<Boolean> infinityRequiresArrows;
public final ConfigValue<Boolean> disableProtection;
public final ConfigValue<Boolean> riptideWorksInCauldrons;
public final ConfigValue<Boolean> soulSpeedHurtsMore;
public final ConfigValue<Float> soulSpeedDamageFactor;
public final ConfigValue<Boolean> enableAlleviating;
public final ConfigValue<Float> alleviatingHealingFactor;
public final ConfigValue<Boolean> enableLaunch;
public final ConfigValue<Double> launchVerticalFactor;
public final ConfigValue<Boolean> enableReeling;
public final ConfigValue<Double> reelingHorizontalFactor;
public final ConfigValue<Double> reelingVerticalFactor;
public final ConfigValue<Boolean> enableReforming;
public final ConfigValue<Integer> reformingTickRate;
public final ConfigValue<Boolean> enableShockwave;
public final ConfigValue<Boolean> shockwaveTramplesFarmland;
public final ConfigValue<Boolean> enableVengeance;
public final ConfigValue<Float> vengeanceDamageFactor;
public final ConfigValue<Boolean> removeLevelScaling;
public final ConfigValue<Integer> experiencePerLevel;
Common(ForgeConfigSpec.Builder builder) {
builder.push("enchantments");
builder.push("alleviating");
enableAlleviating = builder.comment("Armor enchantment that heals the user when collecting experience").define("Enable Alleviating", true);
alleviatingHealingFactor = builder.comment("How much the experience value is multiplied by into health").define("Healing factor", 0.25F);
builder.pop();
builder.push("missile");
enableLaunch = builder.comment("Weapon enchantment that launches enemies upwards rather than away").define("Enable Launch", true);
launchVerticalFactor = builder.comment("How much the target is affected on the vertical axis").define("Vertical factor", 0.35D);
builder.pop();
builder.push("reeling");
enableReeling = builder.comment("Crossbow enchantment that pulls targets towards the user").define("Enable Reeling", true);
reelingHorizontalFactor = builder.comment("How much the target is affected on the horizontal axis").define("Horizontal factor", 0.5D);
reelingVerticalFactor = builder.comment("How much the target is affected on the vertical axis").define("Vertical factor", 0.25D);
builder.pop();
builder.push("reforming");
enableReforming = builder.comment("Gear enchantment that very slowly repairs items over time").define("Enable Reforming", true);
reformingTickRate = builder.comment("How many ticks it takes a reforming item to repair").define("Reforming tick rate", 600);
builder.pop();
builder.push("shockwave");
enableShockwave = builder.comment("Boots enchantment that creates a shockwave when taking fall damage").define("Enable Shockwave", true);
shockwaveTramplesFarmland = builder.comment("If Shockwave tramples farmland within the wave radius").define("Shockwave tramples farmland", true);
builder.pop();
builder.push("vengeance");
enableVengeance = builder.comment("Armor enchantment that stores incoming damage and applies it to user's next attack").define("Enable Vengeance", true);
vengeanceDamageFactor = builder.comment("How much the damage taken with vengeance is multiplied for attacks").define("Damage factor", 0.025F);
builder.pop();
builder.pop();
builder.push("tweaks");
builder.push("horse_armor");
enchantableHorseArmor = builder.comment("Allow horse armor to be enchanted").define("Enchantable horse armor", true);
enchantedHorseArmorGenerates = builder.comment("If horse armor can appear enchanted when found in loot tables").define("Generates in loot tables", true);
unenchantedHorseArmorLootTables = builder.comment("Which loot tables horse armor can't appear enchanted in").define("Unenchanted loot tables", Lists.newArrayList("minecraft:chests/village/village_weaponsmith", "minecraft:chests/stronghold_corridor", "minecraft:chests/nether_bridge"));
builder.pop();
builder.push("bane_of_arthropods");
baneOfArthropodsBreaksCobwebsFaster = builder.comment("If Bane of Arthropods increases the mining speed of Cobwebs").define("Bane of Arthropods mines cobwebs faster", true);
builder.pop();
builder.push("feather_falling");
featherFallingPreventsTrampling = builder.comment("If having Feather Falling prevents farmland from being trampled").define("Feather Falling prevents trampling", true);
builder.pop();
builder.push("infinity");
infinityRequiresArrows = builder.comment("If Infinity requires an arrow in the player's inventory in order to shoot").define("Infinity requires arrows", false);
builder.pop();
builder.push("protection");
disableProtection = builder.comment("Remove the base Protection enchantment, requiring players to choose between the other types").define("Disable Protection", false);
builder.pop();
builder.push("riptide");
riptideWorksInCauldrons = builder.comment("Allow Riptide to function when in cauldrons").define("Riptide works in cauldrons", true);
builder.pop();
builder.push("soul_speed");
soulSpeedHurtsMore = builder.comment("Instead of losing durability as you run, Soul Speed makes incoming damage increase when on Soul Speed blocks").define("Soul Speed change", true);
soulSpeedDamageFactor = builder.comment("How much damage is multiplied when hurt on Soul Speed blocks").define("Damage factor", 1.5F);
builder.pop();
builder.push("level_scaling");
removeLevelScaling = builder.comment("Remove the amount of experience per level increasing (experimental)").define("Remove level scaling", false);
experiencePerLevel = builder.comment("The amount of experience per level, if level scaling is removed (experimental)").define("Experience per level", 50);
builder.pop();
builder.pop();
}
}
public static class Client {
public final ConfigValue<Boolean> infinityArrowTexture;
public final ConfigValue<Boolean> infinityArrowGlint;
Client(ForgeConfigSpec.Builder builder) {
builder.push("tweaks");
builder.push("infinity");
infinityArrowTexture = builder.comment("Adds a special texture for arrows shot from infinity bows").define("Infinity arrow texture", true);
infinityArrowGlint = builder.comment("Adds a glint on arrows shot from infinity bows").define("Infinity arrow glint", true);
builder.pop();
builder.pop();
}
}
public static final ForgeConfigSpec COMMON_SPEC;
public static final Common COMMON;
public static final ForgeConfigSpec CLIENT_SPEC;
public static final Client CLIENT;
static {
final Pair<Common, ForgeConfigSpec> commonSpecPair = new ForgeConfigSpec.Builder().configure(Common::new);
COMMON_SPEC = commonSpecPair.getRight();
COMMON = commonSpecPair.getLeft();
final Pair<Client, ForgeConfigSpec> clientSpecPair = new ForgeConfigSpec.Builder().configure(Client::new);
CLIENT_SPEC = clientSpecPair.getRight();
CLIENT = clientSpecPair.getLeft();
}
}
|
package de.trispeedys.resourceplanning.datasource;
import de.trispeedys.resourceplanning.entity.HelperHistory;
public class HelperHistoryDatasource extends DefaultDatasource<HelperHistory>
{
protected Class<HelperHistory> getGenericType()
{
return HelperHistory.class;
}
} |
package com.example.hante.newprojectsum.pay.fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.hante.newprojectsum.R;
import com.example.hante.newprojectsum.itemdevider.LinearSpacesItemDecoration;
import com.example.hante.newprojectsum.pay.adapter.BuyAdapter;
import com.example.hante.newprojectsum.pay.bean.BuyStyle;
import com.example.hante.newprojectsum.util.Utils;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* 弹出支付方式选择框列表
*/
public class PayStyle extends DialogFragment implements View.OnClickListener {
@Bind(R.id.clear_icon)
ImageView mClearIcon;
@Bind(R.id.RView_payStyle)
RecyclerView mRViewPayStyle;
private BuyAdapter mBuyAdapter;
private List<BuyStyle> list = null;
private BuyStyle buyStyle = null;
@Override
public void onStart () {
super.onStart();
DisplayMetrics dm = new DisplayMetrics();//设置弹出框宽屏显示,适应屏幕宽度
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
if(getDialog().getWindow() != null){
getDialog().getWindow().setLayout(dm.widthPixels,getDialog().getWindow().getAttributes().height);
}
// 移动弹出菜单到底部
WindowManager.LayoutParams wlp = getDialog().getWindow().getAttributes();
wlp.gravity = Gravity.BOTTOM;
getDialog().getWindow().setAttributes(wlp);
}
@Nullable
@Override
public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
if (getDialog().getWindow() != null){
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// getDialog().getWindow().setWindowAnimations(R.style.payStyle);
}
View inflate = inflater.inflate(R.layout.pay_style, container, false);
ButterKnife.bind(this, inflate);
initUi();
loadData();
return inflate;
}
private void loadData () {
list = new ArrayList<>();
for (int i = 0; i < 3; i++){
buyStyle = new BuyStyle();
buyStyle.setId_code(i);
list.add(buyStyle);
}
mBuyAdapter = new BuyAdapter(list, getActivity());
mRViewPayStyle.setHasFixedSize(true);
mRViewPayStyle.setLayoutManager(new LinearLayoutManager(getActivity()));
int left = Utils.dpToPx(2);
int top = Utils.dpToPx(2);
mRViewPayStyle.addItemDecoration(new LinearSpacesItemDecoration(left, top, 0));
mRViewPayStyle.addItemDecoration(new LinearSpacesItemDecoration(left, top,
getResources().getColor(R.color.header_green_bar_color)));
mRViewPayStyle.setItemAnimator(new DefaultItemAnimator());
mRViewPayStyle.setAdapter(mBuyAdapter);
mBuyAdapter.setOnItemClickListener(new BuyAdapter.onItemClickListener() {
@Override
public void onItemClick (View view, int position) {
Toast.makeText(getContext(), "点击位置 :" + position + " " ,
Toast.LENGTH_SHORT).show();
int id_code = list.get(position).getId_code();
PayDetail payDetail = new PayDetail();
payDetail.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.payStyle);
Bundle bundle = new Bundle();
bundle.putInt("payStyle", id_code);
payDetail.setArguments(bundle);
payDetail.show(getFragmentManager(), "Detail");
dismiss();
}
});
}
private void initUi () {
mClearIcon.setOnClickListener(this);
}
@Override
public void onDestroyView () {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onClick (View v) {
if(v == mClearIcon){
dismiss();
}
}
}
|
public class Sum {
static int[] numbers = {23,56,78,45,69,45,100};
public static void main(String[] args) {
// TODO Auto-generated method stub
//call the sum function
int sum = sumTotal( numbers);
System.out.println("Sum is:"+sum);
}
public static int sumTotal( int [] list){
int total = 0;
if (list.length > 0){
for (int i =0; i < list.length; i++){
total += list[i];
}
}
else if ( list.length == 1){
total = sumTotal (list);
}
else
System.out.println("Error");
return total;
}
}
|
package com.generic.core.services.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.generic.core.model.entities.Area;
import com.generic.core.model.entities.City;
import com.generic.core.respository.AreaRepository;
import com.generic.core.services.service.AreaServiceI;
import com.generic.rest.dto.AreaDto;
@Service
@Transactional
public class AreaService implements AreaServiceI{
@Resource
AreaRepository areaRepository;
@Override
public List<AreaDto> getAllArea(String cityId) {
City city = new City(cityId);
List<Area> areas = areaRepository.findByCity(city);
return convertToAreaDto(areas);
}
private List<AreaDto> convertToAreaDto(List<Area> areas) {
List<AreaDto> areaDtos = new ArrayList<AreaDto>();
for(Area anArea : areas) {
areaDtos.add(new AreaDto(anArea.getAreaId(), anArea.getAreaName()));
}
return areaDtos;
}
}
|
/*
* Copyright 2017 Rundeck, Inc. (http://rundeck.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rundeck.client.tool;
import org.jetbrains.annotations.NotNull;
import org.rundeck.client.RundeckClient;
import org.rundeck.client.api.RequestFailed;
import org.rundeck.client.api.RundeckApi;
import org.rundeck.client.api.model.DateInfo;
import org.rundeck.client.api.model.Execution;
import org.rundeck.client.api.model.JobItem;
import org.rundeck.client.api.model.scheduler.ScheduledJobItem;
import org.rundeck.client.tool.commands.*;
import org.rundeck.client.tool.extension.RdCommandExtension;
import org.rundeck.client.tool.extension.RdTool;
import org.rundeck.client.tool.format.*;
import org.rundeck.client.tool.output.SystemOutput;
import org.rundeck.client.tool.util.ExtensionLoaderUtil;
import org.rundeck.client.tool.util.Resources;
import org.rundeck.client.util.*;
import org.rundeck.client.util.DataOutput;
import picocli.CommandLine;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.rundeck.client.RundeckClient.*;
/**
* Entrypoint for commandline
*/
@CommandLine.Command(
name = "rd",
version = org.rundeck.client.Version.VERSION,
mixinStandardHelpOptions = true,
subcommands = {
Adhoc.class,
Jobs.class,
Projects.class,
Executions.class,
Run.class,
Keys.class,
RDSystem.class,
Scheduler.class,
Tokens.class,
Nodes.class,
Users.class,
Main.Something.class,
Retry.class,
Metrics.class,
Version.class
}
)
public class Main {
public static final String RD_USER = "RD_USER";
public static final String RD_PASSWORD = "RD_PASSWORD";
public static final String RD_TOKEN = "RD_TOKEN";
public static final String RD_URL = "RD_URL";
public static final String RD_API_VERSION = "RD_API_VERSION";
public static final String RD_AUTH_PROMPT = "RD_AUTH_PROMPT";
public static final String RD_DEBUG = "RD_DEBUG";
public static final String RD_FORMAT = "RD_FORMAT";
public static final String RD_EXT_DISABLED = "RD_EXT_DISABLED";
public static final String RD_EXT_DIR = "RD_EXT_DIR";
@CommandLine.Spec
CommandLine.Model.CommandSpec spec;
public static final String
USER_AGENT =
RundeckClient.Builder.getUserAgent("rd-cli-tool/" + org.rundeck.client.Version.VERSION);
public static void main(String[] args) {
int result = -1;
try (Rd rd = createRd()) {
RdToolImpl rd1 = new RdToolImpl(rd);
CommandLine commandLine = new CommandLine(new Main(), new CmdFactory(rd1));
CommandLine.Help.ColorScheme colorScheme = new CommandLine.Help.ColorScheme.Builder(CommandLine.Help.defaultColorScheme(CommandLine.Help.Ansi.AUTO))
.commands(CommandLine.Help.Ansi.Style.fg_white)
.applySystemProperties() // optional: allow end users to customize
.build();
commandLine.setColorScheme(colorScheme);
commandLine.setExpandAtFiles(false);
commandLine.setUsageHelpAutoWidth(true);
commandLine.setHelpFactory(new CommandLine.IHelpFactory() {
@Override
public CommandLine.Help create(CommandLine.Model.CommandSpec commandSpec, CommandLine.Help.ColorScheme colorScheme) {
return new CommandLine.Help(commandSpec, colorScheme) {
/**
* Returns a sorted map of the subcommands.
*/
@Override
public Map<String, CommandLine.Help> subcommands() {
return new TreeMap<>(super.subcommands());
}
@Override
public String commandListHeading(Object... params) {
return "\nAvailable commands:\n\n";
}
};
}
});
commandLine.getHelpSectionMap().put(
CommandLine.Model.UsageMessageSpec.SECTION_KEY_HEADER_HEADING,
help -> loadBanner("rd-banner.txt", Collections.singletonMap("$version$", org.rundeck.client.Version.VERSION))
);
commandLine.setExecutionExceptionHandler((Exception ex, CommandLine cl, CommandLine.ParseResult parseResult) -> {
if (ex instanceof InputError) {
return cl.getParameterExceptionHandler().handleParseException(
new CommandLine.ParameterException(cl, ex.getMessage(), ex),
args
);
}
if (ex instanceof RequestFailed) {
rd.getOutput().error(ex.getMessage());
if (rd.getDebugLevel() > 0) {
StringWriter sb = new StringWriter();
ex.printStackTrace(new PrintWriter(sb));
rd.getOutput().error(sb.toString());
}
return 2;
}
throw ex;
});
loadCommands(rd, rd1).forEach(commandLine::addSubcommand);
result = commandLine.execute(args);
} catch (IOException e) {
e.printStackTrace();
}
System.exit(result);
}
@NotNull
private static Rd createRd() {
ConfigSource config = buildConfig();
loadExtensionJars(config);
RdBuilder builder = new RdBuilder();
Rd rd = new Rd(config);
setup(rd, builder);
return rd;
}
static String loadBanner(String resource, Map<String, String> replacements) {
InputStream resourceAsStream = Main.class.getClassLoader().getResourceAsStream(resource);
if (null != resourceAsStream) {
try {
String result;
try (BufferedReader is = new BufferedReader(new InputStreamReader(resourceAsStream))) {
result = is.lines().collect(Collectors.joining("\n"));
}
if (replacements != null && !replacements.isEmpty()) {
for (String s : replacements.keySet()) {
String val = replacements.get(s);
result = result.replaceAll(Pattern.quote(s), Matcher.quoteReplacement(val));
}
}
return CommandLine.Help.Ansi.AUTO.string(result);
} catch (IOException ignored) {
}
}
return null;
}
private static ConfigSource buildConfig() {
return new ConfigBase(new MultiConfigValues(new Env(), new SysProps()));
}
private static void loadExtensionJars(ConfigSource config) {
if (config.getBool(RD_EXT_DISABLED, false)) {
return;
}
String rd_ext_dir = config.get(RD_EXT_DIR);
if(null==rd_ext_dir){
return;
}
File extDir = new File(rd_ext_dir);
if (!extDir.isDirectory()) {
return;
}
File[] jars = extDir.listFiles(f -> f.getName().endsWith(".jar"));
//add to class loader
if(jars==null){
return;
}
URLClassLoader urlClassLoader = buildClassLoader(jars);
Thread.currentThread().setContextClassLoader(urlClassLoader);
}
private static URLClassLoader buildClassLoader(final File[] jars) {
ClassLoader parent = Main.class.getClassLoader();
final List<URL> urls = new ArrayList<>();
try {
for (File jar : jars) {
final URL url = jar.toURI().toURL();
urls.add(url);
}
return URLClassLoader.newInstance(urls.toArray(new URL[0]), parent);
} catch (MalformedURLException e) {
throw new RuntimeException("Error creating classloader for urls: " + urls, e);
}
}
private static void setupFormat(final RdBuilder belt, RdClientConfig config) {
final String format = config.get(RD_FORMAT);
if ("yaml".equalsIgnoreCase(format)) {
configYamlFormat(belt, config);
} else if ("json".equalsIgnoreCase(format)) {
configJsonFormat(belt);
} else {
if (null != format) {
belt.finalOutput().warning(String.format("# WARNING: Unknown value for %s: %s", RD_FORMAT, format));
}
configNiceFormat(belt);
}
}
private static void configNiceFormat(final RdBuilder belt) {
NiceFormatter formatter = new NiceFormatter(null) {
@Override
public String format(final Object o) {
if (o instanceof DataOutput) {
DataOutput o1 = (DataOutput) o;
Map<?, ?> map = o1.asMap();
if (null != map) {
return super.format(map);
}
List<?> objects = o1.asList();
if (null != objects) {
return super.format(objects);
}
}
return super.format(o);
}
};
formatter.setCollectionIndicator("");
belt.formatter(formatter);
belt.channels().info(new FormattedOutput(
belt.defaultOutput(),
new PrefixFormatter("# ", belt.defaultBaseFormatter())
));
}
private static void configJsonFormat(final RdBuilder belt) {
belt.formatter(new JsonFormatter(DataOutputAsFormatable));
belt.channels().infoEnabled(false);
belt.channels().warningEnabled(false);
belt.channels().errorEnabled(false);
}
private static void configYamlFormat(final RdBuilder belt, final RdClientConfig config) {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(
"BLOCK".equalsIgnoreCase(config.getString("RD_YAML_FLOW", "BLOCK")) ?
DumperOptions.FlowStyle.BLOCK :
DumperOptions.FlowStyle.FLOW
);
dumperOptions.setPrettyFlow(config.getBool("RD_YAML_PRETTY", true));
Representer representer = new Representer(dumperOptions);
representer.addClassTag(JobItem.class, Tag.MAP);
representer.addClassTag(ScheduledJobItem.class, Tag.MAP);
representer.addClassTag(DateInfo.class, Tag.MAP);
representer.addClassTag(Execution.class, Tag.MAP);
belt.formatter(new YamlFormatter(DataOutputAsFormatable, new Yaml(representer, dumperOptions)));
belt.channels().infoEnabled(false);
belt.channels().warningEnabled(false);
belt.channels().errorEnabled(false);
}
private static final Function<Object, Optional<Formatable>> DataOutputAsFormatable = o -> {
if (o instanceof DataOutput) {
return Optional.of(new Formatable() {
@Override
public List<?> asList() {
return ((DataOutput) o).asList();
}
@Override
public Map<?, ?> asMap() {
return ((DataOutput) o).asMap();
}
});
}
return Optional.empty();
};
static class CmdFactory implements CommandLine.IFactory {
private final RdTool rd;
private final CommandLine.IFactory defaultFactory;
public CmdFactory(RdTool rd) {
this.rd = rd;
defaultFactory = CommandLine.defaultFactory();
}
@Override
public <K> K create(Class<K> cls) throws Exception {
K k = defaultFactory.create(cls);
if (k instanceof RdCommandExtension) {
rd.initExtension(((RdCommandExtension) k));
}
return k;
}
}
static List<RdCommandExtension> loadCommands(final Rd rd, RdToolImpl commandTool) {
List<RdCommandExtension> extensions = ExtensionLoaderUtil.list();
extensions.forEach(commandTool::initExtension);
if (rd.getDebugLevel() > 0) {
extensions.forEach(ext -> rd.getOutput().warning("# Including extension: " + ext.getClass().getName()));
}
return extensions;
}
public static void setup(final Rd rd, RdBuilder builder) {
builder.printStackTrace(rd.getDebugLevel() > 0);
setupFormat(builder, rd);
boolean insecureSsl = rd.getBool(ENV_INSECURE_SSL, false);
boolean insecureSslNoWarn = rd.getBool(ENV_INSECURE_SSL_NO_WARN, false);
rd.setOutput(builder.finalOutput());
if (insecureSsl && !insecureSslNoWarn) {
rd.getOutput().warning(
"# WARNING: RD_INSECURE_SSL=true, no hostname or certificate trust verification will be performed");
}
}
static class Rd extends ConfigBase implements RdApp, RdClientConfig, Closeable {
private final Resources resources = new Resources();
Client<RundeckApi> client;
private CommandOutput output = new SystemOutput();
public Rd(final ConfigValues src) {
super(src);
}
public boolean isAnsiEnabled() {
String term = getString("TERM", null);
String rd_color = getString("RD_COLOR", null);
return "1".equals(rd_color) ||
(
term != null
&& term.contains("color")
&& !"0".equals(rd_color)
);
}
@Override
public int getDebugLevel() {
return getInt(RD_DEBUG, 0);
}
public String getDateFormat() {
return getString("RD_DATE_FORMAT", "yyyy-MM-dd'T'HH:mm:ssXX");
}
@Override
public Client<RundeckApi> getClient() throws InputError {
if (null == client) {
try {
client = resources.add(Main.createClient(this));
} catch (ConfigSourceError configSourceError) {
throw new InputError(configSourceError.getMessage());
}
}
return client;
}
@Override
public Client<RundeckApi> getClient(final int version) throws InputError {
try {
client = resources.add(Main.createClient(this, version));
} catch (ConfigSourceError configSourceError) {
throw new InputError(configSourceError.getMessage());
}
return client;
}
@Override
public <T> ServiceClient<T> getClient(final Class<T> api, final int version) throws InputError {
try {
return resources.add(Main.createClient(this, api, version));
} catch (ConfigSourceError configSourceError) {
throw new InputError(configSourceError.getMessage());
}
}
@Override
public <T> ServiceClient<T> getClient(final Class<T> api) throws InputError {
try {
return resources.add(Main.createClient(this, api, null));
} catch (ConfigSourceError configSourceError) {
throw new InputError(configSourceError.getMessage());
}
}
@Override
public RdClientConfig getAppConfig() {
return this;
}
public void versionDowngradeWarning(int requested, int supported) {
getOutput().warning(String.format(
"# WARNING: API Version Downgraded: %d -> %d",
requested,
supported
));
getOutput().warning(String.format(
"# WARNING: To avoid this warning, specify the API version via RD_URL: " +
"export RD_URL=%sapi/%s",
client.getAppBaseUrl(),
supported
));
getOutput().warning("# WARNING: To disable downgrading: " +
"export RD_API_DOWNGRADE=false");
}
public CommandOutput getOutput() {
return output;
}
public void setOutput(CommandOutput output) {
this.output = output;
}
@Override
public void close() throws IOException {
resources.close();
}
}
public static Client<RundeckApi> createClient(Rd config) throws ConfigSource.ConfigSourceError {
return createClient(config, RundeckApi.class, null);
}
public static <T> Client<T> createClient(Rd config, Class<T> api) throws ConfigSource.ConfigSourceError {
return createClient(config, api, null);
}
public static Client<RundeckApi> createClient(Rd config, Integer requestedVersion)
throws ConfigSource.ConfigSourceError
{
return createClient(config, RundeckApi.class, requestedVersion);
}
public static <T> Client<T> createClient(Rd config, Class<T> api, Integer requestedVersion)
throws ConfigSource.ConfigSourceError
{
Auth auth = new Auth() {
};
auth = auth.chain(new ConfigAuth(config));
String baseUrl = config.require(
RD_URL,
"Please specify the Rundeck base URL, e.g. http://host:port or http://host:port/api/14"
);
if (!auth.isConfigured() && config.getBool(RD_AUTH_PROMPT, true) && null != System.console()) {
auth = auth.chain(new ConsoleAuth(String.format("Credentials for URL: %s", baseUrl)).memoize());
}
RundeckClient.Builder<T> builder = RundeckClient.builder(api)
.baseUrl(baseUrl)
.config(config);
if (null != requestedVersion) {
builder.apiVersion(requestedVersion);
} else {
int anInt = config.getInt(RD_API_VERSION, -1);
if (anInt > 0) {
builder.apiVersion(anInt);
}
}
if (auth.isTokenAuth()) {
builder.tokenAuth(auth.getToken());
} else {
if (null == auth.getUsername() || "".equals(auth.getUsername().trim())) {
throw new IllegalArgumentException("Username or token must be entered, or use environment variable " +
RD_USER + " or " + RD_TOKEN);
}
if (null == auth.getPassword() || "".equals(auth.getPassword().trim())) {
throw new IllegalArgumentException("Password must be entered, or use environment variable " +
RD_PASSWORD);
}
builder.passwordAuth(auth.getUsername(), auth.getPassword());
}
builder.logger(new OutputLogger(config.getOutput()));
builder.userAgent("rd-cli-tool/" + org.rundeck.client.Version.VERSION);
return builder.build();
}
interface Auth {
default boolean isConfigured() {
return null != getToken() || (
null != getUsername() && null != getPassword()
);
}
default String getUsername() {
return null;
}
default String getPassword() {
return null;
}
default String getToken() {
return null;
}
default boolean isTokenAuth() {
String username = getUsername();
if (null != username && !"".equals(username.trim())) {
return false;
}
String token = getToken();
return null != token && !"".equals(token);
}
default Auth chain(Auth auth) {
return new ChainAuth(Arrays.asList(this, auth));
}
default Auth memoize() {
return new MemoAuth(this);
}
}
static class ConfigAuth implements Auth {
final ConfigSource config;
public ConfigAuth(final ConfigSource config) {
this.config = config;
}
@Override
public String getUsername() {
return config.get(RD_USER);
}
@Override
public String getPassword() {
return config.get(RD_PASSWORD);
}
@Override
public String getToken() {
return config.get(RD_TOKEN);
}
}
static class ConsoleAuth implements Auth {
String username;
String pass;
String token;
final String header;
boolean echoHeader;
public ConsoleAuth(final String header) {
this.header = header;
echoHeader = false;
}
@Override
public String getUsername() {
echo();
return System.console().readLine("Enter username (blank for token auth): ");
}
private void echo() {
if (!echoHeader) {
if (null != header) {
System.out.println(header);
}
echoHeader = true;
}
}
@Override
public String getPassword() {
echo();
char[] chars = System.console().readPassword("Enter password: ");
return new String(chars);
}
@Override
public String getToken() {
echo();
char[] chars = System.console().readPassword("Enter auth token: ");
return new String(chars);
}
}
static class ChainAuth implements Auth {
final Collection<Auth> chain;
public ChainAuth(final Collection<Auth> chain) {
this.chain = chain;
}
@Override
public String getUsername() {
return findFirst(Auth::getUsername);
}
private String findFirst(Function<Auth, String> func) {
for (Auth auth : chain) {
String user = func.apply(auth);
if (null != user) {
return user;
}
}
return null;
}
@Override
public String getPassword() {
return findFirst(Auth::getPassword);
}
@Override
public String getToken() {
return findFirst(Auth::getToken);
}
}
static class MemoAuth implements Auth {
final Auth auth;
public MemoAuth(final Auth auth) {
this.auth = auth;
}
String username;
boolean usermemo = false;
String pass;
boolean passmemo = false;
String token;
boolean tokenmemo = false;
@Override
public String getUsername() {
if (usermemo) {
return username;
}
username = auth.getUsername();
usermemo = true;
return username;
}
@Override
public String getPassword() {
if (passmemo) {
return pass;
}
pass = auth.getPassword();
passmemo = true;
return pass;
}
@Override
public String getToken() {
if (tokenmemo) {
return token;
}
token = auth.getToken();
tokenmemo = true;
return token;
}
}
@CommandLine.Command(name = "pond", hidden = true)
public static class Something implements Runnable{
public void run() {
int i = new Random().nextInt(4);
String kind;
switch (i) {
case 1:
kind = CommandLine.Help.Ansi.AUTO.string("@|blue A little luck.|@");
break;
case 2:
kind = CommandLine.Help.Ansi.AUTO.string("@|green Good luck.|@");
break;
case 3:
kind = CommandLine.Help.Ansi.AUTO.string("@|fg(215) Great luck.|@");
break;
default:
kind = "Big trouble.";
break;
}
System.out.println("For your reference, today you will have:");
System.out.println(kind);
}
}
private static class OutputLogger implements Client.Logger {
final CommandOutput output;
public OutputLogger(final CommandOutput output) {
this.output = output;
}
@Override
public void output(final String out) {
output.output(out);
}
@Override
public void warning(final String warn) {
output.warning(warn);
}
@Override
public void error(final String err) {
output.error(err);
}
}
}
|
package srp.fix;
public interface DataChannel {
void send(char c);
char recive();
}
|
package initializer;
public enum Currency {
HUF,EUR,SFR,GBP,USD
}
|
package com.xinhua.xdcb;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>salesOrganBO complex type�� Java �ࡣ
*
* <p>����ģʽƬ��ָ�������ڴ����е�Ԥ�����ݡ�
*
* <pre>
* <complexType name="salesOrganBO">
* <complexContent>
* <extension base="{http://ws.freshpolicysign.exports.bankpolicy.interfaces.nb.tunan.nci.com/}baseBO">
* <sequence>
* <element name="adminOrganCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="organLevelCode" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="parentCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="salesOrganCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="salesOrganName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "salesOrganBO", propOrder = {
"adminOrganCode",
"organLevelCode",
"parentCode",
"salesOrganCode",
"salesOrganName"
})
public class SalesOrganBO
extends BaseBO
{
protected String adminOrganCode;
protected BigDecimal organLevelCode;
protected String parentCode;
protected String salesOrganCode;
protected String salesOrganName;
/**
* ��ȡadminOrganCode���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getAdminOrganCode() {
return adminOrganCode;
}
/**
* ����adminOrganCode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAdminOrganCode(String value) {
this.adminOrganCode = value;
}
/**
* ��ȡorganLevelCode���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getOrganLevelCode() {
return organLevelCode;
}
/**
* ����organLevelCode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setOrganLevelCode(BigDecimal value) {
this.organLevelCode = value;
}
/**
* ��ȡparentCode���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getParentCode() {
return parentCode;
}
/**
* ����parentCode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParentCode(String value) {
this.parentCode = value;
}
/**
* ��ȡsalesOrganCode���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getSalesOrganCode() {
return salesOrganCode;
}
/**
* ����salesOrganCode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSalesOrganCode(String value) {
this.salesOrganCode = value;
}
/**
* ��ȡsalesOrganName���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getSalesOrganName() {
return salesOrganName;
}
/**
* ����salesOrganName���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSalesOrganName(String value) {
this.salesOrganName = value;
}
}
|
package application;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class ClientAppController
{
@FXML
private ListView<String> log;
@FXML
private Button book;
@FXML
private Button unbook;
@FXML
private TableView<Visit> table;
@FXML
private TableColumn<Visit, String> hourColumn;
@FXML
private TableColumn<Visit, String> bookedColumn;
private ClientBackend clientBackend;
private List<Visit> schedule = new ArrayList<Visit>();
public void logAdd(String message)
{
GregorianCalendar time = new GregorianCalendar();
String timeString = "[" + time.get(GregorianCalendar.HOUR) + ":" + time.get(GregorianCalendar.MINUTE) + ":" + time.get(GregorianCalendar.SECOND) + "] -";
String result = timeString + " " + message;
log.getItems().add(0, result);
}
public void setData(ClientBackend clientBackend)
{
this.clientBackend = clientBackend;
hourColumn.setCellValueFactory(new PropertyValueFactory<>("Hour"));
bookedColumn.setCellValueFactory(new PropertyValueFactory<>("BookedStatus"));
}
public void bookVisit(ActionEvent event)
{
try
{
Visit visit = table.getSelectionModel().getSelectedItem();
if(visit == null)
{
logAdd("Please select hour");
return;
}
logAdd("Trying to book visit at " + visit.getHour());
clientBackend.bookVisit(visit);
}
catch(IOException e)
{
logAdd("Failed to book visit");
}
}
public void cancelVisit(ActionEvent event)
{
try
{
Visit visit = table.getSelectionModel().getSelectedItem();
if(visit == null)
{
logAdd("Please select hour");
return;
}
if(visit.getBookedStatus() == "No")
{
logAdd("Hour is available");
return;
}
logAdd("Trying to cancel visit at " + visit.getHour());
clientBackend.cancelVisit(visit);
}
catch(IOException e)
{
logAdd("Failed to cancel visit");
}
}
public void refreshDisplayedVisits()
{
schedule = clientBackend.getSchedule();
ObservableList<Visit> items = FXCollections.observableArrayList(schedule);
table.setItems(items);
table.refresh();
}
}
|
package fr.aresrpg.tofumanchou.domain.event.entity;
import fr.aresrpg.commons.domain.event.Event;
import fr.aresrpg.commons.domain.event.EventBus;
import fr.aresrpg.dofus.protocol.game.actions.GameMoveAction.PathFragment;
import fr.aresrpg.dofus.util.Pathfinding.Node;
import fr.aresrpg.tofumanchou.domain.data.Account;
import fr.aresrpg.tofumanchou.domain.data.entity.Entity;
import java.util.ArrayList;
import java.util.List;
/**
*
* @since
*/
public class EntityMoveEvent implements Event<EntityMoveEvent> {
private static final EventBus<EntityMoveEvent> BUS = new EventBus<>(EntityMoveEvent.class);
private Account client;
private Entity entity;
private long time;
private List<PathFragment> path = new ArrayList<>();
private List<Node> nodes = new ArrayList<>();
public EntityMoveEvent(Account client, Entity entity, long time, List<PathFragment> path, List<Node> nodes) {
this.client = client;
this.entity = entity;
this.time = time;
this.path = path;
this.nodes = nodes;
}
/**
* @return the time
*/
public long getTime() {
return time;
}
/**
* @param time
* the time to set
*/
public void setTime(long time) {
this.time = time;
}
/**
* @return the nodes
*/
public List<Node> getNodes() {
return nodes;
}
/**
* @param nodes
* the nodes to set
*/
public void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
/**
* @return the entity
*/
public Entity getEntity() {
return entity;
}
/**
* @param entity
* the entity to set
*/
public void setEntity(Entity entity) {
this.entity = entity;
}
/**
* @return the path
*/
public List<PathFragment> getPath() {
return path;
}
/**
* @param path
* the path to set
*/
public void setPath(List<PathFragment> path) {
this.path = path;
}
/**
* @param client
* the client to set
*/
public void setClient(Account client) {
this.client = client;
}
/**
* @return the client
*/
public Account getClient() {
return client;
}
@Override
public EventBus<EntityMoveEvent> getBus() {
return BUS;
}
@Override
public boolean isAsynchronous() {
return false;
}
@Override
public String toString() {
return "EntityMoveEvent [client=" + client + ", entity=" + entity + ", path=" + path + "]";
}
}
|
package io.github.satr.aws.lambda.bookstore.lambda.ask;
// Copyright © 2022, github.com/satr, MIT License
import com.amazon.ask.model.ResponseEnvelope;
import com.amazon.ask.model.ui.SsmlOutputSpeech;
import com.amazon.ask.util.JacksonSerializer;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import io.github.satr.aws.lambda.bookstore.BookStoreAskLambda;
import io.github.satr.aws.lambda.bookstore.entity.Book;
import io.github.satr.aws.lambda.bookstore.services.BasketService;
import io.github.satr.aws.lambda.bookstore.services.BookStorageService;
import io.github.satr.aws.lambda.bookstore.services.SearchBookResultService;
import io.github.satr.aws.lambda.bookstore.services.ServiceFactory;
import io.github.satr.aws.lambda.bookstore.test.ObjectMother;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class BookStoreAskLambdaSearchBookByTitleIntentTest {
private final JacksonSerializer serializer = new JacksonSerializer();
private final static String OUTPUT_SPEECH_TYPE = "SSML";
private BookStoreAskLambda lambda;
@Mock
Context context;
@Mock
LambdaLogger lambdaLogger;
@Mock
ServiceFactory serviceFactory;
@Mock
BookStorageService bookStorageService;
@Mock
SearchBookResultService searchBookResultService;
@Mock
BasketService basketService;
@Before
public void setUp() throws Exception {
when(serviceFactory.getBookStorageService()).thenReturn(bookStorageService);
when(serviceFactory.getSearchBookResultService()).thenReturn(searchBookResultService);
when(serviceFactory.getBasketService()).thenReturn(basketService);
when(context.getLogger()).thenReturn(lambdaLogger);
lambda = new BookStoreAskLambda(serviceFactory);
}
@Test
public void handleRequestReturnsRespond() throws IOException {
InputStream inputStream = ObjectMother.createInputStreamFromJson("search-book-by-title-intent-request-ask.json");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
assert inputStream != null;
lambda.handleRequest(inputStream, outputStream, null);
String respondAsString = outputStream.toString();
assertTrue(respondAsString.length() > 0);
System.out.println(respondAsString);
}
@Test
public void handleRequestWithFullOrderBookIntentRequestHasCorrectRespond() throws IOException {
InputStream inputStream = ObjectMother.createInputStreamFromJson("search-book-by-title-intent-request-ask.json");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
assert inputStream != null;
lambda.handleRequest(inputStream, outputStream, null);
String respondAsString = outputStream.toString();
assertTrue(respondAsString.length() > 0);
System.out.println(respondAsString);
ResponseEnvelope responseEnvelope = serializer.deserialize(respondAsString, ResponseEnvelope.class);
assertEquals(OUTPUT_SPEECH_TYPE, responseEnvelope.getResponse().getOutputSpeech().getType());
SsmlOutputSpeech outputSpeech = (SsmlOutputSpeech) responseEnvelope.getResponse().getOutputSpeech();
assertNotNull(outputSpeech);
assertTrue(outputSpeech.getSsml().length() > 0);
}
/*
* Expected Response:
* Optional[class Response {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>Searched books "contains" in title "Some Book Title"
Found 3 books:
1. "Some Book Title ABC" by Author-97ed66e3-85f3-4d01-b6d9-19bdb16ecb1b
2. "ABC Some Book Title" by Author-b6243adc-93aa-41ba-88f0-2271d92fe83a
3. "ABC Some Book Title XYZ" by Author-f9ffe6b4-9d30-4981-9b25-52a9adff4976</speak>
}
card: null
reprompt: null
directives: []
shouldEndSession: null
canFulfillIntent: null
}]
*/
@Test
public void handleRequestWithFullOrderBookIntentRequestPutsFoundBooksToBasketRepo() throws IOException {
List<Book> foundBookList = ObjectMother.getRandomBookList(3);
foundBookList.get(0).setTitle("Some Book Title ABC");
foundBookList.get(1).setTitle("ABC Some Book Title");
foundBookList.get(2).setTitle("ABC Some Book Title XYZ");
when(bookStorageService.getBooksWithTitleContaining("Some Book Title")).thenReturn(foundBookList);
InputStream inputStream = ObjectMother.createInputStreamFromJson("search-book-by-title-intent-request-ask.json");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
assert inputStream != null;
lambda.handleRequest(inputStream, outputStream, null);
verify(searchBookResultService).put(foundBookList);
}
} |
package com.tensquare.base.bean;
import com.tensquare.base.service.impl.GeneralCustomizationRepositoryImpl;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import javax.persistence.EntityManager;
import java.io.Serializable;
public class GeneralCustomizationRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {
/**
* Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
*
* @param repositoryInterface must not be {@literal null}.
*/
public GeneralCustomizationRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new CustomRepositoryFactory(entityManager);
}
private class CustomRepositoryFactory extends JpaRepositoryFactory { //加了static
/**
* Creates a new {@link JpaRepositoryFactory}.
*
* @param entityManager must not be {@literal null}
*/
public CustomRepositoryFactory(EntityManager entityManager) {
super(entityManager);
}
@Override
protected SimpleJpaRepository<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
return new GeneralCustomizationRepositoryImpl<T, ID>((Class<T>) information.getDomainType(), entityManager);
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return GeneralCustomizationRepositoryImpl.class;
}
}
}
|
package com.github.ofofs.jca.model;
import com.github.ofofs.jca.constants.JcaConstants;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* 方法
*
* @author kangyonggan
* @since 6/22/18
*/
public class JcaMethod extends JcaCommon {
/**
* 方法的标识
*/
private Symbol.MethodSymbol methodSym;
/**
* 方法的声明
*/
private JCTree.JCMethodDecl methodDecl;
/**
* 方法所属的类
*/
private JcaClass jcaClass;
public JcaMethod(Symbol.MethodSymbol methodSym) {
this.methodSym = methodSym;
jcaClass = new JcaClass((Symbol.ClassSymbol) methodSym.owner);
methodDecl = (JCTree.JCMethodDecl) trees.getTree(methodSym);
}
public JcaClass getJcaClass() {
return jcaClass;
}
public Symbol.MethodSymbol getMethodSym() {
return methodSym;
}
/**
* 在方法第一行插入一个变量
*
* @param jcaVariable 变量
* @return 返回当前方法
*/
public JcaMethod insert(JcaVariable jcaVariable) {
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
importPackage(getJcaClass(), jcaVariable.getTypeClass());
statements.append(treeMaker.VarDef(treeMaker.Modifiers(0), names.fromString(jcaVariable.getVarName()), getType(jcaVariable.getTypeClass()), jcaVariable.getValue().getExpression()));
for (JCTree.JCStatement statement : methodDecl.body.stats) {
statements.append(statement);
}
methodDecl.body.stats = statements.toList();
return this;
}
/**
* 在方法第一行插入一个表达式
*
* @param express 表达式
* @return 返回当前方法
*/
public JcaMethod insert(JcaObject express) {
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
statements.append(treeMaker.Exec(express.getExpression()));
for (JCTree.JCStatement statement : methodDecl.body.stats) {
statements.append(statement);
}
methodDecl.body.stats = statements.toList();
return this;
}
/**
* 在方法第一行插入一个代码块
*
* @param statement 代码块
* @return 返回当前方法
*/
public JcaMethod insertBlock(JcaObject statement) {
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
statements.append(statement.getStatement());
for (JCTree.JCStatement stat : methodDecl.body.stats) {
statements.append(stat);
}
methodDecl.body.stats = statements.toList();
return this;
}
/**
* 获取方法名
*
* @return 返回方法名
*/
public String getMethodName() {
return methodSym.name.toString();
}
/**
* 设置方法的修饰符
*
* @param modifier 修饰符
* @return 返回方法名
*/
public JcaMethod setModifier(int modifier) {
methodDecl.mods.flags = modifier;
return this;
}
/**
* 获取方法的参数
*
* @return 返回方法的参数
*/
public List<JcaObject> getArgs() {
com.sun.tools.javac.util.List<Symbol.VarSymbol> params = methodSym.params;
List<JcaObject> result = new ArrayList();
if (params != null) {
for (Symbol.VarSymbol var : params) {
result.add(getVar(var));
}
}
return result;
}
/**
* 获取方法的返回类型
*
* @return 返回方法的返回类型
*/
public JcaObject getReturnType() {
return new JcaObject(methodDecl.restype);
}
/**
* 判断方法是否有返回值
*
* @return 有则返回true,否则返回false
*/
public boolean hasReturnValue() {
return !JcaConstants.RETURN_VOID.equals(getReturnType().getExpression().toString());
}
/**
* 方法返回的回调
*
* @param returnValue 返回值
* @return 返回方法的返回值
*/
public JcaObject onReturn(JcaObject returnValue) {
return returnValue;
}
/**
* 处理方法的返回值,遇到方法返回处,会回调onReturn。
*
* @return 返回放弃方法
*/
public JcaMethod visitReturn() {
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
com.sun.tools.javac.util.List<JCTree.JCStatement> stats = methodDecl.body.stats;
if (stats.isEmpty()) {
JcaObject jcaObject = onReturn(getNull());
statements.append(treeMaker.Exec(jcaObject.getExpression()));
}
JcaObject returnType = getReturnType();
for (int i = 0; i < stats.size(); i++) {
JCTree.JCStatement stat = stats.get(i);
ListBuffer<JCTree.JCStatement> transStats = visitReturn(stat);
for (JCTree.JCStatement st : transStats) {
statements.append(st);
}
if (i == stats.size() - 1) {
if (returnType.getExpression() == null || JcaConstants.RETURN_VOID.equals(returnType.getExpression().toString())) {
if (!(stat instanceof JCTree.JCReturn)) {
JcaObject jcaObject = onReturn(getNull());
if (jcaObject != null && !JcaConstants.NULL.equals(jcaObject.getExpression().toString())) {
statements.append(treeMaker.Exec(jcaObject.getExpression()));
}
}
}
}
}
methodDecl.body.stats = statements.toList();
return this;
}
/**
* 处理返回值
*
* @param stat 当前代码块
* @return 返回方法的代码块
*/
private ListBuffer<JCTree.JCStatement> visitReturn(JCTree.JCStatement stat) {
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
if (stat instanceof JCTree.JCReturn) {
JCTree.JCReturn jcReturn = (JCTree.JCReturn) stat;
if (jcReturn.expr == null) {
// return;
JcaObject jcaObject = onReturn(getNull());
statements.append(treeMaker.Exec(jcaObject.getExpression()));
statements.append(stat);
} else {
// return xxx;
JcaObject jcaObject = onReturn(new JcaObject(jcReturn.expr));
jcReturn.expr = jcaObject.getExpression();
statements.append(jcReturn);
}
} else if (stat instanceof JCTree.JCIf) {
JCTree.JCIf jcIf = (JCTree.JCIf) stat;
JCTree.JCBlock block;
if (jcIf.thenpart != null) {
if (jcIf.thenpart instanceof JCTree.JCBlock) {
block = (JCTree.JCBlock) jcIf.thenpart;
doBlock(block);
jcIf.thenpart = block;
} else {
ListBuffer<JCTree.JCStatement> stats = visitReturn(jcIf.thenpart);
jcIf.thenpart = treeMaker.Block(stats.size(), stats.toList());
}
}
if (jcIf.elsepart != null) {
if (jcIf.elsepart instanceof JCTree.JCBlock) {
block = (JCTree.JCBlock) jcIf.elsepart;
doBlock(block);
jcIf.elsepart = block;
} else {
ListBuffer<JCTree.JCStatement> stats = visitReturn(jcIf.elsepart);
jcIf.elsepart = treeMaker.Block(stats.size(), stats.toList());
}
}
statements.append(jcIf);
} else if (stat instanceof JCTree.JCForLoop) {
JCTree.JCForLoop forLoop = (JCTree.JCForLoop) stat;
forLoop.body = doLoop(forLoop.body);
statements.append(forLoop);
} else if (stat instanceof JCTree.JCDoWhileLoop) {
JCTree.JCDoWhileLoop doWhileLoop = (JCTree.JCDoWhileLoop) stat;
doWhileLoop.body = doLoop(doWhileLoop.body);
statements.append(doWhileLoop);
} else if (stat instanceof JCTree.JCWhileLoop) {
JCTree.JCWhileLoop whileLoop = (JCTree.JCWhileLoop) stat;
whileLoop.body = doLoop(whileLoop.body);
statements.append(whileLoop);
} else {
statements.append(stat);
}
return statements;
}
/**
* 处理循环
*
* @param stat 循环
* @return 返回处理后的循环
*/
private JCTree.JCStatement doLoop(JCTree.JCStatement stat) {
if (stat instanceof JCTree.JCBlock) {
JCTree.JCBlock block = (JCTree.JCBlock) stat;
doBlock(block);
stat = block;
} else {
ListBuffer<JCTree.JCStatement> stats = visitReturn(stat);
stat = treeMaker.Block(stats.size(), stats.toList());
}
return stat;
}
/**
* 处理代码块
*
* @param block 代码块
*/
private void doBlock(JCTree.JCBlock block) {
ListBuffer<JCTree.JCStatement> stats = new ListBuffer();
for (JCTree.JCStatement st : block.getStatements()) {
ListBuffer<JCTree.JCStatement> ss = visitReturn(st);
for (JCTree.JCStatement stat : ss) {
stats.append(stat);
}
}
block.stats = stats.toList();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JcaMethod jcaMethod = (JcaMethod) o;
if (methodSym != null ? !methodSym.equals(jcaMethod.methodSym) : jcaMethod.methodSym != null) {
return false;
}
return jcaClass != null ? jcaClass.equals(jcaMethod.jcaClass) : jcaMethod.jcaClass == null;
}
@Override
public int hashCode() {
int result = methodSym != null ? methodSym.hashCode() : 0;
result = 31 * result + (jcaClass != null ? jcaClass.hashCode() : 0);
return result;
}
/**
* 判断方法是不是静态的
*
* @return 如果方法是静态的返回true,否则返回false
*/
public boolean isStatic() {
return hasModifier(Flags.STATIC);
}
/**
* 判断方法是不是有某个修饰符
*
* @return 如果方法有某个修饰符的返回true,否则返回false
*/
public boolean hasModifier(int modifier) {
return methodDecl.mods.flags % (modifier * 2) >= modifier;
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import art.*;
import java.util.*;
import java.lang.invoke.*;
import java.io.*;
import java.util.zip.*;
public class Main {
public static final String TEST_NAME = "2000-virtual-list-structural";
public static final boolean PRINT_COUNT = false;
public static MethodHandles.Lookup lookup = MethodHandles.publicLookup();
public static MethodHandle getcnt;
public static MethodHandle get_total_cnt;
public static void GetHandles() throws Throwable {
getcnt = lookup.findGetter(AbstractCollection.class, "cnt", Integer.TYPE);
get_total_cnt = lookup.findStaticGetter(AbstractCollection.class, "TOTAL_COUNT", Integer.TYPE);
}
public static byte[] GetDexBytes() throws Throwable {
String jar_loc = System.getenv("DEX_LOCATION") + "/" + TEST_NAME + "-ex.jar";
try (ZipFile zip = new ZipFile(new File(jar_loc))) {
ZipEntry entry = zip.getEntry("classes.dex");
try (InputStream is = zip.getInputStream(entry)) {
byte[] res = new byte[(int)entry.getSize()];
is.read(res);
return res;
}
}
}
public static void PrintListAndData(AbstractCollection<String> c) throws Throwable {
if (PRINT_COUNT) {
System.out.println("List is: " + c + " count = " + getcnt.invoke(c) + " TOTAL_COUNT = " + get_total_cnt.invoke());
} else {
System.out.println("List is: " + c);
}
}
public static void main(String[] args) throws Throwable {
AbstractCollection<String> l1 = (AbstractCollection<String>)Arrays.asList("a", "b", "c", "d");
AbstractCollection<String> l2 = new ArrayList<>();
l2.add("1");
l2.add("2");
l2.add("3");
l2.add("4");
Redefinition.doCommonStructuralClassRedefinition(AbstractCollection.class, GetDexBytes());
GetHandles();
AbstractCollection<String> l3 = new HashSet<>(l2);
AbstractCollection<String> l4 = new LinkedList<>(l1);
PrintListAndData(l1);
PrintListAndData(l2);
for (int i = 0; i < 1000; i++) {
l2.add("xyz: " + i);
}
PrintListAndData(l2);
PrintListAndData(l3);
PrintListAndData(l4);
CheckLE(getcnt.invoke(l1), get_total_cnt.invoke());
CheckLE(getcnt.invoke(l2), get_total_cnt.invoke());
CheckLE(getcnt.invoke(l3), get_total_cnt.invoke());
CheckLE(getcnt.invoke(l4), get_total_cnt.invoke());
CheckEQ(getcnt.invoke(l1), 0);
CheckLE(getcnt.invoke(l2), 0);
CheckLE(getcnt.invoke(l1), getcnt.invoke(l2));
CheckLE(getcnt.invoke(l1), getcnt.invoke(l3));
CheckLE(getcnt.invoke(l1), getcnt.invoke(l4));
CheckLE(getcnt.invoke(l2), getcnt.invoke(l3));
CheckLE(getcnt.invoke(l2), getcnt.invoke(l4));
CheckLE(getcnt.invoke(l3), getcnt.invoke(l4));
}
public static void CheckEQ(Object a, int b) {
CheckEQ(((Integer)a).intValue(), b);
}
public static void CheckLE(Object a, Object b) {
CheckLE(((Integer)a).intValue(), ((Integer)b).intValue());
}
public static void CheckEQ(int a, int b) {
if (a != b) {
throw new Error(a + " is not equal to " + b);
}
}
public static void CheckLE(int a, int b) {
if (!(a <= b)) {
throw new Error(a + " is not less than or equal to " + b);
}
}
}
|
package am.bizis.cds.ciselnik;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Ciselnik cinnosti (okec)
* @author alex
*
*/
public class Okec {
private static final File CISELNIK=new File("/home/alex/okec.xml");
public Okec() {
// TODO Auto-generated constructor stub
}
/**
* Nacte ciselnik ze souboru
* @return XML dokument - ciselnik cinnosti
*/
private Document getCiselnik(){
Document XMLdoc=null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
XMLdoc = db.parse(CISELNIK);
XMLdoc.getDocumentElement().normalize();
SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File schemaURL = new File("/home/alex/ciselnik.xsd");
Schema schema = sf.newSchema(schemaURL);
Validator validator=schema.newValidator();
DOMSource source=new DOMSource(XMLdoc);
validator.validate(source);
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return XMLdoc;
}
/**
* Vrati pole Stringu s nazvy cinnosti
* @return nazvy cinnosti pro zobrazeni v GUI - uzivatel si vybere, metoda get Cnace pro dany String vrati c_nace
*/
public String[] getNazvy(){
Document ciselnik=getCiselnik();
NodeList vety=ciselnik.getElementsByTagName("Veta");
List<String> seznam=new ArrayList<String>();
for(int i=0;i<vety.getLength();i++){
NamedNodeMap attr=vety.item(i).getAttributes();
seznam.add(attr.getNamedItem("naz_nace").getNodeValue());
}
return seznam.toArray(new String[seznam.size()]);
}
/**
* Vrati c_nace z ciselniku cinnosti pro dany String
* @param nazev odpovida polozce z pole vraceneho getNazvy()
* @return c_nace
*/
public int getCnace(String nazev){
int cnace=-255;
Document ciselnik=getCiselnik();
NodeList vety=ciselnik.getElementsByTagName("Veta");
for(int i=0;i<vety.getLength();i++){
NamedNodeMap attr=vety.item(i).getAttributes();
if(attr.getNamedItem("nazu_ufo").getNodeValue().equals(nazev))
cnace=Integer.parseInt(attr.getNamedItem("c_nace").getNodeValue());
}
return cnace;
}
}
|
package com.lq.controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import com.util.Valuable;
@Controller
@RequestMapping("/upload")
public class FileUploadController implements ServletContextAware{
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@Autowired
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext context){
this.servletContext = context;
}
@RequestMapping(value = "image", method = RequestMethod.POST)
public void uploadDiagFile(HttpServletRequest request,HttpServletResponse response) throws IOException, InterruptedException {
request.setCharacterEncoding("utf-8");
FileItem picture = null;
DiskFileItemFactory factory = null;
ServletFileUpload upload = null;
//获取文件需要上传的路径
//String path = "R:\\image";
//String path = "/usr/image";
String path = Valuable.getPath();
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
logger.info("path="+path);
request.setCharacterEncoding("utf-8");//设置编码
//获得磁盘文件条目工厂
factory = new DiskFileItemFactory();
factory.setRepository(dir);
factory.setSizeThreshold(1024*1024);
//创建一个文件上传解析器
upload = new ServletFileUpload(factory);
//说明Request的类名和每个request不同
try{
//[]说明upload.parseRequest(request)没有产生信息
@SuppressWarnings("unchecked")
List<FileItem> list = upload.parseRequest(request);
//null已经被解析过,获取不到传参
for(FileItem item : list){
//获取表单的属性名字
String name = item.getFieldName();
//如果获取的表单信息是普通的文本信息
if(item.isFormField()){
//获取用户具体输入的字符串
String value = item.getString();
request.setAttribute(name, value);
logger.debug("name="+name+",value="+value);
}else{
picture = item;
}
}
String onlycode = (String)request.getAttribute("onlycode");
String filetype = ".jpg";
String fileName = "OpenId"+onlycode +filetype;
//真正写到磁盘上
File file = new File(path,fileName);
OutputStream out = new FileOutputStream(file);
InputStream in = picture.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
//in.read(buf) 每次读到的数据放在buf数组中
while((length = in.read(buf)) != -1){
out.write(buf,0,length);
}
in.close();
out.close();
}catch(FileUploadException e){
logger.error("Could not parse multipart servlet request",e);
}
}
public static String getCurrentDate() {
String pattern = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date today = new Date();
String tString = df.format(today);
return tString;
}
public static String getCurrentTime() {
String pattern = "HH:mm:ss";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date today = new Date();
String tString = df.format(today);
return tString;
}
} |
/**
* Course: Development for mobile applications.
* Umeå University
* Summer 2019
* @author Alex Norrman
*/
package se.umu.cs.alno0025.fjallstugan;
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StationActivity extends AppCompatActivity {
private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/fjallstugan/fjallstugor/";
public static final int PERMISSION_LOCATION = 1;
public static final int PERMISSION_READ = 2;
public static final int PERMISSION_WRITE = 3;
private Fjallstation fjallstation;
private Bitmap imgBitmap = null;
private Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station);
activity = this;
Intent intent = getIntent();
fjallstation = intent.getParcelableExtra("station");
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setTitle(fjallstation.getName());
}
ImageView stationImageView = findViewById(R.id.station_page_image);
// If the premission to read & the file is not downloaded, download the file
// If the file is already downloaded, use that one.
// Else, load the image from the website.
if(isWriteToStoragePermissionGranted()){
if(!isImgAlreadyDownloaded(fjallstation.getName()))
new DownloadImageTask(fjallstation.getName()).execute(fjallstation.getImgUrl());
if(isImgAlreadyDownloaded(fjallstation.getName())){
String file_path = FILE_PATH + fjallstation.getName().replaceAll("[^a-zA-Z]+", "")+".png";
stationImageView.setImageBitmap(BitmapFactory.decodeFile(file_path));
}
}
else{
new LoadImageTask().execute(fjallstation.getImgUrl());
stationImageView.setImageBitmap(imgBitmap);
}
TextView name = findViewById(R.id.station_title);
name.setText(fjallstation.getName());
TextView adress = findViewById(R.id.address);
adress.setText(fjallstation.getAdress());
TextView phone = findViewById(R.id.phone_nr);
phone.setText(fjallstation.getPhoneNr());
TextView email = findViewById(R.id.email);
email.setText(fjallstation.getEmail());
TextView url = findViewById(R.id.homepage);
url.setText(fjallstation.getUrl());
url.setMovementMethod(LinkMovementMethod.getInstance());
}
/**
* Gets the images bitmap to later save to the device.
* Doing it Async to not freeze the activity.
*/
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private String name;
public DownloadImageTask(String fjallstation) {
name = fjallstation;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
downloadImg(name, result);
}
}
/**
* Saves a image to the device.
* @param name image name
* @param bitmap image bitmap
*/
private void downloadImg(String name, Bitmap bitmap){
String file_path = FILE_PATH;
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, name.replaceAll("[^a-zA-Z]+", "")+".png");
if(!file.exists()){
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Checks if the image already exists or not.
* @param name
* @return
*/
private boolean isImgAlreadyDownloaded(String name){
String file_path = FILE_PATH;
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, name.replaceAll("[^a-zA-Z]+", "")+".png");
if(file.exists()){
return true;
}
else
return false;
}
/**
* Load the images from URL
* if read the files from device is not allowed.
* Doing it Async to not freeze the activity, might take a while to
* get all the images showing.
*/
private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
public LoadImageTask() {
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imgBitmap = result;
}
}
/**
* Check permission to write to the device.
* @return
*/
public boolean isWriteToStoragePermissionGranted() {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(activity)
.setTitle("För att spara kartor behöver applikationen tillåtelse!")
.setMessage("Tillåt att kunna spara kartor på din enhet?").setNegativeButton("Nej",null)
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(activity,new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_WRITE);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_WRITE);
}
return false;
} else {
return true;
}
}
/**
* Handles the premissions request.
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_READ: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
case PERMISSION_WRITE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
/**
* When the back-arrow is pressed in the toolbar,
* handle it as a onBackPressed.
* @return
*/
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
|
package lawscraper.client.ui.events;
import com.google.gwt.event.shared.EventHandler;
/**
* Created by erik, IT Bolaget Per & Per AB
* Date: 5/16/12
* Time: 10:09 AM
*/
public interface SetCurrentLawEventHandler extends EventHandler {
void onSetCurrentLaw(SetCurrentLawEvent event);
}
|
package com.monitoring.view;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.GridPane;
public class FxAreaChart {
protected final ObservableList<XYChart.Series> fListSeries = FXCollections.observableArrayList();
private CategoryAxis fXAxis = new CategoryAxis();
private NumberAxis fYAxis = new NumberAxis(0, 10, 1);
private AreaChart fAreaChart = new AreaChart(fXAxis, fYAxis);
public AreaChart getAreaChart() {
return fAreaChart;
}
public ObservableList<XYChart.Series> getListSeries() {
return fListSeries;
}
public void setGridPosition(int aCol, int aRow) {
GridPane.setColumnIndex(fAreaChart, aCol);
GridPane.setRowIndex(fAreaChart, aRow);
GridPane.setMargin(fAreaChart, new Insets(5, 5, 5, 5));
}
public FxAreaChart(String aTitle, boolean aZeroRange) {
fYAxis.setForceZeroInRange(aZeroRange);
fYAxis.setAutoRanging(true);
fAreaChart.setTitle(aTitle);
fAreaChart.setAnimated(false);
fAreaChart.setCreateSymbols(true);
fAreaChart.setData(fListSeries);
}
public void setYAxisTickLabel(String aString) {
fYAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(fYAxis, null, aString));
}
}
|
package net.cglab.hotelpraktikum.ws;
import net.cglab.hotelpraktikum.hibernate.Jobs;
import net.cglab.hotelpraktikum.service.JobService;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
@Endpoint
public class JobEndpoint {
private static final String NAMESPACE_URI = "http://cglab.net/job/schemas";
private XPathExpression<Element> idExpression;
// private XPathExpression<Element> endDateExpression;
// private XPathExpression<Element> firstNameExpression;
// private XPathExpression<Element> lastNameExpression;
private JobService jobService;
@Autowired
public JobEndpoint(JobService jobService) throws JDOMException {
this.jobService = jobService;
Namespace namespace = Namespace.getNamespace("jr", NAMESPACE_URI);
XPathFactory xPathFactory = XPathFactory.instance();
idExpression = xPathFactory.compile("//jr:Id", Filters.element(), null, namespace);
// endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace);
// firstNameExpression = xPathFactory.compile("//hr:FirstName", Filters.element(), null, namespace);
// lastNameExpression = xPathFactory.compile("//hr:LastName", Filters.element(), null, namespace);
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "JobRequest")
public void handleJobRequest(@RequestPayload Element jobRequest) throws Exception {
int id = Integer.parseInt(idExpression.evaluateFirst(jobRequest).getText());//parseI(idExpression, jobRequest);
// Date startDate = parseDate(startDateExpression, jobRequest);
// Date endDate = parseDate(endDateExpression, jobRequest);
// String name = firstNameExpression.evaluateFirst(jobRequest).getText() + " " + lastNameExpression.evaluateFirst(jobRequest).getText();
Jobs job = jobService.getJobById(id);
System.out.print("job Id: "+ job.getJobid());
}
// private Date parseDate(XPathExpression<Element> expression, Element element) throws ParseException {
// Element result = expression.evaluateFirst(element);
// if (result != null) {
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// return dateFormat.parse(result.getText());
// } else {
// throw new IllegalArgumentException("Could not evaluate [" + expression + "] on [" + element + "]");
// }
// }
}
|
package com.bnade.wow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by liufeng0103@163.com on 2017/6/6.
*/
@SpringBootApplication
public class BnadeApplication {
public static void main(String[] args) {
SpringApplication.run(BnadeApplication.class, args);
}
}
|
package com.brainacademy.gae.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.brainacademy.gae.model.User;
import com.brainacademy.gae.utils.HibernateUtils;
import lombok.Getter;
public class UserDao {
@Getter
private static UserDao instance = new UserDao();
public List<User> getAll() {
try (Session session = HibernateUtils.openSession()) {
Query<User> query = session.createQuery("from User", User.class);
return query.list();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<User> finByName(String name) {
try (Session session = HibernateUtils.openSession()) {
Query<User> query = session.createQuery("from User u where u.name like :name", User.class);
query.setParameter("name", "%" + name + "%");
return query.list();
}
}
public void create(User user) {
try (Session session = HibernateUtils.openSession()) {
session.save(user);
}
}
public void update(User user) {
try (Session session = HibernateUtils.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(user);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
}
}
}
public void delete(User user) {
try (Session session = HibernateUtils.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.remove(user);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
}
}
}
}
|
package lesson36.service;
import lesson36.dao.Session;
import lesson36.dao.UserDAO;
import lesson36.exception.BadRequestException;
import lesson36.exception.InternalServerError;
import lesson36.model.User;
public class UserService {
private UserDAO userDAO;
public UserService() throws InternalServerError{
userDAO = new UserDAO();
}
public User registerUser(User user) throws InternalServerError {
if (user.getUserName().equals("") || user.getPassword().equals("") || user.getCountry().equals(""))
throw new BadRequestException("registerUser", "values can not be empty");
if(userDAO.getUserByLoginAndPassword(user.getUserName(), user.getPassword()) != null)
throw new BadRequestException("registerUser", "User with user name: "+user.getUserName()+" is already registered.");
return userDAO.registerUser(user);
}
public void login(String userName, String password) throws InternalServerError {
Session.login(userName, password);
}
public void logout(){
Session.logout();
}
}
|
package pl.coderslab.web.utils;
import com.mysql.jdbc.Driver;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@Component
public class FactoryConnection {
public static final String URL = "jdbc:mysql://localhost:3306/sportbets?useSSL=false";
public static final String USER = "root";
public static final String PASS = "root";
public static Connection getConnection()
{
try {
DriverManager.registerDriver(new Driver());
return DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException ex) {
throw new RuntimeException("Error connecting to the database", ex);
}
}
} |
package L5_ExerciciosFuncoes;
public class Ex05_L5 {
private double valorProduto;
private double taxaProduto;
private double valorTaxa;
private double valorProdutoFinal;
public void setValorProduto(double valorProduto){
this.valorProduto = valorProduto;
}
public double getValorProduto(){
return this.valorProduto;
}
public void setTaxaProduto(double taxaProduto){
this.taxaProduto = taxaProduto;
}
public double getTaxaProduto(){
return this.taxaProduto;
}
public void setValorTaxa() {
this.valorTaxa = this.valorProduto * (this.taxaProduto / 100);
}
public double getValorTaxa() {
return valorTaxa;
}
public void setValorProdutoFinal() {
this.valorProdutoFinal = this.valorProduto + this.valorTaxa;
}
public double getValorProdutoFinal() {
return valorProdutoFinal;
}
}
|
public class Catsup extends IngredienteDecoradorTorta {
Torta torta;
public Catsup(Torta torta) {
this.torta = torta;
}
public String getDescripcion() {
return torta.getDescripcion() + ", Catsup";
}
public double costo() {
return 0.30 + torta.costo();
}
}
|
package Library.entities;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("Janitor")
public class Janitor extends Employee {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package byui.cit260.LehisDream.view;
/**
*
* @author smith
*/
public class SaveGameView {
public SaveGameView(){
}
public static void SaveGame(){
System.out.println("*** saveGame function called ***");
}
}
|
package nl.guuslieben.circle.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@JsonSerialize
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class Topic {
@JsonProperty
@JsonInclude(Include.NON_DEFAULT)
private long id;
@JsonProperty
private String name;
@JsonProperty
private UserData author;
@JsonProperty
private List<Response> responses;
}
|
package com.bridgelabz.addressbook;
public class IOServiceEnum {
enum ioService {
CONSOLE_IO, FILE_IO, JSON_IO, CSV_IO, DB_IO
}
}
|
package f.star.iota.milk.ui.booru;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import f.star.iota.milk.MyApp;
import f.star.iota.milk.base.PVContract;
import f.star.iota.milk.base.StringPresenter;
import f.star.iota.milk.config.OtherConfig;
public class BooruPresenter extends StringPresenter<List<BooruBean>> {
public BooruPresenter(PVContract.View view) {
super(view);
}
@Override
protected List<BooruBean> dealResponse(String s, HashMap<String, String> headers) {
List<BooruBean> beans = new Gson().fromJson(s, new TypeToken<List<BooruBean>>() {
}.getType());
if (OtherConfig.getR(MyApp.mContext)) {
Iterator<BooruBean> iterator = beans.iterator();
while (iterator.hasNext()) {
BooruBean b = iterator.next();
if (b.getRating() != null && !b.getRating().toLowerCase().contains("s")) {
iterator.remove();
}
}
}
return beans;
}
}
|
package 多线程.阻塞;
/**
* Created by 陆英杰
* 2018/9/7 9:58
*/
/**
* DESC: 当线程被sleep阻塞的时候,那么线程会让出cpu资源,并且当sleep时间到了之后会变成可运行状态,
* 当这个线程再次得到cpu资源的时候,那么这个线程会从上一次被阻塞的地方开始继续执行代码
* CREATEBY: luyingjie
* Date: 2018/9/7 14:23
*/
public class 阻塞{
public static void main(String[] args) {
Runnable runnable=new Demo1();
Thread t1=new Thread(runnable,"线程1");//启动线程
Thread t2=new Thread(runnable,"线程2");//启动线程
t1.start();
t2.start();
}
}
class Demo1 implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++){
try {
Thread.sleep(100);//使线程阻塞,那么这个被阻塞的线程就会让出CPU资源,然后时间结束之后就会变成可运行状态,直到这个线程再次获取CPU资源,然后再从这个地方继续往下执行多少个时间片
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}
|
package br.com.tt.petshop.api;
import br.com.tt.petshop.dto.ClienteEntradaDto;
import br.com.tt.petshop.dto.ClienteSaidaDto;
import br.com.tt.petshop.dto.MensagemErroDto;
import br.com.tt.petshop.exception.CpfInvalidoException;
import br.com.tt.petshop.exception.ErroNegocioException;
import br.com.tt.petshop.model.Cliente;
import br.com.tt.petshop.service.ClienteService;
import io.swagger.annotations.Api;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController
@Api(tags = "Clientes")
public class ClienteRestController {
private final ClienteService clienteService;
public ClienteRestController(ClienteService clienteService) {
this.clienteService = clienteService;
}
@PostMapping(value = "/clientes", consumes = APPLICATION_JSON_VALUE)
public ResponseEntity criar(@RequestBody @Valid ClienteEntradaDto dto){
Cliente clienteCriado = clienteService.criarCliente(dto);
String location = String.format("/clientes/%d", clienteCriado.getId());
return ResponseEntity
.created(URI.create(location))
.build();
}
@GetMapping(value = "/clientes", produces = APPLICATION_JSON_VALUE)
public List<ClienteSaidaDto> lista(){
return clienteService.listarClientes();
}
@GetMapping(value = "/clientes/{clienteId}", produces = "application/json")
public Cliente buscarPorId(@PathVariable("clienteId") Integer id){
return clienteService.buscarPorId(id);
}
//Put /clientes/{id} -> body json (campos do objeto a ser atualizado!)
@PutMapping("/clientes/{idCliente}")
public ResponseEntity atualizar(@PathVariable("idCliente") Integer idCliente,
@RequestBody @Valid ClienteEntradaDto clienteEntradaDto){
clienteService.atualizar(idCliente, clienteEntradaDto);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/clientes/{id}")
public ResponseEntity remover(@PathVariable("id") Integer id){
clienteService.removerPorId(id);
return ResponseEntity.noContent().build();
}
/* @ExceptionHandler(CpfInvalidoException.class)
public ResponseEntity<MensagemErroDto>
trataCpfInvalido(CpfInvalidoException e){
return ResponseEntity
.badRequest()
.body("Cpf inválido!!");// ou e.getMessage()
}*/
/**
* Forma mais simples de tratar uma exceção no Spring MVC!
*/
@ExceptionHandler(CpfInvalidoException.class)
public ResponseEntity<MensagemErroDto> trataCpfInvalido(CpfInvalidoException e) {
MensagemErroDto mensagemErro = new MensagemErroDto("cpf_invalido", e.getMessage());
return ResponseEntity.badRequest().body(mensagemErro);
}
}
|
package stock_keeping_app;
import java.util.ArrayList;
import java.util.logging.Logger;
public class Stock_Item {
private Logger logger = Logger.getLogger(Stock_Item.class.getName());
private String itemId;
private String batchNumber;
private ItemCategory stock;
private int totalStock;
public Stock_Item(String itemId, String batchNumber, ItemCategory myStock, int totalStock) {
this.itemId = itemId;
this.batchNumber = batchNumber;
stock = myStock;
this.totalStock = totalStock;
}
public Stock_Item() {
}
public void setItemId(String itemId ) {
this.itemId = itemId;
}
public String getItemId() {
return itemId;
}
public void setBatchNumber(String batchNumber) {
this.batchNumber = batchNumber;
}
public String getBatchNumber() {
return batchNumber;
}
public ItemCategory getStock() {
return stock;
}
public void setStockItem(ItemCategory item) {
stock = item;
}
public void displayAllBrands() {
stock.itemBrand();
}
public String getItemBrand(ItemCategory item) {
return item.getBrand();
}
public void displayItemList() {
stock.itemList();
}
public int calculateTotalStock(ItemCategory item) {
ArrayList<ItemCategory> itemArray = new ArrayList();
for(ItemCategory mystock : item.values()) {
logger.info(mystock.toString());
System.out.println(mystock.getQuantity());
itemArray.add(mystock);
}
for(int count = 0; count < itemArray.size(); count++){
totalStock += item.getQuantity();
}
System.out.println(totalStock);
return totalStock;
}
public double getPriceOfEachItem() {
return stock.getPricePerItem();
}
}
|
package com.cn.daniel.pm.service.impl;
import com.cn.daniel.pm.dao.SalaryHistoryDao;
import com.cn.daniel.pm.domain.SalaryHistory;
import com.cn.daniel.pm.service.SalaryHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author daniel
* @create 2017-08-08 2:28 PM
**/
@Service
public class SalaryHistoryServiceImpl implements SalaryHistoryService{
@Autowired
SalaryHistoryDao salaryHistoryDao;
@Override
public List<SalaryHistory> getSalaryHistories(String eid) {
Map map =new HashMap<String,String>();
map.put("eid",eid);
return salaryHistoryDao.selectAllByEid(map);
}
}
|
package org.webdriver.demo;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ById;
import org.openqa.selenium.By.ByXPath;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void testLoginWithBlankField() {
// open browser firefox
WebDriver driver = new FirefoxDriver();
// truy cap vao trang accounts.google.com
driver.get("https://accounts.google.com");
// dang nhap voi ten dang nhap va mk trong
driver.findElement(ById.id("identifierNext")).click();
String error = driver.findElement(ByXPath.xpath(".//*[@jsname='B34EJ']")).getText();
Assert.assertEquals(error, "Enter an email or phone number");
//close browser
driver.close();
}
@Test
public void testLoginWithBlankPassword() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com");
driver.findElement(By.id("identifierId")).sendKeys("buongdandeu");
driver.findElement(ById.id("identifierNext")).click();
driver.switchTo();
driver.findElement(ByXPath.xpath(".//*[@type='password']")).sendKeys("1234567");
driver.findElement(ByXPath.xpath(".//*[@id='passwordNext']")).click();
String errorPass = driver.findElement(ByXPath.xpath(".//*[@jsname='B34EJ']")).getText();
Assert.assertEquals(errorPass, "Enter a password");
driver.close();
}
}
|
/*
* Created on Mar 1, 2007
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.entity.pl.valueobject;
import java.util.Date;
/**
* @author fernando.salgado
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public class TplErEmHistEntityVO extends BaseTplErEmEntityVO
{
/**
* Comment for <code>m_erEmRefDate</code>
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_erEmRefDate;
/**
* Comment for <code>m_lastAuthDate</code>
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_lastAuthDate;
/**
* Comment for <code>m_lastAuthUserId</code>
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_lastAuthUserId;
/**
* Comment for <code>m_recStatCode</code>
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_recStatCode;
/**
* @return Returns the lastAuthDate.
*/
public Date getLastAuthDate()
{
return m_lastAuthDate;
}
/**
* @param lastAuthDate_ The lastAuthDate to set.
*/
public void setLastAuthDate( Date lastAuthDate_ )
{
m_lastAuthDate = lastAuthDate_;
}
/**
* @return Returns the lastAuthUserId.
*/
public String getLastAuthUserId()
{
return m_lastAuthUserId;
}
/**
* @param lastAuthUserId_ The lastAuthUserId to set.
*/
public void setLastAuthUserId( String lastAuthUserId_ )
{
m_lastAuthUserId = lastAuthUserId_;
}
/**
* @return Returns the recStatCode.
*/
public String getRecStatCode()
{
return m_recStatCode;
}
/**
* @param recStatCode_ The recStatCode to set.
*/
public void setRecStatCode( String recStatCode_ )
{
m_recStatCode = recStatCode_;
}
/**
* @return Returns the erEmRefDate.
*/
public Date getErEmRefDate()
{
return m_erEmRefDate;
}
/**
* @param erEmRefDate_ The erEmRefDate to set.
*/
public void setErEmRefDate( Date erEmRefDate_ )
{
m_erEmRefDate = erEmRefDate_;
}
} |
package com.dbsys.rs.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbsys.rs.lib.entity.Apoteker;
import com.dbsys.rs.lib.entity.Dokter;
import com.dbsys.rs.lib.entity.Pegawai;
import com.dbsys.rs.lib.entity.Pekerja;
import com.dbsys.rs.lib.entity.Perawat;
import com.dbsys.rs.repository.PegawaiRepository;
import com.dbsys.rs.service.PegawaiService;
@Service
@Transactional(readOnly = true)
public class PegawaiServiceImpl implements PegawaiService {
@Autowired
private PegawaiRepository pegawaiRepository;
@Override
@Transactional(readOnly = false)
public Pegawai save(Pegawai pegawai) {
return pegawaiRepository.save(pegawai);
}
@Override
public List<Dokter> getDokter() {
return pegawaiRepository.findAllDokter();
}
@Override
public List<Perawat> getPerawat() {
return pegawaiRepository.findAllPerawat();
}
@Override
public List<Apoteker> getApoteker() {
return pegawaiRepository.findAllApoteker();
}
@Override
public List<Pekerja> getPekerja() {
return pegawaiRepository.findAllPekerja();
}
}
|
package com.training.utils;
import java.sql.SQLException;
import java.util.List;
import com.training.beans.*;
public interface DAO {
public int add(Customer customer) throws SQLException;
public List<Customer> getAllCustomers() throws SQLException;
}
|
/*
* Copyright 2012 Daniel Zwolenski.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zenjava.javafx.maven.plugin;
import com.sun.javafx.tools.packager.CreateJarParams;
import com.sun.javafx.tools.packager.PackagerException;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/**
* <p>Builds an executable JAR for the project that has all the trappings needed to run as a JavaFX app. This will
* include Pre-Launchers and all the other weird and wonderful things that the JavaFX packaging tools allow and/or
* require.</p>
*
* <p>Any runtime dependencies for this project will be included in a separate 'lib' sub-directory alongside the
* resulting JavaFX friendly JAR. The manifest within the JAR will have a reference to these libraries using the
* relative 'lib' path so that you can copy the JAR and the lib directory exactly as is and distribute this bundle.</p>
*
* <p>The JAR and the 'lib' directory built by this Mojo are used as the inputs to the other distribution bundles. The
* native and web Mojos for example, will trigger this Mojo first and then will copy the resulting JAR into their own
* distribution bundles.</p>
*
* @goal jar
* @phase package
* @execute phase="package"
* @requiresDependencyResolution
*/
public class JarMojo extends AbstractJfxToolsMojo {
/**
* Flag to switch on and off the compiling of CSS files to the binary format. In theory this has some minor
* performance gains, but it's debatable whether you will notice them, and some people have experienced problems
* with the resulting compiled files. Use at your own risk. By default this is false and CSS files are left in their
* plain text format as they are found.
*
* @parameter default-value=false
*/
protected boolean css2bin;
/**
* A custom class that can act as a Pre-Loader for your app. The Pre-Loader is run before anything else and is
* useful for showing splash screens or similar 'progress' style windows. For more information on Pre-Loaders, see
* the official JavaFX packaging documentation.
*
* @parameter
*/
protected String preLoader;
/**
* Flag to switch on updating the existing jar created with maven. The jar to be updated is taken from
* '${project.basedir}/target/${project.build.finalName}.jar'.
*
* @parameter default-value=false
*/
protected boolean updateExistingJar;
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Building JavaFX JAR for application");
Build build = project.getBuild();
CreateJarParams createJarParams = new CreateJarParams();
createJarParams.setOutdir(jfxAppOutputDir);
createJarParams.setOutfile(jfxMainAppJarName);
createJarParams.setApplicationClass(mainClass);
createJarParams.setCss2bin(css2bin);
createJarParams.setPreloader(preLoader);
StringBuilder classpath = new StringBuilder();
File libDir = new File(jfxAppOutputDir, "lib");
if (!libDir.exists() && !libDir.mkdirs()) {
throw new MojoExecutionException("Unable to create app lib dir: " + libDir);
}
if (updateExistingJar) {
createJarParams.addResource(null, new File(build.getDirectory() + File.separator + build.getFinalName() + ".jar"));
} else {
createJarParams.addResource(new File(build.getOutputDirectory()), "");
}
try {
for (Object object : project.getRuntimeClasspathElements()) {
String path = (String) object;
File file = new File(path);
if (file.isFile()) {
getLog().debug("Including classpath element: " + path);
File dest = new File(libDir, file.getName());
if (!dest.exists()) {
Files.copy(file.toPath(), dest.toPath());
}
classpath.append("lib/").append(file.getName()).append(" ");
}
}
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Error resolving application classpath to use for application", e);
} catch (IOException e) {
throw new MojoExecutionException("Error copying dependency for application", e);
}
createJarParams.setClasspath(classpath.toString());
try {
getPackagerLib().packageAsJar(createJarParams);
} catch (PackagerException e) {
throw new MojoExecutionException("Unable to build JFX JAR for application", e);
}
}
}
|
// Searching an element in the Big search box and clicking on that element
// Using the DataProvider annotation
package BasePackage;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class BigSearchBox extends BaseTest{
@Test(dataProvider="searchtext")
public void BigSearchBox_Search(String a, String b) {
try {
WebElement dd = driver.findElement(By.xpath("//input[@autocomplete='off']"));
WebDriverWait wait = new WebDriverWait (driver, 10);
wait.until(ExpectedConditions.visibilityOf(dd));
dd.sendKeys(a);
Thread.sleep(3000);
List<WebElement> search_list = driver.findElements(By.xpath("//div[@class='_3f1M']/ul[1]/li/span"));
System.out.println(search_list.size());
for (int i=0; i<search_list.size();i++)
{
System.out.println(search_list.get(i).getText()); //Printing the elements in the list
if (search_list.get(i).getText().equalsIgnoreCase(b)) {
search_list.get(i).click(); //Clicking a specific element in the list
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@DataProvider
public Object[][] searchtext() {
return new Object[][] {{"Nokia","Nokia Smartphones" }};
}
}
|
package Lithe_Data;
import android.graphics.Bitmap;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class GateWay {
private DataOutputStream toServer;
private DataInputStream fromServer;
private Socket socket;
private String MessagefromServer;
private String MessagetoServer;
public GateWay(){
}
// Return int 0 means connection failure; return int 1 means connection successful;
public int ConnectToServer(String username){
try{
socket = new Socket("143.44.77.220", 8007);
//socket = new Socket("143.44.76.222", 8007);
//socket = new Socket("localhost", 8007);
fromServer = new DataInputStream(socket.getInputStream());
toServer =new DataOutputStream(socket.getOutputStream());
toServer.writeUTF(username);
toServer.flush();
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
return 1;
}
catch(IOException ex){
System.out.println("failed to connect");
return 0;
}
}
//login
//to server:1.5%username///password
// 0. login error
// return: 1. “username not found”
// 2. “password incorrect”
// 3. “username and password matched”
// 4. ”login error”
public int Login(String UserName, String Password){
MessagetoServer="1.5%"+UserName+"///"+Password;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. username not found");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. password incorrect");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. username and password matched. Login success!");return 3;}
else if (MessagefromServer.equals("4"))
{System.out.println("4.login error");return 4;}
else{System.out.println("0.Fail to Login");return 0;}
}
catch(IOException ex){
System.out.println("0.Fail to Login");return 0;
}}
//create account
//username and display name will now set to be the same and permission will set to be 1
//username and lawrence e-mail are unique and cannot be changed once account is created
//display name can be changed by edit account
//to server: 1.1%username///password///lawrence_email
//return: 1.“create account success”
//2.“create account FAILURE. Username already exists.”
public int CreateAccount(String UserName, String Password,String LUEmail){
MessagetoServer="1.1%"+UserName+"///"+Password+"///"+LUEmail;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create account success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create account FAILURE. Username already exists");return 2;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//edit account
//to server: 1.2%username///name///contact_email///phone_number///self_bio///gender///lawrence_address
//return: 1.“edit account success”
// 2.“edit account error”
public int EditAccount(String UserName,String name,String ContactEmail, String PhoneNo, String selfBio,String Gender, String LUaddress,Bitmap Photo){
MessagetoServer="1.2%"+UserName+"///"+name+"///"+ContactEmail+"///"+PhoneNo+"///"+selfBio+"///"+Gender+"///"+LUaddress;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. edit account success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. edit account error");return 2;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//get user
//to server:1.6%username
//return:1.”password///lawrence_email///name///contact_email///phone_number///self_bio///gender///lawrence_address///permission_level”
// 2.”username not found”
// 3.”get user error”
public String GetUser(String Username){
MessagetoServer="1.6%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
if (MessagefromServer.equals("2"))return "ERROR";
if (MessagefromServer.equals("3"))return "ERROR";
System.out.println("Message from Server: "+MessagefromServer);
return MessagefromServer;
}
catch(IOException ex){
System.out.println("0.ERROR");return "ERROR";
}
}
//create post
// 2.1%type///posting_time///title///description///username///duration///status///price///quantity
// return:1.”create [post type] success”
// 2.”create [post type] error”
//3. “input error”
public int CreateListing(String title,String Description,String username,String duration,String ExpectedPrice,String quantity,Bitmap Photo){
MessagetoServer="2.1%1///"+title+"///"+Description+"///"+username+"///"+duration+"///1///"+ExpectedPrice+"///"+quantity;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create Listing success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create Listing error");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. input error");return 3;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//to server:2.1%2///title///description///username///duration///status///price///quantity
// return:1.”create [post type] success”
// 2.”create [post type] error”
//3. “input error”
public int CreateRequest(String title,String Description,String username,String duration,String Price,String quantity,Bitmap Photo){
MessagetoServer="2.1%2///"+title+"///"+Description+"///"+username+"///"+duration+"///1///"+Price+"///"+quantity;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create Request success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create Request error");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. input error");return 3;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//to server:2.1%3///title///description///username///duration///status///ticket_type///LostFoundLocation///LostFoundTime
// return:1.”create [post type] success”
// 2.”create [post type] error”
//3. “input error”
public int CreateTicket(String title,String Description,String username,String duration,String ticket_type,String LostFoundLocation,String LostFoundTime,Bitmap Photo){
MessagetoServer="2.1%3///"+title+"///"+Description+"///"+username+"///"+duration+"///1///"+ticket_type+"///"+LostFoundLocation+"///"+LostFoundTime;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create Ticket success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create Ticket error");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. input error");return 3;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//to Server: //2.1%4///title///description///username///duration///status///EventTime///EventLocation
// return:1.”create [post type] success”
// 2.”create [post type] error”
//3. “input error”
public int CreateEvent(String title,String Description,String username,String duration,String EventTime,String EventLocation,Bitmap Photo){
MessagetoServer="2.1%4///"+title+"///"+Description+"///"+username+"///"+duration+"///1///"+EventTime+"///"+EventLocation;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create Event success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create Event error");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. input error");return 3;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server ://2.1%5///title///description///username///duration///status///price///RideShareTime///RideShareDestination///RideShareStartingLocation///RideShareType///RideShareDuration
public int CreateRideShare(String title,String Description,String username,String duration,String Price,String RideShareTime,String RideShareDestination,String RideShareStartingLocation,String RideShareType,String RideShareDuration,Bitmap Photo){
MessagetoServer="2.1%5///"+title+"///"+Description+"///"+username+"///"+duration+"///1///"+Price+"///"+ RideShareTime+"///"+RideShareDestination+"///"+RideShareStartingLocation+"///"+RideShareType+"///"+RideShareDuration;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
//send photo
if(Photo!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
toServer.writeInt(byteArray.length);
if(byteArray.length>0)
toServer.write(byteArray);
toServer.flush();}
else{toServer.writeInt(0); toServer.flush();}
//end send photo
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1. create RideShare success");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2. create RideShare error");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3. input error");return 3;}
else{System.out.println("0.ERROR");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
// 1->2.3%1
// first return number of posts: int
// second return post X times:
// 1->post_id///posting_time///title///description///username///duration///status///price///quantity
public String[] GetPost(int postType){
String[] Listing;
MessagetoServer="2.3%"+postType;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Listing=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Listing[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Listing;
}
catch(IOException ex){
System.out.println("0.ERROR");return Listing=new String[10];
}
}
public String[] GetMyPost(String Username,int gettype){
String[] Listing;
MessagetoServer="3."+gettype+"%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Listing=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Listing[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Listing;
}
catch(IOException ex){
System.out.println("0.ERROR");return Listing=new String[10];
}
}
//To server:
// 4.1%username///newcontactname
public int addContact(String Username, String ContactName){
MessagetoServer="4.1%"+Username+"///"+ContactName;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Add Contact success ");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2.No such User ");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3.Contact has already existed");return 3;}
else{System.out.println("4.Server error");return 4;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
// 4.2%username///newcontactname
//delete a contact from contact list
public int deleteContact(String Username, String ContactName){
MessagetoServer="4.2%"+Username+"///"+ContactName;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Delete Contact success ");return 1;}
else if (MessagefromServer.equals("2"))
{System.out.println("2.No such Contact ");return 2;}
else if (MessagefromServer.equals("3"))
{System.out.println("3.Server error");return 3;}
else{System.out.println("0.Error");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}}
//To server:
// 4.3%username
public String[] GetContact(String Username){
String[] Contact;
MessagetoServer="4.3%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Contact=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Contact[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Contact;
}
catch(IOException ex){
System.out.println("0.ERROR");return Contact=new String[10];
}
}
//To server:
//4.4%sender///receiver///title///content
public int SendAMessage(String sender, String receiver,String title,String content){
MessagetoServer="4.4%"+sender+"///"+receiver+"///"+title+"///"+content;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Send Message success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Send Message fail, no such user ");return 2;}
else {System.out.println("3.Server error ");return 3;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
//4.5%username
//return N times ( MessageID////Sender///Receiver///title///Content//Time///receiver status///sender status )
public String[] GetSendMessage(String Username){
String[] SendMessage;
MessagetoServer="4.5%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
SendMessage=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
SendMessage[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return SendMessage;
}
catch(IOException ex){
System.out.println("0.ERROR");return SendMessage=new String[10];
}
}
//To server:
//4.6%username
//return N times ( MessageID////Sender///Receiver///title///Content//Time///receiver status///sender status )
public String[] GetReceivedMessage(String Username){
String[] ReceivedMessage;
MessagetoServer="4.6%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server:"+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
ReceivedMessage=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
ReceivedMessage[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return ReceivedMessage;
}
catch(IOException ex){
System.out.println("0.ERROR");return ReceivedMessage=new String[10];
}
}
//To server:
//4.7%MessageID///senderstatus
//return 1success,2 fail
public int EditMessageSenderStatus(int MessageID,int senderstatus){
MessagetoServer="4.7%"+MessageID+"///"+senderstatus;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.SenderStatus update success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.SenderStatus update fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
//4.8%MessageID///Receiverstatus
//return 1success,2 fail
public int EditMessageReceiverStatus(int MessageID,int receiverstatus){
MessagetoServer="4.8%"+MessageID+"///"+receiverstatus;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.ReceiverStatus update success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.ReceiverStatus update fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
//4.9%UserName
//return 1yes,2 no,3. error
public int CheckNewMessage(String Username){
MessagetoServer="4.9%"+Username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.user has new messages");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.user has no new messages");return 2;}
else {System.out.println("3.error ");return 3;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
//3.3%PostID
//Get offers by post ID
//return n times offer ( offer_id///username///time///description///type///quantity///status///price///item///other)
public String[] getOfferDetails(int PostID){
String[] Offer;
MessagetoServer="3.3%"+PostID;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server:"+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Offer=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Offer[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Offer;
}
catch(IOException ex){
System.out.println("0.ERROR");return Offer=new String[10];
}
}
//To server
////3.1%post_id///username///description///type///quantity///status///price///item///other
//return 1. success/ 2. fail
public int CreateOffer(int PostID, String Username, String description, int type, int quantity,int status, double price,String item,String other ){
MessagetoServer="3.1%"+PostID+"///"+Username+"///"+description+"///"+type+"///"+quantity+"///"+status+"///"+price+"///"+item+"///"+other;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Create Offer success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Create Offer fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:
//5.2%PostID
//Get Comment by post ID
//return n times offer ( comment_id///Owner///Text///time)
public String[] getCommentDetails(int PostID){
String[] Comment;
MessagetoServer="5.2%"+PostID;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server:"+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Comment=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Comment[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Comment;
}
catch(IOException ex){
System.out.println("0.ERROR");return Comment=new String[10];
}
}
//To server
////5.1%post_id///username///Text
//return 1. success/ 2. fail
public int CreateComment(int PostID, String Username, String Text ){
MessagetoServer="5.1%"+PostID+"///"+Username+"///"+Text;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Create Comment success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Create Comment fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server
///1.4%Username///NewPassword
//return 1. success/ 2. fail
public int ChangePassword(String Username, String NewPassword ){
MessagetoServer="1.4%"+Username+"///"+NewPassword;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.ChangePassword success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Change Password fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//SelectBestOffer
//3.2%offer_id
//1success 2fail
public int SelectBestOffer(int OfferID,int status){
MessagetoServer="3.2%"+OfferID+"///"+status;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.SelectBestOffer success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.SelectBestOffer fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server : 2.5%PostID
public byte[] getPostPhoto(int PostID){
MessagetoServer="2.5%"+PostID;
byte[] photoByte=null;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
int byteLength=fromServer.readInt();
System.out.println("Message from Server: "+byteLength);
if(byteLength>0){
photoByte=new byte[byteLength];
fromServer.readFully(photoByte,0,byteLength);
}
return photoByte;
}
catch(IOException ex){
System.out.println("0.ERROR");return photoByte;
}
}
//To server:5.3%CommentID
//return 1success,2 fail
public int DeleteComment(int CommentID){
MessagetoServer="5.3%"+CommentID;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Delete Comment success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Delete Comment fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:3.6%OfferID
//return 1success,2 fail
public int DeleteOffer(int OfferID){
MessagetoServer="3.6%"+OfferID;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Delete Offer success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Delete Offer fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//To server:2.2%OfferID
//return 1success,2 fail
public int DeletePost(int PostID){
MessagetoServer="2.2%"+PostID;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Delete Post success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Delete Post fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
//toserver: 1.8%Username
//Return FullName///Gender///SelfBio
public String GetOtherInfo(String Username){
MessagetoServer="1.8%"+ Username;
String result=null;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
result=MessagefromServer;
return result;
}
catch(IOException ex){
System.out.println("0.ERROR");return result;
}
}
//To server : 1.7%UserName
public byte[] getUserPhoto (String Username){
MessagetoServer="1.7%"+Username;
byte[] photoByte=null;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
int byteLength=fromServer.readInt();
System.out.println("Message from Server: "+byteLength);
if(byteLength>0){
photoByte=new byte[byteLength];
fromServer.readFully(photoByte,0,byteLength);
}
return photoByte;
}
catch(IOException ex){
System.out.println("0.ERROR");return photoByte;
}
}
//ToServer;2.6%KeyWord
public String[] GetPostBYKeyWord(String keyword){
String[] Listing;
MessagetoServer="2.6%"+keyword;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
int k=Integer.parseInt(MessagefromServer);
Listing=new String[k];
for(int i=0;i<k;i++)
{MessagefromServer=fromServer.readUTF();
Listing[i]= MessagefromServer;
System.out.println("Message from Server: "+MessagefromServer);}
return Listing;
}
catch(IOException ex){
System.out.println("0.ERROR");return Listing=new String[10];
}
}
//To server:1.9%Username
//return 1success,2 fail
public int DeleteUser(String username){
MessagetoServer="1.9%"+username;
try{
toServer.writeUTF(MessagetoServer);
toServer.flush();
System.out.println("Message to Server: "+MessagetoServer);
MessagefromServer=fromServer.readUTF();
System.out.println("Message from Server: "+MessagefromServer);
if (MessagefromServer.equals("1"))
{System.out.println("1.Delete User success ");return 1;}
if (MessagefromServer.equals("2"))
{System.out.println("2.Delete User fail");return 2;}
else {System.out.println("0.error ");return 0;}
}
catch(IOException ex){
System.out.println("0.ERROR");return 0;
}
}
public void end() throws IOException {
toServer.writeUTF("end");
toServer.flush();
socket.close();}
}
|
package com.hjc.java_common_tools.db.mysql.loaddata;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BulkLoadData2MySQL {
private Connection conn = null;
public static InputStream getTestDataInputStream() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 10; i++) {
for (int j = 0; j <= 1; j++) {
builder.append("8abc" + i);
builder.append("\t");
builder.append(4 + 1);
builder.append("\t");
builder.append(4 + 2);
builder.append("\t");
builder.append(4 + 3);
builder.append("\t");
builder.append(4 + 4);
builder.append("\t");
builder.append(4 + 5);
builder.append("\n");
}
}
System.out.println(builder.toString());
byte[] bytes = builder.toString().getBytes();
InputStream is = new ByteArrayInputStream(bytes);
return is;
}
/**
*
* load bulk data from InputStream to MySQL
*/
public int bulkLoadFromInputStream(String loadDataSql,
InputStream dataStream) throws SQLException {
if (dataStream == null) {
System.out.println("InputStream is null ,No data is imported");
return 0;
}
try {
conn = getConnection();
} catch (Exception e) {
e.printStackTrace();
}
PreparedStatement statement = conn.prepareStatement(loadDataSql);
int result = 0;
if (statement.isWrapperFor(com.mysql.jdbc.Statement.class)) {
com.mysql.jdbc.PreparedStatement mysqlStatement = statement
.unwrap(com.mysql.jdbc.PreparedStatement.class);
mysqlStatement.setLocalInfileInputStream(dataStream);
result = mysqlStatement.executeUpdate();
}
return result;
}
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/test";
String user = "root";
String password = "root";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void main(String[] args) {
String testSql = "LOAD DATA LOCAL INFILE 'datax_temp' IGNORE INTO TABLE test.test (a,b,c,d,e,f)";
InputStream dataStream = getTestDataInputStream();
BulkLoadData2MySQL dao = new BulkLoadData2MySQL();
try {
long beginTime = System.currentTimeMillis();
int rows = dao.bulkLoadFromInputStream(testSql, dataStream);
long endTime = System.currentTimeMillis();
System.out.println("importing " + rows
+ " rows data into mysql and cost " + (endTime - beginTime)
+ " ms!");
} catch (SQLException e) {
e.printStackTrace();
}
System.exit(1);
}
} |
package org.giveback.datastructures;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(JUnit4.class)
public class TrieTest {
private static final List<String> words = List.of("train", "trains",
"tramp", "ramp", "rage", "noise", "nose");
private Trie trie;
@Before
public void setUp() {
trie = new Trie();
for (var word : words) {
trie.insert(word);
}
}
@Test
public void rootHasThreeChildren() {
var node = trie.getRoot();
assertEquals(node.getChildren().size(), 3);
}
@Test(expected = IllegalArgumentException.class)
public void insert_emptyString_throwsError() {
trie.insert("");
}
@Test(expected = IllegalArgumentException.class)
public void insert_blankString_throwsError() {
trie.insert(" ");
}
@Test(expected = IllegalArgumentException.class)
public void insert_nullString_throwsError() {
trie.insert(null);
}
@Test
public void insert_recursively_success() {
trie.insertRec("rain");
assertTrue(trie.isWordPresent("rain"));
}
@Test
public void containsAllWordsInTheList() {
assertTrue(trie.isWordPresent("train"));
assertTrue(trie.isWordPresent("trains"));
assertTrue(trie.isWordPresent("tramp"));
assertTrue(trie.isWordPresent("ramp"));
assertTrue(trie.isWordPresent("rage"));
assertTrue(trie.isWordPresent("noise"));
assertTrue(trie.isWordPresent("nose"));
}
@Test
public void isWordPresent_forUnknownWord_returnsFalse() {
assertFalse(trie.isWordPresent("something"));
}
@Test
public void removesExistingWordSuccessfully() {
trie.remove("train");
assertFalse(trie.isWordPresent("train"));
}
@Test
public void removesExistingWord_pruneNode_Successfully() {
trie.remove("trains");
assertFalse(trie.isWordPresent("trains"));
assertTrue(trie.isWordPresent("train"));
}
@Test
public void findAndRemovesExistingWord_pruneNode_Successfully() {
trie.findAndRemove("trains");
assertFalse(trie.isWordPresent("trains"));
assertTrue(trie.isWordPresent("train"));
}
@Test(expected = IllegalArgumentException.class)
public void remove_emptyString_throwsException() {
trie.remove("");
}
@Test(expected = IllegalArgumentException.class)
public void remove_nonexistentString_throwsException() {
trie.remove("rain");
}
@Test(expected = IllegalArgumentException.class)
public void remove_partiallyMatchingShortString_throwsException() {
trie.remove("trai");
}
@Test(expected = IllegalArgumentException.class)
public void remove_partiallyMatchingLongString_throwsException() {
trie.remove("trainsa");
}
@Test(expected = IllegalArgumentException.class)
public void remove_blankString_throwsError() {
trie.remove(" ");
}
}
|
package wan.JavaFxTemplate;
import javafx.application.Application;
import javafx.stage.Stage;
import wan.JavaFxTemplate.utils.MyUtils;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
MyUtils.showMainStage(primaryStage,"测试模板","scene_main",null,600,400);
}
public static void main(String[] args) {
launch(args);
}
}
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
boolean time[]=new boolean[1000001];
for(;;)
{
int n=sc.nextInt();
int m=sc.nextInt();
if(n == 0 && m == 0)
break;
boolean conflict=false;
Arrays.fill(time,false);
for(int i=0;i<n;i++)
{
int s=sc.nextInt();
int e=sc.nextInt();
if(!conflict && !check(s,e,time))
conflict = true;
}
for(int i=0;i<m;i++)
{
int s=sc.nextInt();
int e=sc.nextInt();
int r=sc.nextInt();
while(!conflict && s < 1000000)
{
if(!check(s,e,time))
conflict = true;
s += r;
e =Math.min(e + r,1000000);
}
}
if(!conflict)
System.out.println("NO CONFLICT");
else
System.out.println("CONFLICT");
}
}
public static boolean check(int s,int e,boolean time[])
{
int i=0;
for(i = s; i < e; i++)
{
if(time[i])
return false;
time[i] = true;
}
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Servlet;
import DAO.ClienteDAO;
import DAO.ContaDAO;
import DAO.EmailDAO;
import DAO.EnderecoDAO;
import DAO.EstadoCivilDAO;
import DAO.FuncionarioDAO;
import DAO.LocalizacaoDAO;
import DAO.PessoaDAO;
import DAO.SexoDAO;
import DAO.TelefoneDAO;
import Modelo.ClienteModelo;
import Modelo.ContaModelo;
import Modelo.EmailModelo;
import Modelo.EnderecoModelo;
import Modelo.EstadoCivilModelo;
import Modelo.FuncionarioModelo;
import Modelo.LocalizacaoModelo;
import Modelo.PessoaModelo;
import Modelo.SexoModelo;
import Modelo.TelefoneModelo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.ConstantesProjecto;
/**
*
* @author azm
*/
@WebServlet(name = "FuncionarioServlet", urlPatterns = "/ServLet/FuncionarioServlet")
public class FuncionarioServlet extends HttpServlet
{
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType ("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter ())
{
String operacao = req.getParameter ("operacao");
String redirecionar = req.getParameter ("redirecionar");
if (operacao.equals ("Cadastrar"))
{
/*DAO*/
FuncionarioDAO funcionarioDAO = new FuncionarioDAO ();
ContaDAO contaDAO = new ContaDAO ();
EnderecoDAO enderecoDAO = new EnderecoDAO ();
LocalizacaoDAO localizacaoDAO = new LocalizacaoDAO ();
SexoDAO sexoDAO = new SexoDAO ();
EstadoCivilDAO estadoCivilDAO = new EstadoCivilDAO ();
TelefoneDAO telefoneDAO = new TelefoneDAO ();
EmailDAO emailDAO = new EmailDAO ();
PessoaDAO pessoaDAO = new PessoaDAO ();
/*Modelo*/
ContaModelo contaModelo = new ContaModelo ();
EnderecoModelo enderecoModelo = new EnderecoModelo ();
SexoModelo sexoModelo = new SexoModelo ();
EstadoCivilModelo estadoCivilModelo = new EstadoCivilModelo ();
TelefoneModelo telefoneModelo = new TelefoneModelo ();
EmailModelo emailModelo = new EmailModelo ();
PessoaModelo pessoaModelo = new PessoaModelo ();
FuncionarioModelo funcionarioModelo = new FuncionarioModelo ();
LocalizacaoModelo localizacaoModelo = new LocalizacaoModelo ();
String nome_usuario = req.getParameter ("nome_usuario");
String senha_usuario = req.getParameter ("senha_usuario");
int tipo_conta = ConstantesProjecto.FUNCIONARIO;
contaModelo.setNomeUsuario (nome_usuario);
contaModelo.setSenha_usuario (senha_usuario);
contaModelo.setTipo_conta_fk (tipo_conta);
contaDAO.inserirConta (contaModelo);
int conta_fk = contaDAO.getIDconta (contaModelo);
sexoModelo.setSexo_pk (Integer.parseInt (req.getParameter ("comboSexo").trim ()));
estadoCivilModelo.setEstado_civili_pk (Integer.parseInt (req.getParameter ("comboEstado_civil").trim ()));
telefoneModelo.setNumero (req.getParameter ("txtTelefone"));
emailModelo.setNome (req.getParameter ("txtEmail"));
String paisID = req.getParameter ("comboPais");
// localizacaoModelo.setLocalizacao_pk ("1");
String provinciaID = req.getParameter ("comboProvincia");
String MuniccipioID = req.getParameter ("comboMunicipio");
String ruaID = req.getParameter ("txtRua");
String numero_casaID = req.getParameter ("txtNumero_casa");
// System.out.println ("Servlet.ClienteServlet.service()" + localizacaoDAO.findLocalidade (MuniccipioID));
String nome = req.getParameter ("txtnome");
String data_nascimento = req.getParameter ("txtData_nascimento");
LocalizacaoModelo local = localizacaoDAO.findLocalidade (MuniccipioID);
enderecoModelo.setNumero_casa (numero_casaID);
enderecoModelo.setRua (ruaID);
enderecoModelo.setLocalizacaoModelo (local);
// System.out.println ("Servlet.ClienteServlet.service() ->"+enderecoModelo.toString ());
enderecoDAO.inserirEndereco (enderecoModelo);
telefoneDAO.inserirTelefone (telefoneModelo);
emailDAO.inserirEmail (emailModelo);
int sexoID = sexoModelo.getSexo_pk ();
int estado_civilID = estadoCivilModelo.getEstado_civili_pk ();
int telefoneID = telefoneDAO.pegarUltimoTelefone ();
int enderecoID = enderecoDAO.pegarUltimoEndereco ();
int emailID = emailDAO.pegarUltimoEmail ();
pessoaModelo.setNome (nome);
pessoaModelo.setData_nascimento (data_nascimento);
pessoaModelo.setSexo_fk (sexoDAO.getSexo_pk (sexoID));
pessoaModelo.setEstado_civil_fk (estadoCivilDAO.getEstadoCivil_pk (estado_civilID));
pessoaModelo.setEndereco_fk (enderecoDAO.getEndereco_pk (enderecoID));
pessoaModelo.setTelefone_fk (telefoneDAO.getTelefone (telefoneID));
pessoaModelo.setEmail_fk (emailDAO.getEmail_pk (emailID));
// System.out.println ("Servlet.ClienteServlet.service()" + pessoaModelo.toString ());
pessoaDAO.inserirPessoa (pessoaModelo);
int ultima_pessoa = pessoaDAO.getUltimaPessoa ();
int cboTipoFuncionario = Integer.parseInt (req.getParameter ("comboTipoFuncionario"));
funcionarioModelo.setTipo_funcionario_fk (cboTipoFuncionario);
funcionarioModelo.setPessoa_fk (ultima_pessoa);
funcionarioDAO.inserirFuncionario (funcionarioModelo);
// System.out.println ("Servlet.ClienteServlet.service()" + clienteModelo.toString ());
// imprime o nome do cliente que foi adicionado
out.println ("<html>");
out.println ("<body>");
out.println ("Funcionario " + pessoaModelo.getNome ()
+ " adicionado com sucesso");
out.println ("</body>");
out.println ("</html>");
resp.sendRedirect (redirecionar);
}
else if (operacao.equals ("eliminar"))
{
System.out.println ("Servlet.ClienteServlet.service()");
PessoaDAO pessoaDAO= new PessoaDAO ();
ClienteDAO clienteDAO = new ClienteDAO ();
ClienteModelo clienteModelo = new ClienteModelo ();
PessoaModelo pessoaModelo = new PessoaModelo ();
int cliente_id = pessoaDAO.getPessoa(Integer.parseInt (req.getParameter ("pessoa_fk")));
pessoaModelo.setPessoa_pk (cliente_id);
clienteModelo.setPessoa_fk (cliente_id);
clienteDAO.eliminarCliente (clienteModelo);
pessoaDAO.eliminarPessoa (pessoaModelo);
}
}
catch (ClassNotFoundException ex)
{
Logger.getLogger (ClienteServlet.class.getName ()).log (Level.SEVERE, null, ex);
}
catch (SQLException ex)
{
Logger.getLogger (ClienteServlet.class.getName ()).log (Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest (request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest (request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo ()
{
return "Short description";
}// </editor-fold>
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.console.views;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
public class ViewScrollPane extends JScrollPane implements AdjustmentListener {
private IViewComponent component;
public ViewScrollPane(View view) {
super((JComponent) view.getViewComponent());
this.component = view.getViewComponent();
JScrollBar sb = getVerticalScrollBar();
if (sb != null)
sb.addAdjustmentListener(this);
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if (e.getValueIsAdjusting()) {
component.setIgnorePaintRequests(true);
} else {
component.paintRegionChanged();
component.setIgnorePaintRequests(false);
component.revalidate();
component.repaint();
}
}
}
|
package com.school.sms.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="sms_customer")
public class Customer {
@Id
@GeneratedValue
@Column(name="customer_code")
private Integer customerCode;
@Column(name="customer_type")
private String customerType;
@Column(name="customer_name")
private String customerName;
@Column(name="address")
private String address;
@Column(name="pin")
private String pin;
@Column(name="phone")
private String phone;
@Column(name="contactPerson")
private String contactPerson;
@Column(name="tinNo")
private String tinNo;
@Column(name="dateOfCreation")
private String dateOfCreation;
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Customer){
if(((Customer)obj).getCustomerCode().equals(this.customerCode)){
return true;
}
}
return super.equals(obj);
}
public String getDateOfCreation() {
return dateOfCreation;
}
public void setDateOfCreation(String dateOfCreation) {
this.dateOfCreation = dateOfCreation;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getTinNo() {
return tinNo;
}
public void setTinNo(String tinNo) {
this.tinNo = tinNo;
}
public Integer getCustomerCode() {
return customerCode;
}
public void setCustomerCode(Integer customerCode) {
this.customerCode = customerCode;
}
}
|
package com.example.user.wordquiz;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Quiz5Flower extends AppCompatActivity {
private Button zinnia;
private Button allamanda;
private Button bougainvillea;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz5_flower);
zinnia = findViewById(R.id.zinnia_button);
zinnia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Quiz5Flower.this,MainActivityScore.class);
startActivity(intent);
}
});
allamanda = findViewById(R.id.allamanda_button);
allamanda.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
bougainvillea = findViewById(R.id.bougainvillea_button);
bougainvillea.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
|
/*
* Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.blausql.ui;
import com.github.blausql.core.Constants;
import com.github.blausql.core.preferences.ConfigurationRepository;
import com.github.blausql.core.preferences.LoadException;
import com.googlecode.lanterna.gui.component.EditArea;
import org.easymock.Capture;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.easymock.EasyMock.*;
@PrepareForTest({ConfigurationRepository.class, ConfigurationRepository.class})
public class MainMenuWindowTest extends BlauSQLTestCaseBase {
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Test
public void testQuit() {
Capture<MainMenuWindow> mainMenuWindowCapture = expectWindowIsShownCenter(MainMenuWindow.class);
expectApplicationExitRequest(0);
// --- REPLAY
replaySystemClasses();
invokeMain();
MainMenuWindow mainMenuWindow = mainMenuWindowCapture.getValue();
assertNotNull(mainMenuWindow);
pressEnterOn(getComponent(mainMenuWindow, "quitApplicationButton"));
// --- VERIFY
verifyCoreClasses();
}
@Test
public void testAbout() {
Capture<MainMenuWindow> mainMenuWindowCapture = expectWindowIsShownCenter(MainMenuWindow.class);
expectMessageBoxIsShown("About BlauSQL", Constants.ABOUT_TEXT);
// --- REPLAY
replaySystemClasses();
invokeMain();
MainMenuWindow mainMenuWindow = mainMenuWindowCapture.getValue();
assertNotNull(mainMenuWindow);
pressEnterOn(getComponent(mainMenuWindow, "aboutButton"));
// --- VERIFY
verifyCoreClasses();
}
@Test
public void testSetApplicationClasspathNormalCase() throws LoadException {
PowerMock.mockStatic(ConfigurationRepository.class);
ConfigurationRepository mockConfigurationRepository = createMock(ConfigurationRepository.class);
expect(ConfigurationRepository.getInstance()).andReturn(mockConfigurationRepository);
expect(mockConfigurationRepository.getClasspath())
.andReturn(new String[]{ "foo", "bar" });
Capture<MainMenuWindow> capturedMainMenuWindow = expectWindowIsShownCenter(MainMenuWindow.class);
Capture<SetClasspathWindow> capturedSetClasspathWindow = expectWindowIsShownCenter(SetClasspathWindow.class);
// --- REPLAY
PowerMock.replay(ConfigurationRepository.class);
replay(mockConfigurationRepository);
replaySystemClasses();
replay();
invokeMain();
MainMenuWindow mainMenuWindow = capturedMainMenuWindow.getValue();
assertNotNull(mainMenuWindow);
pressEnterOn(getComponent(mainMenuWindow, "setApplicationClasspathButton"));
SetClasspathWindow setClasspathWindow = capturedSetClasspathWindow.getValue();
assertNotNull(setClasspathWindow);
EditArea classpathEditArea = getComponent(setClasspathWindow, "classpathEditArea");
String classPathEntries = classpathEditArea.getData();
String expected = String.format("foo%sbar%s", LINE_SEPARATOR, LINE_SEPARATOR);
assertEquals(classPathEntries, expected);
// --- VERIFY
verifyCoreClasses();
PowerMock.verify(ConfigurationRepository.class);
verify(mockConfigurationRepository);
}
@Test
public void testSetApplicationClasspathEmpty() throws LoadException {
PowerMock.mockStatic(ConfigurationRepository.class);
ConfigurationRepository mockConfigurationRepository = createMock(ConfigurationRepository.class);
expect(ConfigurationRepository.getInstance()).andReturn(mockConfigurationRepository);
expect(mockConfigurationRepository.getClasspath())
.andReturn(new String[0]);
Capture<MainMenuWindow> capturedMainMenuWindow = expectWindowIsShownCenter(MainMenuWindow.class);
Capture<SetClasspathWindow> capturedSetClasspathWindow = expectWindowIsShownCenter(SetClasspathWindow.class);
// --- REPLAY
PowerMock.replay(ConfigurationRepository.class);
replay(mockConfigurationRepository);
replaySystemClasses();
replay();
invokeMain();
MainMenuWindow mainMenuWindow = capturedMainMenuWindow.getValue();
assertNotNull(mainMenuWindow);
pressEnterOn(getComponent(mainMenuWindow, "setApplicationClasspathButton"));
SetClasspathWindow setClasspathWindow = capturedSetClasspathWindow.getValue();
assertNotNull(setClasspathWindow);
EditArea classpathEditArea = getComponent(setClasspathWindow, "classpathEditArea");
String classPathEntries = classpathEditArea.getData();
assertEquals(classPathEntries, "");
// --- VERIFY
verifyCoreClasses();
PowerMock.verify(ConfigurationRepository.class);
verify(mockConfigurationRepository);
}
@Test
public void testSetApplicationClasspathLoadThrowsException() throws LoadException {
PowerMock.mockStatic(ConfigurationRepository.class);
ConfigurationRepository mockConfigurationRepository = createMock(ConfigurationRepository.class);
expect(ConfigurationRepository.getInstance()).andReturn(mockConfigurationRepository);
RuntimeException dummyException = new RuntimeException("Failed to fetch classpath repository");
expect(mockConfigurationRepository.getClasspath())
.andThrow(dummyException);
Capture<MainMenuWindow> capturedMainMenuWindow = expectWindowIsShownCenter(MainMenuWindow.class);
expectErrorMessageBoxIsShownFrom(dummyException);
// --- REPLAY
PowerMock.replay(ConfigurationRepository.class);
replay(mockConfigurationRepository);
replaySystemClasses();
replay();
invokeMain();
MainMenuWindow mainMenuWindow = capturedMainMenuWindow.getValue();
assertNotNull(mainMenuWindow);
pressEnterOn(getComponent(mainMenuWindow, "setApplicationClasspathButton"));
// --- VERIFY
verifyCoreClasses();
PowerMock.verify(ConfigurationRepository.class);
verify(mockConfigurationRepository);
}
}
|
package januaryChallenge2018;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
int side = 0;
Map<Integer, Integer> rectangleSide = new HashMap<Integer, Integer>();
boolean invalid = false;
for (int j = 0; j < 4; j++) {
side = scan.nextInt();
if (side <= 0) {
invalid = true;
break;
}
if (rectangleSide.containsKey(side)) {
int val = rectangleSide.get(side);
rectangleSide.put(side, ++val);
} else {
rectangleSide.put(side, 1);
}
}
if (rectangleSide.size() == 1) {
System.out.println("YES");
} else if (rectangleSide.size() == 2) {
if (invalid == true) {
System.out.println("NO");
} else {
boolean flag = true;
for (Entry<Integer, Integer> entry : rectangleSide.entrySet()) {
if (entry.getValue() != 2)
flag = false;
}
if (flag == true)
System.out.println("YES");
else
System.out.println("NO");
}
} else {
System.out.println("NO");
}
}
}
}
|
package aulaorientacaoobjeto.exercicio1;
public class Cliente extends Carro {
int idCliente;
String cpf;
String nome;
int cnh;
} |
public class Bool {
public static void main(String[] args) {
int temp = 26;
if(temp > 25){
System.out.println("Кондиционер включен");
}
temp = 26;
boolean hot = temp > 25;
if(hot ){
System.out.println("Кондиционер включен");
}
temp = 20;
hot = temp > 25;
if(!hot ){
System.out.println("Кондиционер выключен");
}
if (25 == 25){
System.out.println("Равно");
}
// Кондиционер включен
// Кондиционер включен
// Кондиционер выключен
temp = 40;
hot = temp > 25;
int time = 24;
boolean late = time >= 23;
if (!hot || late){ //false || true = true
System.out.println("Кондиционер выключен");
}
//Хоть и жарко, но поздно, поэтому выключен
if (!hot && late){ //false && true = false
System.out.println("Кондиционер выключен");
}
// Home work
int time1 = 17;
boolean late1 = time1 >= 23 || time1 <= 5;
boolean night = late1;
boolean goodWeather = true;
if (night) {
System.out.println("Sleep");
}
if (!night && goodWeather){
System.out.println("Go for a walk");
}
if (!night && !goodWeather){
System.out.println("Read a book");
}
//Go for a walk
//Ternary
int one = 10;
int two = 20;
String msg = one >= two ? "Number one greater than two" : "Number one less than or equal to two";
System.out.println(msg); // Number one less than or equal to two
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util.exceptions;
import util.ErrorMsgs;
/**
* @author Andriy Yednarovych
*/
public class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
public MyException(String msg, Exception e) {
super(msg, e);
treatException(e);
}
public MyException(Exception e) {
super(e);
treatException(e);
}
private void treatException(Exception e) {
ErrorMsgs.sysLogThis(e);
}
}
|
package com.example.ciccc_cirac.myapplication;
/**
* Created by CICCC-CIRAC on 7/4/2017.
*/
public class SecondActivity {
}
|
package artronics.gsdwn.node;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
public class SdwnNodeTest
{
Node aNode;
Node sameNode;
Node otherNode;
@Before
public void setUp() throws Exception
{
aNode = new SdwnNode(0);
sameNode = new SdwnNode(0);
otherNode = new SdwnNode(7);
}
@Test
public void test_all_equality_and_hash()
{
assertThat(aNode, equalTo(aNode));
assertThat(aNode, equalTo(sameNode));
assertNotEquals(aNode, otherNode);
assertThat(aNode.hashCode(), equalTo(aNode.hashCode()));
assertThat(aNode.hashCode(), equalTo(sameNode.hashCode()));
assertNotEquals(aNode.hashCode(), otherNode.hashCode());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.