text
stringlengths 10
2.72M
|
|---|
package net.asurovenko.netexam.ui.teacher_screen.edit_exam_questions;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import net.asurovenko.netexam.R;
import net.asurovenko.netexam.network.models.Exam;
import net.asurovenko.netexam.network.models.ExamReadyForm;
import net.asurovenko.netexam.network.models.Questions;
import net.asurovenko.netexam.ui.MainActivity;
import net.asurovenko.netexam.ui.base.BaseFragment;
import net.asurovenko.netexam.ui.teacher_screen.MainTeacherFragment;
import net.asurovenko.netexam.utils.ServerUtils;
import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class EditExamQuestionsFragment extends BaseFragment {
private Questions questions;
private String token;
private String title;
private int examId;
private int semester;
@Bind(R.id.question_recycler_view)
RecyclerView questionRecyclerView;
@Bind(R.id.exam_title)
TextView examTitle;
@Bind(R.id.exam_semester)
TextView examSemester;
@Bind(R.id.progress_bar)
ProgressBar progressBar;
@Bind(R.id.error_text)
TextView errorText;
@Bind(R.id.coordinator_layout)
CoordinatorLayout coordinatorLayout;
@Bind(R.id.save_or_setup_ready_btn)
Button saveOrSetupReadyBtn;
public static EditExamQuestionsFragment newInstance(Exam exam, String token) {
Bundle args = new Bundle();
args.putString(MainTeacherFragment.TOKEN_KEY, token);
args.putInt(MainTeacherFragment.EXAM_ID_KEY, exam.getId());
args.putString(MainTeacherFragment.EXAM_TITLE_KEY, exam.getName());
args.putInt(MainTeacherFragment.SEMESTER_KEY, exam.getSemester());
EditExamQuestionsFragment fragment = new EditExamQuestionsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(MainTeacherFragment.TOKEN_KEY, token);
outState.putInt(MainTeacherFragment.EXAM_ID_KEY, examId);
outState.putString(MainTeacherFragment.EXAM_TITLE_KEY, title);
outState.putInt(MainTeacherFragment.SEMESTER_KEY, semester);
outState.putString(MainTeacherFragment.QUESTIONS_KEY, MainActivity.GSON.toJson(questions));
super.onSaveInstanceState(outState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getData(savedInstanceState != null ? savedInstanceState : getArguments());
}
private void getData(Bundle bundle) {
token = bundle.getString(MainTeacherFragment.TOKEN_KEY);
examId = bundle.getInt(MainTeacherFragment.EXAM_ID_KEY);
title = bundle.getString(MainTeacherFragment.EXAM_TITLE_KEY);
semester = bundle.getInt(MainTeacherFragment.SEMESTER_KEY);
examTitle.setText(title);
examSemester.setText(String.valueOf(semester) + getString(R.string.semester_little_char));
if (bundle.containsKey(MainTeacherFragment.QUESTIONS_KEY)) {
questions = MainActivity.GSON.fromJson(bundle.getString(MainTeacherFragment.QUESTIONS_KEY), Questions.class);
completeLoadExamQuestions(questions);
} else {
loadExamQuestions();
}
}
private void loadExamQuestions() {
getNetExamApi().getQuestions(token, examId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::completeLoadExamQuestions, this::errorLoad);
}
private void errorLoad(Throwable error) {
errorLoadWithoutErrorText(error);
errorText.setVisibility(View.VISIBLE);
}
private void errorLoadWithoutErrorText(Throwable error) {
showSnackBar(ServerUtils.getMsgId(error));
progressBar.setVisibility(View.GONE);
hideProgressBar();
}
private void completeLoadExamQuestions(Questions questions) {
this.questions = questions;
progressBar.setVisibility(View.GONE);
questionRecyclerView.setVisibility(View.VISIBLE);
setupExpandableRecyclerView(questions);
}
private ExamQuestionsAdapter examQuestionsAdapter;
private void setupExpandableRecyclerView(Questions questions) {
RecyclerViewExpandableItemManager expMgr = new RecyclerViewExpandableItemManager(null);
questionRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
examQuestionsAdapter = new ExamQuestionsAdapter(this, coordinatorLayout, questions);
questionRecyclerView.setAdapter(expMgr.createWrappedAdapter(examQuestionsAdapter));
((SimpleItemAnimator) questionRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
expMgr.attachRecyclerView(questionRecyclerView);
}
@OnClick(R.id.add_fab)
public void addQuestionFabClick() {
examQuestionsAdapter.hideSnackBar();
examQuestionsAdapter.addNewQuestion();
}
private AlertDialog setupReadyExamAlertDialog;
@OnClick(R.id.save_or_setup_ready_btn)
public void saveOrSetupReadyBtnClick() {
if (examQuestionsAdapter.isChanged()) {
examQuestionsAdapter.hideSnackBar();
showProgressBar(getString(R.string.wait), ProgressDialog.STYLE_SPINNER);
sendQuestions();
} else {
if (setupReadyExamAlertDialog == null) {
setupAlertDialogSendStateExam();
}
setupReadyExamAlertDialog.show();
}
}
private void setupAlertDialogSendStateExam() {
View alertDialogView = LayoutInflater.from(getContext())
.inflate(R.layout.setup_ready_exam_view, null);
EditText countExamQuestionsEditText = (EditText) alertDialogView.findViewById(R.id.count_exam_questions);
EditText examTimeEditText = (EditText) alertDialogView.findViewById(R.id.exam_time);
setupReadyExamAlertDialog = new AlertDialog.Builder(getContext())
.setTitle(getString(R.string.setup_ready_exam))
.setCancelable(false)
.setView(alertDialogView)
.setNegativeButton(getString(R.string.ok), (dialog, which) -> {
if (countExamQuestionsEditText.getText().toString().isEmpty()) {
countExamQuestionsEditText.setError(getString(R.string.cannot_be_empty_field));
return;
}
if (examTimeEditText.getText().toString().isEmpty()) {
examTimeEditText.setError(getString(R.string.cannot_be_empty_field));
return;
}
showProgressBar(getString(R.string.wait), ProgressDialog.STYLE_SPINNER);
sendStateExamReady(countExamQuestionsEditText, examTimeEditText);
})
.setPositiveButton(getString(R.string.cancel), null)
.create();
}
private void sendStateExamReady(EditText countExamQuestionsEditText, EditText examTimeEditText) {
getNetExamApi().sendStateExamReady(token, examId,
new ExamReadyForm(
Integer.parseInt(countExamQuestionsEditText.getText().toString()),
Integer.parseInt(examTimeEditText.getText().toString())))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::completeSendStateExam, this::errorLoadWithoutErrorText);
}
private void completeSendStateExam(ResponseBody responseBody) {
hideProgressBar();
getActivity().onBackPressed();
}
private void sendQuestions() {
getNetExamApi().sendQuestions(token, examId, examQuestionsAdapter.getQuestions())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::completeSendQuestions, this::errorLoadWithoutErrorText);
}
public void setSaveOrSetupReadyBtnText(int idText) {
saveOrSetupReadyBtn.setText(getString(idText));
}
private void completeSendQuestions(Questions questions) {
hideProgressBar();
examQuestionsAdapter.setChange(false);
saveOrSetupReadyBtn.setText(getString(R.string.setup_ready));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_edit_exam_questions, container, false);
}
}
|
package com.kzw.leisure.event;
/**
* author: kang4
* Date: 2019/12/5
* Description:
*/
public class AddBookEvent {
private String msg;
public AddBookEvent( ) {
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
|
package com.example.webproject.models.util;
import lombok.Data;
@Data
public class EditedRecipe {
private String id;
private String title;
private String ingredients;
private String instructions;
public EditedRecipe(){};
public EditedRecipe(String id, String title, String ingredients, String instructions){
this.id = id;
this.title = title;
this.ingredients = ingredients;
this.instructions = instructions;
}
}
|
package com.t.s.model.dto;
import java.util.Date;
public class GroupDto {
//테이블 명 GROUPINFO
private int groupno;
private String grouptitle;
private String groupcontent;
private Date groupregdate;
private String groupimg;
public GroupDto() {
//super();
}
//파라미터 포함된 생성자는 만들어서 사용하세요 말씀해주시고요
public GroupDto(int groupno, String grouptitle, String groupcontent, Date groupregdate, String groupimg) {
super();
this.groupno = groupno;
this.grouptitle = grouptitle;
this.groupcontent = groupcontent;
this.groupregdate = groupregdate;
this.groupimg = groupimg;
}
public int getGroupno() {
return groupno;
}
public void setGroupno(int groupno) {
this.groupno = groupno;
}
public String getGrouptitle() {
return grouptitle;
}
public void setGrouptitle(String grouptitle) {
this.grouptitle = grouptitle;
}
public String getGroupcontent() {
return groupcontent;
}
public void setGroupcontent(String groupcontent) {
this.groupcontent = groupcontent;
}
public Date getGroupregdate() {
return groupregdate;
}
public void setGroupredate(Date groupregdate) {
this.groupregdate = groupregdate;
}
public String getGroupimg() {
return groupimg;
}
public void setGroupimg(String groupimg) {
this.groupimg = groupimg;
}
}
|
package controllerTest;
import static org.junit.Assert.assertEquals;
import com.task19.jxmall.JxmallApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = JxmallApplication.class)
public class HelloControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void shouldSayAnotherHelloWorld() {
String result = restTemplate.getForObject("/hello", String.class);
assertEquals("hello", result);
}
}
|
package com.ssafy.java;
public class AlpaTest2 {
public static void main(String[] args) {
/*char alpa = 'A';
for(int i =0;i<5;i++) {
String line ="";
String blank="";
for (int j = 0; j < 5 ; j++) {
if(j==0){
line += alpa;
alpa+=1;
}else if(j<=i) {
line += (" " + alpa);
alpa+=1;
}
else {
blank += " ";
}
}
System.out.println(blank + line);
}
System.out.println();
*/
char alpha = 'A';
for(int i =0;i<5;++i) {
for(int j=4;j>=0;--j) {
if(j>i) {
System.out.printf("%3s", " ");
}else {
System.out.printf("%3c",alpha++);
}
}
System.out.println();
}
}
}
|
package com.gxj.controller;
import com.gxj.pojo.User;
import com.gxj.service.UserService;
import com.gxj.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 登陆
* @param user
* @param session
* @return
*/
@RequestMapping("/login")
public Result login(@RequestBody User user, HttpSession session){
try {
User loginUser = userService.login(user);
session.setAttribute("user",loginUser);
return new Result(true,"登陆成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false,"登陆失败");
}
}
/**
* 显示用户信息
* @param session
* @return
*/
@RequestMapping("/getUserInfo")
public User getUserInfo(HttpSession session){
User user = (User) session.getAttribute("user");
return user;
}
/**
* 更新
* @param user
* @return
*/
@RequestMapping("/update")
public Result update(@RequestBody User user){
try {
userService.update(user);
return new Result(true,"保存成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false,"保存失败");
}
}
}
|
package com.example.illuminate_me;
import android.content.Context;
import com.nuance.speechkit.Audio;
import com.nuance.speechkit.AudioPlayer;
import com.nuance.speechkit.Language;
import com.nuance.speechkit.Session;
import com.nuance.speechkit.Transaction;
import com.nuance.speechkit.TransactionException;
import com.nuance.speechkit.Voice;
public class Illustrate implements AudioPlayer.Listener{
private Session speechSession;
private Transaction ttsTransaction;
private Illustrate.State state = Illustrate.State.IDLE;
private String voice ="Tarik";
private Context context;
private String text;
public Illustrate(String tts, Context context) {
this.context=context;
this.text=tts;
//Create a session
speechSession = Session.Factory.session(context, Configuration.SERVER_URI, Configuration.APP_KEY);
speechSession.getAudioPlayer().setListener(this);
setState(Illustrate.State.IDLE);
// startSynthesize();
}
public void startSynthesize() {
toggleTTS();
}
private void toggleTTS() {
switch (state) {
case IDLE:
//If we are not loading TTS from the server, then we should do so.
if(ttsTransaction == null) {
// toggleTTS.setText(getResources().getString(R.string.cancel));
synthesize();
}
//Otherwise lets attempt to cancel that transaction
else {
cancel();
}
break;
case PLAYING:
speechSession.getAudioPlayer().pause();
setState(Illustrate.State.PAUSED);
break;
case PAUSED:
speechSession.getAudioPlayer().play();
setState(Illustrate.State.PLAYING);
break;
}
}
public void synthesize() {
//Setup our TTS transaction options.
Transaction.Options options = new Transaction.Options();
options.setLanguage(new Language(Configuration.LANGUAGE));
options.setVoice(new Voice(voice)); //optionally change the Voice of the speaker, but will use the default if omitted.
//System.out.print(ttsText.getText().toString());
//Start a TTS transaction
ttsTransaction = speechSession.speakString(text, options, new Transaction.Listener() {
//ttsTransaction = speechSession.speakString("hello my name is lulu", options, new Transaction.Listener() {
@Override
public void onAudio(Transaction transaction, Audio audio) {
// logs.append("\nonAudio");
//The TTS audio has returned from the server, and has begun auto-playing.
ttsTransaction = null;
// toggleTTS.setText(getResources().getString(R.string.speak_string));
}
@Override
public void onSuccess(Transaction transaction, String s) {
// logs.append("\nonSuccess");
//Notification of a successful transaction. Nothing to do here.
}
@Override
public void onError(Transaction transaction, String s, TransactionException e) {
// logs.append("\nonError: " + e.getMessage() + ". " + s);
//Something went wrong. Check Configuration.java to ensure that your settings are correct.
//The user could also be offline, so be sure to handle this case appropriately.
ttsTransaction = null;
}
});
}
/**
* Cancel the TTS transaction.
* This will only cancel if we have not received the audio from the server yet.
*/
private void cancel() {
ttsTransaction.cancel();
}
@Override
public void onBeginPlaying(AudioPlayer audioPlayer, Audio audio) {
// logs.append("\nonBeginPlaying");
//The TTS Audio will begin playing.
setState(Illustrate.State.PLAYING);
}
@Override
public void onFinishedPlaying(AudioPlayer audioPlayer, Audio audio) {
// logs.append("\nonFinishedPlaying");
//The TTS Audio has finished playing
setState(Illustrate.State.IDLE);
}
private enum State {
IDLE,
PLAYING,
PAUSED
}
/**
* Set the state and update the button text.
*/
private void setState(Illustrate.State newState) {
state = newState;
switch (newState) {
case IDLE:
// Next possible action is speaking
// toggleTTS.setText(getResources().getString(R.string.speak_string));
break;
case PLAYING:
// Next possible action is pausing
// toggleTTS.setText(getResources().getString(R.string.pause));
break;
case PAUSED:
// Next possible action is resuming the speech
// toggleTTS.setText(getResources().getString(R.string.speak_string));
break;
}
}
}
|
package ua.nure.timoshenko.summaryTask4.web.command.client;
import org.apache.log4j.Logger;
import ua.nure.timoshenko.summaryTask4.Path;
import ua.nure.timoshenko.summaryTask4.db.DBManager;
import ua.nure.timoshenko.summaryTask4.db.bean.OrderBean;
import ua.nure.timoshenko.summaryTask4.db.entity.User;
import ua.nure.timoshenko.summaryTask4.web.command.Command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* Personal account command.
*
* @author L.Timoshenko
*
*/
public class PersonalAccountCommand extends Command {
private static final long serialVersionUID = 5288269143051697851L;
private static final Logger LOG = Logger
.getLogger(PersonalAccountCommand.class);
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Command starts");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (!(user == null)) {
List<OrderBean> orderBeans = DBManager.getInstance()
.getAllOrderBeansByUser(user);
request.setAttribute("orderBeans", orderBeans);
LOG.trace("Set the request attribute: orderBeans --> " + orderBeans);
}
LOG.debug("Command finished");
return Path.PAGE_PERSONAL_ACCOUNT;
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import com.tencent.mm.modelvideo.r;
import com.tencent.mm.modelvideo.t;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.chatting.viewitems.ai.d;
import java.lang.ref.WeakReference;
class ai$d$1 implements Runnable {
final /* synthetic */ r tWJ;
ai$d$1(r rVar) {
this.tWJ = rVar;
}
public final void run() {
WeakReference weakReference = (WeakReference) d.ajb().get(this.tWJ.getFileName());
if (weakReference == null) {
x.w("MicroMsg.VideoItemHoder", "update status, filename %s, holder not found", new Object[]{this.tWJ.getFileName()});
return;
}
d dVar = (d) weakReference.get();
if (dVar == null) {
x.w("MicroMsg.VideoItemHoder", "update status, filename %s, holder gc!", new Object[]{this.tWJ.getFileName()});
return;
}
dVar.tZR.setVisibility(8);
dVar.nEI.setVisibility(8);
dVar.uex.setVisibility(0);
int i = this.tWJ.status;
x.i("MicroMsg.VideoItemHoder", "updateStatus videoStatus : " + i);
if (i == 112 || i == 122 || i == 120) {
dVar.uex.setProgress(t.f(this.tWJ));
} else {
dVar.uex.setProgress(t.g(this.tWJ));
}
}
}
|
package com.sky.weixin.ParamesAPI.util;
/**
* @author Engineer-Jsp
* @date 2014.09.23
* 参数API类*/
public class ParamesAPI {
// token
public static String token = "WeiXinEnterprises";
// 随机戳
public static String encodingAESKey = "tw8ColhrtDzU6XTHJ2shUeTyuaPQkSzdvD8jYtnTIYf";
//你的企业号ID
public static String corpId = "wx3749dc2eafb7bbbc";
// 管理组的凭证密钥,每个secret代表了对应用、通讯录、接口的不同权限;不同的管理组拥有不同的secret
public static String secret = "D3ZJ9tvoACM_RDQayo0k_kYv3okZGUGfQu2tz6SSnpY";
// OAuth2 回调地址
public static String REDIRECT_URI = "";
//企业应用ID
public static String agentid = "0";
public String checkCorpIdAndSecret(){
return null;
}
public static String getCorpId() {
return corpId;
}
public static void setCorpId(String corpId) {
ParamesAPI.corpId = corpId;
}
public static String getSecret() {
return secret;
}
public static void setSecret(String secret) {
ParamesAPI.secret = secret;
}
public static String getAgentid() {
return agentid;
}
public static void setAgentid(String agentid) {
ParamesAPI.agentid = agentid;
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ev extends g {
public c$ev() {
super("openGameCenter", "openGameCenter", 175, true);
}
}
|
/**
*
*/
package io.github.liuzm.distribute.common.zookeeper;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.liuzm.distribute.common.config.Config;
/**
*
* @author xh-liuzhimin
*
*/
public class ZkClient {
private final Logger logger = LoggerFactory.getLogger(ZkClient.class);
private CuratorFramework zkClient;
private static final ConcurrentMap<String,ZkClient> clientCache = new ConcurrentHashMap();
public ZkClient(CuratorFramework zkClient){
this.zkClient = zkClient;
this.zkClient.start();
}
public static final synchronized ZkClient getClient(String connectionStr){
ZkClient zkClient = clientCache.get(connectionStr);
if(zkClient == null){
final CuratorFramework curatorFramework = newZkClient(connectionStr);
zkClient = new ZkClient(curatorFramework);
final ZkClient previous = clientCache.put(connectionStr, zkClient);
if(previous!=null){//如果包含了,则关闭连接
previous.getCuratorClient().close();
}
}
return zkClient;
}
/**
* 为节点添加单个watch,如果已经存在,则不添加
*
* @throws Exception
*/
public synchronized void childrenSingleWatch(String path, CuratorWatcher watcher){
if(!checkChildrenWatcher(path)){
try{
zkClient.getChildren().usingWatcher(watcher).forPath(path);
}catch(Exception e){
if(!checkChildrenWatcher(path)){
try{
zkClient.getChildren().usingWatcher(watcher).forPath(path);
}catch(Exception e1){
logger.error("ex", e);
}
}
}
}else{
logger.warn("path="+path+" hased children watch,add watch canel");
}
}
/**
* 获取节点下的子节点
*
* @param path
* @return
*/
public List<String> getChildByPath(String path){
List<String> list = null ;
try {
list = zkClient.getChildren().forPath(path);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 检查该节点是否存在 child 节点
*/
public boolean checkChildrenWatcher(String path){
try{
//ZooKeeper zoo = zkClient.getZookeeperClient().getZooKeeper();
//List<String> dataWatches = zoo.getChildWatches();
//return dataWatches.contains(path);
}catch(Exception e){
logger.error("exceprion", e);
}
return false;
}
/**
* 获取第一个client nodeid
* @return
*/
public String getRandomClientNodeId(){
try{
List<String> clients = getChildByPath(Config.ZKPath.REGISTER_CLIENT_PATH);
return clients.get(0);
}catch(Exception e){
logger.error("random get node not extists exceprion", e);
}
return null;
}
/**
* 获取CuratorFramework
* @return
*/
public final CuratorFramework getCuratorClient(){
return zkClient;
}
/**
* 根据链接地址来生成一个新的链接对象 </br>
*
* xh-liuzhimin
* @param connectionString
* @return
*/
private static final CuratorFramework newZkClient(String connectionString){
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
return curatorFramework;
}
}
|
package com.tencent.mm.boot.svg.a.a;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.os.Looper;
import com.tencent.mm.svg.WeChatSVGRenderC2Java;
import com.tencent.mm.svg.c;
import com.tencent.smtt.sdk.TbsListener$ErrorCode;
public final class aat extends c {
private final int height = 96;
private final int width = 96;
protected final int b(int i, Object... objArr) {
switch (i) {
case 0:
return 96;
case 1:
return 96;
case 2:
Canvas canvas = (Canvas) objArr[0];
Looper looper = (Looper) objArr[1];
Matrix f = c.f(looper);
float[] e = c.e(looper);
Paint i2 = c.i(looper);
i2.setFlags(385);
i2.setStyle(Style.FILL);
Paint i3 = c.i(looper);
i3.setFlags(385);
i3.setStyle(Style.STROKE);
i2.setColor(-16777216);
i3.setStrokeWidth(1.0f);
i3.setStrokeCap(Cap.BUTT);
i3.setStrokeJoin(Join.MITER);
i3.setStrokeMiter(4.0f);
i3.setPathEffect(null);
c.a(i3, looper).setStrokeWidth(1.0f);
i3 = c.a(i2, looper);
i3.setColor(-14046139);
Path j = c.j(looper);
j.moveTo(0.0f, 0.0f);
j.lineTo(96.0f, 0.0f);
j.lineTo(96.0f, 96.0f);
j.lineTo(0.0f, 96.0f);
j.lineTo(0.0f, 0.0f);
j.close();
canvas.saveLayerAlpha(null, 0, 4);
canvas.drawPath(j, c.a(i3, looper));
canvas.restore();
canvas.save();
Paint a = c.a(i2, looper);
a.setColor(-16777216);
e = c.a(e, 1.0f, 0.0f, 12.0f, 0.0f, 1.0f, 12.0f);
f.reset();
f.setValues(e);
canvas.concat(f);
canvas.saveLayerAlpha(null, TbsListener$ErrorCode.APK_INVALID, 4);
canvas.save();
Paint a2 = c.a(a, looper);
Path j2 = c.j(looper);
j2.moveTo(20.25f, 36.0f);
j2.cubicTo(20.25f, 38.89905f, 17.89905f, 41.25f, 15.0f, 41.25f);
j2.cubicTo(12.10095f, 41.25f, 9.75f, 38.89905f, 9.75f, 36.0f);
j2.cubicTo(9.75f, 33.0999f, 12.10095f, 30.75f, 15.0f, 30.75f);
j2.cubicTo(17.89905f, 30.75f, 20.25f, 33.0999f, 20.25f, 36.0f);
j2.close();
j2.moveTo(36.0f, 30.75f);
j2.cubicTo(38.89905f, 30.75f, 41.25f, 33.0999f, 41.25f, 36.0f);
j2.cubicTo(41.25f, 38.89905f, 38.89905f, 41.25f, 36.0f, 41.25f);
j2.cubicTo(33.10095f, 41.25f, 30.75f, 38.89905f, 30.75f, 36.0f);
j2.cubicTo(30.75f, 33.0999f, 33.10095f, 30.75f, 36.0f, 30.75f);
j2.close();
j2.moveTo(57.0f, 30.75f);
j2.cubicTo(59.89905f, 30.75f, 62.25f, 33.0999f, 62.25f, 36.0f);
j2.cubicTo(62.25f, 38.89905f, 59.89905f, 41.25f, 57.0f, 41.25f);
j2.cubicTo(54.10095f, 41.25f, 51.75f, 38.89905f, 51.75f, 36.0f);
j2.cubicTo(51.75f, 33.0999f, 54.10095f, 30.75f, 57.0f, 30.75f);
j2.close();
WeChatSVGRenderC2Java.setFillType(j2, 2);
canvas.drawPath(j2, a2);
canvas.restore();
canvas.restore();
canvas.restore();
c.h(looper);
break;
}
return 0;
}
}
|
package com.vilio.nlbs.commonMapper.pojo;
import java.io.Serializable;
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.ParseException;
/**
* @实体名称 待办任务列表
* @数表名称 NLBS_TODO
* @开发日期 2017-06-20
* @技术服务 www.fwjava.com
*/
public class NlbsTodo implements Serializable {
/**
* 数据主键(必填项)(主键ID)
*/
private Integer id = null;
/**
* 任务创建时间(分配时间)
*/
private Date dateCreated = null;
/**
* 待办任务详情
*/
private String content = null;
/**
* 待办任务类型
*/
private String todoType = null;
/**
* 待处理人
*/
private String userNo = null;
/**
* 询价系统序列号
*/
private String bpsCode = null;
/**
* 排序
*/
private String orderBy = null;
/*
*--------------------------------------------------
* Getter方法区
*--------------------------------------------------
*/
/**
* 数据主键(必填项)(主键ID)
*/
public Integer getId() {
return id;
}
/**
* 任务创建时间(分配时间)
*/
public Date getDateCreated() {
return dateCreated;
}
/**
* 待办任务详情
*/
public String getContent() {
return trim(content);
}
/**
* 待办任务类型
*/
public String getTodoType() {
return trim(todoType);
}
/**
* 待处理人
*/
public String getUserNo() {
return trim(userNo);
}
/**
* 询价系统序列号
*/
public String getBpsCode() {
return trim(bpsCode);
}
/**
* 排序
*/
public String getOrderBy() {
return trim(orderBy);
}
/*
*--------------------------------------------------
* Setter方法区
*--------------------------------------------------
*/
/**
* 数据主键(必填项)(主键ID)
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 任务创建时间(分配时间)
*/
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* 待办任务详情
*/
public void setContent(String content) {
this.content = content;
}
/**
* 待办任务类型
*/
public void setTodoType(String todoType) {
this.todoType = todoType;
}
/**
* 待处理人
*/
public void setUserNo(String userNo) {
this.userNo = userNo;
}
/**
* 询价系统序列号
*/
public void setBpsCode(String bpsCode) {
this.bpsCode = bpsCode;
}
/**
* 排序
*/
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
/*
*--------------------------------------------------
* 常用自定义字段
*--------------------------------------------------
*/
/**
* 任务创建时间(分配时间)(格式化)
*/
public String getDateCreatedChar() {
return getDate(dateCreated);
}
public void setDateCreatedChar(String dateCreatedChar) {
this.dateCreated = getDate(dateCreatedChar);
}
/**
* 任务创建时间(分配时间)(格式化)
*/
public String getDateCreatedCharAll() {
return getDateTime(dateCreated);
}
public void setDateCreatedCharAll(String dateCreatedCharAll) {
this.dateCreated = getDate(dateCreatedCharAll);
}
/*
*--------------------------------------------------
* 应用小方法
*--------------------------------------------------
*/
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
public String trim(String input)
{
return input==null?null:input.trim();
}
public String getDate(Date date)
{
if( null == date ) return "";
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
public String getDateTime(Date date)
{
if( null == date ) return "";
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
public Date getDate(String date)
{
if( null == date || date.trim().isEmpty() ) return null;
date = date.trim();
Date result = null;
try {
if( date.length() >= 19 )
{
result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
}
else if( date.length() == 10 )
{
result = new SimpleDateFormat("yyyy-MM-dd").parse(date);
}
}
catch (ParseException e)
{
}
return result;
}
}
/**
------------------------------------------------------
Copy专用区
------------------------------------------------------
------------------------------------------------------------------------------------------------------------
Setter方法
------------------------------------------------------------------------------------------------------------
// 待办任务列表
NlbsTodo nlbsTodo = new NlbsTodo();
// 数据主键(必填项)(主键ID)
nlbsTodo.setId( );
// 任务创建时间(分配时间)
nlbsTodo.setDateCreated( );
// 待办任务详情
nlbsTodo.setContent( );
// 待办任务类型
nlbsTodo.setTodoType( );
// 待处理人
nlbsTodo.setUserNo( );
// 询价系统序列号
nlbsTodo.setBpsCode( );
//------ 自定义部分 ------
// 任务创建时间(分配时间)(格式化)
nlbsTodo.setDateCreatedChar( );
------------------------------------------------------------------------------------------------------------
Getter方法
------------------------------------------------------------------------------------------------------------
// 待办任务列表
NlbsTodo nlbsTodo = new NlbsTodo();
// 数据主键(必填项)(主键ID)
nlbsTodo.getId();
// 任务创建时间(分配时间)
nlbsTodo.getDateCreated();
// 待办任务详情
nlbsTodo.getContent();
// 待办任务类型
nlbsTodo.getTodoType();
// 待处理人
nlbsTodo.getUserNo();
// 询价系统序列号
nlbsTodo.getBpsCode();
//------ 自定义部分 ------
// 任务创建时间(分配时间)(格式化)
nlbsTodo.getDateCreatedChar();
------------------------------------------------------------------------------------------------------------
Getter Setter方法
------------------------------------------------------------------------------------------------------------
// 待办任务列表
NlbsTodo nlbsTodo = new NlbsTodo();
// 数据主键(必填项)(主键ID)
nlbsTodo.setId( nlbsTodo2.getId() );
// 任务创建时间(分配时间)
nlbsTodo.setDateCreated( nlbsTodo2.getDateCreated() );
// 待办任务详情
nlbsTodo.setContent( nlbsTodo2.getContent() );
// 待办任务类型
nlbsTodo.setTodoType( nlbsTodo2.getTodoType() );
// 待处理人
nlbsTodo.setUserNo( nlbsTodo2.getUserNo() );
// 询价系统序列号
nlbsTodo.setBpsCode( nlbsTodo2.getBpsCode() );
//------ 自定义部分 ------
// 任务创建时间(分配时间)(格式化)
nlbsTodo.setDateCreatedChar( nlbsTodo2.getDateCreatedChar() );
------------------------------------------------------------------------------------------------------------
HTML标签区
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
属性区
------------------------------------------------------------------------------------------------------------
<!-- 数据主键 -->
<input name="id" value="" type="text" maxlength="11"/>
<!-- 任务创建时间(分配时间) -->
<input name="dateCreated" value="" type="text"/>
<!-- 待办任务详情 -->
<input name="content" value="" type="text" maxlength="255"/>
<!-- 待办任务类型 -->
<input name="todoType" value="" type="text" maxlength="3"/>
<!-- 待处理人 -->
<input name="userNo" value="" type="text" maxlength="36"/>
<!-- 询价系统序列号 -->
<input name="bpsCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
表名 + 属性区
------------------------------------------------------------------------------------------------------------
<!-- 数据主键 -->
<input name="nlbsTodo.id" value="" type="text" maxlength="11"/>
<!-- 任务创建时间(分配时间) -->
<input name="nlbsTodo.dateCreated" value="" type="text"/>
<!-- 待办任务详情 -->
<input name="nlbsTodo.content" value="" type="text" maxlength="255"/>
<!-- 待办任务类型 -->
<input name="nlbsTodo.todoType" value="" type="text" maxlength="3"/>
<!-- 待处理人 -->
<input name="nlbsTodo.userNo" value="" type="text" maxlength="36"/>
<!-- 询价系统序列号 -->
<input name="nlbsTodo.bpsCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
ID + 属性区
------------------------------------------------------------------------------------------------------------
<!-- 数据主键 -->
<input id="NT_ID" name="id" value="" type="text" maxlength="11"/>
<!-- 任务创建时间(分配时间) -->
<input id="NT_DATE_CREATED" name="dateCreated" value="" type="text"/>
<!-- 待办任务详情 -->
<input id="NT_CONTENT" name="content" value="" type="text" maxlength="255"/>
<!-- 待办任务类型 -->
<input id="NT_TODO_TYPE" name="todoType" value="" type="text" maxlength="3"/>
<!-- 待处理人 -->
<input id="NT_USER_NO" name="userNo" value="" type="text" maxlength="36"/>
<!-- 询价系统序列号 -->
<input id="NT_BPS_CODE" name="bpsCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
ID + 表名 + 属性区
------------------------------------------------------------------------------------------------------------
<!-- 数据主键 -->
<input id="NT_ID" name="nlbsTodo.id" value="" type="text" maxlength="11"/>
<!-- 任务创建时间(分配时间) -->
<input id="NT_DATE_CREATED" name="nlbsTodo.dateCreated" value="" type="text"/>
<!-- 待办任务详情 -->
<input id="NT_CONTENT" name="nlbsTodo.content" value="" type="text" maxlength="255"/>
<!-- 待办任务类型 -->
<input id="NT_TODO_TYPE" name="nlbsTodo.todoType" value="" type="text" maxlength="3"/>
<!-- 待处理人 -->
<input id="NT_USER_NO" name="nlbsTodo.userNo" value="" type="text" maxlength="36"/>
<!-- 询价系统序列号 -->
<input id="NT_BPS_CODE" name="nlbsTodo.bpsCode" value="" type="text" maxlength="36"/>
--------------------------------------------------------
*/
|
package com.yicheng.service.data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.yicheng.common.Config;
import com.yicheng.pojo.Cloth;
import com.yicheng.pojo.ClothColor;
public class ClothDetailData implements Serializable {
private static final long serialVersionUID = -6414161446766109730L;
private int id;
private String type;
private String name;
private String client;
private String remark;
private String imagePath;
private Date createdTime;
private String color;
private List<ClothMaterialDetailData> leathers;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public List<ClothMaterialDetailData> getLeathers() {
return leathers;
}
public void setLeathers(List<ClothMaterialDetailData> leathers) {
this.leathers = leathers;
}
public ClothDetailData() {}
public ClothDetailData(Cloth cloth, List<ClothColor> clothColors) {
if(null != cloth) {
this.id = cloth.getId();
this.type = cloth.getType();
this.name = cloth.getName();
this.client = cloth.getClient();
this.remark = cloth.getRemark();
this.imagePath = cloth.getImagePath();
this.createdTime = cloth.getCreatedTime();
}
if(null != clothColors && !clothColors.isEmpty()) {
this.color = "";
int size = clothColors.size();
for(int i = 0; i < size - 1; i++) {
color += clothColors.get(i).getColor();
color += Config.COLOR_SEPERATOR;
}
color += clothColors.get(size - 1).getColor();
}
}
public ClothDetailData(Cloth cloth, List<ClothColor> clothColors, List<ClothMaterialDetailData> leathers) {
this(cloth, clothColors);
if(null != leathers && !leathers.isEmpty()) {
this.leathers = leathers;
}
}
}
|
package question2;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/*Class of the menu.
* There are 4 arrays in the class, representing the existing item types.
* The class receives the information from the file, and puts the items by type into the appropriate array.*/
public class Menu {
private interface Constant{
int NAME = 4;
int DESCRIPTION = 3;
int TYPE = 2;
int PRICE = 1;
}
private final ArrayList<Product> firstCourses = new ArrayList<>();
private final ArrayList<Product> mainCourses = new ArrayList<>();
private final ArrayList<Product> desserts = new ArrayList<>();
private final ArrayList<Product> drinks = new ArrayList<>();
/*File reception function.*/
public Menu(String path) throws IOException {
File text = new File(path);
//Creating Scanner instance to read File
Scanner input = new Scanner(text);
while (input.hasNextLine()) {
Product product = getProductFromFile(input);
addItemByType(product);
}
input.close();
}
/*A function that continues to receive from the file the corresponding lines
* in the order of the information about the items in the file.*/
private static Product getProductFromFile(Scanner input) {
int numOfAttributesInProduct = 4;
String name = null, description = null, category = null, price = null;
while (input.hasNextLine() && numOfAttributesInProduct > 0) {
String line = input.nextLine();
if (line.isEmpty())
continue;
else if (numOfAttributesInProduct == Constant.NAME)
name = line;
else if (numOfAttributesInProduct == Constant.DESCRIPTION)
description = line;
else if (numOfAttributesInProduct == Constant.TYPE)
category = line;
else if (numOfAttributesInProduct == Constant.PRICE)
price = line;
numOfAttributesInProduct--;
}
return new Product(name, description, category, price);
}
public ArrayList<Product> getFirstCourses() {
return firstCourses;
}
public ArrayList<Product> getMainCourses() {
return mainCourses;
}
public ArrayList<Product> getDesserts() {
return desserts;
}
public ArrayList<Product> getDrinks() {
return drinks;
}
/*The function adds the item to the appropriate array, by item type.*/
private void addItemByType(Product product) {
switch (product.getType()) {
case "First Course":
firstCourses.add(product);
break;
case "Main Course":
mainCourses.add(product);
break;
case "Dessert":
desserts.add(product);
break;
case "Drinking":
drinks.add(product);
break;
}
}
}
|
/*
* 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 calculadora;
/**
*
* @author PC07
*/
public class Operacao {
Double a, b;
char code;
public Operacao(Double a, Double b, char code) {
this.a = a;
this.b = b;
this.code = code;
}
public Operacao(Double a) {
this.a = a;
this.code = 'e';
}
public String toString() {
if (code == 'e') {
return Double.toString(a);
} else {
return Character.toString(code);
}
}
public static void main(String[] args) {
Operacao[] op = new Operacao[9];
op[0] = new Operacao(16.0);
op[1] = new Operacao(8.0);
op[2] = new Operacao(4.0);
op[3] = new Operacao(2.0);
op[4] = new Operacao(1.0);
op[5] = new Operacao(2.0, 1.0, '+');
op[6] = new Operacao(4.0, 3.0, '-');
op[7] = new Operacao(8.0, 1.0, '*');
op[8] = new Operacao(16.0, 8.0, '/');
for (int i = 0; i < op.length; i++) {
System.out.print(op[i] + " ");
}
System.out.println();
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.presenter.impl.uom.model;
import net.nan21.dnet.core.api.annotation.Ds;
import net.nan21.dnet.core.api.annotation.SortField;
import net.nan21.dnet.core.presenter.model.AbstractTypeWithCodeLov;
import net.nan21.dnet.module.bd.domain.impl.uom.Uom;
@Ds(entity = Uom.class, jpqlWhere = " e.type.category = 'volume' ", sort = {@SortField(field = UomVolumeLov_Ds.f_code)})
public class UomVolumeLov_Ds extends AbstractTypeWithCodeLov<Uom> {
public UomVolumeLov_Ds() {
super();
}
public UomVolumeLov_Ds(Uom e) {
super(e);
}
}
|
package com.mahii.flavoursdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* @author i_m_mahii, mahi05
*/
public class MainActivity extends AppCompatActivity {
TextView nameTV, typeTV;
ListView itemsList;
MyAdapter adapter;
ArrayList<MyModel> myModels;
String name, type;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
makeCall();
}
protected void initUI() {
nameTV = (TextView) findViewById(R.id.nameTV);
typeTV = (TextView) findViewById(R.id.typeTV);
itemsList = (ListView) findViewById(R.id.itemsList);
myModels = new ArrayList<>();
}
public void makeCall() {
CallService service = new CallService(MainActivity.this, Constants.BaseUrl, "GET", new CallService.OnServiceCall() {
@Override
public void onServiceCall(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
name = jsonObject.getString("name");
type = jsonObject.getString("type");
JSONArray jArr = jsonObject.getJSONArray("item");
for (int i = 0; i < jArr.length(); i++) {
JSONObject innerJObj = jArr.getJSONObject(i);
MyModel myModel = new MyModel();
myModel.setGain(innerJObj.getString("gain"));
myModel.setItemNo(innerJObj.getString("itemNo"));
myModels.add(myModel);
}
nameTV.setText(String.format("Name : %s", name));
typeTV.setText(String.format("Type : %s", type));
adapter = new MyAdapter(MainActivity.this, myModels);
itemsList.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
service.execute();
}
}
|
package in.dailyhunt.internship.userprofile.services;
import in.dailyhunt.internship.userprofile.client_model.request.*;
import in.dailyhunt.internship.userprofile.client_model.response.*;
import in.dailyhunt.internship.userprofile.entities.*;
import in.dailyhunt.internship.userprofile.exceptions.BadRequestException;
import in.dailyhunt.internship.userprofile.exceptions.ResourceNotFoundException;
import in.dailyhunt.internship.userprofile.repositories.*;
import in.dailyhunt.internship.userprofile.security.services.UserPrinciple;
import in.dailyhunt.internship.userprofile.services.interfaces.BlockedService;
import in.dailyhunt.internship.userprofile.services.interfaces.CardService;
import in.dailyhunt.internship.userprofile.services.interfaces.FollowingService;
import in.dailyhunt.internship.userprofile.services.interfaces.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class CardServiceImpl implements CardService {
private final HomeService homeService;
private final FollowingService followingService;
private final BlockedService blockedService;
private final WebClient.Builder webClientBuilder;
private final GenreDataRepository genreDataRepository;
private final LanguageDataRepository languageDataRepository;
private final LocalityDataRepository localityDataRepository;
private final TagDataRepository tagDataRepository;
private final SourceDataRepository sourceDataRepository;
@Autowired
public CardServiceImpl(HomeService homeService, FollowingService followingService,
BlockedService blockedService, WebClient.Builder webClientBuilder,
GenreDataRepository genreDataRepository, LanguageDataRepository languageDataRepository,
LocalityDataRepository localityDataRepository, TagDataRepository tagDataRepository,
SourceDataRepository sourceDataRepository) {
this.homeService = homeService;
this.followingService = followingService;
this.blockedService = blockedService;
this.webClientBuilder = webClientBuilder;
this.genreDataRepository = genreDataRepository;
this.languageDataRepository = languageDataRepository;
this.localityDataRepository = localityDataRepository;
this.tagDataRepository = tagDataRepository;
this.sourceDataRepository = sourceDataRepository;
}
@Override
public DataCardResponse getKeywordCards(String keyword) {
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/keyword";
CardResponse cardResponse = webClientBuilder.build()
.get()
.uri(recoUrl+"/"+keyword)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getGenericCardsWithoutLogin() {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(genreDataRepository.findByGenericTrue()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(languageDataRepository.findAll()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterGenreIds.getGenreIds())
.languageIds(filterLanguageIds.getLanguageIds())
.localityIds(new HashSet<>())
.tagIds(new HashSet<>())
.sourceIds(new HashSet<>())
.build();
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/genreIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getGenreCardsWithoutLogin(Long genreId) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(new HashSet<>(Collections.singleton(genreId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(languageDataRepository.findAll()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterGenreIds.getGenreIds())
.languageIds(filterLanguageIds.getLanguageIds())
.localityIds(new HashSet<>())
.tagIds(new HashSet<>())
.sourceIds(new HashSet<>())
.build();
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/genreIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getGenericCards() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Set<Long> genreIds = genreDataRepository.findByGenericTrue()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet());
FilterLocalityIds filterLocalityIds;
FilterTagIds filterTagIds;
FilterSourceIds filterSourceIds;
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
genreIds.removeAll(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream().map(GenreData::getInjestionId)
.collect(Collectors.toSet()));
filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
}
else {
filterLocalityIds = FilterLocalityIds.builder()
.localityIds(new HashSet<>())
.build();
filterTagIds = FilterTagIds.builder()
.tagIds(new HashSet<>())
.build();
filterSourceIds = FilterSourceIds.builder()
.sourceIds(new HashSet<>())
.build();
}
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(genreIds)
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterGenreIds.getGenreIds())
.localityIds(filterLocalityIds.getLocalityIds())
.tagIds(filterTagIds.getTagIds())
.sourceIds(filterSourceIds.getSourceIds())
.build();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(optional_following.isPresent()) {
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setLanguageIds(filterLanguageIds.getLanguageIds());
}
else {
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(languageDataRepository.findAll()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setLanguageIds(filterLanguageIds.getLanguageIds());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/genreIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getGenresCards(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getFollowingById(userId)
.getGenres().getAll_the_genres()
.stream().map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterGenreIds.getGenreIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/genreIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getGenreCards(Long genreId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(new HashSet<>(Collections.singleton(genreId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterGenreIds.getGenreIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/genreIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getLanguagesCards() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream().map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream().map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/languageIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getLanguageCards(Long langaugeId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(new HashSet<>(Collections.singleton(langaugeId)))
.build();
FilterSet filterSet = FilterSet.builder()
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream().map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/languageIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getLocalitiesCards() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getFollowingById(userId)
.getLocalities().getAll_the_localities()
.stream().map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.localityIds(filterLocalityIds.getLocalityIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/localityIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getLocalityCards(Long localityId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(new HashSet<>(Collections.singleton(localityId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(filterLocalityIds.getLocalityIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setTagIds(filterTagIds.getTagIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/localityIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getTagsCards() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getFollowingById(userId)
.getTags().getAll_the_tags()
.stream().map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.tagIds(filterTagIds.getTagIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/tagIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getTagCards(Long tagId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(new HashSet<>(Collections.singleton(tagId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.tagIds(filterTagIds.getTagIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getBlockedById(userId)
.getSouces().getAll_the_sources()
.stream()
.map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setSourceIds(filterSourceIds.getSourceIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setSourceIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/tagIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getTrendingCards() {
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/trending";
CardResponse cardResponse = webClientBuilder.build()
.get()
.uri(recoUrl)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getCardsByDateRange(DateFilter dateFilter) {
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/date-range";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(dateFilter), DateFilter.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getSourcesCards(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(homeService.getFollowingById(userId)
.getSouces().getAll_the_sources()
.stream().map(SourceData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.sourceIds(filterSourceIds.getSourceIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/sourceIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getSourceCards(Long sourceId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple user = (UserPrinciple) auth.getPrincipal();
Long userId = user.getId();
Optional<FollowingSet> optional_following = followingService.getFollowingSet(userId);
if(!optional_following.isPresent()){
return DataCardResponse.builder()
.dataCards(new HashSet<>())
.build();
}
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(new HashSet<>(Collections.singleton(sourceId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(homeService.getFollowingById(userId)
.getLanguages().getAll_the_languages()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.sourceIds(filterSourceIds.getSourceIds())
.languageIds(filterLanguageIds.getLanguageIds())
.build();
Optional<BlockedSet> optionalBlocked = blockedService.getBlockedSet(userId);
if(optionalBlocked.isPresent()) {
FilterGenreIds filterGenreIds = FilterGenreIds.builder()
.genreIds(homeService.getBlockedById(userId)
.getGenres().getAll_the_genres()
.stream()
.map(GenreData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterLocalityIds filterLocalityIds = FilterLocalityIds.builder()
.localityIds(homeService.getBlockedById(userId)
.getLocalities().getAll_the_localities()
.stream()
.map(LocalityData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterTagIds filterTagIds = FilterTagIds.builder()
.tagIds(homeService.getBlockedById(userId)
.getTags().getAll_the_tags()
.stream()
.map(TagData::getInjestionId)
.collect(Collectors.toSet()))
.build();
filterSet.setGenreIds(filterGenreIds.getGenreIds());
filterSet.setLocalityIds(filterLocalityIds.getLocalityIds());
filterSet.setTagIds(filterTagIds.getTagIds());
}
else {
filterSet.setGenreIds(new HashSet<>());
filterSet.setLocalityIds(new HashSet<>());
filterSet.setTagIds(new HashSet<>());
}
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/sourceIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
@Override
public DataCardResponse getSourceCardsWithoutLogin(Long sourceId) {
FilterSourceIds filterSourceIds = FilterSourceIds.builder()
.sourceIds(new HashSet<>(Collections.singleton(sourceId)))
.build();
FilterLanguageIds filterLanguageIds = FilterLanguageIds.builder()
.languageIds(languageDataRepository.findAll()
.stream()
.map(LanguageData::getInjestionId)
.collect(Collectors.toSet()))
.build();
FilterSet filterSet = FilterSet.builder()
.genreIds(new HashSet<>())
.languageIds(filterLanguageIds.getLanguageIds())
.localityIds(new HashSet<>())
.tagIds(new HashSet<>())
.sourceIds(filterSourceIds.getSourceIds())
.build();
String recoUrl = "https://dailyhunt-reco-service.herokuapp.com/api/v1/filter/sourceIds";
CardResponse cardResponse = webClientBuilder.build()
.post()
.uri(recoUrl)
.body(Mono.just(filterSet), FilterSet.class)
.retrieve()
.bodyToMono(CardResponse.class)
.block();
Set<DataCard> set = new HashSet<>();
assert cardResponse != null;
cardResponse.getCards().forEach(card -> set.add(makeDataCardFromCard(card)));
return DataCardResponse.builder()
.dataCards(set)
.build();
}
public DataCard makeDataCardFromCard(Card card) {
SourceData sourceData;
if(card.getSourceId() == null)
sourceData = null;
else {
if (sourceDataRepository.findByInjestionId(card.getSourceId()).isPresent())
sourceData = sourceDataRepository.findByInjestionId(card.getSourceId()).get();
else
throw new ResourceNotFoundException("Invalid source id");
}
return DataCard.builder()
.id(card.getId())
.injestionId(card.getInjestionId())
.sourceData(sourceData)
.title(card.getTitle())
.genres(new HashSet<>(genreDataRepository.findAllByInjestionIdIn(card.getGenreIds())))
.tags(new HashSet<>(tagDataRepository.findAllByInjestionIdIn(card.getTagIds())))
.languages(new HashSet<>(languageDataRepository.findAllByInjestionIdIn(card.getLanguageIds())))
.localities(new HashSet<>(localityDataRepository.findAllByInjestionIdIn(card.getLocalityIds())))
.thumbnailPath(card.getThumbnailPath())
.trending(card.getTrending())
.publishedAt(card.getPublishedAt())
.build();
}
}
|
package org.lxy.gui;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* @author menglanyingfei
* @date 2017-4-17
*/
public class Demo1_Frame {
/**
* @param args
*/
public static void main(String[] args) {
Frame f = new Frame("my window");
f.setLayout(new FlowLayout());//设置布局管理器
f.setSize(500,400);//设置窗体大小
f.setLocation(300,200);//设置窗体出现在屏幕的位置
f.setIconImage(Toolkit.getDefaultToolkit().createImage("dog.png"));
//demo1(f);
f.addWindowListener(new MyWindowAdapter());
f.setVisible(true);
}
public static void demo1(Frame f) {
// 窗体监听, 实现方法一: 匿名内部类
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);//退出虚拟机,关闭窗口
}
});
}
}
class MyWindowAdapter extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
|
package com.tencent.mm.plugin.luckymoney.f2f.ui;
import com.tencent.mm.hardcoder.HardCoderJNI;
class ShuffleView$c {
public int kPr = 1;
public int kPs = 1;
public int kPt = 2;
public int kPu = HardCoderJNI.sHCDBDELAY_WRITE;
public int kPv = 80;
public float scaleX = 0.01f;
public float scaleY = 0.01f;
ShuffleView$c() {
}
}
|
package com.revature.pms.model;
import java.io.Serializable;
/*
* This is product pojo class mapped to product table in the database
*/
public class Product implements Serializable{
//fields of my product pojo
private int productId;
private String productName;
private int quantityOnHand;
private int price;
private String comments;
//default constructor
public Product() {
// TODO Auto-generated constructor stub
}
//Parametrized constructor
public Product(int productId, String productName, int quantityOnHand, int price, String comments) {
super();
this.productId = productId;
this.productName = productName;
this.quantityOnHand = quantityOnHand;
this.price = price;
this.comments = comments;
}
//getters and setters for all the fields
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantityOnHand() {
return quantityOnHand;
}
public void setQuantityOnHand(int quantityOnHand) {
this.quantityOnHand = quantityOnHand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
@Override
public String toString() {
return "Product [productId=" + productId + ", productName=" + productName + ", quantityOnHand=" + quantityOnHand
+ ", price=" + price + ", comments=" + comments + "]";
}
}
|
package pl.agh.edu.dp.labirynth;
import lombok.Getter;
import lombok.Setter;
import pl.agh.edu.dp.labirynth.Builder.CountingMazeBuilder;
import pl.agh.edu.dp.labirynth.Factory.BombedMazeFactory;
import pl.agh.edu.dp.labirynth.MazeElements.Doors.Door;
import pl.agh.edu.dp.labirynth.MazeElements.MapSite;
import pl.agh.edu.dp.labirynth.MazeElements.Walls.Wall;
import pl.agh.edu.dp.labirynth.Utils.*;
import pl.agh.edu.dp.labirynth.Builder.StandardMazeBuilder;
import pl.agh.edu.dp.labirynth.Factory.EnchantedMazeFactory;
import pl.agh.edu.dp.labirynth.Factory.MazeFactory;
import pl.agh.edu.dp.labirynth.MazeElements.Rooms.Room;
import static pl.agh.edu.dp.labirynth.Utils.Direction.*;
@Getter
@Setter
public class MazeGame {
private Maze maze;
private Player player;
private Vector2d rightLowerPos;
private static MazeGame instance;
public static MazeGame getInstance() {
if( instance == null){
instance = new MazeGame();
}
return instance;
}
public void createMaze(CountingMazeBuilder builder, MazeFactory factory) throws Exception {
buildSampleMaze(builder, factory);
this.rightLowerPos = builder.getRightLowerPos();
this.maze= builder.getCurrentMaze();
}
public void makeMove(Direction dir) throws Exception {
MapSite side = player.currentRoom.getSide(dir);
side.Enter();
}
public void movePlayerTo(Room room){
player.setCurrentRoom(room);
player.setPos(room.getPosition());
}
public void createPlayerAt(Vector2d playerPos) throws Exception {
this.player = new Player(maze.findRoom(playerPos), playerPos);
}
/* below sample 5 by 5 maze hardcoded for simplicity */
private void buildSampleMaze(CountingMazeBuilder builder, MazeFactory factory) throws Exception {
/* Add every room and make common walls with neighbours */
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
Room currRoom = factory.createRoom(new Vector2d(i, j));
builder.addRoom(currRoom);
if (j > 0)
builder.createCommonWall(North, currRoom, builder.findRoom(new Vector2d(i, j - 1)));
if (i > 0)
builder.createCommonWall(West, currRoom, builder.findRoom(new Vector2d(i - 1, j)));
}
}
/* long code ahead, nothing else at bottom ;) */
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 0)),
builder.findRoom(new Vector2d(1, 0))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 0)),
builder.findRoom(new Vector2d(0, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 1)),
builder.findRoom(new Vector2d(0, 2))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(1, 0)),
builder.findRoom(new Vector2d(1, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 2)),
builder.findRoom(new Vector2d(1, 2))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 2)),
builder.findRoom(new Vector2d(0, 3))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(1, 3)),
builder.findRoom(new Vector2d(0, 3))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(1, 3)),
builder.findRoom(new Vector2d(1, 4))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(0, 4)),
builder.findRoom(new Vector2d(1, 4))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(2, 0)),
builder.findRoom(new Vector2d(3, 0))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 0)),
builder.findRoom(new Vector2d(3, 0))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 0)),
builder.findRoom(new Vector2d(4, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 0)),
builder.findRoom(new Vector2d(4, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 1)),
builder.findRoom(new Vector2d(4, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 1)),
builder.findRoom(new Vector2d(2, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(2, 2)),
builder.findRoom(new Vector2d(2, 1))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(2, 2)),
builder.findRoom(new Vector2d(1, 2))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 1)),
builder.findRoom(new Vector2d(3, 2))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 2)),
builder.findRoom(new Vector2d(3, 2))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 2)),
builder.findRoom(new Vector2d(4, 3))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 3)),
builder.findRoom(new Vector2d(4, 3))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 3)),
builder.findRoom(new Vector2d(3, 4))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(4, 4)),
builder.findRoom(new Vector2d(3, 4))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(3, 3)),
builder.findRoom(new Vector2d(2, 3))
);
builder.createDoorBetweenRooms(
builder.findRoom(new Vector2d(2, 4)),
builder.findRoom(new Vector2d(2, 3))
);
}
}
|
package july_29;
public class Arraytask4 {
public static void main(String[] args)
{
//System.out.println(isprime(123));
int arr[]= {101,123,56,78,33,79};
System.out.println("The Prime no in the array are :");
for(int i=0;i<arr.length;i++)
{
if(isprime(arr[i]))
{
System.out.println(arr[i]);
}
}
}
public static boolean isprime(int n)
{
int flag=0;
int n2=n;
int m=n2/2;
if(n2==0||n2==1)
{
flag=1;
}
else
{
for (int i=2;i<m;i++)
{
if(n2%i==0)
{
flag=1;
break;
}
}
}
if(flag==0)
{
return true;
}
else {
return false;
}
}
}
|
package com.hcl.pets.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.hcl.pets.model.Pet;
/**
* @author laxman verma
*
*/
@Repository
public interface PetRepository extends JpaRepository<Pet, Long> {
@Query("from Pet p where petOwnerId = :userId")
public Optional<Pet> findByUserId(long userId);
@Query("from Pet p where p.petName= :petName and p.petAge= :petAge and p.petPlace= :petPlace")
public Optional<Pet> findPetByNameByAgeByPlace(String petName, int petAge, String petPlace);
}
|
package com.neo.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.neo.dao.IOrderDao;
import com.neo.po.TOrder;
import com.neo.service.BusiService;
@Service("busiService")
public class BusiServiceImpl implements BusiService {
@Autowired
private IOrderDao orderDao;
@Override
public String getBusiCode(Map<String, String> param) {
// ScorePointFacade scorePointFacade = null;
// scorePointFacade.queryScorePointList(null);
return null;
}
@Override
public List<TOrder> getAllData() {
return orderDao.getList(null);
}
}
|
package com.jvmless.threecardgame.handlers.commands.dto;
import com.jvmless.threecardgame.domain.shuffle.Card;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PlayGameCommand {
private String hostId;
private List<CardView> cards;
}
|
package com.tencent.mm.g.a;
public final class lr extends com.tencent.mm.sdk.b.b {
public a bWf;
public b bWg;
public static final class b {
public boolean bWe = false;
}
public lr() {
this((byte) 0);
}
private lr(byte b) {
this.bWf = new a();
this.bWg = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package edu.umich.verdict.relation.expr;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.parser.VerdictSQLParser.Lateral_view_functionContext;
public class LateralFunc extends Expr {
public enum LateralFuncName {
EXPLODE, UNKNOWN
}
protected static Map<String, LateralFuncName> string2FunctionType =
ImmutableMap.<String, LateralFuncName>builder()
.put("EXPLODE", LateralFuncName.EXPLODE)
.build();
protected static Map<LateralFuncName, String> functionPattern =
ImmutableMap.<LateralFuncName, String>builder()
.put(LateralFuncName.EXPLODE, "explode(%s)")
.put(LateralFuncName.UNKNOWN, "unknown(%s)")
.build();
private LateralFuncName funcname;
private Expr expr;
// private String tableAlias;
//
// private String columnAlias;
public LateralFuncName getFuncName() {
return funcname;
}
public Expr getExpression() {
return expr;
}
// public String getTableAlias() {
// return tableAlias;
// }
//
// public String getColumnAlias() {
// return columnAlias;
// }
public LateralFunc(LateralFuncName fname, Expr expr) {
super(VerdictContext.dummyContext());
this.funcname = fname;
this.expr = expr;
// this.tableAlias = tableAlias;
// this.columnAlias = columnAlias;
}
public static LateralFunc from(final VerdictContext vc, Lateral_view_functionContext ctx) {
String fname = ctx.function_name.getText().toUpperCase();
// String tableAlias = (ctx.table_alias() == null)? null : ctx.table_alias().getText();
// String columnAlias = (ctx.column_alias() == null)? null : ctx.column_alias().getText();
if (string2FunctionType.containsKey(fname)) {
return new LateralFunc(string2FunctionType.get(fname), Expr.from(vc, ctx.expression()));
}
return new LateralFunc(LateralFuncName.UNKNOWN, Expr.from(vc, ctx.expression()));
}
@Override
public <T> T accept(ExprVisitor<T> v) {
return v.call(this);
}
@Override
public Expr withTableSubstituted(String newTab) {
return new LateralFunc(funcname, expr.withTableSubstituted(newTab));
}
@Override
public String toSql() {
StringBuilder sql = new StringBuilder(50);
sql.append(String.format(functionPattern.get(funcname), expr.toSql()));
// if (tableAlias != null) {
// sql.append(" " + tableAlias);
// }
// if (columnAlias != null) {
// sql.append(" AS " + columnAlias);
// }
return sql.toString();
}
@Override
public String toString() {
return toSql();
}
@Override
public int hashCode() {
return funcname.hashCode() + expr.hashCode();
}
@Override
public boolean equals(Expr o) {
if (o instanceof LateralFunc) {
return getExpression().equals(((LateralFunc) o).getExpression())
&& getFuncName().equals(((LateralFunc) o).getFuncName());
}
return false;
}
}
|
package com.gsonkeno.redis;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
/**
* Created by gaosong on 2018-02-08
*/
public class CommonPool2Test {
public static void main(String[] args) throws Exception {
//使用Apache commons-pool2的ObjectPool的默认实现GenericObjectPool
ObjectPool op = new GenericObjectPool<StringBuffer>(new MyPooledObjectFactoryExample(),new GenericObjectPoolConfig());
//从ObjectPool租借对象StringBuffer
StringBuffer sb = (StringBuffer) op.borrowObject();
StringBuffer sb1 = (StringBuffer) op.borrowObject();
System.out.println("sb:" + sb.hashCode());
sb.append("7819");
System.out.println("修改后sb:" + sb.hashCode());
System.out.println(sb);
System.out.println(sb1.hashCode());
op.returnObject(sb);
StringBuffer sb2 = (StringBuffer) op.borrowObject();
System.out.println("sb2的hasCode:" + sb2.hashCode()); //sb2其实是返还的sb1,它的字符串值也没有改变
System.out.println(sb2);
}
}
|
package client;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* This class contains an application that can drive both the TCP and UDP
* implementations of a <code>MagicClient</code>.
*
* @author Evert Ball
* @version 01 November 2019
*/
public class MagicClientDriver {
private static final int FAILURE = 1;
private static final int SUCCESS = 0;
/**
* Provides the entry point of the program.
*
* @param args Command line arguemnts to the program. There must be exactly
* 2 or 3 arguments. The first argument must be either "tcp" or
* "udp". The second argument must be the hostname or IP
* address of a remote host running a magic server for the
* specified protocol. The third parameter, if present, is
* either the port number or the flag. The four argument, if
* present, must be the flag (in which case the third argument
* must be the port number).
*/
public static void main(String[] args) {
// Check for correct # of args
if(args.length < 2 || args.length > 4) {
System.out.println("Usage: MagicClientDriver <PROTOCOL> " +
"<IP/HOST> [<PORT> [<FLAG>]]");
} // end usage check
if(args[0].toLowerCase().equals("tcp")) {
if(args.length == 2) {
try {
AbstractMagicClient tcp = new MagicTcpClient(InetAddress.getByName(args[1]));
tcp.printToStream(System.out);
} catch (UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch (IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
}
} else if(args.length == 3) {
try {
AbstractMagicClient tcp = new MagicTcpClient(InetAddress.getByName(args[1]), Integer.parseInt(args[2]));
tcp.printToStream(System.out);
} catch(NumberFormatException nfe) {
try {
AbstractMagicClient tcp = new MagicTcpClient(InetAddress.getByName(args[1]), args[2]);
tcp.printToStream(System.out);
} catch(UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch(IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} catch (UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch (IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} else if(args.length == 4) {
try {
AbstractMagicClient tcp = new MagicTcpClient(InetAddress.getByName(args[1]), Integer.parseInt(args[2]), args[3]);
tcp.printToStream(System.out);
} catch(NumberFormatException nfe) {
System.err.println("Third argument must be a port number. Exiting...");
System.exit(FAILURE);
} catch(UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch(IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} // end if statement
} else if(args[0].toLowerCase().equals("udp")) {
if(args.length == 2) {
try {
AbstractMagicClient udp = new MagicUdpClient(InetAddress.getByName(args[1]));
udp.printToStream(System.out);
} catch (UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch (IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
}
} else if(args.length == 3) {
try {
AbstractMagicClient udp = new MagicUdpClient(InetAddress.getByName(args[1]), Integer.parseInt(args[2]));
udp.printToStream(System.out);
} catch(NumberFormatException nfe) {
try {
AbstractMagicClient udp = new MagicUdpClient(InetAddress.getByName(args[1]), args[2]);
udp.printToStream(System.out);
} catch(UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch(IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} catch (UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch (IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} else if(args.length == 4) {
try {
AbstractMagicClient udp = new MagicUdpClient(InetAddress.getByName(args[1]), Integer.parseInt(args[2]), args[3]);
udp.printToStream(System.out);
} catch(NumberFormatException nfe) {
System.err.println("Third argument must be a port number. Exiting...");
System.exit(FAILURE);
} catch(UnknownHostException uhe) {
System.err.println("Unknown host, cannot connect.");
System.exit(FAILURE);
} catch(IOException ioe) {
System.err.println("Encountered IO error. Cannot continue. ");
System.exit(FAILURE);
} // end try-catch
} // end if statement
}
System.exit(SUCCESS);
} // end main method
} // end MagicClientDriver class
|
package patterned;
public class Player {
public int numWin;
public int numLose;
public Strategy strategy;
@Override
public String toString() {
return "Win:" + numWin + ", Lose:" + numLose;
}
public boolean highLow(int num) {
return strategy.highLow(num);
}
}
|
package com.chronos.mvpapi.resource;
import com.chronos.mvpapi.event.ResourceCreatEvent;
import com.chronos.mvpapi.model.Person;
import com.chronos.mvpapi.repository.PersonRepository;
import com.chronos.mvpapi.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Optional;
@RestController
@RequestMapping("/api/people")
public class PersonResource {
@Autowired
private PersonService service;
@Autowired
private PersonRepository repository;
@Autowired
private ApplicationEventPublisher publisher;
@PostMapping
public ResponseEntity<Person> create(@Valid @RequestBody Person person, HttpServletResponse response) {
Person pessoaSalva = service.salve(person);
publisher.publishEvent(new ResourceCreatEvent(this, response, pessoaSalva.getUuid()));
return ResponseEntity.status(HttpStatus.CREATED).body(pessoaSalva);
}
@GetMapping("/{uuid}")
public ResponseEntity<Person> buscarPeloCodigo(@PathVariable String uuid) {
Optional<Person> person = repository.findById(uuid);
return person.isPresent() ? ResponseEntity.ok(person.get()) : ResponseEntity.notFound().build();
}
@DeleteMapping("/{uuid}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void remover(@PathVariable String uuid) {
repository.deleteById(uuid);
}
@PutMapping("/{uuid}")
public ResponseEntity<Person> atualizar(@PathVariable String uuid, @Valid @RequestBody Person person) {
Person pessoaSalve = service.update(uuid, person);
return ResponseEntity.ok(pessoaSalve);
}
}
|
package com.george.projectmanagement.controller;
import com.george.projectmanagement.model.Employee;
import com.george.projectmanagement.repository.EmployeeRepository;
import com.george.projectmanagement.services.EmployeeServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeServices employeeServices;
@GetMapping
public String displayEmployees(Model model) {
List<Employee> employees = employeeServices.findAll();
model.addAttribute("employees", employees);
return "employee/employees";
}
@GetMapping("/new")
public String displayProjectForm(Model model, HttpServletRequest request){
// redirect an obj from another controller ProjectController
Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
if(flashMap != null) {
String emailError = (String) flashMap.get("noEmployeeError");
}
model.addAttribute("employee", new Employee());
return "employee/new-employee";
}
@PostMapping("/save")
public String createProject(@Valid Employee employee, BindingResult bindingResult, Model model) {
//check for errors
if (bindingResult.hasErrors()) {
// return goes to page
return "employee/new-employee";
}
//if there are no errors, show form success screen
employeeServices.save(employee);
// use a redirect to prevent duplicate submissions
// redirect goes to mapping url
return "redirect:/employees";
}
// end
}
|
package controller.service.impl;
import controller.service.*;
import model.dao.DAOFactory;
import model.dao.impl.DAOFactoryImpl;
public class ServiceFactoryImpl implements ServiceFactory {
private static ServiceFactory serviceFactory;
private DAOFactory daoFactory;
private ServiceFactoryImpl() {
daoFactory = DAOFactoryImpl.getInstance();
}
@Override
public UserService getUserService() {
return new UserServiceImpl(daoFactory.getUserDAO());
}
@Override
public AdminService getAdminService() {
return new AdminServiceImpl(daoFactory.getAdminDAO());
}
@Override
public RouteService getRouteService() {
return new RouteServiceImpl(daoFactory.getRouteDAO());
}
@Override
public DriverService getDriverService() {
return new DriverServiceImpl(daoFactory.getDriverDAO());
}
@Override
public BusService getBusService() {
return new BusServiceImpl(daoFactory.getBusDAO());
}
@Override
public ScheduleService getScheduleService() {
return new ScheduleServiceImpl(daoFactory.getScheduleDAO());
}
public static ServiceFactory getInstance(){
if (serviceFactory == null){
synchronized (ServiceFactory.class){
serviceFactory = new ServiceFactoryImpl();
}
}
return serviceFactory;
}
}
|
package com.example.admin3.mobtransyandex;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
private TextView mTextMessage;
private EditText mEditText;
private Spinner spinnerFrom;
private Spinner spinnerTo;
private LangsModel langsModel;
private DBHelper dbHelper;
private HashMap<String,String> LangMap; // "ru","Русский"
private HashMap<String,String> LangMapInvert; // "Русский","ru"
private List<Map.Entry<String,String>> LangListSort;
private ArrayList arrayData;
private String dirs = null;
private DataItem dataItem;
private RequestQueue queue;
private ImageView imageView_fav;
Translator translator;
@Override
public boolean onTouch(View v, MotionEvent event) { // пользователь скорее всего закончил вводить слово - сохраним в Истории.
if(dataItem.getInput() != null && !dataItem.getInput().isEmpty() || dataItem.getOutput() != null && !dataItem.getOutput().isEmpty()){
SaveHistory(dataItem);
}
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (dataItem.getID()!=0) {
outState.putLong("ID", dataItem.getID());
}
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long ID = savedInstanceState.getLong("ID");
if (ID!=0) {
dataItem = DBUtil.getDataItem(dbHelper, ID);
setImageView_fav();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("main onCreate");
setContentView(R.layout.activity_main);
translator=new Translator(this);
dataItem = new DataItem();
LangMap =new HashMap<>();
LangMapInvert =new HashMap<>();
arrayData =new ArrayList();
LangListSort =new ArrayList<>();
View v = findViewById(R.id.container);
v.setOnTouchListener(this);
mTextMessage = (TextView) findViewById(R.id.message);
mEditText = (EditText) findViewById(R.id.editText);
spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
spinnerTo = (Spinner) findViewById(R.id.spinnerTo);
spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
define_dirs();
set_mTextMessage("");
update_dateItem(mEditText.getText().toString());
translator.getTranslation(dataItem,new Translator.VolleyCallback() {
@Override
public void onSuccess(String result) {
set_mTextMessage(result);
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerTo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
define_dirs();
set_mTextMessage("");
update_dateItem(mEditText.getText().toString());
translator.getTranslation(dataItem,new Translator.VolleyCallback() {
@Override
public void onSuccess(String result) {
set_mTextMessage(result);
}
});
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ImageView imageView_del = (ImageView) findViewById(R.id.imageViewDel);
imageView_del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dataItem=new DataItem();
set_mEditText("");
set_mTextMessage("");
setImageView_fav();
}
});
// поменять языки местами
ImageButton imageButton = (ImageButton) findViewById(R.id.imgButtonRok);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String spinnerToLast=spinnerTo.getSelectedItem().toString();
spinnerTo.setSelection(arrayData.indexOf(spinnerFrom.getSelectedItem().toString()));
spinnerFrom.setSelection(arrayData.indexOf(spinnerToLast));
}
});
imageView_fav = (ImageView) findViewById(R.id.imageView_fav);
imageView_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SaveHistory(dataItem);
DBUtil.changeFavorites(dbHelper,dataItem);
setImageView_fav();
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
set_mTextMessage("");
update_dateItem(s.toString());
translator.getTranslation(dataItem,new Translator.VolleyCallback() {
@Override
public void onSuccess(String result) {
set_mTextMessage(result);
}
});
}
});
// Нажатие кнопки Готово однозначно указывает на необходимость сохранить перевод
mEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
|| (actionId == EditorInfo.IME_ACTION_DONE)) {
SaveHistory(dataItem);
}
return false;
}
});
queue = Volley.newRequestQueue(this);
dbHelper = new DBHelper(this,"MyStore.db",null,Constants.DB_VERSION);
// Получить возможные языки для перевода
getTransDirect();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setSelectedItemId(R.id.navigation_home);
}
@Override
protected void onStart() {
super.onStart();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_home);
if (dataItem.getID()!=0){
DBUtil.getFavorites(dbHelper,dataItem);
setImageView_fav();
}
}
@Override
protected void onStop() {
super.onStop();
}
private boolean define_dirs(){
if (LangMapInvert.isEmpty() || spinnerFrom.getCount()==0 || spinnerTo.getCount()==0){
return false;
}
dirs=LangMapInvert.get(spinnerFrom.getSelectedItem().toString())+"-"+LangMapInvert.get(spinnerTo.getSelectedItem().toString());
return true;
}
private void update_dateItem(String in){
if (!in.equals(dataItem.getInput())) {
dataItem = new DataItem(in, dirs);
setImageView_fav();
}
dataItem.setInput(in);
dataItem.setDirs(dirs);
}
private void setImageView_fav(){
if (dataItem.getFav()==1){
imageView_fav.setImageResource(R.drawable.fav1);
} else {
imageView_fav.setImageResource(R.drawable.fav0);
}
}
private void SpinnerSet(Spinner spinner, Boolean from){
if (!LangListSort.isEmpty()) {
if (arrayData.isEmpty()) {
for (Map.Entry<String, String> entry : LangListSort) {
arrayData.add(entry.getValue());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayData);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if (from){
spinner.setSelection(adapter.getPosition("Английский"));
}else {
spinner.setSelection(adapter.getPosition("Русский"));
}
}
}
private void getTransDirect(){
final String url = Constants.Yandex_URL + Constants.Yandex_getLangs + Constants.Yandex_key +"&ui=ru"; // +in
StringRequest request = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
try {
Gson gson = new Gson();
langsModel = gson.fromJson(s, LangsModel.class);
if (langsModel != null) {
LangMap = langsModel.getLangs();
LangListSort = new ArrayList(LangMap.entrySet());
Collections.sort(LangListSort, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> a, Map.Entry<String, String> b) {
return (a.getValue()).compareTo(b.getValue());
}
});
for (Map.Entry<String, String> entry : LangMap.entrySet()) {
LangMapInvert.put(entry.getValue(), entry.getKey());
}
SpinnerSet(spinnerFrom,true);
SpinnerSet(spinnerTo,false);
}
} catch (JsonSyntaxException ex) {
Log.v("error getTransDirect fromJson " + ex.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.v("error getTransDirect onErrorResponse "+volleyError.getMessage());
}
});
queue.add(request);
}
private void SaveHistory(DataItem dataItem){
if(dataItem.getInput() == null || dataItem.getInput().isEmpty() || dataItem.getOutput() == null || dataItem.getOutput().isEmpty()){
return;
}
if(dataItem.getID()!=0){
return;
}
DBUtil.insertDataItem(dbHelper,dataItem);
}
private void set_mEditText(String text){
mEditText.setText(text);
}
private void set_mTextMessage(String text){
mTextMessage.setText(text);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
case R.id.navigation_history:
SaveHistory(dataItem); // 200% что запишем )
Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
return true;
case R.id.navigation_favorites:
SaveHistory(dataItem);
Intent intent1 = new Intent(MainActivity.this, FavoritesActivity.class);
startActivity(intent1);
overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
return true;
}
return false;
}
};
}
|
public class MoodAnalyser {
private String message;
MoodAnalyser(){
}
MoodAnalyser(String message){
this.message= message;
}
public String analyseMood(){
try {
message=message.toLowerCase();
if(message.contains("sad"))
return "SAD";
else
return "HAPPY";
}
catch(NullPointerException e){
return "HAPPY";
}
}
}
|
package com.hesoyam.pharmacy.pharmacy.events;
import com.hesoyam.pharmacy.pharmacy.model.Promotion;
import org.springframework.context.ApplicationEvent;
public class OnNewPromotionEvent extends ApplicationEvent {
private final Promotion promotion;
public OnNewPromotionEvent(Promotion promotion) {
super(promotion);
this.promotion = promotion;
}
public Promotion getPromotion() {
return promotion;
}
}
|
package com.example.makemytrip.fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.makemytrip.R;
import com.example.makemytrip.activity.FlightActivity;
import com.example.makemytrip.activity.HotelAndHomestaysActivity;
import com.example.makemytrip.activity.ViewAllHotelActivity;
import com.example.makemytrip.adapter.HotelAdapter;
import com.example.makemytrip.apiClient.ApiClient;
import com.example.makemytrip.network.Network;
import com.example.makemytrip.response.HotelDTO;
import com.example.makemytrip.response.ResponseDTO;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private TextView mTvViewAll;
private List<HotelDTO> hotelDTOS = new ArrayList<>();
private ImageView mIvHotel;
private ImageView mIvHomestays;
private ImageView mIvFlight;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
callAPI();
}
private void callAPI() {
ApiClient apiClient = Network.getInstance().create(ApiClient.class);
apiClient.getHotelResponse().enqueue(new Callback<ResponseDTO>() {
@Override
public void onResponse(Call<ResponseDTO> call, Response<ResponseDTO> response) {
if (response.body() != null) {
hotelDTOS = response.body().getHotel();
setRecycler();
}
}
@Override
public void onFailure(Call<ResponseDTO> call, Throwable t) {
}
});
}
private void setRecycler() {
HotelAdapter hotelAdapter = new HotelAdapter(hotelDTOS);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(hotelAdapter);
}
private void initViews(View view) {
recyclerView = view.findViewById(R.id.recycler_hotel_homeFragment);
mTvViewAll = view.findViewById(R.id.tv_ViewAll_HomeFragment);
mIvHotel = view.findViewById(R.id.iv_Hotel_HomeFragment);
mIvFlight = view.findViewById(R.id.iv_Flight_HomeFragment);
mIvHomestays = view.findViewById(R.id.iv_HomeStays_HomeFragment);
mIvHotel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), HotelAndHomestaysActivity.class);
startActivity(intent);
}
});
mIvHomestays.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), HotelAndHomestaysActivity.class);
startActivity(intent);
}
});
mTvViewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ViewAllHotelActivity.class);
startActivity(intent);
}
});
mIvFlight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FlightActivity.class);
startActivity(intent);
}
});
}
}
|
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class StringReader {
public static String key, keyLow, str, strLow;
static Set<String> keySet;
static ArrayList<String> keyList = new ArrayList();
static String[] keyMassGeneral;
public static void keyWord(){
System.out.println("Введите ключевое слово:");
keySet = new HashSet();
Scanner in = new Scanner(System.in);
key = in.nextLine();
keyLow = key.toLowerCase(); //Сравнение с ключом вне зависимости от регистра.
// in.close();
System.out.println("Ключевое слово:" + key);
//На случай, если несколько слов в ключе.
String[] keyMass = keyLow.split(" ");
for (int i = 0; i < keyMass.length; i++){
keySet.add(keyMass[i]);
//System.out.println(keySet);
}
keyList.addAll(keySet);
}
public static void filterByKey(){
boolean test = false;
System.out.println("Введите строку:");
Scanner in = new Scanner(System.in);
str = in.nextLine();
strLow = str.toLowerCase();
//in.close();
for(int i = 0; i < keyList.size(); i++){
if(strLow.contains(keyList.get(i))){
test = true;
}
}
if(test == true){
System.out.println(str);
}
}
public static void main(String[] args) {
while(true){
keyWord();
filterByKey();
}
}
}
|
package net.xndk.proxygen.handlers;
import java.lang.annotation.Annotation;
import javax.ws.rs.POST;
public class PostHandler extends HttpMethodHandler {
public PostHandler() {
super("POST");
}
public Class<? extends Annotation> getTarget() {
return POST.class;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.01.28 at 02:10:24 PM CST
//
package org.mesa.xml.b2mml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SingleEventType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SingleEventType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{http://www.mesa.org/xml/B2MML-V0600}BatchProductionRecordEntryType"/>
* <element name="EventType" type="{http://www.mesa.org/xml/B2MML-V0600}EventTypeType"/>
* <element name="EventSubType" type="{http://www.mesa.org/xml/B2MML-V0600}EventSubTypeType"/>
* <element name="EquipmentID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Value" type="{http://www.mesa.org/xml/B2MML-V0600}ValueType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="PreviousValue" type="{http://www.mesa.org/xml/B2MML-V0600}ValueType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="MessageText" type="{http://www.mesa.org/xml/B2MML-V0600}TextType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="PersonID" type="{http://www.mesa.org/xml/B2MML-V0600}NameType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ComputerID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="PhysicalAssetID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProceduralElementReference" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Category" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="AlarmData" type="{http://www.mesa.org/xml/B2MML-V0600}AlarmDataType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="AssociatedEventID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="UserAttribute" type="{http://www.mesa.org/xml/B2MML-V0600}UserAttributeType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SingleEventType", propOrder = {
"entryID",
"objectType",
"timeStamp",
"externalReference",
"description",
"eventType",
"eventSubType",
"equipmentID",
"value",
"previousValue",
"messageText",
"personID",
"computerID",
"physicalAssetID",
"proceduralElementReference",
"category",
"alarmData",
"associatedEventID",
"userAttribute"
})
public class SingleEventType {
@XmlElement(name = "EntryID", required = true)
protected IdentifierType entryID;
@XmlElement(name = "ObjectType", required = true)
protected RecordObjectTypeType objectType;
@XmlElement(name = "TimeStamp")
protected DateTimeType timeStamp;
@XmlElement(name = "ExternalReference")
protected IdentifierType externalReference;
@XmlElement(name = "Description")
protected List<DescriptionType> description;
@XmlElement(name = "EventType", required = true)
protected EventTypeType eventType;
@XmlElement(name = "EventSubType", required = true, nillable = true)
protected EventSubTypeType eventSubType;
@XmlElement(name = "EquipmentID")
protected List<IdentifierType> equipmentID;
@XmlElement(name = "Value")
protected List<ValueType> value;
@XmlElement(name = "PreviousValue")
protected List<ValueType> previousValue;
@XmlElement(name = "MessageText")
protected List<TextType> messageText;
@XmlElement(name = "PersonID")
protected List<NameType> personID;
@XmlElement(name = "ComputerID")
protected List<IdentifierType> computerID;
@XmlElement(name = "PhysicalAssetID")
protected List<IdentifierType> physicalAssetID;
@XmlElement(name = "ProceduralElementReference")
protected List<IdentifierType> proceduralElementReference;
@XmlElement(name = "Category")
protected List<IdentifierType> category;
@XmlElement(name = "AlarmData")
protected List<AlarmDataType> alarmData;
@XmlElement(name = "AssociatedEventID")
protected List<IdentifierType> associatedEventID;
@XmlElement(name = "UserAttribute")
protected List<UserAttributeType> userAttribute;
/**
* Gets the value of the entryID property.
*
* @return
* possible object is
* {@link IdentifierType }
*
*/
public IdentifierType getEntryID() {
return entryID;
}
/**
* Sets the value of the entryID property.
*
* @param value
* allowed object is
* {@link IdentifierType }
*
*/
public void setEntryID(IdentifierType value) {
this.entryID = value;
}
/**
* Gets the value of the objectType property.
*
* @return
* possible object is
* {@link RecordObjectTypeType }
*
*/
public RecordObjectTypeType getObjectType() {
return objectType;
}
/**
* Sets the value of the objectType property.
*
* @param value
* allowed object is
* {@link RecordObjectTypeType }
*
*/
public void setObjectType(RecordObjectTypeType value) {
this.objectType = value;
}
/**
* Gets the value of the timeStamp property.
*
* @return
* possible object is
* {@link DateTimeType }
*
*/
public DateTimeType getTimeStamp() {
return timeStamp;
}
/**
* Sets the value of the timeStamp property.
*
* @param value
* allowed object is
* {@link DateTimeType }
*
*/
public void setTimeStamp(DateTimeType value) {
this.timeStamp = value;
}
/**
* Gets the value of the externalReference property.
*
* @return
* possible object is
* {@link IdentifierType }
*
*/
public IdentifierType getExternalReference() {
return externalReference;
}
/**
* Sets the value of the externalReference property.
*
* @param value
* allowed object is
* {@link IdentifierType }
*
*/
public void setExternalReference(IdentifierType value) {
this.externalReference = value;
}
/**
* Gets the value of the description property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DescriptionType }
*
*
*/
public List<DescriptionType> getDescription() {
if (description == null) {
description = new ArrayList<DescriptionType>();
}
return this.description;
}
/**
* Gets the value of the eventType property.
*
* @return
* possible object is
* {@link EventTypeType }
*
*/
public EventTypeType getEventType() {
return eventType;
}
/**
* Sets the value of the eventType property.
*
* @param value
* allowed object is
* {@link EventTypeType }
*
*/
public void setEventType(EventTypeType value) {
this.eventType = value;
}
/**
* Gets the value of the eventSubType property.
*
* @return
* possible object is
* {@link EventSubTypeType }
*
*/
public EventSubTypeType getEventSubType() {
return eventSubType;
}
/**
* Sets the value of the eventSubType property.
*
* @param value
* allowed object is
* {@link EventSubTypeType }
*
*/
public void setEventSubType(EventSubTypeType value) {
this.eventSubType = value;
}
/**
* Gets the value of the equipmentID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the equipmentID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEquipmentID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getEquipmentID() {
if (equipmentID == null) {
equipmentID = new ArrayList<IdentifierType>();
}
return this.equipmentID;
}
/**
* Gets the value of the value property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the value property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ValueType }
*
*
*/
public List<ValueType> getValue() {
if (value == null) {
value = new ArrayList<ValueType>();
}
return this.value;
}
/**
* Gets the value of the previousValue property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the previousValue property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPreviousValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ValueType }
*
*
*/
public List<ValueType> getPreviousValue() {
if (previousValue == null) {
previousValue = new ArrayList<ValueType>();
}
return this.previousValue;
}
/**
* Gets the value of the messageText property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageText property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageText().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TextType }
*
*
*/
public List<TextType> getMessageText() {
if (messageText == null) {
messageText = new ArrayList<TextType>();
}
return this.messageText;
}
/**
* Gets the value of the personID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the personID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPersonID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NameType }
*
*
*/
public List<NameType> getPersonID() {
if (personID == null) {
personID = new ArrayList<NameType>();
}
return this.personID;
}
/**
* Gets the value of the computerID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the computerID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getComputerID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getComputerID() {
if (computerID == null) {
computerID = new ArrayList<IdentifierType>();
}
return this.computerID;
}
/**
* Gets the value of the physicalAssetID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the physicalAssetID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPhysicalAssetID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getPhysicalAssetID() {
if (physicalAssetID == null) {
physicalAssetID = new ArrayList<IdentifierType>();
}
return this.physicalAssetID;
}
/**
* Gets the value of the proceduralElementReference property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the proceduralElementReference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProceduralElementReference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getProceduralElementReference() {
if (proceduralElementReference == null) {
proceduralElementReference = new ArrayList<IdentifierType>();
}
return this.proceduralElementReference;
}
/**
* Gets the value of the category property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the category property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCategory().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getCategory() {
if (category == null) {
category = new ArrayList<IdentifierType>();
}
return this.category;
}
/**
* Gets the value of the alarmData property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the alarmData property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAlarmData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AlarmDataType }
*
*
*/
public List<AlarmDataType> getAlarmData() {
if (alarmData == null) {
alarmData = new ArrayList<AlarmDataType>();
}
return this.alarmData;
}
/**
* Gets the value of the associatedEventID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the associatedEventID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAssociatedEventID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getAssociatedEventID() {
if (associatedEventID == null) {
associatedEventID = new ArrayList<IdentifierType>();
}
return this.associatedEventID;
}
/**
* Gets the value of the userAttribute property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the userAttribute property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUserAttribute().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link UserAttributeType }
*
*
*/
public List<UserAttributeType> getUserAttribute() {
if (userAttribute == null) {
userAttribute = new ArrayList<UserAttributeType>();
}
return this.userAttribute;
}
}
|
/*
* PrintSDSevk.java
*
* Created on 27 Ekim 2007 Cumartesi, 13:13
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package askan.printing;
import askan.Main;
import askan.systems.*;
import java.awt.*;
import java.awt.print.*;
import javax.print.*;
/**
*
* @author Kerem
*/
public class PrintMMFull implements Printable {
private PurchProcess purchProcess;
/** Creates a new instance of PrintSDSevk */
public PrintMMFull(PurchProcess PP) {
purchProcess = PP;
}
@Override
public int print (Graphics g, PageFormat f, int pageIndex)
{
if (pageIndex == 0)
{
Paper pap = new Paper();
pap.setSize(PrintMaster.paperWidth, PrintMaster.paperHeight);
f.setPaper(pap);
PrintMaster pm = new PrintMaster();
pm.paintTitle(g, "SATINALMA GİRİŞ FİŞİ - " + Main.config.intParam.kantarID + "-" + askan.systems.Sap.getNumc(purchProcess.id));
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "Satıcı", purchProcess.getVendorDisplayText());
pm.newLine();
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "Plaka", purchProcess.trmtyp);
pm.newLine();
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "Malzeme", purchProcess.getMaterialDisplayText());
pm.newLine();
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "İrs. Miktarı", purchProcess.lfimg.toString());
pm.newLine();
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "Dolu Ağırlık", purchProcess.fullWeight.toString());
pm.newLine();
pm.paintTitledString(g, PrintMaster.TABLE_COLUMN.LEFT, "Tarih", purchProcess.dateFull == null ? "" : Sql.sqlFormatDate(purchProcess.dateFull, Sql.DATE_FORMAT.TURKISH, true));
return PAGE_EXISTS;
}
else return NO_SUCH_PAGE;
}
}
|
package com.takshine.wxcrm.message.oauth;
/**
* 权限信息
* @author liulin
*
*/
public class AuthorizeInfo {
private String accessToken; //网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
private int expiresIn;//access_token接口调用凭证超时时间,单位(秒)
private String refreshToken; //用户刷新access_token
private String openId ;//用户唯一标识
private String scope ;//用户授权的作用域,使用逗号(,)分隔
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
|
package in.hocg.defaults.base.body;
import java.io.Serializable;
import java.util.List;
/**
* Created by hocgin on 16-12-21.
*/
public class Page implements Serializable {
// 每页显示数量
private int size;
// 总记录数
private long total;
// 当前页
private int current;
private List<?> result;
public Page(int size, long total, int current, List<?> result) {
this.size = size;
this.total = total;
this.current = current;
this.result = result;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
public List<?> getResult() {
return result;
}
public void setResult(List<Object> result) {
this.result = result;
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.jobs;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import java.util.ArrayList;
import java.util.List;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.beans.DownloadFriendEntry;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.in.DownloadGroupFriendReplyPacket;
import edu.tsinghua.lumaqq.qq.packets.in.GroupDataOpReplyPacket;
import edu.tsinghua.lumaqq.ui.MainShell;
/**
* 下载好友分组的任务
*
* @author luma
*/
public class DownloadGroupJob extends AbstractJob {
// 组名list和组内好友的hash,用在下载分组信息的时候,因为下载分组信息是
// 分两部分进行的,一部分得到组名称一部分得到组的好友,光完成一部分还不
// 行,所以需要暂时保存一下结果
private List<String> groupNames;
private List<DownloadFriendEntry> friends;
// 分组好友是否已经下载完毕
private boolean downloadGroupFriendFinished;
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.jobs.IJob#prepare(edu.tsinghua.lumaqq.ui.MainShell)
*/
@Override
public void prepare(MainShell m) {
super.prepare(m);
downloadGroupFriendFinished = false;
main.getClient().addQQListener(this);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.jobs.IJob#clear()
*/
@Override
public void clear() {
main.getClient().removeQQListener(this);
}
@Override
protected void preLoop() {
if(monitor != null) {
monitor.beginTask("", 100);
monitor.subTask(job_download_group_1);
}
main.getDisplay().syncExec(new Runnable() {
public void run() {
main.setWaitingPanelHint(hint_download_group);
}
});
main.getClient().user_GetGroupNames();
main.getClient().user_DownloadGroups(0);
if(monitor != null)
monitor.worked(10);
}
@Override
protected void postLoop() {
main.getDisplay().syncExec(new Runnable() {
public void run() {
if(main.getCurrentPanel() != MainShell.PANEL_MAIN) {
main.stopWaitingPanelAnimation();
main.switchPanel(MainShell.PANEL_MAIN);
}
}
});
}
@Override
protected void OnQQEvent(QQEvent e) {
switch(e.type) {
case QQEvent.FRIEND_GET_GROUP_NAMES_OK:
processDownloadGroupNameSuccess(e);
break;
case QQEvent.FRIEND_DOWNLOAD_GROUPS_OK:
processDownloadGroupFriendSuccess(e);
break;
case QQEvent.FRIEND_DOWNLOAD_GROUPS_FAIL:
processDownloadGroupFriendFail(e);
break;
case QQEvent.SYS_TIMEOUT:
switch(e.operation) {
case QQ.QQ_CMD_DOWNLOAD_GROUP_FRIEND:
case QQ.QQ_CMD_GROUP_DATA_OP:
processDownloadGroupFriendFail(e);
break;
}
break;
}
}
/**
* 处理下载分组好友列表失败事件
*
* @param e
* QQEvent
*/
private void processDownloadGroupFriendFail(QQEvent e) {
groupNames = null;
friends = null;
errorMessage = job_download_group_error;
wake();
}
/**
* 处理下载分组好友列表成功事件
*
* @param e
* QQEvent
*/
private void processDownloadGroupFriendSuccess(QQEvent e) {
if(friends == null)
friends = new ArrayList<DownloadFriendEntry>();
DownloadGroupFriendReplyPacket packet = (DownloadGroupFriendReplyPacket)e.getSource();
friends.addAll(packet.friends);
if(packet.beginFrom == 0) {
downloadGroupFriendFinished = true;
if(groupNames != null)
resetModel();
} else {
downloadGroupFriendFinished = false;
main.getClient().user_DownloadGroups(packet.beginFrom);
if(monitor != null)
monitor.worked(10);
}
}
/**
* 处理下载分组名称成功事件
*
* @param e
* QQEvent
*/
private void processDownloadGroupNameSuccess(QQEvent e) {
GroupDataOpReplyPacket packet = (GroupDataOpReplyPacket)e.getSource();
groupNames = packet.groupNames;
if(downloadGroupFriendFinished && friends != null)
resetModel();
}
/**
* 重新设置shutter的model
*/
private void resetModel() {
if(monitor != null)
monitor.subTask(job_download_group_2);
downloadGroupFriendFinished = false;
main.getBlindHelper().resetModel(groupNames, friends);
if(monitor != null)
monitor.worked(20);
friends = null;
groupNames = null;
main.getDisplay().syncExec(new Runnable() {
public void run() {
// 得到在线好友, 设置firstTime为true是为了防止不必要的上线提示
main.getTipHelper().setFirstTime(true);
main.getClient().user_GetOnline();
// 处理延迟消息
main.getMessageQueue().setPostpone(false);
main.getMessageHelper().processPostponedIM();
}
});
if(monitor != null)
monitor.done();
wake();
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.jobs.IJob#isSuccess()
*/
@Override
public boolean isSuccess() {
return errorMessage != null;
}
}
|
package com.training.vasivkov;
import org.apache.commons.lang3.ArrayUtils;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class HuffmanCode {
public void encode(String fileName, String destCodeMap, String destHuffmanCode) throws Exception {
File file = new File(fileName);
List<Frequencies> frequenciesList = readFile(file);
Map<String, String> codeMap = findCodes(frequenciesList);
List<Byte> listHuffmanCode = textToByteArray(codeMap, file);
writeCodeToFile(listHuffmanCode, destHuffmanCode);
List<String> listForCodeMap = mapToList(codeMap);
listToFile(listForCodeMap, destCodeMap);
}
public void encode(String fileName) throws Exception {
File file = new File(fileName);
encode(fileName, "codeMap_" + file.getName(), "huffmanCode_" + file.getName());
}
List<Frequencies> readFile(File file) {
Map<String, Integer> mapOfProbabilities = new HashMap<>();
try(BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file))){
while (fis.available() > 0) {
char ch = (char) fis.read();
String symbol = String.valueOf(ch);
if (!mapOfProbabilities.containsKey(symbol)) {
mapOfProbabilities.put(symbol, 1);
} else {
mapOfProbabilities.put(symbol, mapOfProbabilities.get(symbol) + 1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return mapOfProbabilities.entrySet().stream()
.map(entry -> new Frequencies(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
Map<String, String> findCodes(List<Frequencies> frequenciesList) throws IOException {
Map<String, String> codeMap = new HashMap<>();
if (frequenciesList.size() == 0) {
return codeMap;
}
if (frequenciesList.size() == 1) {
codeMap.put(frequenciesList.get(0).getSymbol(), "0");
return codeMap;
}
for (Frequencies aFrequenciesList : frequenciesList) {
codeMap.put(aFrequenciesList.getSymbol(), "");
}
while (frequenciesList.size() > 1) {
Collections.sort(frequenciesList);
Frequencies sumFrequenices = Frequencies.sum(frequenciesList.get(frequenciesList.size() - 1), frequenciesList.get(frequenciesList.size() - 2));
String[] letters = frequenciesList.remove(frequenciesList.size() - 1).getSymbol().split(""); // разбиваю набор символов на отдельные символы
for (String letter : letters) {
codeMap.put(letter, "1" + codeMap.get(letter)); // изменяю значения в карте добавляя вперед 1
}
letters = frequenciesList.remove(frequenciesList.size() - 1).getSymbol().split(""); // те же действия еще раз, но добавляю 0;
for (String letter : letters) {
codeMap.put(letter, "0" + codeMap.get(letter));
}
frequenciesList.add(sumFrequenices); // вставляю в лист результирующее значение
}
return codeMap;
}
List<Byte> textToByteArray(Map<String, String> codeMap, File file) {
List<Byte> byteCode = new ArrayList<>();
StringBuilder tmpString = new StringBuilder();
try(BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file))){
while (fis.available() > 0) {
char ch = (char) fis.read();
String symbol = String.valueOf(ch);
tmpString.append(codeMap.get(symbol));
while (tmpString.length() > 7) {
String tmp = tmpString.substring(0, 7);
byteCode.add(Byte.valueOf(tmp, 2)); // объединяю по 7 и периодически сбрасываю в список ввиде байт
tmpString.delete(0, 7); // удаляю из временной строки этот диапазон
}
}
} catch (IOException e) {
e.printStackTrace();
}
int incompleteGroup = tmpString.length(); // запоминаю кол-во элементов в неполной группе
byteCode.add(Byte.valueOf(tmpString.toString(), 2));
codeMap.put("" + incompleteGroup, "count");
return byteCode;
}
private void writeCodeToFile(List<Byte> listByte, String fileName) {
Byte[] arrayOfByte = listByte.toArray(new Byte[listByte.size()]);
byte[] bytes = ArrayUtils.toPrimitive(arrayOfByte);
try(FileOutputStream fos = new FileOutputStream(fileName); ){
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
private List<String> mapToList(Map<String, String> map) {
List<String> list = new ArrayList<>();
for (Map.Entry entry : map.entrySet()) {
list.add((String) entry.getValue());
list.add((String) entry.getKey());
}
return list;
}
private void listToFile(List<String> list, String fileName) {
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(fileName)));) {
oos.writeObject(list);
} catch (IOException e) {
e.printStackTrace();
}
}
// ++++++++++++ DECODER +++++++++++++++++++++++++++++
private List<String> listFromFile(File file) {
List<String> list = null;
try( ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))){
list = (ArrayList<String>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
private Map<String, String> listToMap(List<String> list) {
Map<String, String> map = new HashMap<>();
for (int i = 1; i < list.size(); i++) {
if (i % 2 != 0) {
map.put(list.get(i - 1), list.get(i));
}
}
return map;
}
private List<Byte> readCodeFromFile(String fileName) {
List<Byte> listFromFile = new ArrayList<>();
try(FileInputStream fis = new FileInputStream(new File(fileName))){
while (fis.available() > 0) {
listFromFile.add((byte) fis.read());
}
} catch (IOException e) {
e.printStackTrace();
}
return listFromFile;
}
public void decode(String huffmanCodeFile, String codeMapFile, String destinationFile) {
Map<String, String> decoderMap = listToMap(listFromFile(new File(codeMapFile)));
List<Byte> listFromFile = readCodeFromFile(huffmanCodeFile);
decoder(listFromFile, decoderMap, destinationFile);
}
private void decoder(List<Byte> resultArray, Map<String, String> decodeMap, String destinationFile) {
try (FileWriter fw = new FileWriter(destinationFile) ){
StringBuilder tmpString = new StringBuilder();
StringBuilder stringForFindCode = new StringBuilder();
for (int i = 0; i < resultArray.size(); i++) {
if (i == resultArray.size() - 1) {// последний байт, который может быть неполным
String shortString = oneZeroString(resultArray.get(i));
int count = Integer.parseInt(decodeMap.get("count"));
tmpString.append(shortString.substring(7 - count, 7));
} else {
tmpString.append(oneZeroString(resultArray.get(i)));
}
for (int j = 0; j < tmpString.length(); j++) {
stringForFindCode.append(tmpString.charAt(j));
if (decodeMap.containsKey(stringForFindCode.toString())) {
fw.write(decodeMap.get(stringForFindCode.toString()));
stringForFindCode.delete(0, stringForFindCode.length());
}
}
tmpString.delete(0, 7);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String oneZeroString(Byte b) {
StringBuilder tmpString = new StringBuilder();
StringBuilder oneZeroString = new StringBuilder();
tmpString.append("0000000");
tmpString.append(Integer.toBinaryString(b)); // байты, преобразованные в двоичный код
oneZeroString.append(tmpString.substring(tmpString.length() - 7, tmpString.length()));
return oneZeroString.toString();
}
}
|
package au.com.flexisoft.redisutil.dto;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class AccountSummary implements Serializable {
@JsonProperty("Id")
private Integer Id;
@JsonProperty("Summary")
private String Summary;
@JsonProperty("Value")
private Double Value;
}
|
package com.vuelos.domain;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table
public class Itinerario implements Serializable{
@Id
@Column(name="id_itinerario")
private Integer id_itinerario;
@Column(name="vuelos")
private Vuelos vuelos;
@Column(name="segmento_vuelos")
private String segmento_vuelos;
@Column(name="routing")
private String routing;
public Itinerario() {
}
public Integer getId_itinerario() {
return id_itinerario;
}
public void setId_itinerario(Integer id_itinerario) {
this.id_itinerario = id_itinerario;
}
public Vuelos getVuelos() {
return vuelos;
}
public void setVuelos(Vuelos vuelos) {
this.vuelos = vuelos;
}
public String getSegmento_vuelos() {
return segmento_vuelos;
}
public void setSegmento_vuelos(String segmento_vuelos) {
this.segmento_vuelos = segmento_vuelos;
}
public String getRouting() {
return routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
}
|
package com.project.database.entities;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class StatementFooterEntity {
private Integer presentCount; // Example: 6,
private Integer absentCount; // Example: 0,
private Integer rejectedCount; // Example: 0
}
|
package com.xiaoxiao.service;
import com.xiaoxiao.pojo.vo.XiaoxiaoArticleVo;
import com.xiaoxiao.pojo.vo.XiaoxiaoLabelVo;
import com.xiaoxiao.pojo.vo.XiaoxiaoSortsVo;
import com.xiaoxiao.utils.PageResult;
import java.util.List;
import java.util.Map;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/2:21:11
* @author:shinelon
* @Describe:
*/
public interface RedisArticleService
{
void insertArticleSumToRedis(Integer sum);
Integer getArticleSumToRedis();
void deleteArticleSumToRedis();
void insertArticleNewRecommend(PageResult articles);
PageResult getArticleNewRecommend();
void deleteArticleNewRecommend();
void insertIndexArticle(PageResult result, Integer page);
PageResult getIndexArticle(Integer page);
void deleteIndexArticle(Integer page);
void insertBlogsBySortsToRedis(PageResult articleVos, Long sortId);
PageResult getBlogsBySortsToRedis(Long sortId);
void deleteBlogsBySortsToRedis(Long sortId);
void insertArticleById(XiaoxiaoArticleVo articles);
XiaoxiaoArticleVo getArticleById(Long articleId);
void insertArticleArchive(Map<String, List<XiaoxiaoArticleVo>> map);
Map<String, List<XiaoxiaoArticleVo>> getArticleArchive();
void deleteArticleArchive();
void insertArticleByLabelId(PageResult result, Long labelId);
void deleteArticleByLabelId(Long labelId);
PageResult getArticleByLabelId(Long labelId);
/**
* 缓存指定分类文章个数
* @param sortId 分类ID
* @param sortsVo
*/
void insertArticleSortSum(Long sortId, XiaoxiaoSortsVo sortsVo);
/**
* 获取指定分类文章的个数
* @param sortId
* @return
*/
XiaoxiaoSortsVo getArticleSortSum(Long sortId);
/**
* 删除的指定分类文章的个数
* @param sortId
*/
void deleteArticleSortSum(Long sortId);
/**
* 删除
* @param labelId
*/
void deleteArticleLabelSum(Long labelId);
/**获取
*
* @return
* @param labelId
*/
XiaoxiaoLabelVo getArticleLabelSum(Long labelId);
/**
* 插入
* @param labelId
* @param labelVo
*/
void insertArticleLabelSum(Long labelId, XiaoxiaoLabelVo labelVo);
/**
* 插入文章浏览量
* @param views
* @param articleId
*/
void insertArticleView(Integer views, Long articleId);
/**
* 获取文章浏览量
* @return
* @param articleId
*/
Integer getArticleView(Long articleId);
/**
* 获取浏览量数据
* @return
*/
Map<Object, Object> getArticleView();
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.acceleratorfacades.productcarousel.impl;
import static de.hybris.platform.cms2.misc.CMSFilter.PREVIEW_TICKET_ID_PARAM;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import de.hybris.bootstrap.annotations.IntegrationTest;
import de.hybris.platform.catalog.CatalogVersionService;
import de.hybris.platform.catalog.model.CatalogVersionModel;
import de.hybris.platform.cms2.servicelayer.services.CMSComponentService;
import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminComponentService;
import de.hybris.platform.cms2lib.model.components.ProductCarouselComponentModel;
import de.hybris.platform.commercefacades.product.data.ProductData;
import de.hybris.platform.core.Registry;
import de.hybris.platform.product.ProductService;
import de.hybris.platform.search.restriction.SearchRestrictionService;
import de.hybris.platform.servicelayer.ServicelayerTest;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.session.SessionService;
import de.hybris.platform.servicelayer.type.TypeService;
import de.hybris.platform.servicelayer.user.UserService;
import de.hybris.platform.util.Utilities;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ClassPathResource;
@IntegrationTest
public class DefaultProductCarouselFacadeIntegrationTest extends ServicelayerTest
{
@Resource(name = "defaultProductCarouselFacade")
private DefaultProductCarouselFacade defaultProductCarouselFacade;
@Resource
private SessionService sessionService;
@Resource
private ModelService modelService;
@Resource
private CMSAdminComponentService cmsAdminComponentService;
@Resource
private CMSComponentService cmsComponentService;
@Resource
private ProductService productService;
@Resource
private CatalogVersionService catalogVersionService;
@Resource
private SearchRestrictionService searchRestrictionService;
@Resource
private TypeService typeService;
@Resource
private UserService userService;
private ProductCarouselComponentModel carouselModel;
private CatalogVersionModel contentCatalogVersionModel;
private CatalogVersionModel productCatalogVersionModel;
@BeforeClass
public static void prepare() throws Exception
{
Registry.activateStandaloneMode();
Utilities.setJUnitTenant();
final ApplicationContext appCtx = Registry.getApplicationContext();
final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx;
final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
if (beanFactory.getRegisteredScope("tenant") == null)
{
beanFactory.registerScope("tenant", new de.hybris.platform.spring.TenantScope());
}
final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
xmlReader.loadBeanDefinitions(new ClassPathResource("product-carousel-spring-test.xml"));
}
@Before
public void setUp() throws Exception
{
importCsv("/acceleratorfacades/test/testProductCarouselFacade.impex", "utf-8");
contentCatalogVersionModel = catalogVersionService.getCatalogVersion("testContentCatalog", "Online");
productCatalogVersionModel = catalogVersionService.getCatalogVersion("testProductCatalog", "Online");
catalogVersionService.setSessionCatalogVersions(Arrays.asList(contentCatalogVersionModel, productCatalogVersionModel));
carouselModel = (ProductCarouselComponentModel) cmsComponentService.getAbstractCMSComponent("testProductCarouselComponent");
userService.setCurrentUser(userService.getUserForUID("anonymous"));
}
@After
public void tearDown()
{
catalogVersionService.setSessionCatalogVersions(Arrays.asList());
searchRestrictionService.enableSearchRestrictions();
}
@Test
public void testCollectProducts_not_preview()
{
sessionService.setAttribute(PREVIEW_TICKET_ID_PARAM, null);
final List<ProductData> products = defaultProductCarouselFacade.collectProducts(carouselModel);
assertThat(products, hasSize(4)); // retrieves only Online (Session catalog) versioned products
assertThat(products, hasItem(hasProperty("code", equalTo("product07"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product08"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product09"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product10"))));
}
@Test
public void testCollectProducts_in_preview()
{
sessionService.setAttribute(PREVIEW_TICKET_ID_PARAM, "previewTicket");
final List<ProductData> products = defaultProductCarouselFacade.collectProducts(carouselModel);
assertThat(products, hasSize(9));
assertThat(products, hasItem(hasProperty("code", equalTo("product01"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product02"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product04"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product05"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product06"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product07"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product08"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product09"))));
assertThat(products, hasItem(hasProperty("code", equalTo("product10"))));
}
}
|
package com.wincentzzz.project.template.springhack.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AppointmentListItem {
private Long id;
private Boolean isPaired;
private String doctorName;
private String doctorSpecialization;
private String hospitalName;
private String date;
}
|
package javax.vecmath;
import java.io.Serializable;
public class TexCoord3f extends Tuple3f implements Serializable {
static final long serialVersionUID = -3517736544731446513L;
public TexCoord3f(float x, float y, float z) {
super(x, y, z);
}
public TexCoord3f(float[] v) {
super(v);
}
public TexCoord3f(TexCoord3f v1) {
super(v1);
}
public TexCoord3f(Tuple3f t1) {
super(t1);
}
public TexCoord3f(Tuple3d t1) {
super(t1);
}
public TexCoord3f() {}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\TexCoord3f.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.gxc.reply.dao.impl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.gxc.reply.dao.ReplyDao;
import com.gxc.reply.domain.Reply;
public class ReplyDaoImpl extends HibernateDaoSupport implements ReplyDao {
/**
* 添加回复
*/
@Override
public void saveReply(Reply reply) {
this.getHibernateTemplate().save(reply);
}
}
|
package customer.gajamove.com.gajamove_customer;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.appcompat.app.AppCompatActivity;
import customer.gajamove.com.gajamove_customer.fragment.SettingsFragment;
import customer.gajamove.com.gajamove_customer.utils.UtilsManager;
public class SettingsScreen extends BaseActivity {
private void setupToolbar(){
// Show menu icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
upArrow.setColorFilter(getResources().getColor(R.color.black_color), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setTitle(getResources().getString(R.string.settings));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_screen);
// setupToolbar();
try {
getSupportFragmentManager().beginTransaction().replace(R.id.settings_frame, new SettingsFragment()).commit();
}
catch (Exception e){
e.printStackTrace();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
}
}
|
package unalcol.reflect.process;
import java.io.InputStream;
import java.io.PrintStream;
/**
* <p>A Class for reading the output streams used by an External Process (command).</p>
*
* @author Jonatan Gomez Perdomo
* @version 1.0
*/
public class ProcessInputStream implements Runnable {
/**
* OutputStream used by the External Process (command) that is going to be read
*/
protected InputStream is;
/**
* Thread used for reading the OutputStream while the External Process is running
*/
protected Thread thread;
/**
* External Process being executed
*/
protected ExternalProcess process;
/**
* OutputStream associated to the OutputStream used by the External Process
*/
protected PrintStream out = null;
/**
* Creates an object for reading the OutputStreams used by an External Process (command).
*
* @param is OutputStream used by the External Process (command) that is going to be read
* @param process External Process being executed
*/
public ProcessInputStream(InputStream is, ExternalProcess process) {
this.is = is;
this.process = process;
}
/**
* Creates an object for reading the OutputStreams used by an External Process (command).
*
* @param is OutputStream used by the External Process (command) that is going to be read
* @param process External Process being executed
* @param out OutputStream associated to the OutputStream used by the External Process
*/
public ProcessInputStream(InputStream is, ExternalProcess process,
PrintStream out) {
this.is = is;
this.process = process;
this.out = out;
}
/**
* Starts the OutputStream processing
*/
public void start() {
thread = new Thread(this);
thread.start();
}
/**
* Process the OutputStream used by the External Process
*/
public void run() {
try {
if (out != null) {
while (is.available() > 0 || process.is_running) {
if (is.available() > 0) {
out.print((char) is.read());
}
}
} else {
while (is.available() > 0 || process.is_running) {
if (is.available() > 0) {
is.read();
}
}
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package TurtleGraphics;
import java.io.*;
import java.awt.*;
public class Point implements Serializable{
int x, y;
Color color;
boolean endPoint; // new field
// etc.
}
|
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
import java.lang.Math;
import java.text.DecimalFormat;
public class FractionalKnapsack {
private static double getOptimalValue(int capacity, int[] values, int[] weights, int n) {
double value = 0;
//write your code here
double[] sortedUnitValue = sort(values, weights,n);
for(int i = 0; i < n; i++)
{
if(capacity==0) return (double) value;
int a = Math.min(capacity,weights[i]);
value += a*sortedUnitValue[i];
weights[i] = weights[i] - a;
capacity = capacity - a;
}
return (double) value;
}
private static double[] sort(int[] values, int[] weights, int n){
double[] result = new double[n];
for(int i = 0; i < n; i++ ){
result[i] = (double) values[i]/weights[i];
}
for(int i = 0; i < n-1; i++){
int max = i;
double maxValue = result[i];
for(int j = i + 1; j < n; j++) {
if(maxValue < result[j]) {
max = j;
maxValue = result[j];
}
}
double temp = result[i];
result[i] = maxValue;
result[max] = temp;
int temp1 = values[i];
values[i] = values[max];
values[max] = temp1;
temp1 = weights[i];
weights[i] = weights[max];
weights[max] = temp1;
}
return result;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int capacity = scanner.nextInt();
int[] values = new int[n];
int[] weights = new int[n];
for (int i = 0; i < n; i++) {
values[i] = scanner.nextInt();
weights[i] = scanner.nextInt();
}
DecimalFormat df = new DecimalFormat("#.####");
System.out.println(df.format(getOptimalValue(capacity, values, weights,n)));
}
}
|
package com.magic.utopia.common.config;
public enum UserLogType {
register(1),login(2);
private int code;
private UserLogType(int code){
this.code=code;
}
public int getCode(){
return code;
}
}
|
package com.hesoyam.pharmacy.appointment.service.impl;
import com.hesoyam.pharmacy.appointment.model.Appointment;
import com.hesoyam.pharmacy.appointment.model.AppointmentStatus;
import com.hesoyam.pharmacy.appointment.model.CheckUp;
import com.hesoyam.pharmacy.appointment.model.Counseling;
import com.hesoyam.pharmacy.appointment.repository.AppointmentRepository;
import com.hesoyam.pharmacy.appointment.repository.CheckUpRepository;
import com.hesoyam.pharmacy.appointment.repository.CounselingRepository;
import com.hesoyam.pharmacy.appointment.repository.TherapyRepository;
import com.hesoyam.pharmacy.appointment.service.IAppointmentService;
import com.hesoyam.pharmacy.employee_management.model.Shift;
import com.hesoyam.pharmacy.employee_management.model.ShiftType;
import com.hesoyam.pharmacy.pharmacy.model.Pharmacy;
import com.hesoyam.pharmacy.pharmacy.repository.PharmacyRepository;
import com.hesoyam.pharmacy.user.dto.PatientDTO;
import com.hesoyam.pharmacy.user.model.*;
import com.hesoyam.pharmacy.util.DateTimeRange;
import com.hesoyam.pharmacy.util.search.QueryMatchResult;
import com.hesoyam.pharmacy.util.search.UserSearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.text.Normalizer;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class AppointmentService implements IAppointmentService {
@Autowired
private AppointmentRepository appointmentRepository;
@Autowired
private TherapyRepository therapyRepository;
@Autowired
private CheckUpRepository checkUpRepository;
@Autowired
private CounselingRepository counselingRepository;
@Autowired
private PharmacyRepository pharmacyRepository;
private static final double MATCHES_FULLY = 1;
private static final double MATCHES_PARTIALLY = 0.5;
@Override
public int getCompletedChecksUpForPatientByDermatologist(Patient patient, Dermatologist dermatologist) {
return checkUpRepository.countChecksUpByPatientAndAppointmentStatusAndDermatologist(patient, AppointmentStatus.COMPLETED, dermatologist);
}
@Override
public int getCompletedCounselingsForPatientByPharmacist(Patient patient, Pharmacist pharmacist) {
return counselingRepository.countCounselingsByPatientAndAppointmentStatusAndPharmacist(patient, AppointmentStatus.COMPLETED, pharmacist);
}
@Override
public List<Counseling> getCounselingsForPharmacist(DateTimeRange dateTimeRange, Pharmacist pharmacist) {
List<Counseling> allCounselings = counselingRepository.findByPharmacist(pharmacist);
return filterByDateRange(dateTimeRange, allCounselings);
}
@Override
public List<CheckUp> getCheckUpsForDermatologist(DateTimeRange dateTimeRange, Dermatologist dermatologist) {
List<CheckUp> allCheckups = checkUpRepository.findCheckUpsByDermatologist(dermatologist);
return filterCheckupsByDateRange(allCheckups, dateTimeRange);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public boolean checkNewAppointment(User user, Patient patient, DateTimeRange range){
int count = 0;
if(user.getRoleEnum().equals(RoleEnum.PHARMACIST)) {
count = counselingRepository.countCounselingsByPharmacistAndDateTimeRange_From((Pharmacist) user,
range.getFrom());
count += countOverlappingAppointments(counselingRepository.getAllByPharmacist((Pharmacist) user), range);
}
else {
count = checkUpRepository.countCheckUpsByDermatologistAndDateTimeRange_From((Dermatologist) user,
range.getFrom());
count += countOverlappingAppointments(checkUpRepository.getAllByDermatologist((Dermatologist) user), range);
}
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
count += appointmentRepository.countAppointmentsByPatientAndDateTimeRange_From(patient, range.getFrom());
count += countOverlappingAppointments(appointmentRepository.getAllByPatient(patient), range);
if(count > 0){
return false;
}
return true;
}
private int countOverlappingAppointments(List<Appointment> allAppointments, DateTimeRange range) {
int count = 0;
for(Appointment appointment : allAppointments) {
if (appointment.getDateTimeRange().overlaps(range)) {
count++;
}
}
return count;
}
private boolean isInShift(Employee user, LocalDateTime range) {
List<Shift> shifts = user.getShifts();
if(shifts != null) {
for (Shift shift : shifts) {
if (shift.getType().equals(ShiftType.WORK) && shift.getDateTimeRange().getFrom().isBefore(range)
&& shift.getDateTimeRange().getTo().isAfter(range)) {
return true;
}
}
return false;
}
return true;
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public Appointment createNewAppointment(Patient patient, Employee employee, long pharmacyId, DateTimeRange range, double price){
if(checkNewAppointment(employee, patient, range)){
return createAppointmentBasedOnEmployeeType(patient, employee, pharmacyId, range, price);
}
return null;
}
private Appointment createAppointmentBasedOnEmployeeType(Patient patient, User employee, long pharmacyId, DateTimeRange range, Double price) {
if(employee.getRoleEnum().equals(RoleEnum.PHARMACIST)){
return createCounseling(patient, (Pharmacist) employee, pharmacyId, range, price);
}
return createCheckUp(patient, (Dermatologist) employee, pharmacyId, range, price);
}
private CheckUp createCheckUp(Patient patient, Dermatologist employee, long pharmacyId, DateTimeRange range, Double price) {
CheckUp appointment = new CheckUp();
appointment.setAppointmentStatus(AppointmentStatus.TAKEN);
appointment.setDateTimeRange(range);
appointment.setReport("");
appointment.setDermatologist(employee);
appointment.setPatient(patient);
appointment.setPharmacy(pharmacyRepository.findById(pharmacyId));
appointment.setPrice(price);
return checkUpRepository.save(appointment);
}
private Counseling createCounseling(Patient patient, Pharmacist employee, long pharmacyId, DateTimeRange range, Double price) {
Counseling appointment = new Counseling();
appointment.setAppointmentStatus(AppointmentStatus.TAKEN);
appointment.setDateTimeRange(range);
appointment.setReport("");
appointment.setPharmacy(pharmacyRepository.findById(pharmacyId));
appointment.setPharmacist(employee);
appointment.setPatient(patient);
appointment.setPrice(price);
return counselingRepository.save(appointment);
}
@Override
public List<PatientDTO> extractPatientsFromCheckups(Dermatologist dermatologist){
List<CheckUp> checkUps = checkUpRepository.findCheckUpsByDermatologist(dermatologist);
List<CheckUp> completedCheckUps = new ArrayList<>();
checkUps.forEach(checkUp -> {
if(checkUp.getAppointmentStatus() == AppointmentStatus.COMPLETED)
completedCheckUps.add(checkUp);
});
List<PatientDTO> patients = extractPatients(completedCheckUps);
return filterUniquePatients(patients);
}
@Override
public List<PatientDTO> extractPatientsFromCounselings(Pharmacist pharmacist) {
List<Counseling> counselings = counselingRepository.findByPharmacist(pharmacist);
List<Counseling> completedCounselings = new ArrayList<>();
counselings.forEach(counseling -> {
if(counseling.getAppointmentStatus() == AppointmentStatus.COMPLETED)
completedCounselings.add(counseling);
});
List<PatientDTO> patients = extractCounselingPatients(completedCounselings);
return filterUniquePatients(patients);
}
private List<PatientDTO> filterUniquePatients(List<PatientDTO> patients) {
List<PatientDTO> unique = new ArrayList<>();
for(PatientDTO patient : patients){
if(!hasPatientWithEmail(unique, patient.getEmail())){
unique.add(patient);
} else {
unique = overwrite(unique, patient);
}
}
return unique;
}
private List<PatientDTO> overwrite(List<PatientDTO> unique, PatientDTO patient) {
List<PatientDTO> overwritten = new ArrayList<>();
for(PatientDTO test : unique){
if(test.getEmail().equals(patient.getEmail())){
overwritten.add(patient);
} else {
overwritten.add(test);
}
}
return overwritten;
}
private boolean hasPatientWithEmail(List<PatientDTO> unique, String email) {
for(PatientDTO patient : unique){
if(patient.getEmail().equals(email)){
return true;
}
}
return false;
}
private List<PatientDTO> extractPatients(List<CheckUp> completedCheckUps) {
List<PatientDTO> patients = new ArrayList<>();
completedCheckUps.forEach(checkUp -> patients.add(new PatientDTO(checkUp)));
return patients;
}
private List<PatientDTO> extractCounselingPatients(List<Counseling> completedCounselings) {
List<PatientDTO> patients = new ArrayList<>();
completedCounselings.forEach(counseling -> patients.add(new PatientDTO(counseling)));
return patients;
}
private List<CheckUp> filterCheckupsByDateRange(List<CheckUp> allCheckups, DateTimeRange dateTimeRange) {
List<CheckUp> filtered = new ArrayList<>();
for(CheckUp checkUp : allCheckups){
if(isInRange(checkUp.getDateTimeRange(), dateTimeRange))
filtered.add(checkUp);
}
return filtered;
}
private List<Counseling> filterByDateRange(DateTimeRange dateTimeRange, List<Counseling> allCounselings) {
List<Counseling> filtered = new ArrayList<>();
for(Counseling counseling : allCounselings){
if(isInRange(counseling.getDateTimeRange(), dateTimeRange))
filtered.add(counseling);
}
return filtered;
}
private boolean isInRange(DateTimeRange toCheck, DateTimeRange constraintRange) {
return isNested(toCheck, constraintRange) || endsInRange(toCheck, constraintRange) ||
startsInRange(toCheck, constraintRange) || stretchesThroughRange(toCheck, constraintRange);
}
private boolean stretchesThroughRange(DateTimeRange toCheck, DateTimeRange constraintRange) {
return toCheck.getFrom().isBefore(constraintRange.getFrom()) && toCheck.getTo().isBefore(constraintRange.getTo());
}
private boolean startsInRange(DateTimeRange toCheck, DateTimeRange constraintRange) {
return toCheck.getFrom().isAfter(constraintRange.getFrom()) && toCheck.getTo().isAfter(constraintRange.getTo());
}
private boolean endsInRange(DateTimeRange toCheck, DateTimeRange constraintRange) {
return toCheck.getFrom().isBefore(constraintRange.getFrom()) && toCheck.getTo().isBefore(constraintRange.getTo());
}
private boolean isNested(DateTimeRange toCheck, DateTimeRange constraintRange) {
return toCheck.getFrom().isAfter(constraintRange.getFrom()) && toCheck.getTo().isBefore(constraintRange.getTo());
}
public int getCompletedAppointmentsCountInPharmacyByPatient(Pharmacy pharmacy, Patient patient) {
return appointmentRepository.countAppointmentsByPatientAndAppointmentStatusAndPharmacy(patient, AppointmentStatus.COMPLETED, pharmacy);
}
@Override
public List<UserSearchResult> searchUsers(Employee user, String query) {
List<PatientDTO> patients = new ArrayList<>();
if(user.getRoleEnum().equals(RoleEnum.PHARMACIST))
patients = extractPatientsFromCounselings((Pharmacist) user);
else if(user.getRoleEnum().equals(RoleEnum.DERMATOLOGIST))
patients = extractPatientsFromCheckups((Dermatologist) user);
return filterPatientsByQuery(patients, query);
}
private List<UserSearchResult> filterPatientsByQuery(List<PatientDTO> patients, String query) {
List<UserSearchResult> filtered = new ArrayList<>();
QueryMatchResult currentIterationResult = null;
for(PatientDTO patient : patients){
currentIterationResult = matchesQuery(patient, query);
if(currentIterationResult.getMatches()){
filtered.add(new UserSearchResult(patient, currentIterationResult.getGrade()));
}
}
return filtered;
}
private QueryMatchResult matchesQuery(PatientDTO patient, String query) {
String normalized = Normalizer.normalize(query, Normalizer.Form.NFD);
String[] parts = normalized.split(" ");
String singleEntry = "";
String firstName = "";
String lastName = "";
if(parts.length == 1){
singleEntry = parts[0];
}
else if(parts.length > 1){
firstName = parts[0];
lastName = parts[1];
}
else{
return new QueryMatchResult(false);
}
if(!singleEntry.isBlank()) {
if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD).equalsIgnoreCase(singleEntry.toLowerCase())
|| Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD).equalsIgnoreCase(singleEntry.toLowerCase()))
return new QueryMatchResult(true, MATCHES_FULLY);
else if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD)
.toLowerCase().startsWith(singleEntry.toLowerCase())
|| Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD)
.toLowerCase().startsWith(singleEntry.toLowerCase())){
return new QueryMatchResult(true, MATCHES_PARTIALLY);
}
return new QueryMatchResult(false);
} else {
if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD).equalsIgnoreCase(firstName.toLowerCase()) &&
Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD).equalsIgnoreCase(lastName.toLowerCase()))
return new QueryMatchResult(true, MATCHES_FULLY);
else if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD).equalsIgnoreCase(lastName.toLowerCase()) &&
Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD).equalsIgnoreCase(firstName.toLowerCase()))
return new QueryMatchResult(true, MATCHES_FULLY);
else if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD).toLowerCase().startsWith(firstName.toLowerCase()) &&
Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD).toLowerCase().startsWith(lastName.toLowerCase()))
return new QueryMatchResult(true, MATCHES_PARTIALLY);
else if(Normalizer.normalize(patient.getFirstName(), Normalizer.Form.NFD).toLowerCase().startsWith(lastName.toLowerCase()) &&
Normalizer.normalize(patient.getLastName(), Normalizer.Form.NFD).toLowerCase().startsWith(firstName.toLowerCase()))
return new QueryMatchResult(true, MATCHES_PARTIALLY);
else
return new QueryMatchResult(false);
}
}
}
|
package chapter11;
import java.util.ArrayList;
public class Exercise11_11 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(-5);
list.add(-55);
list.add(95);
list.add(15);
sort(list);
for (Integer integer : list) {
System.out.print(integer + " ");
}
}
public static void sort(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
int min = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
if (min > list.get(j)) {
list.set(i, list.get(j));
list.set(j, min);
min = list.get(i);
}
}
}
}
}
|
/*
* Implemente um programa em Java que leia o nome de um vendedor, o seu salário fixo e o total de vendas efetuadas por ele no mês.
* Sabendo que este vendedor ganha 15% de comissão sobre suas vendas efetuadas, o programa deve mostrar como resultado o seu nome e o seu salário no final do mês.
*/
package aula2exercicio3;
import java.util.Scanner;
public class Programa {
public static void main(String args[]) {
double salario, valorVendas, soma, salarioTotal;
double comissao = 0.15;
System.out.print("Salário: ");
salario = new Scanner(System.in).nextDouble();
System.out.print("Valor em vendas: ");
valorVendas = new Scanner(System.in).nextDouble();
soma = valorVendas * comissao;
salarioTotal = salario + soma;
System.out.println("Salario Total: " + salarioTotal);
}
}
|
package main.java.parrot;
public class NorwegianBlueParrot extends Parrot {
private final boolean isNailed;
private final double voltage;
public NorwegianBlueParrot(double voltage, boolean isNailed) {
this.isNailed = isNailed;
this.voltage = voltage;
}
@Override
public double getSpeed() {
return (isNailed) ? 0 : getBaseSpeed(voltage);
}
private double getBaseSpeed(double voltage) {
return Math.min(24.0, voltage * getBaseSpeed());
}
}
|
package stubmanagement;
import com.github.tomakehurst.wiremock.common.Slf4jNotifier;
import com.jayway.restassured.RestAssured;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static com.jayway.restassured.RestAssured.given;
/**
* Created by dvt on 27-02-17.
*/
public class VideodetailStub {
public void setupStub() {
stubFor(get(urlEqualTo("/an/endpoint"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withStatus(200)
.withBody("You've reached a valid WireMock endpoint")));
}
@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8090)
.httpsPort(8443).notifier(new Slf4jNotifier(true)));
@Test
public void testStatusCodePositive() {
this.setupStub();
given().
when().
get("http://localhost:8090/an/endpoint").
then().
assertThat().statusCode(200);
}
@Test
public void testResponseContents() {
setupStub();
String response = RestAssured.get("http://localhost:8090/an/endpoint").asString();
Assert.assertEquals("You've reached a valid WireMock endpoint", response);
}
}
|
package com.youthchina.dto.applicant;
import com.youthchina.domain.Qinghong.JobCollect;
import com.youthchina.dto.ResponseDTO;
import com.youthchina.dto.job.JobResponseDTO;
/**
* @program: youthchina
* @description: 职位收藏返回DTO
* @author: Qinghong Wang
* @create: 2019-02-26 11:28
**/
public class JobCollectResponseDTO implements ResponseDTO<JobCollect> {
private Integer id;
private JobResponseDTO job;
public JobCollectResponseDTO(JobCollect jobCollect) {
if(jobCollect!=null){
this.id = jobCollect.getCollect_id();
if(jobCollect.getJob()!=null){
this.job = new JobResponseDTO(jobCollect.getJob());
}
}
}
public JobCollectResponseDTO() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public JobResponseDTO getJob() {
return job;
}
public void setJob(JobResponseDTO job) {
this.job = job;
}
@Override
public void convertToDTO(JobCollect jobCollect) {
this.id = jobCollect.getCollect_id();
this.job = new JobResponseDTO(jobCollect.getJob());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Beans;
import java.sql.Date;
/**
*
* @author babman92
*/
public class InstallmentMonthly {
private String ID;
private String CustomerID;
private float RateInterestMonney;
private float MoneyRoot;
private float Total;
private Date PayDate;
private int State;
public InstallmentMonthly(){}
public String getCustomerID() {
return CustomerID;
}
public void setCustomerID(String CustomerID) {
this.CustomerID = CustomerID;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public float getMoneyRoot() {
return MoneyRoot;
}
public void setMoneyRoot(float MoneyRoot) {
this.MoneyRoot = MoneyRoot;
}
public Date getPayDate() {
return PayDate;
}
public void setPayDate(Date PayDate) {
this.PayDate = PayDate;
}
public float getRateInterestMonney() {
return RateInterestMonney;
}
public void setRateInterestMonney(float RateInterestMonney) {
this.RateInterestMonney = RateInterestMonney;
}
public int getState() {
return State;
}
public void setState(int State) {
this.State = State;
}
public float getTotal() {
return Total;
}
public void setTotal(float Total) {
this.Total = Total;
}
}
|
package com.example.imdb.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicUpdate;
/**
*
* @author Binnur Kurt <binnur.kurt@gmail.com>
*
*/
@Entity
@Table(name="movies")
@NamedQueries({
@NamedQuery(name="Movie.findAll",
query = "select m from Movie m"),
@NamedQuery(name="Movie.findAllByYearBetween",
query = "select m from Movie m where m.year between :from and :to")
})
@DynamicUpdate
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="movieid")
private Integer movieId;
private String title;
private int year;
private String imdb;
public Movie() {
}
public Movie(String title, int year, String imdb) {
this.title = title;
this.year = year;
this.imdb = imdb;
}
public Integer getMovieId() {
return movieId;
}
public void setMovieId(Integer movieId) {
this.movieId = movieId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getImdb() {
return imdb;
}
public void setImdb(String imdb) {
this.imdb = imdb;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((movieId == null) ? 0 : movieId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (movieId == null) {
if (other.movieId != null)
return false;
} else if (!movieId.equals(other.movieId))
return false;
return true;
}
@Override
public String toString() {
return "Movie [movieId=" + movieId + ", title=" + title + ", year=" + year + ", imdb=" + imdb + "]";
}
}
|
package ch22.ex22_11;
public abstract class SimpleTreeNode<V> implements Acceptable{
private SimpleTreeNode<V> parent;
private SimpleTreeNode<?> left;
private SimpleTreeNode<?> right;
private final V value;
SimpleTreeNode(SimpleTreeNode<V> parent, V value){
this.parent = parent;
this.value = value;
}
public V get(){
return this.value;
}
public void setRight(SimpleTreeNode<?> right){
this.right = right;
}
public void setLeft(SimpleTreeNode<?> left){
this.left = left;
}
public SimpleTreeNode<?> left(){
return left;
}
public SimpleTreeNode<?> right(){
return right;
}
public abstract void accept(Visitor visitor);
}
|
package de.mycinema.dao;
import de.mycinema.model.OpenAirCinema;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
/**
* Created by 13912 on 14.10.2017.
*/
@Component
public class OpenAirCinemaDAO {
@PersistenceContext
private EntityManager entityManager;
public List<OpenAirCinema> loadAll() {
return entityManager.createQuery("select c from OpenAirCinema c",
OpenAirCinema.class).getResultList();
}
public OpenAirCinema findById(Long id) {
return entityManager.find(OpenAirCinema.class, id);
}
public void save(OpenAirCinema openAirCinema) {
entityManager.persist(openAirCinema);
}
public void delete(OpenAirCinema openAirCinema) {
entityManager.remove(openAirCinema);
}
}
|
/* 1: */ package com.kaldin.questionbank.answer.dto;
/* 2: */
/* 3: */ public class AnswerDTO
/* 4: */ {
/* 5: */ private int answerId;
/* 6: */ private String optionA;
/* 7: */ private String optionB;
/* 8: */ private String optionC;
/* 9: */ private String optionD;
/* 10: */ private String optionE;
/* 11: */ private String optionF;
/* 12: */ private String optionG;
/* 13: */ private String answer;
/* 14: */ private int questionId;
/* 15: */
/* 16: */ public int getAnswerId()
/* 17: */ {
/* 18:20 */ return this.answerId;
/* 19: */ }
/* 20: */
/* 21: */ public void setAnswerId(int answerId)
/* 22: */ {
/* 23:23 */ this.answerId = answerId;
/* 24: */ }
/* 25: */
/* 26: */ public String getOptionA()
/* 27: */ {
/* 28:26 */ return this.optionA;
/* 29: */ }
/* 30: */
/* 31: */ public void setOptionA(String optionA)
/* 32: */ {
/* 33:29 */ this.optionA = optionA;
/* 34: */ }
/* 35: */
/* 36: */ public String getOptionB()
/* 37: */ {
/* 38:32 */ return this.optionB;
/* 39: */ }
/* 40: */
/* 41: */ public void setOptionB(String optionB)
/* 42: */ {
/* 43:35 */ this.optionB = optionB;
/* 44: */ }
/* 45: */
/* 46: */ public String getOptionC()
/* 47: */ {
/* 48:38 */ return this.optionC;
/* 49: */ }
/* 50: */
/* 51: */ public void setOptionC(String optionC)
/* 52: */ {
/* 53:41 */ this.optionC = optionC;
/* 54: */ }
/* 55: */
/* 56: */ public String getOptionD()
/* 57: */ {
/* 58:44 */ return this.optionD;
/* 59: */ }
/* 60: */
/* 61: */ public void setOptionD(String optionD)
/* 62: */ {
/* 63:47 */ this.optionD = optionD;
/* 64: */ }
/* 65: */
/* 66: */ public String getOptionE()
/* 67: */ {
/* 68:50 */ return this.optionE;
/* 69: */ }
/* 70: */
/* 71: */ public void setOptionE(String optionE)
/* 72: */ {
/* 73:53 */ this.optionE = optionE;
/* 74: */ }
/* 75: */
/* 76: */ public String getOptionF()
/* 77: */ {
/* 78:56 */ return this.optionF;
/* 79: */ }
/* 80: */
/* 81: */ public void setOptionF(String optionF)
/* 82: */ {
/* 83:59 */ this.optionF = optionF;
/* 84: */ }
/* 85: */
/* 86: */ public String getOptionG()
/* 87: */ {
/* 88:62 */ return this.optionG;
/* 89: */ }
/* 90: */
/* 91: */ public void setOptionG(String optionG)
/* 92: */ {
/* 93:65 */ this.optionG = optionG;
/* 94: */ }
/* 95: */
/* 96: */ public String getAnswer()
/* 97: */ {
/* 98:68 */ return this.answer;
/* 99: */ }
/* :0: */
/* :1: */ public void setAnswer(String answer)
/* :2: */ {
/* :3:71 */ this.answer = answer;
/* :4: */ }
/* :5: */
/* :6: */ public int getQuestionId()
/* :7: */ {
/* :8:74 */ return this.questionId;
/* :9: */ }
/* ;0: */
/* ;1: */ public void setQuestionId(int questionId)
/* ;2: */ {
/* ;3:77 */ this.questionId = questionId;
/* ;4: */ }
/* ;5: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.questionbank.answer.dto.AnswerDTO
* JD-Core Version: 0.7.0.1
*/
|
package shared;
import java.lang.*;
/** This object contains the result information on one instance passed through
* an inducer.
* @author James Louis 12/08/2000 Ported to Java.
*/
public class CatOneTestResult {
/** The instance whose information is stored in this object.**/
public Instance instance;
/** The information on the category of the instance associated with this
object. **/
public AugCategory augCat;
/** The correct category for the instance. **/
public int correctCat;
/** The predicted classification distribution. **/
public CatDist predDist;
/** The correct classification distribution. **/
public CatDist correctDist;
/** Indicator for whether this instance is part of a training instance
list. **/
public boolean inTrainIL;
/** Constructor.
*/
public CatOneTestResult() {
instance = null;
augCat = null;
correctCat = Globals.UNDEFINED_INT;
predDist = null;
correctDist = null;
inTrainIL = false;
}
}
|
package programmers.level2;
import java.util.*;
public class OpenChatRoom {
class Solution {
HashMap<String, String> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
ArrayList<String> ids = new ArrayList<>();
public String[] solution(String[] record) {
splitRecord(record);
return printRecord();
}
public String[] printRecord() {
String[] answer = new String[list.size()];
int idx = 0;
for (String target : list) {
switch (target) {
case "Enter":
answer[idx] = map.get(ids.get(idx)) + "님이 들어왔습니다.";
idx++;
break;
case "Leave":
answer[idx] = map.get(ids.get(idx)) + "님이 나갔습니다.";
idx++;
break;
}
}
return answer;
}
public void splitRecord(String[] record) {
for (int i = 0; i < record.length; i++) {
String[] temp = record[i].split(" ");
putRecord(temp);
}
}
public void putRecord(String[] temp) {
if (!temp[0].equals("Leave"))
map.put(temp[1], temp[2]);
if (!temp[0].equals("Change")) {
list.add(temp[0]);
ids.add(temp[1]);
}
}
}
}
|
package name.kevinlocke.appveyor;
import static name.kevinlocke.appveyor.testutils.AssertMediaType.assertIsPng;
import static name.kevinlocke.appveyor.testutils.AssertMediaType.assertIsSvg;
import static name.kevinlocke.appveyor.testutils.AssertModels.assertModelAgrees;
import static name.kevinlocke.appveyor.testutils.AssertModels.assertModelAgreesExcluding;
import static name.kevinlocke.appveyor.testutils.AssertModels.assertModelEquals;
import static name.kevinlocke.appveyor.testutils.AssertModels.assertModelEqualsExcluding;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import org.testng.SkipException;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.Test;
import com.migcomponents.migbase64.Base64;
import name.kevinlocke.appveyor.api.BuildApi;
import name.kevinlocke.appveyor.api.CollaboratorApi;
import name.kevinlocke.appveyor.api.DeploymentApi;
import name.kevinlocke.appveyor.api.EnvironmentApi;
import name.kevinlocke.appveyor.api.ProjectApi;
import name.kevinlocke.appveyor.api.RoleApi;
import name.kevinlocke.appveyor.api.UserApi;
import name.kevinlocke.appveyor.model.ArtifactModel;
import name.kevinlocke.appveyor.model.Build;
import name.kevinlocke.appveyor.model.BuildMode;
import name.kevinlocke.appveyor.model.BuildStartRequest;
import name.kevinlocke.appveyor.model.CollaboratorAddition;
import name.kevinlocke.appveyor.model.CollaboratorUpdate;
import name.kevinlocke.appveyor.model.Deployment;
import name.kevinlocke.appveyor.model.DeploymentEnvironment;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentAddition;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentDeploymentsResults;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentLookupModel;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentProject;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentSettings;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentSettingsResults;
import name.kevinlocke.appveyor.model.DeploymentEnvironmentWithSettings;
import name.kevinlocke.appveyor.model.DeploymentProviderType;
import name.kevinlocke.appveyor.model.DeploymentStartRequest;
import name.kevinlocke.appveyor.model.EncryptRequest;
import name.kevinlocke.appveyor.model.EnvironmentDeploymentModel;
import name.kevinlocke.appveyor.model.NuGetFeed;
import name.kevinlocke.appveyor.model.Project;
import name.kevinlocke.appveyor.model.ProjectAddition;
import name.kevinlocke.appveyor.model.ProjectBuildNumberUpdate;
import name.kevinlocke.appveyor.model.ProjectBuildResults;
import name.kevinlocke.appveyor.model.ProjectConfiguration;
import name.kevinlocke.appveyor.model.ProjectDeployment;
import name.kevinlocke.appveyor.model.ProjectDeploymentModel;
import name.kevinlocke.appveyor.model.ProjectDeploymentsResults;
import name.kevinlocke.appveyor.model.ProjectHistory;
import name.kevinlocke.appveyor.model.ProjectSettingsResults;
import name.kevinlocke.appveyor.model.ProjectWithConfiguration;
import name.kevinlocke.appveyor.model.ReRunBuildRequest;
import name.kevinlocke.appveyor.model.RepositoryProvider;
import name.kevinlocke.appveyor.model.Role;
import name.kevinlocke.appveyor.model.RoleAce;
import name.kevinlocke.appveyor.model.RoleAddition;
import name.kevinlocke.appveyor.model.RoleWithGroups;
import name.kevinlocke.appveyor.model.Script;
import name.kevinlocke.appveyor.model.ScriptLanguage;
import name.kevinlocke.appveyor.model.SecurityDescriptor;
import name.kevinlocke.appveyor.model.Status;
import name.kevinlocke.appveyor.model.StoredNameValue;
import name.kevinlocke.appveyor.model.StoredValue;
import name.kevinlocke.appveyor.model.TestMode;
import name.kevinlocke.appveyor.model.UserAccount;
import name.kevinlocke.appveyor.model.UserAccountRolesResults;
import name.kevinlocke.appveyor.model.UserAddition;
import name.kevinlocke.appveyor.testutils.Resources;
import name.kevinlocke.appveyor.testutils.TestApiClient;
import name.kevinlocke.appveyor.testutils.json.FieldNameExclusionStrategy;
/**
* Tests for the AppVeyor API client.
*
* This class should be split into smaller classes, probably based on testing
* each *Api class separately. However, it is difficult to capture the API state
* dependencies since TestNG doesn't support cross-class method dependencies and
* requires data providers to either be in the same class or static. Group
* dependencies can be used, but are not reliable for running single tests
* https://stackoverflow.com/q/15762998 So for now the tests are all in this
* class.
*/
public class ApiTest {
/**
* Gets a short random string safe for use in URLs and filenames.
*
* Names for resources created by tests are made unique to avoid collisions
* during concurrent test runs. This is particularly a problem for
* deployment environments where names are not unique and startDeployment
* identifies the environment by name resulting in an unavoidable race.
*/
protected static final String randStr() {
byte[] randBytes = new byte[6];
ThreadLocalRandom.current().nextBytes(randBytes);
String randStr = Base64.encodeToString(randBytes, false);
String randUrlSafe = randStr.replace('+', '-').replace('/', '_');
return randUrlSafe;
}
public static final String TEST_BADGE_PROVIDER = RepositoryProvider.GITHUB
.toString();
public static final String TEST_BADGE_ACCOUNT = "gruntjs";
public static final String TEST_BADGE_SLUG = "grunt";
// AppVeyor account must exist and be different than APPVEYOR_API_TOKEN acct
public static final String TEST_COLLABORATOR_EMAIL = "appveyor-swagger@example.com";
public static final String TEST_COLLABORATOR_ROLE_NAME = "User";
public static final String TEST_ENCRYPT_VALUE = "encryptme";
public static final String TEST_ENVIRONMENT_PREFIX = "Test Env ";
public static final String TEST_ENVIRONMENT_NAME = TEST_ENVIRONMENT_PREFIX
+ randStr();
public static final Integer TEST_PROJECT_BUILD_NUMBER = 45;
public static final String TEST_PROJECT_BUILD_SCRIPT = Resources
.getAsString("/buildscript.ps1");
public static final String TEST_PROJECT_BRANCH = "master";
// Note: Using GitHub provider requires GitHub auth to AppVeyor test user
public static final RepositoryProvider TEST_PROJECT_REPO_PROVIDER = RepositoryProvider.GIT;
public static final String TEST_PROJECT_REPO_NAME = "https://github.com/kevinoid/empty.git";
public static final String TEST_PROJECT_TEST_SCRIPT = Resources
.getAsString("/testscript.ps1");
public static final String TEST_ROLE_PREFIX = "Test Role ";
public static final String TEST_ROLE_NAME = TEST_ROLE_PREFIX + randStr();
public static final String TEST_USER_EMAIL_AT_DOMAIN = "@example.com";
public static final String TEST_USER_EMAIL = randStr()
+ TEST_USER_EMAIL_AT_DOMAIN;
public static final String TEST_USER_PREFIX = "Test User ";
public static final String TEST_USER_NAME = TEST_USER_PREFIX + randStr();
public static final String TEST_USER_ROLE_NAME = "User";
// Exclude jobs property of a build for operations which do not return it
private static final FieldNameExclusionStrategy buildExcludeJobs = new FieldNameExclusionStrategy(
"jobs", "updated");
// The message counts are updated asychronously via the Build Worker API.
// Messages can be added after the build reaches a final state and are
// therefore not reliable enough for comparison in the tests.
private static final FieldNameExclusionStrategy buildJobExcludes = new FieldNameExclusionStrategy(
"compilationErrorsCount", "compilationMessagesCount",
"compilationWarningsCount", "failedTestsCount", "messagesCount",
"passedTestsCount", "testsCount", "updated");
// Exclude updated field due to change on update operation
private static final FieldNameExclusionStrategy excludeUpdated = new FieldNameExclusionStrategy(
"updated");
// Exclude currentBuildId, nuGetFeed, repositoryBranch, securityDescriptor when comparing
// Project results from endpoints which don't include these
// Exclude builds and updated which change as the result of other tests
private static final FieldNameExclusionStrategy projectExcludes = new FieldNameExclusionStrategy(
"builds", "currentBuildId", "nuGetFeed", "repositoryBranch", "securityDescriptor",
"updated");
protected final ApiClient apiClient;
protected final BuildApi buildApi;
protected final CollaboratorApi collaboratorApi;
protected final DeploymentApi deploymentApi;
protected final EnvironmentApi environmentApi;
protected final ProjectApi projectApi;
protected final RoleApi roleApi;
protected final UserApi userApi;
private final ReentrantLock systemRolesLock = new ReentrantLock();
private volatile Map<String, Role> systemRolesByName;
protected volatile ArtifactModel testArtifact;
protected volatile ArtifactModel testArtifactPath;
protected volatile Build testBuild;
protected volatile UserAccount testCollaborator;
protected volatile Deployment testDeployment;
protected volatile DeploymentEnvironmentWithSettings testEnvironment;
protected volatile Project testProject;
protected volatile ProjectWithConfiguration testProjectConfig;
protected volatile String testProjectYaml;
protected volatile Build testRebuild;
protected volatile RoleWithGroups testRole;
protected volatile UserAccount testUser;
public ApiTest() {
apiClient = TestApiClient.getTestApiClient();
buildApi = new BuildApi(apiClient);
collaboratorApi = new CollaboratorApi(apiClient);
deploymentApi = new DeploymentApi(apiClient);
environmentApi = new EnvironmentApi(apiClient);
projectApi = new ProjectApi(apiClient);
roleApi = new RoleApi(apiClient);
userApi = new UserApi(apiClient);
}
/**
* "Normalizes" a SecurityDescriptor to only include system roles, to make
* it consistent regardless of which roles exist.
*/
protected void normalizeSecurity(SecurityDescriptor securityDescriptor)
throws ApiException {
Iterator<RoleAce> roleAcesIter = securityDescriptor.getRoleAces()
.iterator();
while (roleAcesIter.hasNext()) {
RoleAce roleAce = roleAcesIter.next();
if (getSystemRoleByName(roleAce.getName()) == null) {
roleAcesIter.remove();
}
}
}
/**
* "Normalizes" the SecurityDescriptor to only include system roles, to make
* it consistent regardless of which roles exist.
*/
protected void normalizeSecurity(
DeploymentEnvironment deploymentEnvironment) throws ApiException {
normalizeSecurity(deploymentEnvironment.getSecurityDescriptor());
}
/**
* "Normalizes" the SecurityDescriptor to only include system roles, to make
* it consistent regardless of which roles exist.
*/
protected void normalizeSecurity(
DeploymentEnvironmentWithSettings deploymentEnvironment)
throws ApiException {
normalizeSecurity(deploymentEnvironment.getSecurityDescriptor());
}
/**
* "Normalizes" the SecurityDescriptor to only include system roles, to make
* it consistent regardless of which roles exist.
*/
protected void normalizeSecurity(Project project) throws ApiException {
normalizeSecurity(project.getSecurityDescriptor());
}
/**
* "Normalizes" the SecurityDescriptor to only include system roles, to make
* it consistent regardless of which roles exist.
*/
protected void normalizeSecurity(ProjectWithConfiguration project)
throws ApiException {
normalizeSecurity(project.getSecurityDescriptor());
}
@AfterGroups(groups = "role", alwaysRun = true)
public void cleanupTestRole() throws ApiException {
if (testRole != null) {
roleApi.deleteRole(testRole.getRoleId());
testRole = null;
}
}
public void cleanupOldTestRoles() throws ApiException {
for (Role role : getRolesInternal()) {
if (role.getName().startsWith(TEST_ROLE_PREFIX)) {
roleApi.deleteRole(role.getRoleId());
}
}
}
@Test(groups = "role")
public void addRole() throws ApiException {
RoleAddition roleAddition = new RoleAddition().name(TEST_ROLE_NAME);
RoleWithGroups role = roleApi.addRole(roleAddition);
testRole = role;
assertEquals(role.getName(), TEST_ROLE_NAME);
}
@Test(dependsOnMethods = "addRole", groups = "role")
public void addRoleDuplicate() {
RoleAddition roleAddition = new RoleAddition().name(TEST_ROLE_NAME);
try {
roleApi.addRole(roleAddition);
fail("Duplicate role added?");
} catch (ApiException e) {
assertTrue(e.getResponseBody().indexOf("already exists") >= 0);
}
}
@Test(dependsOnMethods = "addRole", groups = "role")
public void getRole() throws ApiException {
RoleWithGroups gotRole = roleApi.getRole(testRole.getRoleId());
assertModelEqualsExcluding(gotRole, testRole, excludeUpdated);
}
/** Gets Roles and caches (immutable) system roles if not yet cached. */
protected List<Role> getRolesInternal() throws ApiException {
// If the system roles haven't been cached yet, do the caching.
//
// Note: The lock must be held before the API call so that calls to
// getSystemRoleByName while roleApi.getRoles() is in progress do not
// cause a second (unnecessary) API call.
if (systemRolesByName == null) {
// Note: tryLock() so non-system calls do not block unnecessarily
if (systemRolesLock.tryLock()) {
try {
if (systemRolesByName == null) {
List<Role> roles = roleApi.getRoles();
Map<String, Role> newSystemRolesByName = new TreeMap<>();
for (Role role : roles) {
if (role.getIsSystem()) {
newSystemRolesByName.put(role.getName(), role);
}
}
systemRolesByName = newSystemRolesByName;
return roles;
}
} finally {
systemRolesLock.unlock();
}
}
}
return roleApi.getRoles();
}
protected Role getRoleByName(String roleName) throws ApiException {
for (Role role : getRolesInternal()) {
if (role.getName().equals(roleName)) {
return role;
}
}
return null;
}
protected Role getSystemRoleByName(String roleName) throws ApiException {
if (systemRolesByName == null) {
systemRolesLock.lock();
try {
if (systemRolesByName == null) {
getRolesInternal();
}
} finally {
systemRolesLock.unlock();
}
}
return systemRolesByName.get(roleName);
}
protected Collection<Role> getSystemRoles() throws ApiException {
if (systemRolesByName == null) {
systemRolesLock.lock();
try {
if (systemRolesByName == null) {
getRolesInternal();
}
} finally {
systemRolesLock.unlock();
}
}
return systemRolesByName.values();
}
protected void assertHasSystemRoles(Iterable<Role> roles)
throws ApiException {
TreeSet<Role> systemRoles = new TreeSet<>(new RoleNameComparator());
for (Role role : roles) {
if (role.getIsSystem()) {
systemRoles.add(role);
}
}
assertModelEquals(systemRoles, getSystemRoles());
}
@Test(dependsOnMethods = "addRole", groups = "role")
public void getRoles() throws ApiException {
Role testRoleByName = getRoleByName(TEST_ROLE_NAME);
assertNotNull(testRoleByName, TEST_ROLE_NAME + " not in list!?");
assertModelAgreesExcluding(testRoleByName, testRole, excludeUpdated);
}
@Test(dependsOnMethods = "addRole", groups = "role")
public void updateRole() throws ApiException {
RoleWithGroups updatedRole = roleApi.updateRole(testRole);
assertNotNull(updatedRole);
assertNotNull(updatedRole.getUpdated());
assertModelAgreesExcluding(updatedRole, testRole, excludeUpdated);
}
@AfterGroups(groups = "user", alwaysRun = true)
public void cleanupTestUser() throws ApiException {
if (testUser != null) {
userApi.deleteUser(testUser.getUserId());
testUser = null;
}
}
public void cleanupOldTestUsers() throws ApiException {
for (UserAccount user : userApi.getUsers()) {
if (user.getEmail().endsWith(TEST_USER_EMAIL_AT_DOMAIN)) {
userApi.deleteUser(user.getUserId());
}
}
}
@Test(groups = "user")
public void addUser() throws ApiException {
UserAddition userAddition = new UserAddition();
userAddition.setFullName(TEST_USER_NAME);
userAddition.setEmail(TEST_USER_EMAIL);
Role role = getSystemRoleByName(TEST_USER_ROLE_NAME);
userAddition.setRoleId(role.getRoleId());
userApi.addUser(userAddition);
}
@Test(dependsOnMethods = "addUser", groups = "user")
public void addUserDuplicate() throws ApiException {
UserAddition userAddition = new UserAddition();
userAddition.setFullName(TEST_USER_NAME);
userAddition.setEmail(TEST_USER_EMAIL);
Role role = getSystemRoleByName(TEST_USER_ROLE_NAME);
userAddition.setRoleId(role.getRoleId());
try {
userApi.addUser(userAddition);
fail("Duplicate user added?");
} catch (ApiException e) {
assertTrue(e.getResponseBody().indexOf("already exists") >= 0);
}
}
protected UserAccount getUserByEmail(String email) throws ApiException {
List<UserAccount> users = userApi.getUsers();
for (UserAccount user : users) {
if (user.getEmail().equals(TEST_USER_EMAIL)) {
return user;
}
}
return null;
}
@Test(dependsOnMethods = "addUser", groups = "user")
public void getUsers() throws ApiException {
UserAccount user = getUserByEmail(TEST_USER_EMAIL);
testUser = user;
assertNotNull(user, "Test user not found");
assertEquals(user.getEmail(), TEST_USER_EMAIL);
assertEquals(user.getFullName(), TEST_USER_NAME);
}
@Test(dependsOnMethods = "getUsers", groups = "user")
public void getUser() throws ApiException {
Integer testUserId = testUser.getUserId();
UserAccountRolesResults userRoles = userApi.getUser(testUserId);
UserAccount gotUser = userRoles.getUser();
assertNotNull(gotUser, "Test user not found");
assertModelEqualsExcluding(gotUser, testUser, excludeUpdated);
assertHasSystemRoles(userRoles.getRoles());
}
@Test(dependsOnMethods = "getUsers", groups = "user")
public void updateUser() throws ApiException {
userApi.updateUser(testUser);
UserAccountRolesResults updatedUserWithRoles = userApi
.getUser(testUser.getUserId());
UserAccount updatedUser = updatedUserWithRoles.getUser();
assertNotNull(updatedUser.getUpdated());
assertModelEqualsExcluding(updatedUser, testUser, excludeUpdated);
assertHasSystemRoles(updatedUserWithRoles.getRoles());
}
@AfterGroups(groups = "collaborator", alwaysRun = true)
public void cleanupTestCollaborator() throws ApiException {
if (testCollaborator != null) {
collaboratorApi.deleteCollaborator(testCollaborator.getUserId());
testCollaborator = null;
}
}
public void cleanupOldTestCollaborators() throws ApiException {
for (UserAccount user : collaboratorApi.getCollaborators()) {
if (user.getEmail().equals(TEST_COLLABORATOR_EMAIL)) {
collaboratorApi.deleteCollaborator(user.getUserId());
}
}
}
@Test(groups = "collaborator")
public void addCollaborator() throws ApiException {
CollaboratorAddition collaboratorAddition = new CollaboratorAddition();
collaboratorAddition.setEmail(TEST_COLLABORATOR_EMAIL);
int roleId = getSystemRoleByName(TEST_COLLABORATOR_ROLE_NAME)
.getRoleId();
collaboratorAddition.setRoleId(roleId);
try {
collaboratorApi.addCollaborator(collaboratorAddition);
} catch (ApiException e) {
if (e.getResponseBody().indexOf("already") >= 0) {
cleanupOldTestCollaborators();
collaboratorApi.addCollaborator(collaboratorAddition);
} else {
throw e;
}
}
}
@Test(dependsOnMethods = "addCollaborator", groups = "collaborator")
public void addCollaboratorDuplicate() throws ApiException {
CollaboratorAddition collaboratorAddition = new CollaboratorAddition();
collaboratorAddition.setEmail(TEST_COLLABORATOR_EMAIL);
int roleId = getSystemRoleByName(TEST_COLLABORATOR_ROLE_NAME)
.getRoleId();
collaboratorAddition.setRoleId(roleId);
try {
collaboratorApi.addCollaborator(collaboratorAddition);
fail("Duplicate collaborator added?");
} catch (ApiException e) {
assertTrue(e.getResponseBody().indexOf("already") >= 0);
}
}
protected UserAccount getCollaboratorByEmail(String collaboratorEmail)
throws ApiException {
List<UserAccount> collaborators = collaboratorApi.getCollaborators();
for (UserAccount collaborator : collaborators) {
if (collaborator.getEmail().equals(collaboratorEmail)) {
return collaborator;
}
}
return null;
}
@Test(dependsOnMethods = "addCollaborator", groups = "collaborator")
public void getCollaborators() throws ApiException {
UserAccount collaborator = getCollaboratorByEmail(
TEST_COLLABORATOR_EMAIL);
assertNotNull(collaborator, "Test collaborator not found");
testCollaborator = collaborator;
assertEquals(collaborator.getRoleName(), TEST_COLLABORATOR_ROLE_NAME);
Integer roleId = getSystemRoleByName(TEST_COLLABORATOR_ROLE_NAME)
.getRoleId();
assertEquals(collaborator.getRoleId(), roleId);
}
@Test(dependsOnMethods = "getCollaborators", groups = "collaborator")
public void getCollaborator() throws ApiException {
UserAccountRolesResults collaboratorWithRoles = collaboratorApi
.getCollaborator(testCollaborator.getUserId());
assertNotNull(collaboratorWithRoles, "Test collaborator not found");
UserAccount gotCollaborator = collaboratorWithRoles.getUser();
assertModelEqualsExcluding(gotCollaborator, testCollaborator,
excludeUpdated);
assertHasSystemRoles(collaboratorWithRoles.getRoles());
}
@Test(dependsOnMethods = "getCollaborators", groups = "collaborator")
public void updateCollaborator() throws ApiException {
CollaboratorUpdate collabUpdate = new CollaboratorUpdate();
collabUpdate.setUserId(testCollaborator.getUserId());
collabUpdate.setRoleId(testCollaborator.getRoleId());
collaboratorApi.updateCollaborator(collabUpdate);
}
@AfterGroups(groups = "environment", alwaysRun = true)
public void cleanupTestEnvironment() throws ApiException {
if (testEnvironment != null) {
environmentApi.deleteEnvironment(
testEnvironment.getDeploymentEnvironmentId());
testEnvironment = null;
}
}
public void cleanupOldTestEnvironments() throws ApiException {
for (DeploymentEnvironmentLookupModel environment : environmentApi
.getEnvironments()) {
if (environment.getName().startsWith(TEST_ENVIRONMENT_PREFIX)) {
environmentApi.deleteEnvironment(
environment.getDeploymentEnvironmentId());
}
}
}
@Test(groups = "environment")
public void addEnvironment() throws ApiException {
// Use a Webhook to http://example.com since Webhooks always succeed
DeploymentEnvironmentSettings settings = new DeploymentEnvironmentSettings();
settings.addProviderSettingsItem(new StoredNameValue().name("url")
.value(new StoredValue().value("http://example.com")));
DeploymentEnvironmentAddition environmentAddition = new DeploymentEnvironmentAddition()
.name(TEST_ENVIRONMENT_NAME)
.provider(DeploymentProviderType.WEBHOOK).settings(settings);
DeploymentEnvironmentWithSettings environment = environmentApi
.addEnvironment(environmentAddition);
normalizeSecurity(environment);
testEnvironment = environment;
assertEquals(environment.getName(), TEST_ENVIRONMENT_NAME);
}
protected DeploymentEnvironmentLookupModel getEnvironmentByName(String name)
throws ApiException {
for (DeploymentEnvironmentLookupModel environment : environmentApi
.getEnvironments()) {
if (environment.getName().equals(name)) {
return environment;
}
}
return null;
}
@Test(dependsOnMethods = "addEnvironment", groups = "environment")
public void getEnvironments() throws ApiException {
DeploymentEnvironmentLookupModel namedEnvironment = getEnvironmentByName(
testEnvironment.getName());
assertModelAgrees(namedEnvironment, testEnvironment);
}
@Test(dependsOnMethods = "addEnvironment", groups = "environment")
public void getEnvironmentSettings() throws ApiException {
Integer testEnvId = testEnvironment.getDeploymentEnvironmentId();
DeploymentEnvironmentSettingsResults gotEnvSettingsObj = environmentApi
.getEnvironmentSettings(testEnvId);
DeploymentEnvironmentWithSettings gotEnv = gotEnvSettingsObj
.getEnvironment();
List<DeploymentEnvironmentProject> projects = gotEnv.getProjects();
assertNotEquals(projects.size(), 0);
DeploymentEnvironmentProject project = projects.get(0);
// Assert that project contains expected properties
assertNotEquals(project.getName().length(), 0);
assertNotEquals((int) project.getProjectId(), 0);
assertNotNull(project.getIsSelected());
List<DeploymentEnvironmentProject> emptyProjects = Collections
.emptyList();
gotEnv.setProjects(emptyProjects);
normalizeSecurity(gotEnv);
assertModelEqualsExcluding(gotEnv, testEnvironment, excludeUpdated);
}
@Test(dependsOnMethods = "addEnvironment", groups = "environment")
public void updateEnvironment() throws ApiException {
DeploymentEnvironmentWithSettings updatedEnv = environmentApi
.updateEnvironment(testEnvironment);
assertNotNull(updatedEnv);
normalizeSecurity(updatedEnv);
assertModelEqualsExcluding(updatedEnv, testEnvironment, excludeUpdated);
assertNotNull(updatedEnv.getUpdated());
}
@AfterGroups(groups = "project", alwaysRun = true)
public void cleanupTestProject() throws ApiException {
if (testProject != null) {
projectApi.deleteProject(testProject.getAccountName(),
testProject.getSlug());
testProject = null;
}
}
public void cleanupOldTestProjects() throws ApiException {
for (Project project : projectApi.getProjects()) {
if (project.getRepositoryName().equals(TEST_PROJECT_REPO_NAME)) {
projectApi.deleteProject(project.getAccountName(),
project.getSlug());
}
}
}
@Test
public void encryptValue() throws ApiException {
EncryptRequest encryptReq = new EncryptRequest();
encryptReq.setPlainValue(TEST_ENCRYPT_VALUE);
String encrypted = projectApi.encryptValue(encryptReq);
// This isn't an API guarantee, just a sanity check
assertTrue(Pattern.matches("^[A-Za-z0-9/+]+={0,2}$", encrypted),
encrypted + " is base64-encoded string");
}
@Test(groups = "project")
public void addProject() throws ApiException {
ProjectAddition projectAddition = new ProjectAddition();
projectAddition.setRepositoryProvider(TEST_PROJECT_REPO_PROVIDER);
projectAddition.setRepositoryName(TEST_PROJECT_REPO_NAME);
Project project = projectApi.addProject(projectAddition);
testProject = project;
assertEquals(project.getRepositoryType(), TEST_PROJECT_REPO_PROVIDER);
assertEquals(project.getRepositoryName(), TEST_PROJECT_REPO_NAME);
}
@Test(dependsOnMethods = "addProject", groups = "project")
public void getProjects() throws ApiException {
int testProjectId = testProject.getProjectId();
Project foundProject = null;
for (Project project : projectApi.getProjects()) {
if (project.getProjectId() == testProjectId) {
foundProject = project;
break;
}
}
assertNotNull(foundProject);
assertModelEqualsExcluding(foundProject, testProject, projectExcludes);
}
// Note: Does not depend on startBuild since it creates a separate build
// to avoid interfering with testBuild (cancelled builds do not show
// up in all queries).
@Test(dependsOnMethods = "addProject", groups = "project")
public void cancelBuild() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
BuildStartRequest buildStart = new BuildStartRequest()
.accountName(accountName).projectSlug(slug);
Build cancelBuild = buildApi.startBuild(buildStart);
String version = cancelBuild.getVersion();
buildApi.cancelBuild(accountName, slug, version);
ProjectBuildResults cancelledBuildProject = projectApi
.getProjectBuildByVersion(accountName, slug, version);
Build cancelledBuild = cancelledBuildProject.getBuild();
Status cancelledBuildStatus = cancelledBuild.getStatus();
assertTrue(cancelledBuildStatus == Status.CANCELLED
|| cancelledBuildStatus == Status.CANCELLING);
}
@Test(dependsOnMethods = "addProject", groups = "project")
public void getProjectSettings() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
ProjectSettingsResults settings = projectApi
.getProjectSettings(accountName, slug);
ProjectWithConfiguration projectConfig = settings.getSettings();
normalizeSecurity(projectConfig);
testProjectConfig = projectConfig;
Project project = settings.getProject();
// Check both copies in response agree
assertModelAgreesExcluding(projectConfig, project, projectExcludes);
// Check each agrees with testProject
assertModelAgreesExcluding(projectConfig, testProject, projectExcludes);
assertModelEqualsExcluding(project, testProject, projectExcludes);
assertEquals(projectConfig.getRepositoryBranch(), TEST_PROJECT_BRANCH);
NuGetFeed nuGetFeed = projectConfig.getNuGetFeed();
assertNotNull(nuGetFeed.getAccountId());
assertNotNull(nuGetFeed.getCreated());
assertNotNull(nuGetFeed.getId());
assertNotNull(nuGetFeed.getName());
assertNotNull(nuGetFeed.getProjectId());
assertNotNull(nuGetFeed.getPublishingEnabled());
SecurityDescriptor security = projectConfig.getSecurityDescriptor();
assertNotNull(security);
assertNotEquals(security.getAccessRightDefinitions().size(), 0);
assertNotEquals(security.getRoleAces().size(), 0);
}
@Test(dependsOnMethods = "addProject", groups = "project")
public void getProjectSettingsYaml() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
testProjectYaml = projectApi.getProjectSettingsYaml(accountName, slug);
}
// Run after updateProjectSettingsYaml to ensure build scripts are
// configured for startBuild and not reset by the Yaml get/update ordering.
@Test(dependsOnMethods = { "getProjectSettings",
"updateProjectSettingsYaml" }, groups = "project")
public void updateProject() throws ApiException {
// Set dummy build/test scripts so build succeeds
// Note: appveyor.yml is ignored outside of GitHub unless configured:
// https://github.com/appveyor/ci/issues/1089#issuecomment-264549196
ProjectWithConfiguration projectConfig = testProjectConfig;
ProjectConfiguration config = projectConfig.getConfiguration();
// Set environment variables for getProjectEnvironmentVariables
config.addEnvironmentVariablesItem(new StoredNameValue().name("NULL")
.value(new StoredValue().isEncrypted(false)));
config.addEnvironmentVariablesItem(new StoredNameValue().name("EMPTY")
.value(new StoredValue().isEncrypted(false).value("")));
config.addEnvironmentVariablesItem(
new StoredNameValue().name("UNTRIMMED").value(
new StoredValue().isEncrypted(false).value(" val ")));
config.addEnvironmentVariablesItem(new StoredNameValue().name("NUM")
.value(new StoredValue().isEncrypted(false).value("1")));
config.addEnvironmentVariablesItem(
new StoredNameValue().name("ENCRYPTED").value(
new StoredValue().isEncrypted(true).value("foo")));
config.setBuildMode(BuildMode.SCRIPT);
config.setBuildScripts(
Arrays.asList(new Script().language(ScriptLanguage.PS)
.script(TEST_PROJECT_BUILD_SCRIPT)));
config.setTestMode(TestMode.SCRIPT);
config.setTestScripts(Arrays.asList(new Script()
.language(ScriptLanguage.PS).script(TEST_PROJECT_TEST_SCRIPT)));
projectApi.updateProject(projectConfig);
String accountName = projectConfig.getAccountName();
String slug = projectConfig.getSlug();
ProjectSettingsResults updatedProjectSettings = projectApi
.getProjectSettings(accountName, slug);
ProjectWithConfiguration updatedProject = updatedProjectSettings
.getSettings();
assertNotNull(updatedProject.getUpdated());
ProjectConfiguration updatedConfig = updatedProject.getConfiguration();
List<Script> buildScripts = updatedConfig.getBuildScripts();
assertEquals(buildScripts.size(), 1);
assertEquals(buildScripts.get(0).getScript(),
TEST_PROJECT_BUILD_SCRIPT);
List<Script> testScripts = updatedConfig.getTestScripts();
assertEquals(testScripts.size(), 1);
assertEquals(testScripts.get(0).getScript(), TEST_PROJECT_TEST_SCRIPT);
}
@Test(dependsOnMethods = "updateProject", groups = "project")
public void getProjectEnvironmentVariables() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
List<StoredNameValue> envVars = projectApi
.getProjectEnvironmentVariables(accountName, slug);
List<StoredNameValue> testVars = testProjectConfig.getConfiguration()
.getEnvironmentVariables();
assertNotEquals(testVars.size(), 0);
assertModelAgrees(envVars, testVars);
}
@Test(dependsOnMethods = "getProjectEnvironmentVariables", groups = "project")
public void updateProjectEnvironmentVariables() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
List<StoredNameValue> newVars = Arrays
.asList(new StoredNameValue().name("UPDATED").value(
new StoredValue().isEncrypted(false).value("value")));
projectApi.updateProjectEnvironmentVariables(accountName, slug,
newVars);
List<StoredNameValue> envVars = projectApi
.getProjectEnvironmentVariables(accountName, slug);
assertModelAgrees(envVars, newVars);
}
@Test(dependsOnMethods = "getProjectSettingsYaml", groups = "project")
public void updateProjectSettingsYaml() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
projectApi.updateProjectSettingsYaml(accountName, slug,
testProjectYaml.getBytes());
}
// Depends on cancelBuild so that the build number will be set after the
// cancelled build is started. That way there is no chance of the build
// number being used by cancelBuild instead of startBuild.
@Test(dependsOnMethods = { "cancelBuild",
"updateProject" }, groups = "project")
public void updateProjectBuildNumber() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
ProjectBuildNumberUpdate pbnu = new ProjectBuildNumberUpdate()
.nextBuildNumber(TEST_PROJECT_BUILD_NUMBER);
projectApi.updateProjectBuildNumber(accountName, slug, pbnu);
}
@Test(dependsOnMethods = "updateProjectBuildNumber", groups = "project")
public void startBuild() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
BuildStartRequest buildStart = new BuildStartRequest()
.accountName(accountName).projectSlug(slug)
.branch(TEST_PROJECT_BRANCH)
.putEnvironmentVariablesItem("TEST_VAR", "1");
Build build = buildApi.startBuild(buildStart);
testBuild = build;
assertEquals(build.getBranch(), TEST_PROJECT_BRANCH);
assertEquals(build.getBuildNumber(), TEST_PROJECT_BUILD_NUMBER);
}
private ProjectBuildResults waitForBuild(String accountName, String slug, String version)
throws ApiException, InterruptedException
{
while (true) {
ProjectBuildResults projectBuild = projectApi.getProjectBuildByVersion(accountName,
slug, version);
Status buildStatus = projectBuild.getBuild().getStatus();
if (buildStatus != Status.QUEUED
&& buildStatus != Status.STARTING
&& buildStatus != Status.RUNNING) {
return projectBuild;
}
Thread.sleep(1000);
}
}
// This is not really a test, but is used for synchronization by other tests
@Test(dependsOnMethods = "startBuild", groups = "project")
public void waitForBuild() throws ApiException, InterruptedException {
ProjectBuildResults projectBuild = this.waitForBuild(
testProject.getAccountName(),
testProject.getSlug(),
testBuild.getVersion());
Build build = projectBuild.getBuild();
testBuild = build;
assertNotNull(build.getFinished());
Project project = projectBuild.getProject();
assertModelEqualsExcluding(project, testProject, projectExcludes);
}
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void successfulBuild() {
Status status = testBuild.getStatus();
if (status != Status.SUCCESS) {
throw new AssertionError(String.format(
"Build status %s != %s. Check getBuildLog output.", status,
Status.SUCCESS));
}
}
@Test(dependsOnMethods = "successfulBuild", groups = "project")
public void reRunBuild() throws ApiException {
Build origBuild = testBuild;
int buildId = origBuild.getBuildId();
try {
ReRunBuildRequest reRunIncompleteBuild = new ReRunBuildRequest()
.buildId(buildId)
.reRunIncomplete(true);
buildApi.reRunBuild(reRunIncompleteBuild);
fail("Expected ApiException due to reRunIncomplete: true");
} catch (ApiExceptionWithModel ex) {
assertEquals(ex.getCode(), 500);
assertEquals(
ex.getResponseModel().getMessage(),
"No failed or cancelled jobs in build with ID " + buildId);
}
ReRunBuildRequest reRunBuild = new ReRunBuildRequest()
.buildId(buildId);
Build rebuild = buildApi.reRunBuild(reRunBuild);
testRebuild = rebuild;
assertEquals(rebuild.getCommitId(), origBuild.getCommitId());
assertEquals(rebuild.getProjectId(), origBuild.getProjectId());
assertNotEquals(rebuild.getBuildId(), origBuild.getBuildId());
assertNotEquals(rebuild.getVersion(), origBuild.getVersion());
}
// This is not really a test, but is used for synchronization by other tests
@Test(dependsOnMethods = "reRunBuild", groups = "project")
public void waitForRebuild() throws ApiException, InterruptedException {
ProjectBuildResults projectBuild = this.waitForBuild(
testProject.getAccountName(),
testProject.getSlug(),
testRebuild.getVersion());
Build build = projectBuild.getBuild();
testRebuild = build;
assertNotNull(build.getFinished());
Project project = projectBuild.getProject();
assertModelEqualsExcluding(project, testProject, projectExcludes);
}
@Test(dependsOnMethods = "waitForRebuild", groups = "project")
public void successfulRebuild() {
Status status = testRebuild.getStatus();
if (status != Status.SUCCESS) {
throw new AssertionError(String.format(
"Rebuild status %s != %s. Check getBuildLog output.", status,
Status.SUCCESS));
}
}
// Note: Will 404 for projects with no build
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void getProjectStatusBadge()
throws ApiException, FileNotFoundException, IOException {
String statusBadgeId = testProjectConfig.getStatusBadgeId();
File pngBadge = projectApi.getProjectStatusBadge(statusBadgeId, false,
false, null, null, null);
assertTrue(pngBadge.exists());
long pngSize = pngBadge.length();
try {
assertIsPng(pngBadge.toPath());
} finally {
pngBadge.delete();
}
File retinaBadge = projectApi.getProjectStatusBadge(statusBadgeId,
false,
true, null, null, null);
assertTrue(retinaBadge.exists());
long retinaSize = retinaBadge.length();
try {
assertIsPng(retinaBadge.toPath());
assertTrue(retinaSize > pngSize);
} finally {
retinaBadge.delete();
}
String uid = new BigInteger(128, new Random()).toString(36);
File svgBadge = projectApi.getProjectStatusBadge(statusBadgeId, true,
false,
uid, uid, uid);
assertTrue(svgBadge.exists());
try {
assertIsSvg(svgBadge.toPath());
String svgBadgeText = new String(
Files.readAllBytes(svgBadge.toPath()));
assertTrue(svgBadgeText.contains(uid));
} finally {
svgBadge.delete();
}
}
@Test
public void getPublicProjectStatusBadge()
throws ApiException, FileNotFoundException, IOException {
File pngBadge = projectApi.getPublicProjectStatusBadge(
TEST_BADGE_PROVIDER, TEST_BADGE_ACCOUNT, TEST_BADGE_SLUG, null,
false, false, null, null, null);
assertTrue(pngBadge.exists());
long pngSize = pngBadge.length();
try {
assertIsPng(pngBadge.toPath());
} finally {
pngBadge.delete();
}
File retinaBadge = projectApi.getPublicProjectStatusBadge(
TEST_BADGE_PROVIDER, TEST_BADGE_ACCOUNT, TEST_BADGE_SLUG, null,
false, true, null, null, null);
assertTrue(retinaBadge.exists());
long retinaSize = retinaBadge.length();
try {
assertIsPng(retinaBadge.toPath());
assertTrue(retinaSize > pngSize);
} finally {
retinaBadge.delete();
}
String uid = new BigInteger(128, new Random()).toString(36);
File svgBadge = projectApi.getPublicProjectStatusBadge(
TEST_BADGE_PROVIDER, TEST_BADGE_ACCOUNT, TEST_BADGE_SLUG, null,
true, false, uid, uid, uid);
assertTrue(svgBadge.exists());
try {
assertIsSvg(svgBadge.toPath());
String svgBadgeText = new String(
Files.readAllBytes(svgBadge.toPath()));
assertTrue(svgBadgeText.contains(uid));
} finally {
svgBadge.delete();
}
String branchUid = new BigInteger(128, new Random()).toString(36);
File svgBranchBadge = projectApi.getPublicProjectStatusBadge(
TEST_BADGE_PROVIDER, TEST_BADGE_ACCOUNT, TEST_BADGE_SLUG,
"master", true, false, branchUid, branchUid, branchUid);
assertTrue(svgBranchBadge.exists());
try {
assertIsSvg(svgBranchBadge.toPath());
String svgBranchBadgeText = new String(
Files.readAllBytes(svgBranchBadge.toPath()));
assertTrue(svgBranchBadgeText.contains(branchUid));
} finally {
svgBranchBadge.delete();
}
}
@Test(dependsOnMethods = "successfulBuild", groups = "project")
public void getBuildArtifacts() throws ApiException {
String jobId = testBuild.getJobs().get(0).getJobId();
List<ArtifactModel> artifacts = buildApi.getBuildArtifacts(jobId);
for (ArtifactModel artifact : artifacts) {
String fileName = artifact.getFileName();
if (fileName.indexOf('/') >= 0) {
testArtifactPath = artifact;
} else {
testArtifact = artifact;
}
}
assertNotNull(testArtifact);
assertNotNull(testArtifactPath);
}
@Test(dependsOnMethods = "getBuildArtifacts", groups = "project")
public void getBuildArtifact() throws ApiException {
String jobId = testBuild.getJobs().get(0).getJobId();
String testName = testArtifact.getFileName();
File artifact1 = buildApi.getBuildArtifact(jobId, testName);
assertTrue(artifact1.exists());
try {
assertNotEquals(artifact1.length(), 0L);
} finally {
artifact1.delete();
}
String testPath = testArtifactPath.getFileName();
File artifact2 = buildApi.getBuildArtifact(jobId, testPath);
assertTrue(artifact2.exists());
try {
assertNotEquals(artifact2.length(), 0L);
} finally {
artifact2.delete();
}
}
@Test(dependsOnMethods = "getBuildArtifacts", groups = "project")
public void getProjectArtifact() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
String testName = testArtifact.getFileName();
File artifact1 = projectApi.getProjectArtifact(accountName, slug,
testName, null, null, null, null, null);
assertTrue(artifact1.exists());
try {
assertNotEquals(artifact1.length(), 0L);
} finally {
artifact1.delete();
}
String testPath = testArtifactPath.getFileName();
File artifact2 = projectApi.getProjectArtifact(accountName, slug,
testPath, null, null, null, null, null);
assertTrue(artifact2.exists());
try {
assertNotEquals(artifact2.length(), 0L);
} finally {
artifact2.delete();
}
}
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void getBuildLog()
throws ApiException, FileNotFoundException, IOException {
File buildLog = buildApi
.getBuildLog(testBuild.getJobs().get(0).getJobId());
assertTrue(buildLog.exists());
try (BufferedReader buildLogReader = new BufferedReader(
new FileReader(buildLog))) {
assertTrue(buildLogReader.readLine().contains("Build started"));
} finally {
buildLog.delete();
}
}
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void getProjectLastBuild() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
ProjectBuildResults lastProjectBuild = projectApi
.getProjectLastBuild(accountName, slug);
Project project = lastProjectBuild.getProject();
assertModelEqualsExcluding(project, testProject, projectExcludes);
Build lastBuild = lastProjectBuild.getBuild();
assertModelEqualsExcluding(lastBuild, testBuild, buildJobExcludes);
}
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void getProjectLastBuildBranch() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
String branch = testBuild.getBranch();
ProjectBuildResults branchBuild = projectApi
.getProjectLastBuildBranch(accountName, slug, branch);
Project project = branchBuild.getProject();
assertModelEqualsExcluding(project, testProject, projectExcludes);
Build build = branchBuild.getBuild();
assertModelEqualsExcluding(build, testBuild, buildJobExcludes);
}
@Test(dependsOnMethods = "waitForBuild", groups = "project")
public void getProjectHistory() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
ProjectHistory history = projectApi.getProjectHistory(accountName, slug,
10, null, null);
Project project = history.getProject();
assertModelEqualsExcluding(project, testProject, projectExcludes);
List<Build> builds = history.getBuilds();
assertNotEquals(builds.size(), 0);
Build lastBuild = builds.get(0);
// This operation does not include the jobs property
assertTrue(lastBuild.getJobs().isEmpty());
assertModelEqualsExcluding(lastBuild, testBuild, buildExcludeJobs);
}
@Test(dependsOnMethods = { "addEnvironment", "addProject",
"successfulBuild" }, groups = { "environment", "project" })
public void startDeployment() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
String buildJobId = testBuild.getJobs().get(0).getJobId();
DeploymentStartRequest deploymentStart = new DeploymentStartRequest();
deploymentStart.setEnvironmentName(testEnvironment.getName());
deploymentStart.setAccountName(accountName);
deploymentStart.setProjectSlug(slug);
deploymentStart.setBuildVersion(testBuild.getVersion());
deploymentStart.setBuildJobId(buildJobId);
Deployment deployment = deploymentApi.startDeployment(deploymentStart);
DeploymentEnvironment environment = deployment.getEnvironment();
normalizeSecurity(environment);
testDeployment = deployment;
Build build = deployment.getBuild();
// "jobs" property is not returned by this operation
assertTrue(build.getJobs().isEmpty());
assertModelEqualsExcluding(build, testBuild, buildExcludeJobs);
assertModelAgreesExcluding(environment, testEnvironment,
excludeUpdated);
}
// This is not really a test, but is used for synchronization by other tests
// Set priority > 0 so build can run during default priority tests
@Test(dependsOnMethods = "startDeployment", groups = { "environment",
"project" })
public void waitForDeployment() throws ApiException, InterruptedException {
Integer deploymentId = testDeployment.getDeploymentId();
Deployment deployment;
Status deploymentStatus;
while (true) {
ProjectDeployment projectDeployment = deploymentApi
.getDeployment(deploymentId);
deployment = projectDeployment.getDeployment();
deploymentStatus = deployment.getStatus();
if (deploymentStatus != Status.QUEUED
&& deploymentStatus != Status.RUNNING) {
break;
}
Thread.sleep(1000);
}
testDeployment = deployment;
// Note: This may fail if AppVeyor starts checking Webhook results
// In that case, adjust Webhook URL to something valid.
assertEquals(deploymentStatus, Status.SUCCESS);
assertNotNull(deployment.getFinished());
}
@Test(dependsOnMethods = "waitForDeployment", groups = { "environment",
"project" })
public void getEnvironmentDeployments() throws ApiException {
Integer testEnvId = testEnvironment.getDeploymentEnvironmentId();
DeploymentEnvironmentDeploymentsResults envDeps = environmentApi
.getEnvironmentDeployments(testEnvId);
List<EnvironmentDeploymentModel> deployments = envDeps.getDeployments();
assertEquals(deployments.size(), 1);
EnvironmentDeploymentModel deployment = deployments.get(0);
assertModelAgrees(deployment, testDeployment);
assertModelAgrees(deployment.getProject(), testProject);
}
@Test(dependsOnMethods = "waitForDeployment", groups = { "environment",
"project" })
public void getProjectDeployments() throws ApiException {
String accountName = testProject.getAccountName();
String slug = testProject.getSlug();
// getProjectDeployments is flaky and often returns 500 due to timeout.
// The recordsNumber value used by the website often changes.
// Document observed changes and ignore timeout errors.
//
// Note: On 2018-06-05 started failing for recordsNumber < 11.
// Use 12 as the website currently does.
// Note: On 2018-09-03 started failing for recordsNumber == 12.
// Use 10 as the website currently does.
// Note: On 2018-09-20 started failing for recordsNumber == 10.
// Use 11 as the website currently does.
// Note: On 2018-10-31 timeout errors.
// Website using 10 again.
ProjectDeploymentsResults projectDeployments;
try {
projectDeployments =
projectApi.getProjectDeployments(accountName, slug, 11);
} catch (ApiExceptionWithModel ex) {
String errMsg = ex.getResponseModel().getMessage();
if (Pattern.matches("(?i)\\btime\\s*out\\b", errMsg))
{
throw new SkipException("getProjectDeployments timeout", ex);
}
throw ex;
}
Project project = projectDeployments.getProject();
assertModelAgreesExcluding(project, testProject, projectExcludes);
List<ProjectDeploymentModel> environmentDeployments = projectDeployments
.getDeployments();
assertEquals(environmentDeployments.size(), 1);
ProjectDeploymentModel environmentDeployment = environmentDeployments
.get(0);
assertModelAgrees(environmentDeployment, testDeployment);
}
public static void main(String[] args) throws ApiException {
ApiTest apiTest = new ApiTest();
apiTest.cleanupOldTestProjects();
apiTest.cleanupOldTestEnvironments();
apiTest.cleanupOldTestCollaborators();
apiTest.cleanupOldTestUsers();
apiTest.cleanupOldTestRoles();
}
}
class RoleNameComparator implements Comparator<Role> {
@Override
public int compare(Role role1, Role role2) {
return role1.getName().compareTo(role2.getName());
}
}
|
/**
*****************************************
*****************************************
* Cpr E 419 - Lab 4 *********************
*****************************************
*****************************************
*/
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler;
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class MySort extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new MySort(), args);
System.exit(res);
}
public int run(String[] args) throws Exception {
if (args.length != 4) {
throw new IllegalArgumentException("\nargs format: input_path output_path temp_path partitionlist_path");
}
int reduce_tasks = 15;
// based on the input file (last 4 chars), calculate the number of samples
double freq = 0.05;
int numSamples = 1000000;
String inputStr = args[0];
int length = inputStr.length();
String numRecords = inputStr.substring(length - 4);
if (numRecords.equals("250M")) {
numSamples = (int) (250 * 1000 * 1000 * freq);
if (numSamples > 1000000) {
numSamples = 1000000;
freq = (double) numSamples / (250.0 * 1000 * 1000);
}
}
else if (numRecords.equals("500K")) {
numSamples = (int) (500 * 1000 * freq);
}
else if (numRecords.equals("-50K")) {
numSamples = (int) (50 * 1000 * freq);
}
else if (numRecords.equals("-50M")) {
numSamples = (int) (50 * 1000 * 1000 * freq);
if (numSamples > 1000000) {
numSamples = 1000000;
freq = (double) numSamples / (50.0 * 1000 * 1000);
}
}
else if (numRecords.equals("t-5K")) {
numSamples = (int) (5 * 1000 * freq);
}
else if (numRecords.equals("t-5M")) {
numSamples = (int) (5 * 1000 * 1000 * freq);
}
// set the first job
Configuration conf = new Configuration();
Job job_one = new Job(conf, "Lab4: Large Dataset Sort (Phase One)");
job_one.setJarByClass(MySort.class);
job_one.setNumReduceTasks(0);
job_one.setOutputKeyClass(Text.class);
job_one.setOutputValueClass(Text.class);
job_one.setMapperClass(CleanerMapper.class);
job_one.setInputFormatClass(TextInputFormat.class);
job_one.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(job_one, new Path(args[0]));
FileOutputFormat.setOutputPath(job_one, new Path(args[2]));
job_one.waitForCompletion(true);
// set the second job
Job job_two = new Job(conf, "Lab4: Large Dataset Sort (Phase Two)");
job_two.setJarByClass(MySort.class);
FileInputFormat.addInputPath(job_two, new Path(args[2]));
FileOutputFormat.setOutputPath(job_two, new Path(args[1]));
job_two.setOutputKeyClass(Text.class);
job_two.setOutputValueClass(Text.class);
job_two.setInputFormatClass(SequenceFileInputFormat.class);
job_two.setOutputFormatClass(TextOutputFormat.class);
//job_two.setMapperClass(Map.class);
job_two.setReducerClass(Reduce.class);
job_two.setNumReduceTasks(reduce_tasks);
job_two.setPartitionerClass(TotalOrderPartitioner.class);
// path for the sample file
Path p = new Path(args[3]);
TotalOrderPartitioner.setPartitionFile(job_two.getConfiguration(), p);
// InputSampler.Sampler<Text, Text> sampler = new InputSampler.SplitSampler<Text, Text>(numSamples);
InputSampler.Sampler<Text, Text> sampler = new InputSampler.RandomSampler<Text, Text>(freq, numSamples, 20);
// InputSampler.Sampler<Text, Text> sampler = new InputSampler.IntervalSampler<Text, Text>(freq);
InputSampler.writePartitionFile(job_two, sampler);
// Add partitionFile to DistributedCache
Configuration jobconf = job_two.getConfiguration();
String partitionFile =TotalOrderPartitioner.getPartitionFile(jobconf);
URI partitionUri = new URI(partitionFile + "#" + TotalOrderPartitioner.DEFAULT_PATH);
DistributedCache.addCacheFile(partitionUri, jobconf);
DistributedCache.createSymlink(conf);
// Run the job
job_two.waitForCompletion(true);
return 0;
}
// The CleanerMapper Class
public static class CleanerMapper extends Mapper<LongWritable, Text, Text, Text> {
// The map method
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
if (line != null) {
String keystr = line.substring(0, 10);
String valuestr = line.substring(10);
context.write(new Text(keystr), new Text(valuestr));
}
}
}
// // The Map Class
// public static class Map extends Mapper<Text, Text, Text, Text> {
//
// // The map method
// public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
//
// context.write(key, value);
// }
// }
// The reduce class
public static class Reduce extends Reducer<Text, Text, Text, Text> {
// The reduce method
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
for (Text val : values) {
context.write(key, val);
}
}
}
}
|
package com.example.cjcu.listenertry;
public abstract class AOperator {
protected double num_A;
protected double num_B;
public AOperator(){
this.num_A = 0;
this.num_B = 0;
}
public void setNum_A(double num_A){
this.num_A = num_A;
}
public void setNum_B(double num_B){
this.num_B = num_B;
}
public void setNumbers(double num_A,double num_B){
setNum_A(num_A);
setNum_B(num_B);
}
public abstract double getAns() throws DivisionException;
}
|
package com.plivo.constants;
public class EndPoints {
public static final String GET_NUMBERS = "/v1/Account/{authid}/Number/";
public static final String POST_MESSAGE = "/v1/Account/{authid}/Message/";
public static final String GET_MESSAGE_DETAILS = "/v1/Account/{authid}/Message/{message_uuid}/";
public static final String GET_PRICING = "/v1/Account/{authid}/Pricing/";
public static final String GET_ACCOUNT_DETAILS = "/v1/Account/{auth_id}/";
}
|
import javafx.application.Application;
import javafx.animation.PauseTransition;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.HashMap;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
public class GUIServer extends Application{
Label welcomeLabel, portLabel, waitingLabel, currentGameLabel;//currentGameLabel show the message on Scene 3 top
TextField serverport;//Get the port number input from server listening
Button serverChoice; // This is the button for Scene 1 "Enter" button;
HashMap<String, Scene> sceneMap;//sceneMap use to store 3 different GUI scenes on server
HBox portBox;
VBox startBox; // a Container to store the all contents such as labels,TextField,button in scene 1
Scene startScene; //First Scene in server : Scene1
BorderPane startPane;
Server serverConnection;
PauseTransition pause = new PauseTransition(Duration.seconds(5));
//Client clientConnection;
ListView<String> listItemsServer;
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
//feel free to remove the starter code from this method
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("(Server) Let's Play Word Guess!!!");
welcomeLabel = new Label("Welcome to Word Guess!");
welcomeLabel.setFont(new Font("Cambria", 30));
welcomeLabel.setTextFill(Color.web("white"));
portLabel = new Label("Enter port #:");
portLabel.setFont(new Font("Cambria", 30));
portLabel.setTextFill(Color.web("white"));
this.serverChoice = new Button("Enter");
serverChoice.setDisable(false);
this.serverChoice.setStyle("-fx-pref-width: 150px");
//Set pause event
pause.setOnFinished(e->serverChoice.setDisable(false));
//Set button listening
this.serverChoice.setOnAction(e->{
String portString= serverport.getText();
//Test port input is number or not
if(!GUIServer.isNumeric(portString)) {
serverChoice.setDisable(true);
serverport.setText("Input should be a number!");
pause.play();
}
else {
primaryStage.setScene(sceneMap.get("waiting"));
primaryStage.setTitle("Welcome to Word Guess Server");
serverConnection = new Server(data -> {
Platform.runLater(()->{
listItemsServer.getItems().add(data.toString());
});
}, Integer.parseInt(serverport.getText()));//For constructor you made
}//end else
}); //End Enter Button setOnAction
this.serverport = new TextField("Input port number");
this.serverport.setStyle("-fx-pref-width: 200px");
portBox = new HBox(20,portLabel,serverport);
this.startBox = new VBox(30, welcomeLabel,portBox,serverChoice);
//startBox.setStyle("-fx-background-image:url(./wordguess.jpg);-fx-background-repeat:no-repeat");
//HBox.setMargin(startBox,new Insets(50,50,100,100) );
VBox.setMargin(startBox, new Insets(200,100,200,50));
startPane = new BorderPane();
startPane.setPadding(new Insets(0));
BorderPane.setMargin(startBox, new Insets(20,50,300,100));
startPane.setStyle("-fx-background-image:url(./wordguess.jpg);-fx-background-repeat:no-repeat");
startPane.setCenter(startBox);
startScene = new Scene(startPane,600,600);
startScene.setFill(Color.TRANSPARENT);
listItemsServer = new ListView<String>();
sceneMap = new HashMap<String, Scene>();
sceneMap.put("waiting", createWaitingGui());
//primaryStage.setScene(sceneMap.get("server"));
sceneMap.put("server", createServerGui());
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
primaryStage.setScene(startScene);
primaryStage.show();
}
public Scene createWaitingGui() {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(70));
pane.setStyle("-fx-background-color: green");
waitingLabel= new Label("Waiting for players......");
waitingLabel.setFont(new Font("Cambria", 30));
waitingLabel.setTextFill(Color.web("white"));
pane.setCenter(waitingLabel);
return new Scene(pane, 600, 600);
}
public Scene createServerGui() {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(70));
pane.setStyle("-fx-background-color: coral");
pane.setCenter(listItemsServer);
return new Scene(pane, 600, 600);
}
public final static boolean isNumeric(String s) {
if (s != null && !"".equals(s.trim()))
return s.matches("^[0-9]*$");
else
return false;
}
}
|
package com.google.android.exoplayer2.a;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.i.i;
import com.tencent.map.lib.mapstructure.MapRouteSectionWithName;
import java.nio.ByteBuffer;
public final class h {
private static final int[] ahj = new int[]{1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8};
private static final int[] ahk = new int[]{-1, 8000, 16000, 32000, -1, -1, 11025, 22050, 44100, -1, -1, 12000, 24000, 48000, -1, -1};
private static final int[] ahl = new int[]{64, 112, MapRouteSectionWithName.kMaxRoadNameLength, 192, 224, 256, 384, 448, 512, 640, 768, 896, 1024, 1152, 1280, 1536, 1920, 2048, 2304, 2560, 2688, 2816, 2823, 2944, 3072, 3840, 4096, 6144, 7680};
public static Format a(byte[] bArr, String str, String str2) {
i iVar = new i(bArr);
iVar.cX(60);
int i = ahj[iVar.cY(6)];
int i2 = ahk[iVar.cY(4)];
int cY = iVar.cY(5);
cY = cY >= ahl.length ? -1 : (ahl[cY] * 1000) / 2;
iVar.cX(10);
return Format.a(str, "audio/vnd.dts", cY, -1, i + (iVar.cY(2) > 0 ? 1 : 0), i2, null, null, str2);
}
public static int g(byte[] bArr) {
return ((((bArr[4] & 1) << 6) | ((bArr[5] & 252) >> 2)) + 1) * 32;
}
public static int d(ByteBuffer byteBuffer) {
int position = byteBuffer.position();
return ((((byteBuffer.get(position + 5) & 252) >> 2) | ((byteBuffer.get(position + 4) & 1) << 6)) + 1) * 32;
}
public static int h(byte[] bArr) {
return ((((bArr[5] & 2) << 12) | ((bArr[6] & 255) << 4)) | ((bArr[7] & 240) >> 4)) + 1;
}
}
|
package team;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import rescuecore2.misc.gui.ScreenTransform;
import rescuecore2.standard.entities.Area;
import rescuecore2.standard.view.StandardViewLayer;
import rescuecore2.view.RenderedObject;
import rescuecore2.worldmodel.Entity;
import rescuecore2.worldmodel.EntityID;
import rescuecore2.worldmodel.WorldModel;
public class SampleLayer extends StandardViewLayer {
protected List<Area> entities;
public SampleLayer() {
entities = new ArrayList<Area>();
}
@Override
public Rectangle2D view(Object... objects) {
synchronized (entities) {
entities.clear();
Rectangle2D result = super.view(objects);
return result;
}
}
@Override
protected void viewObject(Object o) {
super.viewObject(o);
if(o instanceof Area) {
entities.add((Area)o);
}
if (o instanceof WorldModel) {
WorldModel<? extends Entity> wm = (WorldModel<? extends Entity>)o;
for (Entity next : wm) {
viewObject(next);
}
}
}
@Override
public Collection<RenderedObject> render(Graphics2D g,
ScreenTransform transform, int width, int height) {
synchronized (entities) {
Collection<RenderedObject> result = new ArrayList<RenderedObject>();
for (Area next : entities) {
for(EntityID neighbour_id : next.getNeighbours())
{
if(neighbour_id.getValue() < next.getID().getValue())
{
Entity e = world.getEntity(neighbour_id);
if(e instanceof Area)
{
Area neighbour = (Area)e;
Line2D shape = new Line2D.Double(
transform.xToScreen(next.getX()), transform.yToScreen(next.getY()),
transform.xToScreen(neighbour.getX()), transform.yToScreen(neighbour.getY()));
g.setColor(Color.green);
g.draw(shape);
result.add(new RenderedObject(next, shape));
}
}
}
}
return result;
}
}
@Override
public String getName() {
return "Sample";
}
}
|
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
/*
* 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.
*/
/**
*
* @author vipin
*/
public class manageCourseForm extends javax.swing.JFrame {
/**
* Creates new form manageCourseForm
*/
course c = new course();
public manageCourseForm() {
initComponents();
c.fillCourseJtable(jTable1);
jTable1.setRowHeight(40);
jTable1.setShowGrid(true);
jTable1.setSelectionBackground(Color.BLUE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField_CourseLabel = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jSpinner1 = new javax.swing.JSpinner();
jButton_EditCourse = new javax.swing.JButton();
jButtonRemoveCourse = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel4 = new javax.swing.JLabel();
jTextField_CourseId = new javax.swing.JTextField();
jButton_AddCourse1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 153));
jLabel1.setBackground(new java.awt.Color(153, 255, 153));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel1.setText("Manage course");
jLabel1.setOpaque(true);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("Label:");
jTextField_CourseLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("Hours:");
jSpinner1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jSpinner1.setModel(new javax.swing.SpinnerNumberModel(4, 4, 300, 1));
jButton_EditCourse.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButton_EditCourse.setText("Edit");
jButton_EditCourse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_EditCourseActionPerformed(evt);
}
});
jButtonRemoveCourse.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButtonRemoveCourse.setText("Remove");
jButtonRemoveCourse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonRemoveCourseActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Id", "Label", "Hours"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("Id:");
jTextField_CourseId.setEditable(false);
jTextField_CourseId.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton_AddCourse1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButton_AddCourse1.setText("Add");
jButton_AddCourse1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_AddCourse1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(470, 470, 470)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_CourseId, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_CourseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jButtonRemoveCourse)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_EditCourse, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel3)
.addGap(62, 62, 62)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(60, 60, 60)
.addComponent(jButton_AddCourse1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(65, 65, 65))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_CourseId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_CourseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(133, 133, 133)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_EditCourse, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonRemoveCourse, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_AddCourse1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(175, 175, 175))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_EditCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditCourseActionPerformed
int id = Integer.valueOf(jTextField_CourseId.getText());
String label = jTextField_CourseLabel.getText();
int hours = Integer.valueOf(jSpinner1.getValue().toString());
c.insertUpdateDeleteStudent('u', id, label, hours);
manageCourseForm.jTable1.setModel(new DefaultTableModel(null, new Object[]{"Id","Label","Hours"}));
c.fillCourseJtable(manageCourseForm.jTable1);
// JOptionPane.showMessageDialog(null, "Course Edited");
}//GEN-LAST:event_jButton_EditCourseActionPerformed
private void jButtonRemoveCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveCourseActionPerformed
//whewn we delete a course we must also delete all score affected to this course
//we have to add a constraint to score table to do this
// constraint => foreign key + on delete cascade
/*
ALTER TABLE score add CONSTRAINT fk_score_course FOREIGN KEY(`course_id`) REFERENCES course (Id) on DELETE CASCADE
*/
if(!jTextField_CourseId.getText().equals("")){
int id = Integer.valueOf(jTextField_CourseId.getText());
c.insertUpdateDeleteStudent('d', id, null, null);
manageCourseForm.jTable1.setModel(new DefaultTableModel(null, new Object[]{"Id","Label","Hours"}));
c.fillCourseJtable(manageCourseForm.jTable1);
jTextField_CourseId.setText("");
jTextField_CourseLabel.setText("");
jSpinner1.setValue(4);
}
}//GEN-LAST:event_jButtonRemoveCourseActionPerformed
private void jButton_AddCourse1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AddCourse1ActionPerformed
addCourseForm Addcrsf = new addCourseForm();
Addcrsf.setVisible(true);
Addcrsf.pack();
Addcrsf.setLocationRelativeTo(null);
Addcrsf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}//GEN-LAST:event_jButton_AddCourse1ActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
int index = jTable1.getSelectedRow();
jTextField_CourseId.setText(jTable1.getValueAt(index, 0).toString() );
jTextField_CourseLabel.setText(jTable1.getValueAt(index, 1).toString() );
jSpinner1.setValue(Integer.valueOf(jTable1.getValueAt(index, 2).toString()));
}//GEN-LAST:event_jTable1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(manageCourseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(manageCourseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(manageCourseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(manageCourseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new manageCourseForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonRemoveCourse;
private javax.swing.JButton jButton_AddCourse1;
private javax.swing.JButton jButton_EditCourse;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSpinner jSpinner1;
public static javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField_CourseId;
private javax.swing.JTextField jTextField_CourseLabel;
// End of variables declaration//GEN-END:variables
}
|
package com.lito.fupin.business.organize;
import java.util.Map;
public interface IOrganizeBusinessService {
Map createOrganize(Map in) throws Exception;
/**
* 根据机构名称模糊查询机构列表,支持分页
* @param in
* @return
* @throws Exception
*/
Map listOrganize(Map in) throws Exception;
void updateOrganize(Map in) throws Exception;
void deleteOrganize(Map in) throws Exception;
Map listOrganizeByToken(Map in) throws Exception;
}
|
package race;
public class RaceGame {
public static void main(String[] args) throws InterruptedException {
System.out.println("지금부터 경주마 게임을 시작합니다..");
System.out.println("준비");
Horse horse1 = new Horse("대용");
Horse horse2 = new Horse("홍규");
Horse horse3 = new Horse("세준");
Horse horse4 = new Horse("방그리");
System.out.println("땅");
horse1.start();
horse2.start();
horse3.start();
horse4.start();
horse1.join();
horse2.join();
horse3.join();
horse4.join();
System.out.println("지금부터 경주마 게임을 종료합니다.");
}
}
|
/*
* Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* 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 edu.mayo.cts2.framework.util.spring;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import edu.mayo.cts2.framework.core.plugin.PluginConfigManager;
import edu.mayo.cts2.framework.core.url.UrlConstructor;
/**
* A factory for creating UrlConstructor objects.
*
* @author <a href="mailto:kevin.peterson@mayo.edu">Kevin Peterson</a>
*/
public class UrlConstructorSpringFactory implements FactoryBean<UrlConstructor> {
protected Log log = LogFactory.getLog(getClass().getName());
@Resource
private PluginConfigManager pluginConfigManager;
public UrlConstructor getObject() throws Exception {
return new UrlConstructor(this.pluginConfigManager.getServerContext());
}
public Class<?> getObjectType() {
return UrlConstructor.class;
}
public boolean isSingleton() {
return true;
}
}
|
package com.originspark.drp.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.originspark.drp.models.User;
import com.originspark.drp.service.projects.inventories.InventoryService;
import com.originspark.drp.service.projects.invoices.StockInInvoiceService;
import com.originspark.drp.service.projects.invoices.StockOutInvoiceService;
import com.originspark.drp.service.resources.VendorService;
import com.originspark.drp.service.resources.WareCategoryService;
import com.originspark.drp.service.resources.WareService;
import com.originspark.drp.service.users.UserService;
import com.originspark.drp.util.json.Jackson;
public class BaseController extends HandlerInterceptorAdapter {
@Autowired
protected UserService userService;
@Autowired
protected WareService wareService;
@Autowired
protected WareCategoryService wareCategoryService;
@Autowired
protected VendorService vendorService;
@Autowired
protected StockInInvoiceService stockInInvoiceService;
@Autowired
protected StockOutInvoiceService stockOutInvoiceService;
@Autowired
protected InventoryService inventoryService;
private static final ThreadLocal<HttpServletRequest> REQUEST = new ThreadLocal<HttpServletRequest>();
private static final ThreadLocal<HttpServletResponse> RESPONSE = new ThreadLocal<HttpServletResponse>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
REQUEST.set(request);
RESPONSE.set(response);
return super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
REQUEST.remove();
RESPONSE.remove();
if (ex != null) {
response.sendError(500);
}
super.afterCompletion(request, response, handler, ex);
}
public HttpServletRequest request() {
return REQUEST.get();
}
public HttpServletResponse response() {
return RESPONSE.get();
}
public HttpSession session() {
return request().getSession();
}
public User getCurrentUser() {
return (User) session().getAttribute("user");
}
// 一般用于create、update、delete的返回值
protected final static String ok(String message) {
Map<String, Object> modelMap = new HashMap<String, Object>(2);
modelMap.put("success", "true");
modelMap.put("message", message);
return Jackson.toJson(modelMap);
}
protected final static String ok(String message, Object object) {
Map<String, Object> modelMap = new HashMap<String, Object>(3);
modelMap.put("success", "true");
modelMap.put("message", message);
modelMap.put("object", object);
return Jackson.toJson(modelMap);
}
// 一般用于list分页数据的返回值
@SuppressWarnings("rawtypes")
protected final static String ok(List items, Long total) {
Map<String, Object> modelMap = new HashMap<String, Object>(3);
modelMap.put("success", "true");
modelMap.put("data", items);
modelMap.put("total", total);
return Jackson.toJson(modelMap);
}
// 一般用于list不分页的返回值
@SuppressWarnings("rawtypes")
protected final static String ok(List items) {
Map<String, Object> modelMap = new HashMap<String, Object>(2);
modelMap.put("success", "true");
modelMap.put("data", items);
return Jackson.toJson(modelMap);
}
// 失败信息的处理
protected final static String failure(String message) {
Map<String, Object> modelMap = new HashMap<String, Object>(2);
modelMap.put("success", "false");
modelMap.put("message", message);
return Jackson.toJson(modelMap);
}
}
|
public class Load extends Instruction {
public void exec(CMA state) {
state.stack[state.SP] = state.stack[state.stack[state.SP]];
}
@Override
public String toString()
{
return "load";
}
}
|
public class Thread {
public Thread () {
}
}
|
/**
* Created on 14-oct-2004
* @author a999942
*
*/
package com.bdb.util;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.ecs.ElementContainer;
import org.apache.struts.Globals;
import org.apache.struts.util.RequestUtils;
/**
* Este tag sirve para el caso en que existan 2 dropdowns en un JSP
* en donde en base a la seleccion del primer dropdown se llene dinamicamente
* el 2do. dropdown.
*
*/
public class LinkedDropDown extends BodyTagSupport {
private Object mapaObj = null;
private String mapa = null;
private String origen = null;
private String destino = null;
private String idOrigen = null;
private Object idPadre = null;
private String idDestino = null;
private Object idHijo = null;
private String form = null;
private String propertyOrigen = null;
private String propertyDestino = null;
private String keyOrigen = null;
private String keyDestino = null;
private String styleOrigen = null;
private String styleDestino = null;
private String onChangeOrigen = null;
private String onChangeDestino = null;
private boolean disabledOrigen = false;
private boolean disabledDestino = false;
private String orientacion = null;
private String colspan = null;
private String identificador = null;
private String widthTituloOrigen = null;
private String widthTituloDestino = null;
private String widthSelectOrigen = null;
private String widthSelectDestino = null;
private String keyMensajeSeleccionOrigen = null;
private String keyMensajeSeleccionDestino = null;
private String messageOrigen = new String();
private String messageDestino = new String();
private String messageSeleccionOrigen = new String();
private String messageSeleccionDestino = new String();
/**
* The servlet context attribute key for our resources.
*/
protected String bundle = null;
public String getBundle() {
return (this.bundle);
}
public void setBundle(String bundle) {
this.bundle = bundle;
}
/**
* The session scope key under which our Locale is stored.
*/
protected String localeKey = Globals.LOCALE_KEY;
public String getLocale() {
return (this.localeKey);
}
public void setLocale(String localeKey) {
this.localeKey = localeKey;
}
/**
* The first optional argument.
*/
protected String arg0 = null;
public String getArg0() {
return (this.arg0);
}
public void setArg0(String arg0) {
this.arg0 = arg0;
}
/**
* The second optional argument.
*/
protected String arg1 = null;
public String getArg1() {
return (this.arg1);
}
public void setArg1(String arg1) {
this.arg1 = arg1;
}
/**
* The third optional argument.
*/
protected String arg2 = null;
public String getArg2() {
return (this.arg2);
}
public void setArg2(String arg2) {
this.arg2 = arg2;
}
/**
* The fourth optional argument.
*/
protected String arg3 = null;
public String getArg3() {
return (this.arg3);
}
public void setArg3(String arg3) {
this.arg3 = arg3;
}
/**
* The fifth optional argument.
*/
protected String arg4 = null;
public String getArg4() {
return (this.arg4);
}
public void setArg4(String arg4) {
this.arg4 = arg4;
}
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
//Logger log = Logger.getLogger(this.getClass());
//log.info("doStartTag()" , "Inicio");
mapaObj = pageContext.findAttribute(mapa);
// TODO reemplazar el try/catch de abajo por el codigo comentado (es más correcto)
// Enumeration atributesInScope = pageContext.getAttributeNamesInScope(pageContext.SESSION_SCOPE);
// while (atributesInScope.hasMoreElements()) {
// Object nombreAtributo = atributesInScope.nextElement();
// log.info("doStartTag","nombreAtributo="+nombreAtributo );
// if (nombreAtributo.equals(idOrigen)) {
// idPadre = (String) pageContext.findAttribute(idOrigen);
// }
// if (nombreAtributo.equals(idDestino)) {
// idHijo = (String) pageContext.findAttribute(idDestino);
// }
// }
try {
idPadre = pageContext.findAttribute(idOrigen);
idHijo = pageContext.findAttribute(idDestino);
} catch (NullPointerException e1) {
// No hago nada --> soy un vago, ja, ja!!
}
try {
// Construct the optional arguments array we will be using
Object args[] = new Object[5];
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
args[3] = arg3;
args[4] = arg4;
if (keyOrigen!=null && keyOrigen.length()>0) this.messageOrigen = RequestUtils.message(pageContext, this.bundle, this.localeKey, keyOrigen, args);
if (keyDestino!=null && keyDestino.length()>0) this.messageDestino = RequestUtils.message(pageContext, this.bundle, this.localeKey, keyDestino, args);
if (keyMensajeSeleccionOrigen!=null && keyMensajeSeleccionOrigen.length()>0)
this.messageSeleccionOrigen = RequestUtils.message(pageContext, this.bundle, this.localeKey, keyMensajeSeleccionOrigen, args);
else
this.messageSeleccionOrigen = RequestUtils.message(pageContext, this.bundle, this.localeKey, "mensaje.seleccion.generico", args);
if (keyMensajeSeleccionDestino!=null && keyMensajeSeleccionDestino.length()>0)
this.messageSeleccionDestino = RequestUtils.message(pageContext, this.bundle, this.localeKey, keyMensajeSeleccionDestino, args);
else
this.messageSeleccionDestino = RequestUtils.message(pageContext, this.bundle, this.localeKey, "mensaje.seleccion.generico", args);
if (identificador == null) this.identificador = new String("1");
//System.out.println("---->messageSeleccionOrigen="+this.messageSeleccionOrigen);
//System.out.println("---->messageSeleccionDestino="+this.messageSeleccionDestino);
out.print(scriptGenerateArrays());
out.print(scriptPopulate());
// Imprime el HTML con los select
// out.print("<tr>");
String indDisabled = "";
if (disabledOrigen) {
indDisabled = " DISABLED ";
}
//out.print("<table width='100%'>");
out.print(" <tr>");
// out.print(" <td>");
// out.print(" <table>");
// out.print(" <tr>");
if (keyOrigen!=null)
System.out.println("<th valign='top' class="+styleOrigen+" "+((widthTituloOrigen!=null)?" width='"+widthTituloOrigen+"'":"")+"><span class="+styleOrigen+">"+messageOrigen+"</span></th>");
out.print(" <th valign='top' class="+styleOrigen+" "+((widthTituloOrigen!=null)?" width='"+widthTituloOrigen+"'":"")+"><span class="+styleOrigen+">"+messageOrigen+"</span></th>");
out.print(" <td valign='top' "+((widthSelectOrigen!=null)?" width='"+widthSelectOrigen+"'":"")+">");
out.print(" <select class="+styleOrigen+" name="+origen+" onchange='populateDropDown"+identificador+"(document."+form+",document."+form+"."+origen+".options[document."+form+"."+origen+".selectedIndex].value);"+onChangeOrigen+"'"+ ((disabledOrigen)?" DISABLED ":"")+">" );
if(messageSeleccionOrigen!=null)
out.print(" <option value='0'>...</option>");
//out.print(" <option value='0'>"+messageSeleccionOrigen+"...</option>");
else
out.print(" <option value='0'>...</option>");
// Genero el resto de los option
Object padre = null;
Object padreSelected = null;
Iterator it = ((Map) this.mapaObj).entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
padre = entry.getKey();
Collection hijos = (Collection) entry.getValue();
// Genero el option del padre unicamente si este tiene hijos
if (hijos.size() > 0) {
Class claseDePadre = padre.getClass();
// Recupero el Id del objeto padre
Method metodo = claseDePadre.getMethod(generarNombreMetodo(propertyOrigen), null);
Long id = (Long)metodo.invoke(padre, null);
// Evalua si esta ocurrencia se encuentra seleccionada de antemano (por ej.
// para las pantallas de modificacion)
String selected = "'";
if (this.idPadre != null) {
if (this.idPadre.equals(id)) {
padreSelected = padre;
selected = "' selected";
}
}
// Recupero la descripcion del objeto padre
metodo = claseDePadre.getMethod(generarNombreMetodo("descrip"), null);
String label = (String)metodo.invoke(padre, null);
out.print("<option value='"+id+selected+">"+label+"</option>");
}
}
out.print(" </select>");
out.print(" </td>");
if (this.orientacion.equals("V")) {
out.print(" </tr>");
out.print(" <tr>");
}
if (keyDestino!=null)
System.out.println("<th valign='top' class="+styleDestino+" "+((widthTituloDestino!=null)?" width='"+widthTituloDestino+"'":"")+"><span class="+styleOrigen+">"+messageDestino+"</span></th>");
out.print(" <th valign='top' class="+styleDestino+" "+((widthTituloDestino!=null)?" width='"+widthTituloDestino+"'":"")+"><span class="+styleOrigen+">"+messageDestino+"</span></th>");
out.print(" <td valign='top' "+((widthSelectDestino!=null)?" width='"+widthSelectDestino+"'":"")+"><select class="+this.styleDestino+" name="+destino+" onchange='"+onChangeDestino+"'" +((disabledDestino)?" DISABLED ":"")+">");
if(messageSeleccionDestino!=null)
out.print(" <option value='0'>...</option>");
//out.print(" <option value='0'>"+messageSeleccionDestino+"...</option>");
else
out.print(" <option value='0'>...</option>");
// Si el idDestino viene informado entonces debo dibujar los option para ese padre
if (padreSelected != null) {
Map mapa = (Map) this.mapaObj;
Collection hijos = (Collection) mapa.get(padreSelected);
it = hijos.iterator();
while (it.hasNext()) {
Object hijo = it.next();
Class claseDeHijo = hijo.getClass();
// Recupero la descripcion para el 2do. drop down. Para ello antes debo recuperar el
// getter correspondiente a la property solicitada
Method metodo = claseDeHijo.getMethod(generarNombreMetodo("descrip"), null);
String descripcionHijo = (String) metodo.invoke(hijo, null);
metodo = claseDeHijo.getMethod(generarNombreMetodo(propertyDestino), null);
Long idHijoRenglon = (Long)metodo.invoke(hijo, null);
// Evalua si esta ocurrencia se encuentra seleccionada de antemano (por ej.
// para las pantallas de modificacion)
String selected = "'";
if (this.idHijo != null) {
if (this.idHijo.equals(idHijoRenglon)) {
padreSelected = padre;
selected = "' selected";
}
}
out.print("<option value='"+idHijoRenglon+selected+">"+descripcionHijo+"</option>");
}
}
out.print(" </select>");
out.print(" </td>");
// out.print(" </tr>");
// out.print(" </table>");
// out.print(" </td>");
out.print(" </tr>");
// out.print("</table>");
// out.print(" </tr>");
} catch(IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//log.info("doStartTag()" , "Fin");
return (EVAL_BODY_AGAIN);
}
/**
* Genera el JavaScript que se utiliza para popular el 2do. drop down.
* @return
*/
public ElementContainer scriptPopulate () {
ElementContainer script = new ElementContainer();
script.setPrettyPrint(false);
// Creo:
// function populateAgentes(inForm,selected) {
// var selectedArray = eval("Array" + selected);
// // Borra el contenido de la Selection de destino
// for (var i=1; i < inForm.idAgenteFiltro.options.length; i++) {
// inForm.idAgenteFiltro.options[i] = null;
// }
// for (var i=1; i < selectedArray.length; i++) {
// var texto = selectedArray[i];
// var posicion = texto.indexOf ("&");
// var descripcion = texto.substring(2,posicion);
// var clave = texto.substring(posicion+1,texto.length - 2);
// eval("inForm.idAgenteFiltro.options[i]=" + "new Option(descripcion,clave)");
// }
// if (inForm.idAgenteFiltro.options[0].value == '') {
// inForm.idAgenteFiltro.options[0].value = 'Seleccione un Agente Colaborador ... ';
// }
// }
script.addElement("function populateDropDown"+identificador+"(inForm,selected) { ");
script.addElement(" var descripcion = null;");
script.addElement(" var texto = null;");
script.addElement(" var selectedArray = null;");
script.addElement(" var posicion = null;");
// Borra 2do. combo
script.addElement(" var cantidad = inForm."+destino+".options.length;");
script.addElement(" for (var i = (cantidad-1); i >= 0; i--) { ");
script.addElement(" inForm."+destino+".options[i] = null;");
script.addElement(" }");
script.addElement(" if (selected != 0) {");
script.addElement(" selectedArray = eval('Array' + selected +"+identificador+");");
script.addElement(" for (var i=0; i < selectedArray.length; i++) { ");
script.addElement(" if (i == 0) {");
//script.addElement(" var descripcion='"+messageSeleccionDestino+" ...';");
script.addElement(" var descripcion='...';");
script.addElement(" var clave=0;");
script.addElement(" } else {");
script.addElement(" texto = selectedArray[i];");
script.addElement(" posicion = texto.indexOf ('&');");
script.addElement(" descripcion = texto.substring(2,posicion);");
script.addElement(" clave = texto.substring(posicion+1,texto.length - 2);");
script.addElement(" }");
script.addElement(" inForm."+destino+".options[i]= new Option(descripcion,clave);");
script.addElement(" if (i == 0) { ");
script.addElement(" inForm."+destino+".options[0].selected=true;");
script.addElement(" }");
script.addElement(" }");
script.addElement(" } else {");
//script.addElement(" inForm."+destino+".options[0]= new Option('"+messageSeleccionDestino+" ...',0);");
script.addElement(" inForm."+destino+".options[0]= new Option('...',0);");
script.addElement(" inForm."+destino+".options[0].selected=true;");
script.addElement(" }");
script.addElement("}");
script.addElement("</SCRIPT>");
return script;
}
/**
* Generacion de JavaScript para cambiar dinamicamente el 2do. drop down
*
* @return
*/
public ElementContainer scriptGenerateArrays() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
//Logger log = Logger.getLogger(this.getClass());
//log.info("scriptGenerateArrays" , "Inicio");
ElementContainer script = new ElementContainer();
script.setPrettyPrint(true);
script.addElement("<SCRIPT language=JavaScript>");
// La key del mapa contiene el padre y el value contiene una Collection de hijos
Object padre = null;
Iterator it = ((Map) mapaObj).entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
padre = (Object) entry.getKey();
Collection hijos = (Collection) entry.getValue();
// Creo tantos array de hijos, como padres existan
if (hijos.size() > 0) {
Class claseDePadre = padre.getClass();
// Recupero el Id del objeto padre
//Method metodo = claseDePadre.getMethod(propertyOrigen, null);
Method metodo = claseDePadre.getMethod(generarNombreMetodo(propertyOrigen), null);
Long id = (Long)metodo.invoke(padre, null);
//String mensaje = new String("'Seleccione " + messageSeleccionOrigen + " ...'");
String mensaje = new String("'Seleccione...'");
script.addElement("var Array"+id+identificador+" = new Array(\"("+messageSeleccionOrigen+",'',true,true)\",");
// var Array<%=empresa.getId()%> = new Array("('Seleccione un Agente ...','',true,true)",<%
// Ahora pre-cargo los arrays de JavaScript con los posibles contenidos del 2do.drop down
Iterator it2 = hijos.iterator();
int j = 0;
while (it2.hasNext()) {
Object hijo = it2.next();
Class claseDeHijo = hijo.getClass();
// Recupero la descripcion para el 2do. drop down. Para ello antes debo recuperar el
// getter correspondiente a la property solicitada
metodo = claseDeHijo.getMethod(generarNombreMetodo("descrip"), null);
String descripcionHijo = (String) metodo.invoke(hijo, null);
metodo = claseDeHijo.getMethod(generarNombreMetodo(propertyDestino), null);
String idHijo = (Long)metodo.invoke(hijo, null)+"'";
if (j < hijos.size() - 1) {
String texto = new String ("'"+descripcionHijo);
script.addElement("\"("+texto+"&"+idHijo+")\" ,");
// "('<%=agente.getNombre()%>&<%=agente.getId()%>')", <%
} else {
String texto = new String ("'"+descripcionHijo);
script.addElement("\"("+texto+"&"+idHijo+")\");");
// "('<%=agente.getNombre()%>&<%=agente.getId()%>')";<%
}
j++;
}
} else {
//String mensaje = new String("'Seleccione " + messageSeleccionDestino + " ...'");
String mensaje = new String("'Seleccione...'");
script.addElement("var Array0"+identificador+" = new Array(\"("+messageSeleccionDestino+",'',true,true)\");");
// var Array<%=empresa.getId()%> = new Array("('Seleccione un Agente ...','',true,true)");<%
}
}
return script;
}
/** Devuelve el nombre del getter de acuerdo al property (nombre del campo) que
* se desea mostrar como descripcion del drop down.
* @param property
* @return
*/
private String generarNombreMetodo(String property) {
String primeraLetra = property.substring(0,1);
String resto = property.substring(1);
String nombreMetodo = "get" + primeraLetra.toUpperCase() + resto;
return nombreMetodo;
}
/**
* @return
*/
public String getDestino() {
return this.destino;
}
/**
* @return
*/
public String getForm() {
return this.form;
}
/**
* @return
*/
public String getKeyDestino() {
return this.keyDestino;
}
/**
* @return
*/
public String getKeyOrigen() {
return this.keyOrigen;
}
/**
* @return
*/
public String getMapa() {
return this.mapa;
}
/**
* @return
*/
public String getOrientacion() {
return this.orientacion;
}
/**
* @return
*/
public String getOrigen() {
return this.origen;
}
/**
* @return
*/
public String getStyleDestino() {
return this.styleDestino;
}
/**
* @return
*/
public String getStyleOrigen() {
return this.styleOrigen;
}
/**
* @param string
*/
public void setDestino(String destino) {
this.destino = destino;
}
/**
* @param string
*/
public void setForm(String form) {
this.form = form;
}
/**
* @param string
*/
public void setKeyDestino(String keyDestino) {
this.keyDestino = keyDestino;
}
/**
* @param string
*/
public void setKeyOrigen(String keyOrigen) {
this.keyOrigen = keyOrigen;
}
/**
* @param map
*/
public void setMapa(String newMapa) {
this.mapa = newMapa;
}
/**
* @param string
*/
public void setOrientacion(String orientacion) {
this.orientacion = orientacion;
}
/**
* @param string
*/
public void setOrigen(String origen) {
this.origen = origen;
}
/**
* @param string
*/
public void setStyleDestino(String styleDestino) {
this.styleDestino = styleDestino;
}
/**
* @param string
*/
public void setStyleOrigen(String styleOrigen) {
this.styleOrigen = styleOrigen;
}
/**
* @return
*/
public String getPropertyDestino() {
return this.propertyDestino;
}
/**
* @return
*/
public String getPropertyOrigen() {
return this.propertyOrigen;
}
/**
* @param string
*/
public void setPropertyDestino(String propertyDestino) {
this.propertyDestino = propertyDestino;
}
/**
* @param string
*/
public void setPropertyOrigen(String propertyOrigen) {
this.propertyOrigen = propertyOrigen;
}
/**
* @return
*/
public String getIdDestino() {
return this.idDestino;
}
/**
* @return
*/
public String getIdOrigen() {
return this.idOrigen;
}
/**
* @param string
*/
public void setIdDestino(String idDestino) {
this.idDestino = idDestino;
}
/**
* @param string
*/
public void setIdOrigen(String idOrigen) {
this.idOrigen = idOrigen;
}
/**
* @return
*/
public String getOnChangeDestino() {
return onChangeDestino;
}
/**
* @return
*/
public String getOnChangeOrigen() {
return onChangeOrigen;
}
/**
* @param string
*/
public void setOnChangeDestino(String string) {
onChangeDestino = string;
}
/**
* @param string
*/
public void setOnChangeOrigen(String string) {
onChangeOrigen = string;
}
/**
* @return
*/
public String getColspan() {
return colspan;
}
/**
* @param string
*/
public void setColspan(String string) {
colspan = string;
}
/**
* @return Returns the disabledDestino.
*/
public boolean isDisabledDestino() {
return disabledDestino;
}
/**
* @param disabledDestino The disabledDestino to set.
*/
public void setDisabledDestino(boolean disabledDestino) {
this.disabledDestino = disabledDestino;
}
/**
* @return Returns the disabledOrigen.
*/
public boolean isDisabledOrigen() {
return disabledOrigen;
}
/**
* @param disabledOrigen The disabledOrigen to set.
*/
public void setDisabledOrigen(boolean disabledOrigen) {
this.disabledOrigen = disabledOrigen;
}
/**
* @return Returns the identificador.
*/
public String getIdentificador() {
if (identificador == null) {
identificador = new String("1");
}
return identificador;
}
/**
* @param identificador The identificador to set.
*/
public void setIdentificador(String identificador) {
this.identificador = identificador;
}
/**
* @return Returns the widthSelectDestino.
*/
public String getWidthSelectDestino() {
return widthSelectDestino;
}
/**
* @param widthSelectDestino The widthSelectDestino to set.
*/
public void setWidthSelectDestino(String widthSelectDestino) {
this.widthSelectDestino = widthSelectDestino;
}
/**
* @return Returns the widthSelectOrigen.
*/
public String getWidthSelectOrigen() {
return widthSelectOrigen;
}
/**
* @param widthSelectOrigen The widthSelectOrigen to set.
*/
public void setWidthSelectOrigen(String widthSelectOrigen) {
this.widthSelectOrigen = widthSelectOrigen;
}
/**
* @return Returns the widthTituloDestino.
*/
public String getWidthTituloDestino() {
return widthTituloDestino;
}
/**
* @param widthTituloDestino The widthTituloDestino to set.
*/
public void setWidthTituloDestino(String widthTituloDestino) {
this.widthTituloDestino = widthTituloDestino;
}
/**
* @return Returns the widthTituloOrigen.
*/
public String getWidthTituloOrigen() {
return widthTituloOrigen;
}
/**
* @param widthTituloOrigen The widthTituloOrigen to set.
*/
public void setWidthTituloOrigen(String widthTituloOrigen) {
this.widthTituloOrigen = widthTituloOrigen;
}
/**
* @return Returns the keyMensajeSeleccionDestino.
*/
public String getKeyMensajeSeleccionDestino() {
return keyMensajeSeleccionDestino;
}
/**
* @param keyMensajeSeleccionDestino The keyMensajeSeleccionDestino to set.
*/
public void setKeyMensajeSeleccionDestino(String keyMensajeSeleccionDestino) {
this.keyMensajeSeleccionDestino = keyMensajeSeleccionDestino;
}
/**
* @return Returns the keyMensajeSeleccionOrigen.
*/
public String getKeyMensajeSeleccionOrigen() {
return keyMensajeSeleccionOrigen;
}
/**
* @param keyMensajeSeleccionOrigen The keyMensajeSeleccionOrigen to set.
*/
public void setKeyMensajeSeleccionOrigen(String keyMensajeSeleccionOrigen) {
this.keyMensajeSeleccionOrigen = keyMensajeSeleccionOrigen;
}
public String getMessageDestino() {
return messageDestino;
}
public void setMessageDestino(String messageDestino) {
this.messageDestino = messageDestino;
}
public String getMessageOrigen() {
return messageOrigen;
}
public void setMessageOrigen(String messageOrigen) {
this.messageOrigen = messageOrigen;
}
public String getMessageSeleccionDestino() {
return messageSeleccionDestino;
}
public void setMessageSeleccionDestino(String messageSeleccionDestino) {
this.messageSeleccionDestino = messageSeleccionDestino;
}
public String getMessageSeleccionOrigen() {
return messageSeleccionOrigen;
}
public void setMessageSeleccionOrigen(String messageSeleccionOrigen)
{
this.messageSeleccionOrigen = messageSeleccionOrigen;
}
}
|
package de.jmda.gen.java;
import de.jmda.gen.CompoundGenerator;
/**
* Generator for technical package declarations.
*
* @author rwegner
*/
public interface DeclaredPackageGenerator
extends CompoundGenerator, DeclaredElementGenerator
{
PackageStatementGenerator getPackageStatementGenerator();
void setPackageStatementGenerator(PackageStatementGenerator generator);
}
|
package com.ibiscus.myster.service.user;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.text.RandomStringGenerator;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ibiscus.myster.model.security.User;
import com.ibiscus.myster.service.security.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Ignore
@Test
public void crud() {
User user = new UserBuilder().build();
user = userService.save(user);
assertTrue(user.getId() > 0);
User storedUser = userService.get(user.getId());
assertEquals(user.getUsername(), storedUser.getUsername());
assertEquals(user.getPassword(), storedUser.getPassword());
assertEquals(user.isEnabled(), storedUser.isEnabled());
String newName = getUsername();
String newPassword = getPassword();
boolean enabled = !storedUser.isEnabled();
user = new UserBuilder()
.withId(storedUser.getId())
.withUsername(newName)
.withPassword(newPassword)
.withEnabled(enabled)
.build();
userService.save(user);
storedUser = userService.get(user.getId());
assertEquals(newName, storedUser.getUsername());
assertEquals(newPassword, storedUser.getPassword());
assertEquals(enabled, storedUser.isEnabled());
}
private String getUsername() {
return new RandomStringGenerator.Builder().withinRange('a', 'z').build()
.generate(5);
}
private String getPassword() {
return new RandomStringGenerator.Builder().withinRange('a', 'z').build()
.generate(5);
}
}
|
import java.util.*;
class palindrome {
public static void main(String args[]) {
String a,b;
Scanner in=new Scanner(System.in);
a=in.nextLine();
String b=new StringBuffer(a).reverse().toString();
if(a.equals(b)){
System.out.println("Palindrome");
else
System.out.println("Not");
}}
|
package pl.finapi.paypal;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pl.finapi.paypal.model.AccountantInfo;
import pl.finapi.paypal.model.BuyerInfo;
import pl.finapi.paypal.model.City;
import pl.finapi.paypal.model.Currency;
import pl.finapi.paypal.model.EmailAddress;
import pl.finapi.paypal.model.SaldoAndStanWaluty;
import pl.finapi.paypal.model.output.DocumentModels;
import pl.finapi.paypal.output.pdf.PaypalFeeReportAndInvoiceAndEwidencjaAndDowodPdfWriter;
import pl.finapi.paypal.source.report.PaypalReport;
import pl.finapi.paypal.util.NumberUtil;
public class PaypalFeeReportAndInvoiceInSameFileMain {
public static void main(String[] args) throws IOException {
ToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);
try {
String outputFilePath = "/home/maciek/dev/finapi/output/foo.pdf";
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/main.xml");
ReportFacade reportFacade = ctx.getBean(ReportFacade.class);
NumberUtil numberUtil = ctx.getBean(NumberUtil.class);
PaypalFeeReportAndInvoiceAndEwidencjaAndDowodPdfWriter writer = ctx.getBean(PaypalFeeReportAndInvoiceAndEwidencjaAndDowodPdfWriter.class);
// File file = new File("src/test/resources/paypal/" + "Pobierz-2012.01.csv");
// File file = new File("src/test/resources/paypal/" + "wrzesien-marzec2012-PL.csv");
// File file = new File("src/test/resources/paypal/" + "styczen-marzec-onlydefaultcolumns.csv");
// File file = new File("src/test/resources/paypal/" + "grudzien-marzec-szczegoly-koszyka-onlydefaultcolumns.csv");
// File file = new File("src/test/resources/paypal/" + "grudzien-marzec-szczegoly-koszyka-allcolumns.csv");
// File file = new File("src/test/resources/paypal/" + "hanatopshop-onlydefaultfields-PL.csv");
// File file = new File("src/test/resources/paypal/" + "hanatopshop-onlydefaultfields-grudzien-luty-EN.csv");
// File file = new File("C:/Documents and Settings/maciek/Desktop/Pobierz.csv");
// File file = new File("src/test/resources/paypal/" + "infant-luty-PL.csv");
File file = new File("/home/maciek/dev/finapi/Pobierz4.csv");
// List<String> reportLines = FileUtils.readLines(file, "UTF-8");
List<String> reportLines = FileUtils.readLines(file, "windows-1250");
PaypalReport report = new PaypalReport(reportLines.get(0), reportLines.subList(1, reportLines.size()));
// 3 exchange rate difference model
City city = new City("");
EmailAddress emailAddress = new EmailAddress("");
AccountantInfo accountantInfo = new AccountantInfo("");
Map<Currency, SaldoAndStanWaluty> initialSaldoAndStanWaluty = SampleData.emptySaldoAndStanWalutyForEachCurrency(numberUtil);
BuyerInfo buyerInfo = BuyerInfo.EMPTY_BUYER;
List<DocumentModels> models = reportFacade.createModels(report, /* initialSaldoAndStanWaluty, */emailAddress, city, accountantInfo, buyerInfo);
writer.writePaypalFeeReportAndInvoiceAndDokumentWewnetrzny(outputStream, models);
flush(outputStream);
Desktop.getDesktop().open(new File(outputFilePath));
} finally {
// System.exit(0);
}
}
private static BuyerInfo sampleBuyerInfo() {
return new BuyerInfo("P.H.U. Biedronka", "address line 1", "address line 2", "1234567890");
}
private static void flush(OutputStream outputStream) {
try {
outputStream.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package techokami.computronics.audio;
import java.util.HashMap;
import techokami.computronics.Computronics;
import techokami.lib.audio.StreamingAudioPlayer;
import techokami.lib.audio.StreamingPlaybackManager;
public class DFPWMPlaybackManager extends StreamingPlaybackManager {
public DFPWMPlaybackManager(boolean isClient) {
super(isClient);
}
public StreamingAudioPlayer create() {
return new StreamingAudioPlayer(32768, false, false, (int)Math.round(Computronics.BUFFER_MS / 250));
}
}
|
package ayou.model;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class BoardTest {
Card test;
Card test2;
Card test3;
Board board;
Player player;
@Before
public void setUp(){
test = new Card(1, "card1", "img1", 6, 10, true, true, 0, false, 0, false, 0, false,0);
test2 = new Card(2, "card1", "img1", 5, 10, false, true, 3, true, 0, false, 0, false,0);
test3 = new Card(3, "card1", "img1", 4, 15, true, true, 0, true, 0, false, 0, false,0);
board = new Board(player);
}
@Test
public void test(){
assertTrue(board.isEmpty());
}
}
|
package com.google.android.gms.wearable.internal;
import android.os.ParcelFileDescriptor;
import android.os.ParcelFileDescriptor.AutoCloseInputStream;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.wearable.c.d;
import java.io.IOException;
import java.io.InputStream;
public class bg$c implements d {
private final Status bcQ;
private volatile ParcelFileDescriptor bfy;
private volatile InputStream bfz;
private volatile boolean mClosed = false;
public bg$c(Status status, ParcelFileDescriptor parcelFileDescriptor) {
this.bcQ = status;
this.bfy = parcelFileDescriptor;
}
public final InputStream getInputStream() {
if (this.mClosed) {
throw new IllegalStateException("Cannot access the input stream after release().");
} else if (this.bfy == null) {
return null;
} else {
if (this.bfz == null) {
this.bfz = new AutoCloseInputStream(this.bfy);
}
return this.bfz;
}
}
public final Status oF() {
return this.bcQ;
}
public final void release() {
if (this.bfy != null) {
if (this.mClosed) {
throw new IllegalStateException("releasing an already released result.");
}
try {
if (this.bfz != null) {
this.bfz.close();
} else {
this.bfy.close();
}
this.mClosed = true;
this.bfy = null;
this.bfz = null;
} catch (IOException e) {
}
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.common.service.impl;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.model.restrictions.AbstractRestrictionModel;
import de.hybris.platform.cmsfacades.data.AbstractRestrictionData;
import de.hybris.platform.servicelayer.search.SearchResult;
import de.hybris.platform.servicelayer.search.impl.SearchResultImpl;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultSearchResultConverterTest
{
@Mock
private AbstractRestrictionModel model1;
@Mock
private AbstractRestrictionModel model2;
@Mock
private AbstractRestrictionData data1;
@Mock
private AbstractRestrictionData data2;
@Mock
private Function<AbstractRestrictionModel, AbstractRestrictionData> convertFunction;
private final DefaultSearchResultConverter converter = new DefaultSearchResultConverter();
@Before
public void setUp()
{
when(convertFunction.apply(any())).thenReturn(data1).thenReturn(data2);
}
@Test
public void shouldConvertSearchResultModelToData()
{
final List<AbstractRestrictionModel> models = Arrays.asList(model1, model2);
final SearchResult<AbstractRestrictionModel> modelSearchResult = new SearchResultImpl<>(models, 10, 2, 0);
final SearchResult<AbstractRestrictionData> result = converter.convert(modelSearchResult, convertFunction);
assertThat(result.getResult(), contains(data1, data2));
assertThat(result.getTotalCount(), equalTo(10));
assertThat(result.getRequestedCount(), equalTo(2));
assertThat(result.getRequestedStart(), equalTo(0));
}
}
|
package com.pearl.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.pearl.domain.EmotionVO;
@Mapper
public interface EmotionMapper {
int emotionInsert(EmotionVO vo);
EmotionVO getEmo(EmotionVO vo);
int updateEmo(EmotionVO vo);
List<EmotionVO> emoCount(int boardNum);
}
|
package com.fixkomun.CSGOSmokeGuide;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<MapHolder> mapHolder;
private Context mContext;
public RecyclerViewAdapter(ArrayList<MapHolder> mapHolder, Context mContext) {
this.mapHolder=mapHolder;
this.mContext = mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_listitem,viewGroup,false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
Glide.with(mContext)
.asBitmap()
.load(mapHolder.get(i).getMapURL())
.into(viewHolder.image);
viewHolder.imageName.setText(mapHolder.get(i).getMapName());
viewHolder.parent_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext,mapHolder.get(i).getMapName(),Toast.LENGTH_SHORT).show();
ThirdActivity.fill(i);
Intent intent=new Intent(mContext,ThirdActivity.class);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mapHolder.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView image;
TextView imageName;
RelativeLayout parent_layout;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image);
imageName=itemView.findViewById(R.id.image_name);
parent_layout=itemView.findViewById(R.id.parent_layout);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.