text
stringlengths 10
2.72M
|
|---|
package com.example.android.popularmovies.dataobjects;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Original class generated with http://www.jsonschema2pojo.org/
* It's quite handy and customisable. Outpu looks a bit overklill though.
* Not sure if the annotations are really needed, AFAIK GSON can handle the camelCase conceversion,
* but seeing the amount of output, I was not keen to try changing this just now..
*/
public class MovieData implements Parcelable{
/**
* Constant to path to load images from
*/
public static final String IMG_BASE_URL = "http://image.tmdb.org/t/p/w500";
/**
* Members with GSON annotation
*/
@SerializedName("page")
@Expose
private int page;
@SerializedName("results")
@Expose
private List<Result> results = null;
@SerializedName("total_results")
@Expose
private int totalResults;
@SerializedName("total_pages")
@Expose
private int totalPages;
/**
* Standard Parcelable implementation
*/
protected MovieData(Parcel in) {
page = in.readInt();
results = in.createTypedArrayList(Result.CREATOR);
totalResults = in.readInt();
totalPages = in.readInt();
}
public static final Creator<MovieData> CREATOR = new Creator<MovieData>() {
@Override
public MovieData createFromParcel(Parcel in) {
return new MovieData(in);
}
@Override
public MovieData[] newArray(int size) {
return new MovieData[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(page);
parcel.writeTypedList(results);
parcel.writeInt(totalResults);
parcel.writeInt(totalPages);
}
/**
* Getters and setters
*/
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
public int getTotalResults() {
return totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
/**
* Inner class must be static so that it can implement static methods for Parcelable
*/
public static class Result implements Parcelable{
/**
* Members with some GSON annotation
*/
@SerializedName("poster_path")
@Expose
private String posterPath;
@SerializedName("adult")
@Expose
private boolean adult;
@SerializedName("overview")
@Expose
private String overview;
@SerializedName("release_date")
@Expose
private String releaseDate;
@SerializedName("genre_ids")
@Expose
private List<Integer> genreIds = null;
@SerializedName("id")
@Expose
private int id;
@SerializedName("original_title")
@Expose
private String originalTitle;
@SerializedName("original_language")
@Expose
private String originalLanguage;
@SerializedName("title")
@Expose
private String title;
@SerializedName("backdrop_path")
@Expose
private String backdropPath;
@SerializedName("popularity")
@Expose
private float popularity;
@SerializedName("vote_count")
@Expose
private int voteCount;
@SerializedName("video")
@Expose
private boolean video;
@SerializedName("vote_average")
@Expose
private float voteAverage;
/**
* Standard Parcelable implementation
*/
protected Result(Parcel in) {
posterPath = in.readString();
adult = in.readByte() != 0;
overview = in.readString();
releaseDate = in.readString();
id = in.readInt();
originalTitle = in.readString();
originalLanguage = in.readString();
title = in.readString();
backdropPath = in.readString();
popularity = in.readFloat();
voteCount = in.readInt();
video = in.readByte() != 0;
voteAverage = in.readFloat();
}
// Preserving every single member, unsued ones inlc., so the app remains extendable later
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(posterPath);
dest.writeByte((byte) (adult ? 1 : 0));
dest.writeString(overview);
dest.writeString(releaseDate);
dest.writeInt(id);
dest.writeString(originalTitle);
dest.writeString(originalLanguage);
dest.writeString(title);
dest.writeString(backdropPath);
dest.writeFloat(popularity);
dest.writeInt(voteCount);
dest.writeByte((byte) (video ? 1 : 0));
dest.writeFloat(voteAverage);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Result> CREATOR = new Creator<Result>() {
@Override
public Result createFromParcel(Parcel in) {
return new Result(in);
}
@Override
public Result[] newArray(int size) {
return new Result[size];
}
};
/**
* Getters and setters
*/
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public float getPopularity() {
return popularity;
}
public void setPopularity(float popularity) {
this.popularity = popularity;
}
public int getVoteCount() {
return voteCount;
}
public void setVoteCount(int voteCount) {
this.voteCount = voteCount;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public float getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(float voteAverage) {
this.voteAverage = voteAverage;
}
}
}
|
package mc.monacotelecom.auth.config;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
@Configuration
@EnableSpringHttpSession
@ConditionalOnMissingBean(annotation=EnableSpringHttpSession.class)
@ConditionalOnClass(AbstractSecurityWebSocketMessageBrokerConfigurer.class)
@ConditionalOnWebApplication
public class HttpSessionConfiguration {
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String AUTHORIZATION_HEADER_BEARER = "Bearer ";
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
public MapSessionRepository sessionRepository() {
return new MapSessionRepository(new ConcurrentHashMap<>());
}
}
|
package com.mobilephone.foodpai.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.mobilephone.foodpai.R;
import com.mobilephone.foodpai.activity.EditUserInfoActivity;
import com.mobilephone.foodpai.activity.LoginActivity;
import com.mobilephone.foodpai.activity.MyCollectActivity;
import com.mobilephone.foodpai.activity.SetingActivity;
import com.mobilephone.foodpai.activity.UpdataFoodActivity;
import com.mobilephone.foodpai.base.BaseFragment;
import com.mobilephone.foodpai.bean.UserBean;
import com.mobilephone.foodpai.widget.MyCircleImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Administrator on 2016/10/31.
*/
public class MineFragment extends BaseFragment {
private static final String TAG = "MineFragment-test";
@BindView(R.id.ivSeting)
ImageView ivSeting;
@BindView(R.id.ivPhoto)
ImageView ivPhoto;
@BindView(R.id.rlPhoto)
RelativeLayout rlPhoto;
@BindView(R.id.ivMyCollect)
ImageView ivMyCollect;
@BindView(R.id.rlMyCollect)
RelativeLayout rlMyCollect;
@BindView(R.id.iv)
ImageView iv;
@BindView(R.id.rlUpload)
RelativeLayout rlUpload;
@BindView(R.id.ivMyOrdr)
ImageView ivMyOrdr;
@BindView(R.id.rlMyCordr)
RelativeLayout rlMyCordr;
private View view;
private TextView tvUserName;
private TextView tvEditUserInfo;
private TextView tvLand;
private MyCircleImageView ivUserCover;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_mine, container, false);
tvUserName = ((TextView) view.findViewById(R.id.tvUserName));
tvEditUserInfo = ((TextView) view.findViewById(R.id.tvEditUserInfo));
ivUserCover = ((MyCircleImageView) view.findViewById(R.id.ivUserCover));
tvLand = ((TextView) view.findViewById(R.id.tvLand));
// getCurrentUser();
tvLand.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
});
tvEditUserInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), EditUserInfoActivity.class);
startActivity(intent);
}
});
}
ButterKnife.bind(this, view);
return view;
}
@Override
public void onResume() {
super.onResume();
getCurrentUser();
}
private void getCurrentUser() {
//获取当前用户信息
UserBean currentUser = UserBean.getCurrentUser(UserBean.class);
if (currentUser != null) {
tvLand.setVisibility(View.GONE);
tvUserName.setVisibility(View.VISIBLE);
tvUserName.setText(currentUser.getUsername());
tvEditUserInfo.setVisibility(View.VISIBLE);
String userCoverUrl = currentUser.getUserCover();
Glide.with(getActivity())
.load(userCoverUrl)
.into(ivUserCover);
Log.e(TAG, "onCreateView: " + currentUser.getUsername());
} else {
tvUserName.setVisibility(View.GONE);
tvLand.setVisibility(View.VISIBLE);
tvEditUserInfo.setVisibility(View.GONE);
}
}
@OnClick(R.id.ivSeting)
public void onIvSeting(View view) {
Intent intent = new Intent(getContext(), SetingActivity.class);
getActivity().startActivity(intent);
}
@OnClick(R.id.rlUpload)
public void onRlUpload(View view) {
Intent intent = new Intent(getContext(), UpdataFoodActivity.class);
getActivity().startActivity(intent);
}
@OnClick(R.id.rlMyCollect)
public void onRlMyCollect() {
Intent intent = new Intent(getActivity(), MyCollectActivity.class);
startActivity(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
|
package br.com.codenation.domain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import br.com.codenation.domain.PlayersCollection;
public class TeamRepository {
private final Map<Long, Team> teams = new HashMap<>();
private final Map<Long, Player> players = new HashMap<>();
private final Map<Long, List<Long>> playersByTeam = new HashMap<>();
public void addTeam(Team team) {
teams.put(team.getId(), team);
}
public void addPlayer(Player player) {
players.put(player.getId(), player);
List<Long> players = playersByTeam.get(player.getTeamId());
if (players == null) {
players = new ArrayList<>();
}
players.add(player.getId());
playersByTeam.put(player.getTeamId(), players);
}
public Player findPlayer(Long id) {
return players.get(id);
}
public Team findTeam(Long id) {
return teams.get(id);
}
public PlayersCollection retrieveAllPlayers() {
return new PlayersCollection(players.values().stream());
}
public TeamsCollection retrieveAllTeams() {
return new TeamsCollection(teams.values().stream());
}
public PlayersCollection findPlayersByTeam(Long teamId) {
return new PlayersCollection(playersByTeam.get(teamId).stream().map(players::get));
}
public void updateTeam(Team team) {
this.addTeam(team);
}
}
|
package cn.izouxiang.manager.job.dao;
import java.util.List;
import cn.izouxiang.manager.common.mapper.MyMapper;
import cn.izouxiang.manager.job.domain.Job;
public interface JobMapper extends MyMapper<Job> {
List<Job> queryList();
}
|
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.zsl.web.common.dao.IOperations;
import com.zsl.web.common.service.AbstractService;
@Repository(value="modelService")
public class ModelServiceImpl extends AbstractService<Model> implements
IModelService {
@Resource(name="modelDao")
private IModelDao modelDao;
@Override
protected IOperations<Model> getDao() {
return modelDao;
}
}
|
package com.niit.MobileShoppingBackend.DTO;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.validator.constraints.NotBlank;
//entity annotaion for giving the hibernate sql query
@Entity
public class Brand {
//getter and setter methods
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
//private fields
//indicating that id is a primary key in the brand table
@Id
//indicating that id should be generate there value automatically by increase id value with 1
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@NotBlank(message="Please enter brand name ")
private String name;
@NotBlank(message="Please enter description")
private String description;
@Column(name="is_active")
private boolean active;
}
|
package ru.molkov.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.molkov.service.TakenItemServiceImpl;
@Controller
@RequestMapping("/index/takenitem")
public class TakenItemController {
@Autowired
private TakenItemServiceImpl service;
}
|
package com.tencent.mm.plugin.appbrand.jsapi.appdownload;
import com.tencent.mm.plugin.appbrand.ipc.AppBrandMainProcessService;
import com.tencent.mm.plugin.appbrand.jsapi.a;
import com.tencent.mm.plugin.appbrand.l;
import org.json.JSONObject;
public final class JsApiAddDownloadTaskStraight extends a {
public static final int CTRL_INDEX = 440;
public static final String NAME = "addDownloadTaskStraight";
public final void a(l lVar, JSONObject jSONObject, int i) {
AppBrandMainProcessService.a(new AddDownloadTaskStraightTask(this, lVar, i, jSONObject));
b.f(lVar);
}
}
|
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(); // num -> index
for(int i = 0; i < nums.length; i++){
int current = nums[i];
int op = target - current;
if(map.containsKey(op)){
return new int[] {map.get(op), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
}
|
package com.services.utils.object;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DateFormat {
public String format() default "yyyy-MM-dd HH:mm:ss";
}
|
package com.tencent.mm.plugin.offline.ui;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class b$4 implements OnClickListener {
final /* synthetic */ Activity mr;
b$4(Activity activity) {
this.mr = activity;
}
public final void onClick(DialogInterface dialogInterface, int i) {
if (this.mr instanceof WalletOfflineCoinPurseUI) {
((WalletOfflineCoinPurseUI) this.mr).lMa = false;
}
dialogInterface.dismiss();
}
}
|
package EmptyClass;
import java.util.Calendar;
public class Edge {
private String start;
private String end;
private int time_weight;
public Edge next;
public Edge() {
}
// for edgehead in Facility
public Edge(String start, String end) {
this.start = start;
this.end = end;
this.time_weight = 0;
this.next = null;
}
// to create Edge
public Edge(String start, String end, int time_weight) {
this.start = start;
this.end = end;
if (start.substring(1, 2).equals("e") && end.substring(1, 2).equals("e"))
this.time_weight = time_change_elevator(time_weight);
else
this.time_weight = time_weight;
this.next = null;
}
// 시간 따라 엘리베이터 time_weight 가중치 변경
public int time_change_elevator(int time_weight) {
int num;
Calendar cal = Calendar.getInstance();
num = cal.get(Calendar.MINUTE);
if (num >= 50 && num < 60) // 이부분 가중치 수정 요망
num = time_weight * 20;
else
num = time_weight;
return num;
}
public String get_edge_start() {
return start;
}
public String get_edge_end() {
return end;
}
public int get_time_weight() {
return this.time_weight;
}
// print edge's information
public void PrintEdge() {
System.out.println(start + " -> " + end + " : " + time_weight);
}
// // unit test
// public static void main(String[] args) {
// int weight = 1;
// int num;
// num = time_change_elevator(weight);
//
// System.out.println(weight + " " + num );
//
// }
}
|
package com.devcamp.currencyconverter.model.views;
import com.devcamp.currencyconverter.model.entities.Currency;
import java.math.BigDecimal;
public class RateView {
private Currency sourceCurrency;
private Currency targetCurrency;
private BigDecimal rate;
private Boolean rateHasDropped;
public RateView() {
}
public Currency getSourceCurrency() {
return this.sourceCurrency;
}
public void setSourceCurrency(Currency sourceCurrency) {
this.sourceCurrency = sourceCurrency;
}
public Currency getTargetCurrency() {
return this.targetCurrency;
}
public void setTargetCurrency(Currency targetCurrency) {
this.targetCurrency = targetCurrency;
}
public BigDecimal getRate() {
return this.rate;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
public Boolean getRateHasDropped() {
return this.rateHasDropped;
}
public void setRateHasDropped(Boolean rateHasDropped) {
this.rateHasDropped = rateHasDropped;
}
}
|
package eu.tivian.musico.database;
import android.database.sqlite.SQLiteStatement;
import androidx.annotation.NonNull;
/**
* A simplified version of {@link SQLiteStatement} for retrieving single string value from the database.
*/
public class SimpleStatement {
/**
* The compiled SQL statement.
*/
private final SQLiteStatement statement;
/**
* Constructs the object using the supplied SQL statement.
*
* @param sql SQL statement to compile.
*/
public SimpleStatement(@NonNull String sql) {
statement = DatabaseAdapter.get().getDb().compileStatement(sql);
}
/**
* Returns the result of the compiled SQL query.
*
* @return result of the SQL query, or empty string if anything failed.
*/
@NonNull
public String get() {
try {
return statement.simpleQueryForString();
} catch (Exception ex) {
return "";
}
}
}
|
package org.cheng.login.model.impl;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import org.cheng.login.MyApp;
import org.cheng.login.activity.LoginActivity;
import org.cheng.login.entity.User;
import org.cheng.login.model.IModel;
import org.cheng.login.model.IUserModel;
import org.cheng.login.service.PreferencesService;
import org.cheng.login.utils.OtherUtils;
import org.cheng.login.utils.ShowInfoUtils;
import org.cheng.login.utils.StaticFinal;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
/**
* Created by admin on 2016/12/29.
*/
public class UserModel implements IUserModel {
private RequestQueue queue;
public UserModel() {
queue = Volley.newRequestQueue(MyApp.getContext());
}
@Override
public void login(final String username, final String password, final IModel.AsyncCallback callback) {
BmobQuery<User> query = new BmobQuery<User>();
query.findObjects(new FindListener<User>() {
@Override
public void done(List<User> list, BmobException e) {
if (OtherUtils.getNetwork_connection_state()==OtherUtils.NETWORK_STATE_NO){
callback.onError("登录失败"+StaticFinal.NETWORK_STATE_ERROR);
return;
}
if(e==null){
for (User user:list){
String s = user.getName();
Log.i("TAG", "Person name:" +user.getName() + ";pass`;" + user.getPass());
if (username.equals(s) && password.equals(user.getPass())) {
callback.onSuccess("欢迎登录");
PreferencesService.saveUser(user);
return;
}else if (username.equals(s)){
callback.onError("密码输入错误,请重新输入");
return;
}
}
callback.onError("该账号不存在,请注册");
return;
}else{
if (MyApp.isLog) Log.i("UserModel",e.getMessage());
callback.onError(StaticFinal.UNKNOWN_ERROR);
}
}
});
}
@Override
public void register(final User user,final IModel.AsyncCallback callback) {
user.save(new SaveListener<String>() {
@Override
public void done(String objectId,BmobException e) {
if (OtherUtils.getNetwork_connection_state()==OtherUtils.NETWORK_STATE_NO){
callback.onError("注册失败"+StaticFinal.NETWORK_STATE_ERROR);
return;
}
if(e==null){
callback.onSuccess("欢迎登录");
PreferencesService.saveUser(user);
return;
}else{
if (MyApp.isLog) Log.i("Message",e.getMessage());
callback.onError("该账号已存在");
return;
}
}
});
}
}
|
package com.tencent.mm.plugin.game.wepkg.utils;
import com.tencent.mm.plugin.game.wepkg.ipc.WepkgMainProcessService;
import com.tencent.mm.plugin.game.wepkg.model.WepkgCrossProcessTask;
import com.tencent.mm.plugin.game.wepkg.model.WepkgVersion;
import com.tencent.mm.plugin.game.wepkg.model.h;
import com.tencent.mm.plugin.game.wepkg.utils.c.2;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
class c$2$1 implements Runnable {
final /* synthetic */ 2 kgr;
c$2$1(2 2) {
this.kgr = 2;
}
public final void run() {
WepkgCrossProcessTask wepkgCrossProcessTask = new WepkgCrossProcessTask();
wepkgCrossProcessTask.nc = 2003;
if (ad.cic()) {
wepkgCrossProcessTask.aai();
} else {
WepkgMainProcessService.b(wepkgCrossProcessTask);
}
WepkgVersion wepkgVersion = wepkgCrossProcessTask.kff;
if (wepkgVersion != null && !bi.oW(wepkgVersion.kfA)) {
h.aVz().aC(wepkgVersion.kfA, true);
}
}
}
|
package io.gdiazs.sample.service;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.gdiazs.sample.exception.SampleException;
import io.gdiazs.sample.model.Sample;
import io.gdiazs.sample.repository.SampleDAO;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {
"/application-context-test.xml"
})
public class SampleServiceImplTest {
@Mock
private SampleDAO sampleDAO;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testFindWithSomeBussinesRule() throws SampleException {
SampleServiceImpl sampleService = new SampleServiceImpl();
List<Sample> samples = Arrays.asList(new Sample(1, "Test Sample", new Date()));
when(sampleDAO.findAll()).thenReturn(samples);
sampleService.setSampleDAO(sampleDAO);
List<Sample> samplesActual= sampleService.findWithSomeBussinesRule();
verify(sampleDAO, atLeastOnce()).findAll();
Assert.assertTrue(samplesActual.size() == 1);
}
}
|
package com.example.strongM.mycalendarview.calendar;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.strongM.mycalendarview.R;
public class RowView extends LinearLayout {
private static final int COLUMN = 7;
private int distanceTop, distanceBottom;
public RowView(Context context) {
super(context);
setOrientation(HORIZONTAL);
setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_downline_common));
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (getChildCount() >= COLUMN) {
return;
}
super.addView(child, index, params);
}
public void setDistanceTop(int distanceTop) {
this.distanceTop = distanceTop;
}
public void setDistanceBottom(int distanceBottom) {
this.distanceBottom = distanceBottom;
}
public int getDistanceTop(){
return distanceTop;
}
public int getDistanceBottom(){
return distanceBottom;
}
}
|
package lib.game;
import math.geom.Point3i;
public class Face {
public Point3i vertices;
public Point3i normals;
public Point3i texCoords;
public Face(Point3i vertices, Point3i normals) {
this.vertices = vertices;
this.normals = normals;
}
public Face(Point3i vertices, Point3i normals, Point3i texCoords) {
this(vertices, normals);
this.texCoords = texCoords;
}
}
|
package matth.dungeon.GameUI;
import android.widget.TextView;
public class TextLines {
public static String getLine(LevelTile tile, int direction) {
String result = "";
if (tile.getType() == LevelTile.EMPTY) {
result += "There is an empty space";
}
else if (tile.getType() == LevelTile.WALL) {
result += "There is a wall";
}
if (direction == 0) {
result += " in front of you";
}
else if (direction == 1) {
result += " to your right";
}
else if (direction == 2) {
result += " behind you";
}
else if (direction == 3) {
result += " to your left";
}
if (tile.getEvent() == LevelTile.NO_EVENT) {
result += "\n Nothing of interest here";
}
else if (tile.getEvent() == LevelTile.ENEMY_EVENT) {
result += "\n Enemies spotted here";
}
else if (tile.getEvent() == LevelTile.ITEM_EVENT) {
result += "\n An item of interest here";
}
else if (tile.getEvent() == LevelTile.END_POS) {
result += "You see the end";
}
return result;
}
public static void animateText(TextView up, TextView right, TextView down, TextView left) {
up.setAlpha(0.0f);
up.animate().alpha(1.0f).setListener(null).setDuration(500);
right.setAlpha(0.0f);
right.animate().alpha(1.0f).setListener(null).setDuration(700);
down.setAlpha(0.0f);
down.animate().alpha(1.0f).setListener(null).setDuration(900);
left.setAlpha(0.0f);
left.animate().alpha(1.0f).setListener(null).setDuration(1100);
}
}
|
package com.tencent.mm.app;
import com.tencent.mm.plugin.report.service.KVCommCrossProcessReceiver;
import com.tencent.mm.sdk.platformtools.ak.c;
class ToolsProfile$1 implements c {
final /* synthetic */ ToolsProfile bzj;
ToolsProfile$1(ToolsProfile toolsProfile) {
this.bzj = toolsProfile;
}
public final void c(String str, Throwable th) {
KVCommCrossProcessReceiver.brP();
}
}
|
package wicket;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import vo.ClientVO;
import vo.StockVO;
import wicket.services.Services;
public class StockTradingSessionPanel extends Panel {
@SpringBean
private Services services;
public StockTradingSessionPanel(String id, final IModel model, final Item item) {
super(id, model);
StockVO stockVO;
if(this.getDefaultModel().getObject() instanceof StockVO) {
stockVO = (StockVO) this.getDefaultModel().getObject();
}else{
ClientVO clientVO = (ClientVO) this.getDefaultModel().getObject();
stockVO = services.getStockVO(clientVO.getSecurityId());
}
Model<String> status = Model.of(stockVO.getStatusText());
Label statusLabel = new Label("tradingSessionLabel", status);
statusLabel.setOutputMarkupId(true);
statusLabel.add(new AttributeAppender("class", "label label-info", ";"));
add(statusLabel);
}
}
|
package com.jayqqaa12.abase.exception;
public class HttpException extends AbaseException {
private static final long serialVersionUID = 1L;
}
|
package com.pangpang6.hadoop.kafka;
import com.google.common.collect.Lists;
import org.apache.kafka.clients.admin.*;
import org.apache.kafka.common.KafkaFuture;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import java.util.Properties;
public class TopicTest {
AdminClient adminClient;
@Before
public void before() {
Properties properties = new Properties();
properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "node1:9092,node2:9092,node3:9092,node4:9092");
adminClient = KafkaAdminClient.create(properties);
}
@Test
public void desc() throws Exception {
DescribeTopicsResult topicsResult = adminClient.describeTopics(Lists.newArrayList("flink-output-p2"));
KafkaFuture<Map<String, TopicDescription>> kafkaFuture = topicsResult.all();
Map<String, TopicDescription> map = kafkaFuture.get();
for (Map.Entry<String, TopicDescription> entry : map.entrySet()) {
String topic = entry.getKey();
TopicDescription topicDescription = entry.getValue();
System.out.println(topicDescription.toString());
}
}
}
|
import java.util.*;
public class NumberInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number: ");
input.close();
try {
int number = input.nextInt();
System.out.println("You entered " + number);
}
catch (InputMismatchException e) {
System.out.println("You didn't enter a number!");
}
// catch (IllegalStateException e2) {
// // do this if an IllegalStateException is caught
// System.out.println("Illegal state exception");
// }
catch (NoSuchElementException e3) {
// do this if an IllegalStateException is caught
System.out.println("No such element exception");
}
finally {
// do this whether or not any exceptions are caught
System.out.println("This prints whether or not an exception is thrown");
}
System.out.println("Bye!");
}
}
|
import java.util.Scanner;
public class GuessMyNumberAISolver {
public static void main(String[] args){
new GuessMyNumberAISolver();
}
public GuessMyNumberAISolver(){
showComputerBanter();
faceOff();
}
public void showComputerBanter(){
System.out.println("Guess a Number between 0 and 1000 inclusive and Remember it!");
System.out.println("I am quite the number guessing master");
}
public void faceOff(){
int tries = 0;
int lowestPossible = 0;
int highestPossible = 1000;
int number = 500;
Scanner player = new Scanner(System.in);
while(true){
System.out.println("Is your number " + number);
System.out.println("yes or no");
boolean correct = (player.nextLine().equals("yes"))?true:false;
if(correct){
System.out.println("Got emmmm! " + tries + " as well! ");
break;
}else{
tries++;
System.out.println("Was I low or high");
boolean tooLow = (player.nextLine().equals("low"))?true:false;
if(tooLow){
System.out.println("hmmmmmm so higher huh....");
lowestPossible = number;
number = lowestPossible + (int)(highestPossible-lowestPossible)/2;
}else{
System.out.println("hmmmmm so lower huh....");
highestPossible = number;
number = lowestPossible + (int)(highestPossible-lowestPossible)/2;
}
}
}
player.close();
}
}
|
package org.browsexml.timesheetjob.dao;
import java.sql.Date;
import java.util.List;
import org.browsexml.timesheetjob.model.PayPer;
public interface PayPeriodDao extends Dao{
public void savePeriod(PayPer period);
public void removePayPeriod(Integer id);
public PayPer getPeriod(Integer id);
public PayPer getPeriod(Date beginDate, boolean fulltime);
public PayPer getPeriodFromEndDate(Date endDate, boolean fulltime);
public List<PayPer> getContainingPeriods(Date date, boolean fulltime);
public java.util.Date getLastPeriodDefined(boolean fulltime);
public List<PayPer> getPeriods(String year);
public List<Integer> getYears();
public List<PayPer> getPeriods(String year, Boolean fulltime);
public List<String> getYearTerms(boolean fulltime, Date date);
public java.util.Date getLastPeriodEnd(boolean fulltime, boolean processed);
public Integer needPayPeriods(Date today);
}
|
/*
* 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 org.opensoft.model.services;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.opensoft.model.entities.Periodos;
import org.opensoft.model.enums.Estado;
/**
*
* @author MLLERENA
*/
@Stateless
public class PeriodosFacade extends AbstractFacade<Periodos> {
@PersistenceContext(unitName = "funec-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public PeriodosFacade() {
super(Periodos.class);
}
public List<Periodos> findByEstado(Estado estado) {
Query query = em.createNamedQuery("Periodos.findByEstado");
query.setParameter("estado", estado);
return query.getResultList();
}
}
|
package com.emn.common;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class EmnIntercepter extends AbstractInterceptor{
private static final long serialVersionUID = 6167222277768493258L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> session = (Map<String, Object>) ActionContext.getContext().getSession();
Object member = session.get("member");
String result = "";
if( member == null)
result = Action.LOGIN;
else
result = invocation.invoke();
return result;
}
}
|
/* 제목 : 13-6 flag를 이용한 스레드 강제 종료
* 학번 : 201611321
* 이름 : 임민수
*/
package SW;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class RandomThread extends Thread {
private Container contentPane;
private boolean flag = false; //flag를 통하여 스레드 종료 표시
public RandomThread(Container contentPane) {
this.contentPane = contentPane;
}
void finish() { //스레드 종료 명령을 flag에 표시
flag = true;
}
@Override
public void run() {
while (true) {
int x = ((int) (Math.random() * contentPane.getWidth()));
int y = ((int) (Math.random() * contentPane.getHeight()));//JFrame의 크기 면적 가져오기
JLabel label = new JLabel("Java");
label.setSize(80, 30);
label.setLocation(x, y);
contentPane.add(label);
contentPane.repaint();
try {
Thread.sleep(300);
if (flag == true) {
contentPane.removeAll();
label = new JLabel("finish");
label.setSize(80, 30);
label.setLocation(100, 100);
label.setForeground(Color.RED);
contentPane.add(label);
contentPane.repaint();
return; //스레드 종료
}
} catch (InterruptedException e) {
return;
}//0.3초마다 Java라는 글자를 JFrame창에 띄움
}
}
}
public class ThreadFinishFlagEx extends JFrame {
private RandomThread th;
public ThreadFinishFlagEx() {
setTitle("ThreadFinishFlagEx 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
c.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
th.finish(); //RandomThread 스레드 종료 명령
}
});
setSize(300, 200);
setVisible(true);
th = new RandomThread(c); //스레드 생성
th.start(); //스레드 동작시킴
}
public static void main(String[] args) {
new ThreadFinishFlagEx();
}
}
//"Java"라는 글자를 화면의 크기에 맞춰진 곳에 랜덤으로 띄워 표시한다.
//마우스로 클릭시 더이상 "Java"라는 글자가 띄워지지 않고 화면이 정리되고 "Finish"라는 글자가 뜨면서 끝나는 프로그램
|
package team.Training;
import java.util.List;
import team.Squad;
import team.player.Player;
public class Training {
private TrainingIntensity intensity;
public Training() {
// Default
intensity = TrainingIntensity.BALANCED;
}
public void workout(Squad squad) {
List<Player> playerList = squad.getPlayerList();
for(Player p : playerList) {
if(p.isAvalibleToPlayOrTraining()) {
workout(p);
}
}
}
public void workout(Player player){
float improveFactor = intensity.getImproveFactor();
int fatigueFactor = intensity.getFadigueFactor();
player.setAttributeImprove(improveFactor);
player.setFatigue(fatigueFactor);
}
}
|
package tk.mybatis.simple;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import tk.mybatis.simple.model.Country;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class JavaApiConfig {
public static void main(String[] args) throws IOException {
UnpooledDataSource dataSource = new UnpooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/mybatis",
"root",
"");
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("Java", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.getTypeAliasRegistry().registerAliases("tk.mybatis.simple.model");
configuration.setLogImpl(Log4jImpl.class);
InputStream inputStream = Resources.getResourceAsStream("tk/mybatis/simple/mapper/CountryMapper.xml");
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, "tk/mybatis/simple/mapper/CountryMapper.xml", configuration.getSqlFragments());
mapperParser.parse();
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
List<Country> countryList = sqlSession.selectList("selectAll");
printCountryList(countryList);
} finally {
sqlSession.close();
}
}
private static void printCountryList(List<Country> countryList){
for(Country country : countryList){
System.out.printf("%-4d%4s%4s\n",country.getId(), country.getCountryname(), country.getCountrycode());
}
}
}
|
package jbyco.analysis.patterns.instructions;
import jbyco.analysis.patterns.operations.AbstractOperation;
import jbyco.analysis.patterns.parameters.AbstractParameter;
import java.util.Arrays;
/**
* The representation of abstracted instruction.
* Abstract instructions are created by Abstractor.
*/
public class Instruction implements AbstractInstruction {
/**
* The abstraction of the operation code.
*/
final AbstractOperation operation;
/**
* The abstraction of parameters.
*/
final AbstractParameter[] parameters;
/**
* Instantiates a new instruction.
*
* @param operation the operation
* @param params the parameters
*/
public Instruction(AbstractOperation operation, AbstractParameter[] params) {
this.operation = operation;
this.parameters = params;
}
public AbstractOperation getOperation() {
return operation;
}
public AbstractParameter[] getParameters() {
return parameters;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer(operation.toString());
for (Object parameter : parameters) {
buffer.append(' ');
buffer.append(parameter);
}
return buffer.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((operation == null) ? 0 : operation.hashCode());
result = prime * result + Arrays.hashCode(parameters);
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
// this?
if (this == obj) {
return true;
}
// null?
if (obj == null) {
return false;
}
// same class?
if (getClass() != obj.getClass()) {
return false;
}
Instruction other = (Instruction) obj;
// same operation?
if (operation == null) {
if (other.operation != null) {
return false;
}
} else if (!operation.equals(other.operation)) {
return false;
}
// same parameters?
if (!Arrays.equals(parameters, other.parameters)) {
return false;
}
// ok
return true;
}
}
|
package com.uvaysss.queuemanager.data.database.entity;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
@Entity
public class TaskEntity {
public static final int STATUS_QUEUE = 1;
public static final int STATUS_PROGRESS = 2;
public static final int STATUS_ERROR = 3;
@PrimaryKey(autoGenerate = true)
private long id;
private final int typeId;
private final int priorityId;
private int status;
public TaskEntity(long id, int typeId, int priorityId, int status) {
this.id = id;
this.typeId = typeId;
this.priorityId = priorityId;
this.status = status;
}
@Ignore
public TaskEntity(int typeId, int priorityId, int status) {
this.typeId = typeId;
this.priorityId = priorityId;
this.status = status;
}
@Ignore
public TaskEntity(int typeId, int priorityId) {
this.typeId = typeId;
this.priorityId = priorityId;
this.status = STATUS_QUEUE;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getTypeId() {
return typeId;
}
public int getPriorityId() {
return priorityId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
|
package com.example.currency.util;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateUtil {
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static LocalDate convertToLocalDate (Object param) {
//string to date
return LocalDate.parse(param.toString(), dateTimeFormatter);
}
}
|
package co.staruml.awt;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import co.staruml.core.Cursor;
import co.staruml.core.DiagramControl;
import co.staruml.core.DiagramView;
import co.staruml.graphics.*;
import co.staruml.handler.Handler;
import co.staruml.handler.MouseEvent;
public class DiagramControlAWT extends Component
implements DiagramControl, MouseListener, MouseMotionListener {
private static final long serialVersionUID = -8428629581765608447L;
private static final MouseEvent toAbstractMouseEvent(
java.awt.event.MouseEvent e) {
return new MouseEvent(e.getX(), e.getY(), e.getButton(), e.getClickCount(),
e.isShiftDown(), e.isAltDown(), e.isControlDown());
}
private Handler handler;
private CanvasAWT canvas;
private DiagramView diagramView;
private java.awt.Color backgroundColor;
private BufferedImage backgroundImage;
private java.awt.Cursor toAWTCursor(Cursor cursor) {
return java.awt.Cursor.getPredefinedCursor(cursor.getType());
}
public DiagramControlAWT(ImageManager imageManager) {
canvas = new CanvasAWT();
canvas.setImageManager(imageManager);
backgroundColor = java.awt.Color.WHITE;
backgroundImage = null;
addMouseListener(this);
addMouseMotionListener(this);
}
private void drawBackground(Graphics2D g) {
if (backgroundImage == null) {
int w = getDiagramWidth();
int h = getDiagramHeight();
backgroundImage = new BufferedImage(
w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) backgroundImage.getGraphics();
g2.setColor(backgroundColor);
g2.fillRect(0, 0, w, h);
g2.setColor(new java.awt.Color(240, 240, 240));
GridFactor gf = canvas.getGridFactor();
int xc = w / (gf.getWidth() * 4) + 1;
int yc = h / (gf.getHeight() * 4) + 1;
// solid line
for (int i = 0; i < xc; i++) {
int x = i * gf.getWidth() * 4;
g2.drawLine(x, 0, x, h);
}
for (int i = 0; i < yc; i++) {
int y = i * gf.getHeight() * 4;
g2.drawLine(0, y, h, y);
}
// dot line
java.awt.BasicStroke stroke =
new java.awt.BasicStroke(1, java.awt.BasicStroke.CAP_BUTT,
java.awt.BasicStroke.JOIN_BEVEL, 0, new float[] {1}, 0);
g2.setStroke(stroke);
for (int i = 0; i < xc; i++) {
int x = (i * gf.getWidth() * 4) + (gf.getWidth() * 2);
g2.drawLine(x, 0, x, h);
}
for (int i = 0; i < yc; i++) {
int y = (i * gf.getHeight() * 4) + (gf.getWidth() * 2);
g2.drawLine(0, y, h, y);
}
}
g.drawImage(backgroundImage, 0, 0, null);
}
public void paint(Graphics g) {
// TEST CODE
canvas.setGraphics((Graphics2D) g);
// canvas.setAntialias(Canvas.AS_ON);
drawBackground((Graphics2D) g);
// Dimension d = getSize();
// canvas.setColor(Color.WHITE);
// canvas.setFillColor(Color.WHITE);
// canvas.fillRect(0, 0, d.width, d.height);
// g.clearRect(0, 0, d.width, d.height);
diagramView.drawDiagram(canvas);
// TEST CODE
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler h) {
handler = h;
}
public Canvas getCanvas() {
return canvas;
}
public DiagramView getDiagramView() {
return diagramView;
}
public void setDiagramView(DiagramView diagramView) {
this.diagramView = diagramView;
}
public int getDiagramWidth() {
return getWidth();
}
public int getDiagramHeight() {
return getHeight();
}
public ZoomFactor getZoomFactor() {
return canvas.getZoomFactor();
}
public GridFactor getGridFactor() {
return canvas.getGridFactor();
}
public void setCursor(Cursor cursor) {
setCursor(toAWTCursor(cursor));
}
public void drawRubberband(int x1, int y1, int x2, int y2) {
Toolkit.drawRange(canvas, x1, y1, x2, y2);
}
public void eraseRubberband(int x1, int y1, int x2, int y2) {
Toolkit.drawRange(canvas, x1, y1, x2, y2);
}
public void drawRubberlines(Points points) {
Toolkit.drawDottedLine(canvas, points);
}
public void eraseRubberlines(Points points) {
Toolkit.drawDottedLine(canvas, points);
}
public void mouseClicked(java.awt.event.MouseEvent e) {
}
public void mouseEntered(java.awt.event.MouseEvent e) {
}
public void mouseExited(java.awt.event.MouseEvent e) {
}
public void mousePressed(java.awt.event.MouseEvent e) {
if (handler != null) {
((CanvasAWT) canvas).setGraphics((Graphics2D) getGraphics());
handler.mousePressed(this, canvas, toAbstractMouseEvent(e));
}
}
public void mouseReleased(java.awt.event.MouseEvent e) {
if (handler != null)
handler.mouseReleased(this, canvas, toAbstractMouseEvent(e));
}
public void mouseDragged(java.awt.event.MouseEvent e) {
if (handler != null) {
((CanvasAWT) canvas).setGraphics((Graphics2D) getGraphics());
handler.mouseDragged(this, canvas, toAbstractMouseEvent(e));
}
}
public void mouseMoved(java.awt.event.MouseEvent e) {
if (handler != null)
handler.mouseMoved(this, canvas, toAbstractMouseEvent(e));
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.c.a;
import java.util.LinkedList;
public final class bwo extends bhd {
public double altitude;
public int bjj;
public double latitude;
public double longitude;
public double ssO;
public double ssP;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.shX != null) {
aVar.fV(1, this.shX.boi());
this.shX.a(aVar);
}
aVar.c(2, this.latitude);
aVar.c(3, this.longitude);
aVar.c(4, this.altitude);
aVar.c(5, this.ssO);
aVar.c(6, this.ssP);
aVar.fT(7, this.bjj);
return 0;
} else if (i == 1) {
if (this.shX != null) {
fS = f.a.a.a.fS(1, this.shX.boi()) + 0;
} else {
fS = 0;
}
return (((((fS + (f.a.a.b.b.a.ec(2) + 8)) + (f.a.a.b.b.a.ec(3) + 8)) + (f.a.a.b.b.a.ec(4) + 8)) + (f.a.a.b.b.a.ec(5) + 8)) + (f.a.a.b.b.a.ec(6) + 8)) + f.a.a.a.fQ(7, this.bjj);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bwo bwo = (bwo) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
switch (intValue) {
case 1:
LinkedList IC = aVar3.IC(intValue);
int size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
byte[] bArr = (byte[]) IC.get(intValue);
fk fkVar = new fk();
f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (boolean z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) {
}
bwo.shX = fkVar;
}
return 0;
case 2:
bwo.latitude = aVar3.vHC.readDouble();
return 0;
case 3:
bwo.longitude = aVar3.vHC.readDouble();
return 0;
case 4:
bwo.altitude = aVar3.vHC.readDouble();
return 0;
case 5:
bwo.ssO = aVar3.vHC.readDouble();
return 0;
case 6:
bwo.ssP = aVar3.vHC.readDouble();
return 0;
case 7:
bwo.bjj = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package com.chuxin.family.parse.been;
import com.chuxin.family.parse.been.data.CxCallDataField;
/**
* 对应Pair/call接口数据
* @author shichao.wang
*
*/
public class CxCall extends CxParseBasic{
private CxCallDataField data;
public CxCallDataField getData() {
return data;
}
public void setData(CxCallDataField data) {
this.data = data;
}
}
|
package me.jessepayne.pad4j.core.enums;
public enum CCButtonEnum {
SCENE_1(89),
SCENE_2(79),
SCENE_3(69),
SCENE_4(59),
SCENE_5(49),
SCENE_6(39),
SCENE_7(29),
SCENE_8(19),
UP_ARROW(91),
DOWN_ARROW(92),
LEFT_ARROW(93),
RIGHT_ARROW(94),
SESSION(95),
NOTE(96),
DEVICE(97),
USER(98),
SHIFT(80),
CLICK(70),
UNDO(60),
DELETE(50),
QUANTISE(40),
DUPLICATE(30),
DOUBLE(20),
RECORD(10),
RECORD_ARM(1),
TRACK_SELECT(2),
MUTE(3),
SOLO(4),
VOLUME(5),
PAN(6),
SENDS(7),
STOP_CLIP(8);
int note;
CCButtonEnum(int note){
this.note = note;
}
public int getNote(){
return note;
}
}
|
package entities;
import lombok.*;
import repository.TableManagement;
import javax.persistence.*;
import java.util.Scanner;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = "prisoner")
public class Prisoner {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idPrisoner;
@Column(name = "firstname", nullable = false)
private String firstName;
@Column(name = "lastname", nullable = false)
private String lastName;
@Column(name = "securitylevel", nullable = false)
private int securityLevel;
@Column(name = "entrydate", nullable = false)
private String entryDate;
@Column(name = "releasedate", nullable = false)
private String releaseDate;
@ManyToOne(targetEntity = Prison.class)
@JoinColumn(name = "idPrison")
@ToString.Exclude
private Prison prison;
@Column(name = "reason", nullable = false)
private String reason;
public Prisoner insertNewPrisonerDetails() {
Prisoner prisoner = new Prisoner();
Scanner scanner = new Scanner(System.in);
System.out.println("Insert prisoner's first name: ");
String firstName = scanner.next();
prisoner.setFirstName(firstName);
System.out.println("Insert prisoner's last name: ");
String lastName = scanner.next();
prisoner.setLastName(lastName);
System.out.println("Insert prisoner's security level: ");
int securityLevel = scanner.nextInt();
prisoner.setSecurityLevel(securityLevel);
System.out.println("Insert prisoner's date of incarceration: ");
String incarcerationDate = scanner.next();
prisoner.setEntryDate(incarcerationDate);
System.out.println("Insert prisoner's release date: ");
String releaseDate = scanner.next();
prisoner.setReleaseDate(releaseDate);
System.out.println("Insert the ID for the prison the prisoner should be assigned to: ");
int idPrison = scanner.nextInt();
prisoner.prison = new TableManagement().returnPrisonById(idPrison);
System.out.println("Insert reason for incarceration: ");
String reason = scanner.next();
prisoner.setReason(reason);
return prisoner;
}
}
|
package Hipermarket;
/**
* Classe abstrata Company
*/
abstract class Company {
// variaveis de instancia de Company
private String name;
private int vatNumber;
/**
* Default company constructor
*/
public Company() {
}
/**
* construtor de company
* @param name
* @param vatNumber
*/
public Company(String name, int vatNumber) {
this.name = name;
this.vatNumber = vatNumber;
}
// GETTERS E SETTERS
/**
* Getter para name
* @return name
*/
public String getName() {
return name;
}
/**
* Setter para name
* @param val
*/
public void setName(String val) {
this.name = val;
}
/**
* Getter para vatNumber
* @return varNumber
*/
public int getVatNumber() {
return vatNumber;
}
/**
* Setter para vatNumber
* @param val
*/
public void setVatNumber(int val) {
this.vatNumber = val;
}
/**
* Método toString para imprimir
* @return text
*/
@Override
public String toString() {
String text = "";
text += "Company name: " + name + "\n";
text += "Company vatNumber: " + vatNumber + "\n";
return text;
}
}
|
import textio.TextIO;
public class WhatsYourName {
public static void main (String [] args) {
String userName;
int nameSpace;
String firstName;
String lastName;
char firstInitial;
char lastInitial;
System.out.println("Please enter your first name and last name, separated by a space.");
userName = TextIO.getln();
nameSpace = userName.indexOf(' ');
firstName = userName.substring(0,nameSpace);
lastName = userName.substring(nameSpace + 1);
firstInitial = firstName.charAt(0);
lastInitial = lastName.charAt(0);
System.out.println("Your first name is " + firstName + ", which has " + firstName.length() + " characters");
System.out.println("Your last name is " + lastName + ", which has " + lastName.length() + " characters");
System.out.println("Your initials are " + firstInitial + lastInitial);
}
}
|
/*
* [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.acceleratorservices.order.impl;
import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull;
import de.hybris.platform.acceleratorservices.order.AcceleratorCheckoutService;
import de.hybris.platform.acceleratorservices.store.pickup.PickupPointOfServiceConsolidationStrategy;
import de.hybris.platform.commerceservices.order.CommerceCartModification;
import de.hybris.platform.commerceservices.order.CommerceCartModificationException;
import de.hybris.platform.commerceservices.order.CommerceCartModificationStatus;
import de.hybris.platform.commerceservices.order.CommerceCartService;
import de.hybris.platform.commerceservices.order.impl.DefaultCommerceCheckoutService;
import de.hybris.platform.commerceservices.service.data.CommerceCartParameter;
import de.hybris.platform.commerceservices.stock.CommerceStockService;
import de.hybris.platform.commerceservices.storefinder.data.PointOfServiceDistanceData;
import de.hybris.platform.core.model.order.AbstractOrderEntryModel;
import de.hybris.platform.core.model.order.CartEntryModel;
import de.hybris.platform.core.model.order.CartModel;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.order.CartService;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.store.services.BaseStoreService;
import de.hybris.platform.storelocator.model.PointOfServiceModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Required;
/**
* Accelerator specific implementation of {@link DefaultCommerceCheckoutService}
*/
public class DefaultAcceleratorCheckoutService implements AcceleratorCheckoutService
{
private PickupPointOfServiceConsolidationStrategy pickupPointOfServiceConsolidationStrategy;
private CartService cartService;
private CommerceCartService commerceCartService;
private ModelService modelService;
private CommerceStockService commerceStockService;
private BaseStoreService baseStoreService;
@Override
public List<PointOfServiceDistanceData> getConsolidatedPickupOptions(final CartModel cartModel)
{
validateParameterNotNull(cartModel, "CartModel cannot be null");
return getPickupPointOfServiceConsolidationStrategy().getConsolidationOptions(cartModel);
}
@Override
public List<CommerceCartModification> consolidateCheckoutCart(final CartModel cartModel,
final PointOfServiceModel consolidatedPickupPointModel) throws CommerceCartModificationException
{
validateParameterNotNull(cartModel, "CartModel cannot be null");
validateParameterNotNull(consolidatedPickupPointModel, "PointOfServiceModel cannot be null");
boolean needRefreshCart = false;
final List<AbstractOrderEntryModel> entriesToBeRemovedDueToPOS = new ArrayList<>();
final List<AbstractOrderEntryModel> consolidatedEntriesToBeRemoved = new ArrayList<>();
final List<CommerceCartModification> unsuccessfulModifications = new ArrayList<>();
final List<AbstractOrderEntryModel> entriesToConsolidate = getEntriesToConsolidate(cartModel, consolidatedPickupPointModel,
entriesToBeRemovedDueToPOS, consolidatedEntriesToBeRemoved, unsuccessfulModifications);
// consolidate entries
for (final AbstractOrderEntryModel entryToConsolidate : entriesToConsolidate)
{
// update quantity for consolidated anchor entry
final CommerceCartParameter parameter = createCartParameter(cartModel, entryToConsolidate,
calculateProductQtyInCart(entryToConsolidate.getProduct(), cartModel));
final CommerceCartModification updateQtyModification = getCommerceCartService().updateQuantityForCartEntry(parameter);
if (!CommerceCartModificationStatus.SUCCESS.equals(updateQtyModification.getStatusCode()))
{
unsuccessfulModifications.add(updateQtyModification);
}
}
// remove entries that are consolidated
for (final AbstractOrderEntryModel entryToRemove : consolidatedEntriesToBeRemoved)
{
getModelService().remove(entryToRemove);
needRefreshCart = true;
}
// remove entries that product is not available in the POS
for (final AbstractOrderEntryModel entryToRemove : entriesToBeRemovedDueToPOS)
{
final AbstractOrderEntryModel clone = getModelService().clone(entryToRemove);
getModelService().detach(clone);
getModelService().remove(entryToRemove);
needRefreshCart = true;
// add modification
final CommerceCartModification noStockModification = new CommerceCartModification();
noStockModification.setEntry(clone);
noStockModification.setQuantity(clone.getQuantity().longValue());
noStockModification.setQuantityAdded(-clone.getQuantity().longValue());
noStockModification.setStatusCode(CommerceCartModificationStatus.NO_STOCK);
unsuccessfulModifications.add(noStockModification);
}
// refresh cart if any entry was removed
if (needRefreshCart)
{
getModelService().refresh(cartModel);
}
return unsuccessfulModifications;
}
protected CommerceCartParameter createCartParameter(final CartModel cartModel, final AbstractOrderEntryModel entryToRemove,
final long qty)
{
final CommerceCartParameter removeEntryParameter = new CommerceCartParameter();
removeEntryParameter.setEnableHooks(true);
removeEntryParameter.setCart(cartModel);
removeEntryParameter.setEntryNumber(entryToRemove.getEntryNumber().longValue());
removeEntryParameter.setQuantity(qty);
return removeEntryParameter;
}
/**
* Gets the consolidate entries.
*
* @param cartModel
* the cart model
* @param consolidatedPickupPointModel
* the consolidated pickup point model
* @param entriesToBeRemovedDueToPOS
* the entries to be removed due to out of stock in POS
* @param consolidatedEntriesToBeRemoved
* the entries that has the same product but different POS from consolidate POS.
* @param unsuccessfulModifications
* the unsuccessful modifications
* @return the entries to consolidate. Key: the entry that has the same POS as consolidate POS. Value: the entries
* that has the same product as the entry in the key, but different POS.
* @throws CommerceCartModificationException
* the commerce cart modification exception
*/
protected List<AbstractOrderEntryModel> getEntriesToConsolidate(final CartModel cartModel,
final PointOfServiceModel consolidatedPickupPointModel, final List<AbstractOrderEntryModel> entriesToBeRemovedDueToPOS,
final List<AbstractOrderEntryModel> consolidatedEntriesToBeRemoved,
final List<CommerceCartModification> unsuccessfulModifications) throws CommerceCartModificationException
{
final List<AbstractOrderEntryModel> entriesToConsolidate = new ArrayList<>();
for (final AbstractOrderEntryModel entry : cartModel.getEntries())
{
if (entry.getDeliveryPointOfService() != null)
{
// entry POS is the same as consolidate POS
if (entry.getDeliveryPointOfService().equals(consolidatedPickupPointModel))
{
// if no anchor entry in the map, add it
if (!entriesToConsolidate.contains(entry))
{
entriesToConsolidate.add(entry);
}
}
else
{
// entry POS is not the same as consolidate POS
final AbstractOrderEntryModel anchorEntryToConsolidate = getExistingAnchorEntryByProduct(entry.getProduct(),
entriesToConsolidate);
if (anchorEntryToConsolidate != null)
{
consolidatedEntriesToBeRemoved.add(entry);
}
else
{
final AbstractOrderEntryModel anchorEntry = getAnchorEntryToConsolidate(entry, cartModel,
consolidatedPickupPointModel);
if (anchorEntry == null)
{
// if there is no entry that has the same POS as consolidate POS in the cart, check current entry stock level in the consolidate POS. If in stock, update the entry POS to consolidate POS and use it as anchor entry.
if (isInStock(entry.getProduct(), consolidatedPickupPointModel))
{
updatePOS(cartModel, consolidatedPickupPointModel, unsuccessfulModifications, entry);
entriesToConsolidate.add(entry);
}
else
{
// to be removed if it's not available in the POS
entriesToBeRemovedDueToPOS.add(entry);
}
}
else
{
// if there is one entry that has the same POS as consolidate POS in the cart, use the one in the cart as anchor and add current entry to the map value
entriesToConsolidate.add(anchorEntry);
consolidatedEntriesToBeRemoved.add(entry);
}
}
}
}
}
return entriesToConsolidate;
}
/**
* Gets the anchor entry to consolidate.
*
* @param entry
* the entry
* @param cartModel
* the cart model
* @param consolidatedPickupPointModel
* the consolidated pickup point model
* @return the anchor entry to consolidate
*/
protected AbstractOrderEntryModel getAnchorEntryToConsolidate(final AbstractOrderEntryModel entry, final CartModel cartModel,
final PointOfServiceModel consolidatedPickupPointModel)
{
return cartModel.getEntries().stream().filter(Objects::nonNull)
.filter(cartEntry -> cartEntry.getDeliveryPointOfService() != null)
.filter(cartEntry -> cartEntry.getDeliveryPointOfService().equals(consolidatedPickupPointModel))
.filter(cartEntry -> cartEntry.getProduct().equals(entry.getProduct())).findFirst().orElse(null);
}
protected void updatePOS(final CartModel cartModel, final PointOfServiceModel consolidatedPickupPointModel,
final List<CommerceCartModification> unsuccessfulModifications, final AbstractOrderEntryModel entry)
throws CommerceCartModificationException
{
final CommerceCartParameter parameter = new CommerceCartParameter();
parameter.setEnableHooks(true);
parameter.setCart(cartModel);
parameter.setEntryNumber(entry.getEntryNumber().longValue());
parameter.setPointOfService(consolidatedPickupPointModel);
final CommerceCartModification modification = getCommerceCartService().updatePointOfServiceForCartEntry(parameter);
if (!CommerceCartModificationStatus.SUCCESS.equals(modification.getStatusCode()))
{
unsuccessfulModifications.add(modification);
}
}
protected boolean isInStock(final ProductModel productModel, final PointOfServiceModel pointOfServiceModel)
{
if (!getCommerceStockService().isStockSystemEnabled(getBaseStoreService().getCurrentBaseStore()))
{
return true;
}
final Long availableStockLevel = getCommerceStockService().getStockLevelForProductAndPointOfService(productModel,
pointOfServiceModel);
return availableStockLevel == null || availableStockLevel.longValue() > 0;
}
protected AbstractOrderEntryModel getExistingAnchorEntryByProduct(final ProductModel product,
final List<AbstractOrderEntryModel> entriesToConsolidate)
{
return entriesToConsolidate.stream().filter(Objects::nonNull).filter(entry -> Objects.equals(product, entry.getProduct()))
.findFirst().orElse(null);
}
protected long calculateProductQtyInCart(final ProductModel productModel, final CartModel cartModel)
{
long cartLevel = 0;
for (final CartEntryModel entryModel : getCartService().getEntriesForProduct(cartModel, productModel))
{
if (entryModel.getDeliveryPointOfService() != null)
{
cartLevel += entryModel.getQuantity() != null ? entryModel.getQuantity().longValue() : 0;
}
}
return cartLevel;
}
protected PickupPointOfServiceConsolidationStrategy getPickupPointOfServiceConsolidationStrategy()
{
return pickupPointOfServiceConsolidationStrategy;
}
@Required
public void setPickupPointOfServiceConsolidationStrategy(
final PickupPointOfServiceConsolidationStrategy pickupPointOfServiceConsolidationStrategy)
{
this.pickupPointOfServiceConsolidationStrategy = pickupPointOfServiceConsolidationStrategy;
}
protected CartService getCartService()
{
return cartService;
}
@Required
public void setCartService(final CartService cartService)
{
this.cartService = cartService;
}
protected CommerceCartService getCommerceCartService()
{
return commerceCartService;
}
@Required
public void setCommerceCartService(final CommerceCartService commerceCartService)
{
this.commerceCartService = commerceCartService;
}
protected ModelService getModelService()
{
return modelService;
}
@Required
public void setModelService(final ModelService modelService)
{
this.modelService = modelService;
}
protected CommerceStockService getCommerceStockService()
{
return commerceStockService;
}
@Required
public void setCommerceStockService(final CommerceStockService commerceStockService)
{
this.commerceStockService = commerceStockService;
}
protected BaseStoreService getBaseStoreService()
{
return baseStoreService;
}
@Required
public void setBaseStoreService(final BaseStoreService baseStoreService)
{
this.baseStoreService = baseStoreService;
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.searchresult;
import java.util.HashMap;
import java.util.Map;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.SelectionGrid;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTDocument;
import com.openkm.frontend.client.bean.GWTFolder;
import com.openkm.frontend.client.bean.GWTMail;
import com.openkm.frontend.client.bean.GWTPermission;
import com.openkm.frontend.client.bean.GWTProfileFileBrowser;
import com.openkm.frontend.client.bean.GWTQueryResult;
import com.openkm.frontend.client.util.CommonUI;
import com.openkm.frontend.client.util.Util;
/**
* Extends ScrollTable functionalities
*
* @author jllort
*
*/
public class ExtendedScrollTable extends ScrollTable {
// Holds the data rows of the table this is a list of RowData Object
public Map<Integer, GWTQueryResult> data = new HashMap<Integer, GWTQueryResult>();
private int mouseX = 0;
private int mouseY = 0;
private int dataIndexValue = 0;
private boolean panelSelected = false; // Indicates if panel is selected
private FixedWidthGrid dataTable;
private FixedWidthFlexTable headerTable;
private ExtendedColumnSorter columnSorter;
// Columns
private GWTProfileFileBrowser profileFileBrowser;
public int colDataIndex = 0;
/**
* ExtendedScrollTable
*/
public ExtendedScrollTable(FixedWidthGrid dataTable, FixedWidthFlexTable headerTable, ScrollTableImages scrollTableImages) {
super(dataTable, headerTable, scrollTableImages);
this.dataTable = dataTable;
this.headerTable = headerTable;
dataTable.setSelectionPolicy(SelectionGrid.SelectionPolicy.ONE_ROW);
setResizePolicy(ResizePolicy.FILL_WIDTH);
setScrollPolicy(ScrollPolicy.BOTH);
columnSorter = new ExtendedColumnSorter();
dataTable.setColumnSorter(columnSorter);
// Sets some events
DOM.sinkEvents(getDataWrapper(),Event.ONDBLCLICK | Event.ONMOUSEDOWN );
}
/**
* isSorted
*
* @return
*/
public boolean isSorted() {
return columnSorter.isSorted();
}
/**
* refreshSort
*/
public void refreshSort() {
columnSorter.refreshSort();
}
/* (non-Javadoc)
* @see com.google.gwt.user.client.EventListener#onBrowserEvent(com.google.gwt.user.client.Event)
*/
public void onBrowserEvent(Event event) {
boolean headerFired = false; // Controls when event is fired by header
// Case targe event is header must disable drag & drop
if (headerTable.getEventTargetCell(event)!=null) {
headerFired = true;
}
// Selects the panel
setSelectedPanel(true);
// When de button mouse is released
mouseX = DOM.eventGetClientX(event);
mouseY = DOM.eventGetClientY(event);
// On double click not sends event to onCellClicked across super.onBrowserEvent();
if (DOM.eventGetType(event) == Event.ONDBLCLICK) {
// Disables the event propagation the sequence is:
// Two time entry onCellClicked before entry on onBrowserEvent and disbles the
// Tree onCellClicked that produces inconsistence error refreshing
DOM.eventCancelBubble(event, true);
if ((isDocumentSelected() || isAttachmentSelected()) && Main.get().workspaceUserProperties.getWorkspace().getAvailableOption().isDownloadOption()) {
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.downloadDocument();
}
} else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
switch (DOM.eventGetButton(event)) {
case Event.BUTTON_RIGHT:
if (!headerFired) {
if (isDocumentSelected() || isAttachmentSelected()) {
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.menuPopup.menu.checkMenuOptionPermissions(getDocument());
} else if (isFolderSelected()) {
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.menuPopup.menu.checkMenuOptionPermissions(getFolder());
} else if (isMailSelected()) {
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.menuPopup.menu.checkMenuOptionPermissions(getMail());
}
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.menuPopup.menu.evaluateMenuOptions();
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.showMenu();
DOM.eventPreventDefault(event); // Prevent to fire event to browser
}
break;
default:
break;
}
}
super.onBrowserEvent(event);
}
/**
* Sets the selected panel value
*
* @param selected The selected panel value
*/
public void setSelectedPanel(boolean selected) {
if (selected){
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.addStyleName("okm-PanelSelected");
Main.get().mainPanel.search.historySearch.searchSaved.setSelectedPanel(false);
Main.get().mainPanel.search.historySearch.userNews.setSelectedPanel(false);
} else {
Main.get().mainPanel.search.searchBrowser.searchResult.searchCompactResult.removeStyleName("okm-PanelSelected");
}
panelSelected = selected;
}
/**
* Is panel selected
*
* @return The panel selected value
*/
public boolean isPanelSelected() {
return panelSelected;
}
/**
* Gets the X position on mouse click
*
* @return The x position on mouse click
*/
public int getMouseX() {
return mouseX;
}
/**
* Gets the Y position on mouse click
*
* @return The y position on mouse click
*/
public int getMouseY() {
return mouseY;
}
/**
* Gets the selected row
*
* @return The selected row
*/
public int getSelectedRow() {
int selectedRow = -1;
if (!dataTable.getSelectedRows().isEmpty()) {
selectedRow = ((Integer) dataTable.getSelectedRows().iterator().next()).intValue();
}
Log.debug("ExtendedScrollPanel selectedRow:"+selectedRow);
return selectedRow;
}
/**
* Resets the values
*/
public void reset() {
mouseX = 0;
mouseY = 0;
dataIndexValue = 0;
// Only resets rows table the header is never reset
data = new HashMap<Integer, GWTQueryResult>();
}
/**
* Adds a document to the panel
*
* @param doc The doc to add
*/
public void addRow(GWTQueryResult gwtQueryResult) {
if (gwtQueryResult.getDocument()!=null || gwtQueryResult.getAttachment()!=null) {
addDocumentRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
} else if (gwtQueryResult.getFolder()!=null) {
addFolderRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
} else if (gwtQueryResult.getMail()!=null) {
addMailRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
}
}
/**
* Adding document row
*
* @param gwtQueryResult Query result
* @param score Document score
*/
private void addDocumentRow(GWTQueryResult gwtQueryResult, Score score) {
int col = 0;
int rows = dataTable.getRowCount();
dataTable.insertRow(rows);
GWTDocument doc = new GWTDocument();
if (gwtQueryResult.getDocument()!=null) {
doc = gwtQueryResult.getDocument();
} else if (gwtQueryResult.getAttachment()!=null) {
doc = gwtQueryResult.getAttachment();
}
// Sets folder object
data.put(new Integer(dataIndexValue), gwtQueryResult);
// Score is always visible
dataTable.setHTML(rows, col++, score.getHTML());
dataTable.getCellFormatter().setHorizontalAlignment(rows, 0, HasHorizontalAlignment.ALIGN_LEFT);
if (profileFileBrowser.isIconVisible()) {
dataTable.setHTML(rows, col, dataTable.getHTML(rows,col) + Util.mimeImageHTML(doc.getMimeType()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_RIGHT);
}
if (profileFileBrowser.isNameVisible()) {
Anchor anchor = new Anchor();
anchor.setHTML(doc.getName());
anchor.setStyleName("okm-Hyperlink");
// On attachemt case must remove last folder path, because it's internal usage not for visualization
String path = "";
if (doc.isAttachment()) {
anchor.setTitle(Util.getParent(doc.getParentPath()));
path = doc.getParentPath();
} else {
anchor.setTitle(doc.getParentPath());
path = doc.getPath();
}
final String docPath = path;
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CommonUI.openPath(Util.getParent(docPath), docPath);
}
});
dataTable.setWidget(rows, col, anchor);
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_LEFT);
}
if (profileFileBrowser.isSizeVisible()) {
dataTable.setHTML(rows, 3, Util.formatSize(doc.getActualVersion().getSize()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isLastModifiedVisible()) {
DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern"));
dataTable.setHTML(rows, col, dtf.format(doc.getLastModified()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isAuthorVisible()) {
dataTable.setHTML(rows, col, doc.getActualVersion().getUser().getUsername());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isVersionVisible()) {
dataTable.setHTML(rows, col, doc.getActualVersion().getName());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
dataTable.setHTML(rows, col, ""+(dataIndexValue++));
dataTable.getCellFormatter().setVisible(rows,col,false);
for (int i=0; i<col; i++) {
dataTable.getCellFormatter().addStyleName(rows, i, "okm-DisableSelect");
}
}
/**
* Adding folder
*
* @param gwtQueryResult Query result
* @param score The folder score
*/
private void addFolderRow(GWTQueryResult gwtQueryResult, Score score) {
int col = 0;
int rows = dataTable.getRowCount();
dataTable.insertRow(rows);
final GWTFolder folder = gwtQueryResult.getFolder();
// Sets folder object
data.put(new Integer(dataIndexValue), gwtQueryResult);
// Score is always visible
dataTable.setHTML(rows, col, score.getHTML());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_LEFT);
if (profileFileBrowser.isIconVisible()) {
// Looks if must change icon on parent if now has no childs and properties with user security atention
if ( (folder.getPermissions() & GWTPermission.WRITE) == GWTPermission.WRITE) {
if (folder.isHasChildren()) {
dataTable.setHTML(rows, col, Util.imageItemHTML("img/menuitem_childs.gif"));
} else {
dataTable.setHTML(rows, col, Util.imageItemHTML("img/menuitem_empty.gif"));
}
} else {
if (folder.isHasChildren()) {
dataTable.setHTML(rows, col, Util.imageItemHTML("img/menuitem_childs_ro.gif"));
} else {
dataTable.setHTML(rows, col, Util.imageItemHTML("img/menuitem_empty_ro.gif"));
}
}
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_RIGHT);
}
if (profileFileBrowser.isNameVisible()) {
Anchor anchor = new Anchor();
anchor.setHTML(folder.getName());
anchor.setTitle(folder.getParentPath());
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CommonUI.openPath(folder.getPath(), "");
}
});
anchor.setStyleName("okm-Hyperlink");
dataTable.setWidget(rows, col, anchor);
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_LEFT);
}
if (profileFileBrowser.isSizeVisible()) {
dataTable.setHTML(rows, col, " ");
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isLastModifiedVisible()) {
DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern"));
dataTable.setHTML(rows, col, dtf.format(folder.getCreated()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isAuthorVisible()) {
dataTable.setHTML(rows, col, folder.getUser().getUsername());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isVersionVisible()) {
dataTable.setHTML(rows, col, " ");
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
dataTable.setHTML(rows, col, ""+(dataIndexValue++));
dataTable.getCellFormatter().setVisible(rows,col,false);
for (int i=0; i<col; i++) {
dataTable.getCellFormatter().addStyleName(rows, i, "okm-DisableSelect");
}
}
/**
* Adding mail
*
* @param gwtQueryResult Query result
* @param score The mail score
*/
private void addMailRow(GWTQueryResult gwtQueryResult, Score score) {
int col = 0;
int rows = dataTable.getRowCount();
dataTable.insertRow(rows);
final GWTMail mail = gwtQueryResult.getMail();
// Sets folder object
data.put(new Integer(dataIndexValue), gwtQueryResult);
// Score is always visible
dataTable.setHTML(rows, col, score.getHTML());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_LEFT);
if (profileFileBrowser.isIconVisible()) {
if (mail.getAttachments().size()>0) {
dataTable.setHTML(rows, col , Util.imageItemHTML("img/email_attach.gif"));
} else {
dataTable.setHTML(rows, col, Util.imageItemHTML("img/email.gif"));
}
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_RIGHT);
}
if (profileFileBrowser.isNameVisible()) {
Anchor anchor = new Anchor();
anchor.setHTML(mail.getSubject());
anchor.setTitle(mail.getParentPath());
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String docPath = mail.getPath();
CommonUI.openPath(Util.getParent(docPath), docPath);
}
});
anchor.setStyleName("okm-Hyperlink");
dataTable.setWidget(rows, col, anchor);
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_LEFT);
}
if (profileFileBrowser.isSizeVisible()) {
dataTable.setHTML(rows, col, Util.formatSize(mail.getSize()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isLastModifiedVisible()) {
DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern"));
dataTable.setHTML(rows, col, dtf.format(mail.getReceivedDate()));
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isAuthorVisible()) {
dataTable.setHTML(rows, col, mail.getFrom());
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
if (profileFileBrowser.isVersionVisible()) {
dataTable.setHTML(rows, col, " ");
dataTable.getCellFormatter().setHorizontalAlignment(rows, col++, HasHorizontalAlignment.ALIGN_CENTER);
}
dataTable.setHTML(rows, col, ""+(dataIndexValue++));
dataTable.getCellFormatter().setVisible(rows,col,false);
for (int i=0; i<col; i++) {
dataTable.getCellFormatter().addStyleName(rows, i, "okm-DisableSelect");
}
}
/**
* Sets the selected row
*
* @param row The row number
*/
public void setSelectedRow(int row) {
Log.debug("ExtendedScrollPanel setSelectedRow:"+row);
dataTable.selectRow(row,true);
}
/**
* Gets a actual document object row
*
* @return
*/
public GWTDocument getDocument() {
if (isDocumentSelected()) {
return ((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getDocument();
} else {
return null;
}
}
/**
* Gets a actual attachment object row
*
* @return
*/
public GWTDocument getAttachment() {
if (isAttachmentSelected()) {
return ((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getAttachment();
} else {
return null;
}
}
/**
* Gets a actual document object row
*
* @return
*/
public GWTFolder getFolder() {
if (isFolderSelected()) {
return ((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getFolder();
} else {
return null;
}
}
/**
* Gets a actual mail object row
*
* @return
*/
public GWTMail getMail() {
if (isMailSelected()) {
return ((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getMail();
} else {
return null;
}
}
/**
* Return true or false if actual selected row is document
*
* @return True or False if actual row is document type
*/
public boolean isDocumentSelected() {
if (!dataTable.getSelectedRows().isEmpty()) {
if (((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getDocument()!=null ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Return true or false if actual selected row is attachment
*
* @return True or False if actual row is attachment type
*/
public boolean isAttachmentSelected() {
if (!dataTable.getSelectedRows().isEmpty()) {
if (((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getAttachment()!=null ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Return true or false if actual selected row is mail
*
* @return True or False if actual row is mail type
*/
public boolean isFolderSelected() {
if (!dataTable.getSelectedRows().isEmpty()) {
if (((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getFolder()!=null ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Return true or false if actual selected row is mail
*
* @return True or False if actual row is mail type
*/
public boolean isMailSelected() {
if (!dataTable.getSelectedRows().isEmpty()) {
if (((GWTQueryResult) data.get(Integer.parseInt(dataTable.getText(getSelectedRow(),colDataIndex)))).getMail()!=null ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* setProfileFileBrowser
*
* @param profileFileBrowser
*/
public void setProfileFileBrowser(GWTProfileFileBrowser profileFileBrowser) {
this.profileFileBrowser = profileFileBrowser;
columnSorter.setProfileFileBrowser(profileFileBrowser);
}
/**
* setDataColumn
*
* @param dataColumn
*/
public void setColDataIndex(int colDataIndex) {
this.colDataIndex = colDataIndex;
columnSorter.setColDataIndex(colDataIndex);
}
}
|
/*
* created 11.10.2005
*
* $Id: ModifyForeignKeyOperation.java 668 2007-10-04 18:48:16Z cse $
*/
package com.byterefinery.rmbench.operations;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import com.byterefinery.rmbench.EventManager;
import com.byterefinery.rmbench.RMBenchMessages;
import com.byterefinery.rmbench.RMBenchPlugin;
import com.byterefinery.rmbench.external.model.IForeignKey;
import com.byterefinery.rmbench.model.schema.Column;
import com.byterefinery.rmbench.model.schema.ForeignKey;
/**
* undoable operation for modifying foreign key properties
* @author cse
*/
public class ModifyForeignKeyOperation extends RMBenchOperation {
/**
* an enum describing the available modifications, with the ability to map to a
* GUI resource string
*/
public enum Modification {
NAME(RMBenchMessages.ForeignkeysTab_Column_Key) {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.setName((String)newVal);
return EventManager.Properties.NAME;
}
},
DELETE_RULE(RMBenchMessages.ForeignkeysTab_Column_DeleteRule) {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.setDeleteAction((IForeignKey.Action)newVal);
return EventManager.Properties.FK_DELETE_RULE;
}
},
UPDATE_RULE(RMBenchMessages.ForeignkeysTab_Column_UpdateRule) {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.setUpdateAction((IForeignKey.Action)newVal);
return EventManager.Properties.FK_UPDATE_RULE;
}
},
REPLACE_COLUMN(RMBenchMessages.ForeignkeysTab_Column_Column) {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.replaceColumn((Column)oldVal, (Column)newVal);
return EventManager.Properties.FK_COLUMN_REPLACED;
}
},
DELETE_COLUMN() {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.removeColumn((Column)oldVal);
return EventManager.Properties.FK_COLUMN_DELETED;
}
},
ADD_COLUMN() {
public String execute(ForeignKey foreignKey, Object oldVal, Object newVal) {
foreignKey.addColumn((Column)newVal);
return EventManager.Properties.FK_COLUMN_ADDED;
}
};
private final String property;
private Modification(String property) {
this.property = property;
}
private Modification() {
this.property = null;
}
public abstract String execute(ForeignKey foreignKey, Object oldVal, Object newVal);
/**
* map a GUI resource to an enum value
*/
public static Modification forProperty(String property) {
for (Modification modification : values()) {
if(modification.property == property)
return modification;
}
throw new IllegalArgumentException(); //hopefully dont happen
}
}
private final ForeignKey foreignKey;
private final Modification modification;
private final Object newValue, oldValue;
/**
* @param foreignKey the foreign key to modify
* @param resource the resource string
* @param newValue the new value
* @param oldValue the old value
*/
public ModifyForeignKeyOperation(
ForeignKey foreignKey,
String resource,
Object newValue,
Object oldValue) {
super(Messages.Operation_ModifyForeignKey);
this.foreignKey = foreignKey;
this.modification = Modification.forProperty(resource);
this.newValue = newValue;
this.oldValue = oldValue;
}
/**
* @param foreignKey the foreign key to modify
* @param modification the modification to perform
* @param newValue the new value
* @param oldValue the old value
*/
public ModifyForeignKeyOperation(
ForeignKey foreignKey,
Modification modification,
Object newValue,
Object oldValue) {
super(Messages.Operation_ModifyForeignKey);
this.foreignKey = foreignKey;
this.modification = modification;
this.newValue = newValue;
this.oldValue = oldValue;
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
String eventProperty = modification.execute(foreignKey, oldValue, newValue);
RMBenchPlugin.getEventManager().fireForeignKeyModified(eventProperty, foreignKey);
return Status.OK_STATUS;
}
public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
String eventProperty = modification.execute(foreignKey, newValue, oldValue);
RMBenchPlugin.getEventManager().fireForeignKeyModified(eventProperty, foreignKey);
return Status.OK_STATUS;
}
}
|
package com.hxzy.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.util.MD5Util;
import com.hxzy.common.vo.BSTable;
import com.hxzy.common.vo.PageSearch;
import com.hxzy.common.vo.ResponseMessage;
import com.hxzy.entity.Classes;
import com.hxzy.entity.Major;
import com.hxzy.entity.Teacher;
import com.hxzy.mapper.TeacherMapper;
import com.hxzy.service.MajorService;
import com.hxzy.service.TeacherService;
import com.hxzy.vo.TeachClassesSearch;
import lombok.extern.log4j.Log4j2;
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 org.springframework.util.StringUtils;
import java.util.List;
@Log4j2
@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {
@Autowired
private TeacherMapper teacherMapper;
@Autowired
private MajorService majorService;
@Override
public boolean insert(Teacher record) {
return this.teacherMapper.insert(record)>0;
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public Teacher selectByPrimaryKey(Integer id) {
return this.teacherMapper.selectByPrimaryKey(id);
}
@Override
public boolean updateByPrimaryKeySelective(Teacher record) {
return this.teacherMapper.updateByPrimaryKeySelective(record)>0;
}
@Override
public boolean updateByPrimaryKey(Teacher record) {
return this.teacherMapper.updateByPrimaryKey(record)>0;
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public ResponseMessage search(PageSearch pageSearch) {
PageHelper.offsetPage(pageSearch.getOffset(),pageSearch.getLimit());
List<Teacher> data=this.teacherMapper.search(pageSearch);
Page pg=(Page) data;
long total=pg.getTotal();
//查询专业对应的名称
List<Major> arrMajor=this.majorService.searchAll();
for(Teacher t : data){
String know=t.getTeachKnowledge();
if(StringUtils.isEmpty(know)){
t.setMajorNames("");
}else{
//设定专业的名称
setMajorNames(t, arrMajor);
}
}
//封装
BSTable bs=new BSTable();
bs.setTotal(total);
bs.setRows(data);
return ResponseMessage.success("成功", bs);
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<Teacher> searchAll() {
//查询所有专业
List<Major> arrMajor=this.majorService.searchAll();
List<Teacher> allTeacher=this.teacherMapper.searchAll();
for(Teacher t : allTeacher){
String know=t.getTeachKnowledge();
if(StringUtils.isEmpty(know)){
t.setMajorNames("");
}else{
//设定专业的名称
setMajorNames(t, arrMajor);
}
}
return allTeacher;
}
/**
* 加载班级的认课老师(未离职)
* @param classesId
* @return
*/
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<Teacher> searchTeacher(Integer classesId) {
return this.teacherMapper.searchTeacher(classesId);
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public ResponseMessage login(Teacher teacher) {
ResponseMessage rm=null;
Teacher dbTeacher=this.teacherMapper.login(teacher);
if(dbTeacher!=null){
String md5Pwd= MD5Util.MD5Encode(teacher.getPassword(),dbTeacher.getSalt());
if(md5Pwd.equals(dbTeacher.getPassword())){
if(dbTeacher.getState()==3){
log.warn(teacher.getMobile()+"已离职不能登录");
rm=ResponseMessage.failed(406,"该账户已被锁定!");
}else{
rm=ResponseMessage.success("登录成功",dbTeacher);
}
}else{
log.warn(teacher.getMobile()+"密码错误");
rm=ResponseMessage.failed(405,"用户名或密码错误");
}
}else{
log.warn(teacher.getMobile()+"登录的手机号不存在");
rm=ResponseMessage.failed(404,"用户名或密码错误");
}
return rm;
}
private void setMajorNames(Teacher t, List<Major> arrMajor) {
//1,2
String[] arrs=t.getTeachKnowledge().split(",");
StringBuffer str=new StringBuffer();
for(String s : arrs){
int id=Integer.parseInt(s);
String name=arrMajor.stream().filter(p -> p.getId() ==id ).map(Major::getName).findFirst().get();
str.append(name).append(",");
}
//最后删除最后一个 ","
str.deleteCharAt(str.length()-1);
t.setMajorNames(str.toString());
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.g.a.hp;
import com.tencent.mm.g.a.hq;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.friend.a.x;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.ui.base.h;
class BindMobileVerifyUI$2 implements OnMenuItemClickListener {
final /* synthetic */ BindMobileVerifyUI eHl;
BindMobileVerifyUI$2(BindMobileVerifyUI bindMobileVerifyUI) {
this.eHl = bindMobileVerifyUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
String trim = BindMobileVerifyUI.a(this.eHl).getText().toString().trim();
if (trim.equals("")) {
h.i(this.eHl, j.bind_mcontact_verifynull, j.app_tip);
} else {
this.eHl.YC();
hp hpVar = new hp();
hpVar.bQV.context = this.eHl;
a.sFg.m(hpVar);
String str = hpVar.bQW.bQX;
hq hqVar = new hq();
a.sFg.m(hqVar);
final x xVar = new x(BindMobileVerifyUI.b(this.eHl), 2, trim, "", str, hqVar.bQY.bQZ);
g.DF().a(xVar, 0);
BindMobileVerifyUI bindMobileVerifyUI = this.eHl;
BindMobileVerifyUI bindMobileVerifyUI2 = this.eHl;
this.eHl.getString(j.app_tip);
BindMobileVerifyUI.a(bindMobileVerifyUI, h.a(bindMobileVerifyUI2, this.eHl.getString(j.bind_mcontact_verifing), true, new OnCancelListener() {
public final void onCancel(DialogInterface dialogInterface) {
g.DF().c(xVar);
}
}));
}
return true;
}
}
|
package com.tencent.mm.plugin.wallet.balance;
import android.app.Activity;
import android.os.Bundle;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceFetchPwdInputUI;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceFetchResultUI;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceFetchUI;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceManagerUI;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceResultUI;
import com.tencent.mm.plugin.wallet_core.c.y;
import com.tencent.mm.plugin.wallet_core.id_verify.util.RealnameGuideHelper;
import com.tencent.mm.plugin.wallet_core.model.Authen;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import com.tencent.mm.plugin.wallet_core.model.Orders;
import com.tencent.mm.plugin.wallet_core.model.o;
import com.tencent.mm.plugin.wallet_core.ui.WalletBankcardIdUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletCardElementUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletCheckPwdUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletConfirmCardIDUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletPwdConfirmUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletSetPasswordUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletVerifyCodeUI;
import com.tencent.mm.plugin.wxpay.a$i;
import com.tencent.mm.plugin.wxpay.a.h;
import com.tencent.mm.pluginsdk.wallet.PayInfo;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.wallet_core.a;
import com.tencent.mm.wallet_core.c;
import com.tencent.mm.wallet_core.c.p;
import com.tencent.mm.wallet_core.d.g;
import com.tencent.mm.wallet_core.d.i;
import com.tencent.mm.wallet_core.ui.e;
import java.text.SimpleDateFormat;
import java.util.Date;
public class b extends c {
static /* synthetic */ String n(b bVar) {
if (bVar.jfZ != null) {
PayInfo payInfo = (PayInfo) bVar.jfZ.getParcelable("key_pay_info");
if (payInfo != null) {
return payInfo.bOd;
}
}
return "";
}
public final c a(Activity activity, Bundle bundle) {
p.GZ(14);
if (activity instanceof WalletBalanceFetchUI) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (!com.tencent.mm.plugin.wallet.a.p.bNq().bPs()) {
this.jfZ.putInt("key_pay_flag", 1);
c(activity, WalletBankcardIdUI.class, bundle);
} else if (((Bankcard) this.jfZ.getParcelable("key_bankcard")) != null) {
this.jfZ.putInt("key_pay_flag", 3);
this.jfZ.putString("key_pwd_cash_title", activity.getString(a$i.wallet_balance_fetch_title));
Orders orders = (Orders) this.jfZ.getParcelable("key_orders");
if (orders != null) {
this.jfZ.putString("key_pwd_cash_money", e.B(orders.mBj));
}
c(activity, WalletBalanceFetchPwdInputUI.class, bundle);
} else {
this.jfZ.putInt("key_pay_flag", 2);
c(activity, WalletCheckPwdUI.class, bundle);
}
} else {
c(activity, WalletBalanceFetchUI.class, bundle);
}
return this;
}
public final void a(Activity activity, int i, Bundle bundle) {
if (activity instanceof WalletBalanceFetchUI) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (!com.tencent.mm.plugin.wallet.a.p.bNq().bPs()) {
this.jfZ.putInt("key_pay_flag", 1);
c(activity, WalletBankcardIdUI.class, bundle);
} else if (((Bankcard) this.jfZ.getParcelable("key_bankcard")) != null) {
this.jfZ.putInt("key_pay_flag", 3);
this.jfZ.putString("key_pwd_cash_title", activity.getString(a$i.wallet_balance_fetch_title));
Orders orders = (Orders) this.jfZ.getParcelable("key_orders");
if (orders != null) {
this.jfZ.putString("key_pwd_cash_money", e.B(orders.mBj));
}
c(activity, WalletBalanceFetchPwdInputUI.class, bundle);
} else {
this.jfZ.putInt("key_pay_flag", 2);
c(activity, WalletCheckPwdUI.class, bundle);
}
} else if (activity instanceof WalletBalanceFetchPwdInputUI) {
if (bundle.getBoolean("key_need_verify_sms", false)) {
c(activity, WalletVerifyCodeUI.class, bundle);
} else {
c(activity, WalletBalanceFetchResultUI.class, bundle);
}
} else if (activity instanceof WalletCheckPwdUI) {
c(activity, WalletBankcardIdUI.class, bundle);
} else if ((activity instanceof WalletBankcardIdUI) || (activity instanceof WalletConfirmCardIDUI)) {
c(activity, WalletCardElementUI.class, bundle);
} else if (activity instanceof WalletCardElementUI) {
c(activity, WalletVerifyCodeUI.class, bundle);
} else if (activity instanceof WalletVerifyCodeUI) {
com.tencent.mm.plugin.wallet.a.p.bNp();
if (com.tencent.mm.plugin.wallet.a.p.bNq().bPs()) {
c(activity, WalletBalanceFetchResultUI.class, bundle);
} else {
c(activity, WalletSetPasswordUI.class, bundle);
}
} else if (activity instanceof WalletSetPasswordUI) {
c(activity, WalletPwdConfirmUI.class, bundle);
} else if (activity instanceof WalletPwdConfirmUI) {
c(activity, WalletBalanceFetchResultUI.class, bundle);
} else if (activity instanceof WalletBalanceFetchResultUI) {
b(activity, bundle);
}
}
public final void c(Activity activity, int i) {
if (activity instanceof WalletPwdConfirmUI) {
a(activity, WalletSetPasswordUI.class, i);
} else if (activity instanceof WalletBalanceResultUI) {
p.cDe();
b(activity, this.jfZ);
} else {
p.cDe();
z(activity);
}
}
public final void b(Activity activity, Bundle bundle) {
a(activity, WalletBalanceManagerUI.class, -1, true);
}
public final boolean c(Activity activity, Bundle bundle) {
return false;
}
public final g a(MMActivity mMActivity, i iVar) {
if (mMActivity instanceof WalletBalanceFetchUI) {
return new 1(this, mMActivity, iVar);
}
if (mMActivity instanceof WalletBalanceFetchPwdInputUI) {
return new g(mMActivity, iVar) {
public final boolean d(int i, int i2, String str, l lVar) {
boolean z = false;
if (i != 0 || i2 != 0 || !(lVar instanceof com.tencent.mm.plugin.wallet.pay.a.a.b)) {
return false;
}
com.tencent.mm.plugin.wallet.pay.a.a.b bVar = (com.tencent.mm.plugin.wallet.pay.a.a.b) lVar;
b.this.jfZ.putString("kreq_token", bVar.token);
b.this.jfZ.putParcelable("key_authen", bVar.pfc);
Bundle d = b.this.jfZ;
String str2 = "key_need_verify_sms";
if (!bVar.pfa) {
z = true;
}
d.putBoolean(str2, z);
RealnameGuideHelper realnameGuideHelper = bVar.lJN;
if (realnameGuideHelper != null) {
b.this.jfZ.putParcelable("key_realname_guide_helper", realnameGuideHelper);
}
a.j(this.fEY, b.this.jfZ);
this.fEY.finish();
return true;
}
public final boolean m(Object... objArr) {
Bankcard bankcard = (Bankcard) b.this.jfZ.getParcelable("key_bankcard");
b.this.jfZ.putString("key_pwd1", (String) objArr[0]);
b.this.jfZ.putString("key_mobile", bankcard.field_mobile);
Authen authen = new Authen();
authen.bWA = 3;
authen.pli = (String) objArr[0];
authen.lMW = bankcard.field_bindSerial;
authen.lMV = bankcard.field_bankcardType;
authen.mpb = (PayInfo) b.this.jfZ.getParcelable("key_pay_info");
authen.plq = bankcard.field_arrive_type;
this.uXK.a(new com.tencent.mm.plugin.wallet.pay.a.a.b(authen, (Orders) b.this.jfZ.getParcelable("key_orders")), true, 1);
return true;
}
};
}
if (mMActivity instanceof WalletCardElementUI) {
return new g(mMActivity, iVar) {
public final boolean d(int i, int i2, String str, l lVar) {
if (i != 0 || i2 != 0) {
return false;
}
if (lVar instanceof com.tencent.mm.plugin.wallet.pay.a.a.b) {
com.tencent.mm.plugin.wallet.pay.a.a.b bVar = (com.tencent.mm.plugin.wallet.pay.a.a.b) lVar;
b.this.jfZ.putString("kreq_token", bVar.token);
if (bVar.pgm) {
b.this.jfZ.putParcelable("key_orders", bVar.pfb);
}
}
if (b.this.c(this.fEY, null)) {
this.uXK.a(new y(b.n(b.this), 13), true, 1);
return true;
}
b.this.a(this.fEY, 0, b.this.jfZ);
return true;
}
public final boolean m(Object... objArr) {
Authen authen = (Authen) objArr[0];
Orders orders = (Orders) objArr[1];
switch (b.this.jfZ.getInt("key_pay_flag", 0)) {
case 1:
if (!b.this.bQH()) {
authen.bWA = 1;
break;
}
authen.bWA = 4;
break;
case 2:
if (!b.this.bQH()) {
authen.bWA = 2;
break;
}
authen.bWA = 5;
break;
case 3:
if (!b.this.bQH()) {
authen.bWA = 3;
break;
}
authen.bWA = 6;
break;
default:
return false;
}
b.this.jfZ.putParcelable("key_authen", authen);
this.uXK.a(new com.tencent.mm.plugin.wallet.pay.a.a.b(authen, orders), true, 1);
return true;
}
};
}
if (mMActivity instanceof WalletVerifyCodeUI) {
return new 4(this, mMActivity, iVar);
}
if (mMActivity instanceof WalletBalanceFetchResultUI) {
return new g(mMActivity, iVar) {
public final boolean r(Object... objArr) {
Orders orders = (Orders) b.this.jfZ.getParcelable("key_orders");
Bankcard bankcard = o.bOW().paw;
bankcard.plV -= orders.mBj;
b.this.jfZ.putInt("key_balance_result_logo", h.remittance_wait);
return super.r(objArr);
}
public final boolean d(int i, int i2, String str, l lVar) {
return false;
}
public final boolean m(Object... objArr) {
return false;
}
public final CharSequence ui(int i) {
Orders orders;
switch (i) {
case 0:
return this.fEY.getString(a$i.wallet_balance_result_fetch_title);
case 1:
orders = (Orders) b.this.jfZ.getParcelable("key_orders");
if (orders == null || bi.oW(orders.ppa)) {
return this.fEY.getString(a$i.wallet_balance_result_fetch_request_title);
}
return orders.ppa;
case 2:
orders = (Orders) b.this.jfZ.getParcelable("key_orders");
if (orders != null && orders.poZ > 0) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(orders.poZ));
}
}
return super.ui(i);
}
};
}
return mMActivity instanceof WalletPwdConfirmUI ? new 6(this, mMActivity, iVar) : super.a(mMActivity, iVar);
}
public final int a(MMActivity mMActivity, int i) {
return a$i.wallet_balance_fetch_finish_confirm;
}
public final String aNK() {
return "BalanceFetchProcess";
}
}
|
package com.beiyelin.projectportal.controller;
import com.beiyelin.account.bean.AccountQuery;
import com.beiyelin.account.bean.EntityRelationAvailablePoolsReqBody;
import com.beiyelin.account.bean.EntityRelations;
import com.beiyelin.account.entity.Account;
import com.beiyelin.account.security.AccessPermission;
import com.beiyelin.common.reqbody.QueryReqBody;
import com.beiyelin.common.resbody.PageResp;
import com.beiyelin.common.resbody.ResultBody;
import com.beiyelin.projectportal.bean.ProjectAuthQuery;
import com.beiyelin.projectportal.entity.ProjectAuth;
import com.beiyelin.projectportal.service.ProjectAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import static com.beiyelin.account.constant.PermissionConstant.PERMISSION_ACTION_DELETE;
import static com.beiyelin.account.constant.PermissionConstant.PERMISSION_ACTION_NEW;
import static com.beiyelin.projectportal.constant.PermissionConstant.PERMISSION_PROJECT_PACKAGE_NAME;
/**
* @Description: 项目可见范围管理
* @Author: newmann
* @Date: Created in 9:26 2018-06-29
*/
@RestController
@RequestMapping("/api/project/project-auth")
public class ProjectAuthController {
public final static String PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME="项目可见范围管理";
private ProjectAuthService projectAuthService;
@Autowired
public void setProjectAuthService(ProjectAuthService service){
this.projectAuthService = service;
}
/**
* 新增
* @param qualificationPool
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/add")
public ResultBody< ProjectAuth> add(@RequestBody ProjectAuth qualificationPool) {
return new ResultBody< ProjectAuth>(projectAuthService.create(qualificationPool));
}
/**
* 批量新增
* @param qualificationPools
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/batch-add")
public ResultBody< List<ProjectAuth>> batchAdd(@RequestBody List<ProjectAuth> qualificationPools) {
return new ResultBody< List<ProjectAuth>>(projectAuthService.batchAdd(qualificationPools));
}
/**
* 修改
* @param qualificationPool
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/update")
public ResultBody< ProjectAuth> update(@RequestBody ProjectAuth qualificationPool) {
return new ResultBody< ProjectAuth>(projectAuthService.update(qualificationPool));
}
/**
* 删除
* @param qualificationPool
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_DELETE)
@PostMapping("/delete")
public ResultBody< ProjectAuth> delete(@RequestBody ProjectAuth qualificationPool) {
return new ResultBody< ProjectAuth>(projectAuthService.update(qualificationPool));
}
/**
* 删除
* @param id
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_DELETE)
@DeleteMapping("/delete-by-id/{id}")
public ResultBody<Boolean> deleteById(@PathVariable String id) {
try{
projectAuthService.delete(id);
return new ResultBody<>(true);
} catch (Exception e){
throw e;
}
}
/**
* 删除
* @param entity
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECT_AUTH_MODULE_NAME,
action = PERMISSION_ACTION_DELETE)
@PostMapping("/delete-by-projectid-and-accountid")
public ResultBody< Boolean> deleteByProjectIdAndAccountId(@RequestBody ProjectAuth entity) {
return new ResultBody<>(
projectAuthService.deleteByProjectIdAndAccountId(entity.getProjectId(),
entity.getAccountId())
);
}
@PostMapping("/batch-add-account-relation-by-ids")
public ResultBody<Boolean> batchAddAccountRelationByIds(@RequestBody EntityRelations entityRelations) {
String masterId = entityRelations.getMasterId();
List<String> accountIds = entityRelations.getRelationIds();
List<ProjectAuth> addList = new ArrayList<>();
accountIds.stream().sorted().forEach(accountId -> {
ProjectAuth item = new ProjectAuth();
item.setAccountId(accountId);
item.setProjectId(masterId);
addList.add(item);
});
List<ProjectAuth> addResults = this.projectAuthService.batchAdd(addList);
return new ResultBody<>(true);
}
@PostMapping("/batch-delete-account-relation-by-ids")
public ResultBody<Boolean> batchDeleteAccountRelationByIds(@RequestBody EntityRelations entityRelations){
String masterId = entityRelations.getMasterId();
List<String > accountIds = entityRelations.getRelationIds();
accountIds.stream().forEach(accountId ->{
projectAuthService.deleteByProjectIdAndAccountId(masterId,accountId);
});
return new ResultBody<>(true);
}
@GetMapping("/find-by-id/{id}")
public ResultBody<ProjectAuth> findById(@PathVariable String id) {
return new ResultBody<>(projectAuthService.findById(id));
}
// @GetMapping("/find-by-type-and-poolid")
// public ResultBody<ProjectAuth> findByTypeAndPoolId(@RequestParam int type, @RequestParam String poolid) {
//
// return new ResultBody<>(projectAuthService.findByTypeAndPoolId(type,poolid));
//
// }
@PostMapping("/find-page")
public ResultBody<PageResp<ProjectAuth>> findPage(@RequestBody QueryReqBody<ProjectAuthQuery> reqBody){
return new ResultBody<>(projectAuthService.fetchByQuery(reqBody.getQueryReq(),reqBody.getPageReq()));
}
@PostMapping("/find-available-account-pools")
public ResultBody<PageResp<Account>> findAvailableAccountPools(@RequestBody EntityRelationAvailablePoolsReqBody<AccountQuery> reqBody){
return new ResultBody<>(projectAuthService.findAccountAvailablePools(reqBody.getMasterId(),reqBody.getQueryReq(),reqBody.getPageReq()));
}
@GetMapping("/fetch-accounts-by-projectid/{id}")
public ResultBody<List<Account>> fetchAccountsByPorjectId(@PathVariable String id){
return new ResultBody<>(projectAuthService.fetchAccountsByProjectId(id));
}
@GetMapping("/check-allow-all-by-projectid/{id}")
public ResultBody<Boolean> checkAllowAllByProjedtId(@PathVariable String id){
return new ResultBody<>(projectAuthService.checkAllowAllByProjectId(id));
}
@GetMapping("/enable-allow-all/{id}")
public ResultBody<ProjectAuth> enableAllowAll(@PathVariable String id) {
return new ResultBody<>(projectAuthService.enableAllowAll(id));
}
@GetMapping("/disable-allow-all/{id}")
public ResultBody<Boolean> disableAllowAll(@PathVariable String id) {
return new ResultBody<>(projectAuthService.disableAllowAll(id));
}
}
|
package com.example.mireia.sharetool_appnativa;
public class Latitudes {
private static Latitudes instance;
// Global variable
private Double datalt;
private Double datalg;
String address;
// Restrict the constructor from being instantiated
private Latitudes(){}
public void setData(Double lt, Double lg){
this.datalt=lt;
this.datalg=lg;
}
public void setDataAdd(String address){
this.address= address;
}
public Double getDatalt(){
return this.datalt;
}
public Double getDatalg(){
return this.datalg;
}
public String getDataAdd(){
return this.address;
}
public static synchronized Latitudes getInstance(){
if(instance==null){
instance=new Latitudes();
}
return instance;
}
}
|
package com.santander.bi.configuration;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.sql.DataSource;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.santander.bi.utils.Constants;
//@EnableJpaRepositories
@Configuration
@ComponentScan("com.santander.bi.model")
@EnableTransactionManagement
public class HibernateConfiguration {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
//@Resource
//private Environment environment;
/*
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
*/
@Bean
public DataSource dataSource() {
//DriverManagerDataSource dataSource = new DriverManagerDataSource();
DataSource ds= null;
try{
try {
InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> list = ctx.list("java:comp/env/jdbc");
System.out.println("------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------");
System.out.println("-------------JNDI:"+Constants.JNDI_POOL);
System.out.println("-------------CONFIGLOOKUP:"+Constants.CONFIGLOOKUP);
System.out.println("------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------");
System.out.println("-------------JDBC RECUPERADOS:");
while (list.hasMore()) {
System.out.println(list.next().getName());
}
System.out.println("-------------TERMINA JDBC");
}catch(Exception ex) {
System.out.println("Error al recupera JNDI de JDBC :"+ex.getMessage());
}
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup(Constants.CONFIGLOOKUP);
ds = (DataSource) envContext.lookup(Constants.JNDI_POOL);
//dataSource = (DriverManagerDataSource) ds;
}catch(Exception ext) {
System.out.println("Error al recupera y conectarse a JNDI de JDBC :"+ext.getMessage());
System.out.println("-------------INTENTA POR CONEXION DIRECTA JDBC");
try {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Constants.DB_DRIVER);
dataSource.setUrl(Constants.DB_CONNECTION);
dataSource.setUsername(Constants.DB_USER);
dataSource.setPassword(Constants.DB_PASSWORD);
System.out.println("-------------Conexion por JDBC!! Exitosa!!");
ds = dataSource;
}catch(Exception ex) {
System.out.println("Error de Conexion por JDBC!! ERROR: "+ex.getMessage());
}
}
//dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
return ds;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("com.santander.bi.model");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean lfb = new LocalContainerEntityManagerFactoryBean();
// lfb.setDataSource(dataSource());
// lfb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
// lfb.setPackagesToScan("com.santander.bi.model");
// lfb.setJpaProperties(hibernateProperties());
// return lfb;
// }
// @Bean
// EntityManagerFactory entityManagerFactory() {
// EntityManagerFactory emf =
// Persistence.createEntityManagerFactory("LOCAL_PERSISTENCE");
// return emf;
// }
// @Bean
// public PlatformTransactionManager transactionManager() {
// JpaTransactionManager txManager = new JpaTransactionManager();
// txManager.setEntityManagerFactory(entityManagerFactory());
// return txManager;
// }
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.Oracle10gDialect");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "true");
return properties;
}
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
// LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
// // entityManager.setPersistenceXmlLocation("classpath*:META-INF/persistence.xml");
// // entityManager.setPersistenceUnitName("hibernatePersistenceUnit");
// entityManager.setPackagesToScan("com.santander.bi.model");
// entityManager.setDataSource(dataSource);
// entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
//
//// Properties jpaProperties = new Properties();
//// jpaProperties.put("hibernate.hbm2ddl.auto",
//// env.getRequiredProperty("hibernate.hbm2ddl.auto"));
//// jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
//// jpaProperties.put("hibernate.connection.autocommit",
//// env.getRequiredProperty("hibernate.connection.autocommit"));
//// jpaProperties.put("hibernate.cache.use_second_level_cache",
//// env.getRequiredProperty("hibernate.cache"));
//// jpaProperties.put("hibernate.cache.use_query_cache",
//// env.getRequiredProperty("hibernate.query.cache"));
//// jpaProperties.put("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider");
//// jpaProperties.put("hibernate.cache.region.factory_class",
//// "org.hibernate.cache.ehcache.EhCacheRegionFactory");
//// jpaProperties.put("hibernate.generate_statistics",
//// env.getRequiredProperty("hibernate.statistics"));
//// jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
//// jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
////
// entityManager.setJpaProperties(hibernateProperties());
//
// return entityManager;
// }
//
// @Bean
// JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
// transactionManager.setEntityManagerFactory(entityManagerFactory);
// return transactionManager;
// }
}
|
package com.jim.multipos.data.operations;
import com.jim.multipos.data.db.model.unit.SubUnitsList;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by DEV on 06.09.2017.
*/
public interface SubUnitOperations {
Observable<Long> addSubUnitList(SubUnitsList subUnitsList);
Observable<List<SubUnitsList>> getSubUnitList();
Observable<Boolean> deleteSubUnitList(SubUnitsList subUnitsList);
}
|
package com.tts;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// 1) Ask user for 5 numbers to be in your array list
// Intro
System.out.println("Let's create an array! You will be asked to enter five numbers.");
// Setup
Scanner question = new Scanner(System.in);
ArrayList<Integer> newArr = new ArrayList<Integer>();
// Questions
System.out.println("Please enter your first number:");
int numOne = question.nextInt();
newArr.add(numOne);
System.out.println("Please enter your second number:");
int numTwo = question.nextInt();
newArr.add(numTwo);
System.out.println("Please enter your third number:");
int numThree = question.nextInt();
newArr.add(numThree);
System.out.println("Please enter your fourth number:");
int numFour = question.nextInt();
newArr.add(numFour);
System.out.println("Please enter your fifth number:");
int numFive = question.nextInt();
newArr.add(numFive);
// Completed Array we're working with:
System.out.println("Great. Your array now looks like this: \n" + newArr);
// Find the sum of the elements in the array list
int sum = 0;
for (int value : newArr) {
sum += value;
}
System.out.println("\n The sum of the array is: \n" + sum);
// Find the product of elements in array list
int product = 1;
for (int value : newArr) {
product *= value;
}
System.out.println("\n The product of this array is: \n" + product);
// Find the minimum of the elements in the array list
int min = Collections.min(newArr);
for (int num : newArr) {
if (num < min) {
min = num;
}
}
System.out.println("\n The smallest number in your array is: " + min);
// Find the max of the elements in the array list
int max = Collections.max(newArr);
for (int numMax : newArr) {
if (numMax > max) {
max = numMax;
}
}
System.out.println("\n The largest number in your array is: " + max);
// Goodbye, now!
System.out.println("\nThank you for your participation. Goodbye!");
}
}
|
package br.org.funcate.glue.controller.listener;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.TreePath;
import br.org.funcate.eagles.example.system.EditionTool;
import br.org.funcate.glue.controller.Mediator;
import br.org.funcate.glue.controller.TreeController;
import br.org.funcate.glue.event.FocusedThemeEvent;
import br.org.funcate.glue.event.SelectedThemeEvent;
import br.org.funcate.glue.event.UnselectedThemeEvent;
import br.org.funcate.glue.main.AppSingleton;
import br.org.funcate.glue.model.LookAndFeelService;
import br.org.funcate.glue.model.thread.PlotterController;
import br.org.funcate.glue.model.tree.CustomNode;
import br.org.funcate.glue.model.tree.TreeService;
import br.org.funcate.glue.view.LocalOptionPane;
import br.org.funcate.glue.view.NodeType;
import br.org.funcate.glue.view.ScaleView;
import br.org.funcate.glue.view.ThemeOptionsView;
import br.org.funcate.glue.view.TreeView;
import br.org.funcate.glue.view.VisualOptionsView;
/** \file TreeAdapter.java
* This file creates the listener responsible for handling the events related
* to the selection of the nodes
*/
/**
* \brief This Class defines the attributes and the functions required to handle
* the copy, move and rearrange functions of the nodes in a Tree and showing the
* appropriated popups
*
* @author OLIVEIRA, André G.
* @author OLIVEIRA, Paulo Renato M.
*/
@SuppressWarnings("unused")
public class TreeAdapter implements MouseListener, MouseMotionListener,
KeyListener, ActionListener {
private TreePath path;
private JTree tree;
private TreeView treeView;
private TreeController treeController;
private CustomNode nodeSource;
private CustomNode nodeTarget;
private CustomNode parent;
public TreeAdapter(TreeView treeView) {
this.treeView = treeView;
this.treeController = new TreeController(treeView);
}
@Override
public void keyPressed(KeyEvent evt) {
}
@Override
public void keyReleased(KeyEvent evt) {
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_C) {
treeController.copyNode();
}
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_X) {
treeController.cutNode();
}
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
treeController.pasteNode();
}
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
treeController.deleteNode();
}
if (evt.getKeyCode() == KeyEvent.VK_F2) {
treeController.renameNode();
}
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
treeController.setCurrentView((CustomNode) treeView.getRoot()
.getFirstChild());
PlotterController.getInstance().startPlotter();
}
if (evt.getKeyCode() == KeyEvent.VK_END) {
treeController.setCurrentView((CustomNode) treeView.getRoot()
.getLastChild());
PlotterController.getInstance().startPlotter();
}
}
@Override
public void keyTyped(KeyEvent evt) {
}
@Override
public void mouseDragged(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
int row = tree.getRowForLocation(x, y);
path = tree.getPathForRow(row);
if (path != null) {
treeView.getTree().setSelectionPath(path);
}
}
@Override
public void mouseMoved(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
int row = tree.getRowForLocation(x, y);
TreePath path = tree.getPathForRow(row);
if (path != null) {
parent = (CustomNode) path.getLastPathComponent();
switch (parent.getNodeType()) {
case VIEW:
if (parent.isSelected()) {
parent.setToolTipText("Vista selecionada");
} else {
parent.setToolTipText("Vista não selecionada");
}
break;
case TOOLBAR:
Rectangle click = new Rectangle(new Point(x, y));
int posX = click.x - ((parent.getLevel() - 1) * 23);
if (LookAndFeelService.isNimbusActivated()) {
if (posX < 4 || posX > 60) {
parent.setToolTipText(null);
return;
}
if (posX >= 4 && posX < 20) {
parent.setToolTipText("Define o visual do tema");
}
if (posX >= 24 && posX <= 40) {
parent.setToolTipText("Consulta por atributo");
}
if (posX >= 44 && posX < 60) {
parent.setToolTipText("Habilita ferramenta de escala");
}
} else {
if (posX < 16 || posX > 60) {
parent.setToolTipText(null);
return;
}
if (posX >= 16 && posX < 28) {
parent.setToolTipText("Define o visual do tema");
}
if (posX >= 31 && posX <= 44) {
parent.setToolTipText("Consulta por atributo");
}
if (posX >= 46 && posX < 58) {
parent.setToolTipText("Habilita ferramenta de escala");
}
}
break;
default:
if (parent.isSelected()) {
if (!parent.isScaleVisible()) {
parent.setToolTipText("Tema não visível");
} else {
parent.setToolTipText("Tema selecionado");
}
} else {
parent.setToolTipText("Tema não selecionado");
}
}
}
treeController.setLastTheme(TreeService.getCurrentTheme());
}
@Override
public void mouseClicked(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
int row = tree.getRowForLocation(x, y);
path = tree.getPathForRow(row);
if (path != null) {
tree.setSelectionPath(path);
treeController.setCurrentView((CustomNode) treeView.getTree()
.getLastSelectedPathComponent());
}
}
@Override
public void mouseEntered(MouseEvent evt) {
}
@Override
public void mouseExited(MouseEvent evt) {
}
@Override
public void mousePressed(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
int row = tree.getRowForLocation(x, y);
Rectangle positionClicked = new Rectangle(new Point(x, y));
path = tree.getPathForRow(row);
if (path != null) {
treeView.getTree().setSelectionPath(path);
parent = (CustomNode) path.getLastPathComponent();
treeController.setSelectedNode(parent);
Mediator mediator = AppSingleton.getInstance().getMediator();
if (parent.getNodeType() == NodeType.VIEW && parent.isLeaf()) {
mediator.disableAllTools();
} else if (!treeController.getNodeView(parent).isPersisted()
&& !treeController.getNodeView(parent).isApplied()) {
mediator.disableAllTools();
} else if (!treeController.getNodeView(parent).getChildSelection(
treeController.getNodeView(parent))) {
mediator.disableAllTools();
} else {
mediator.enableAllTools();
mediator.verifyScaleLimits();
}
nodeSource = (CustomNode) path.getLastPathComponent();
if (nodeSource == null)
return;
if (evt.isShiftDown() && nodeSource.getNodeType().isTheme()) {
treeController.copyNode();
return;
}
if (parent.getNodeType() == NodeType.TOOLBAR) {
treeController.setCurrentTheme((CustomNode) parent.getParent());
Rectangle click = new Rectangle(new Point(x, y));
int posX = click.x - ((parent.getLevel() - 1) * 20);
if (LookAndFeelService.isNimbusActivated()) {
if (posX < 8 || posX > 65)
return;
if (posX >= 11 && posX <= 25) {
treeController.setCurrentTheme((CustomNode) parent
.getParent());
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
VisualOptionsView.getInstance();
PlotterController.getInstance().pausePlotter();
}
if (posX > 31 && posX <= 43) {
treeController.getNodeView(parent);
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
LocalOptionPane
.getInstance(
"Ferramenta temporariamente desabilitada. Desculpe-nos o transtorno.",
"Atenção");
// showAttributeSearchScreen();
}
if (posX > 50 && posX <= 62) {
treeController.setCurrentTheme((CustomNode) parent
.getParent());
ScaleView.getInstance();
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
}
} else {
if (posX < 22 || posX > 65)
return;
if (posX >= 22 && posX <= 33) {
treeController.setCurrentTheme((CustomNode) parent
.getParent());
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
VisualOptionsView.getInstance();
PlotterController.getInstance().pausePlotter();
}
if (posX > 38 && posX <= 50) {
treeController.getNodeView(parent);
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
LocalOptionPane
.getInstance(
"Ferramenta temporariamente desabilitada. Desculpe-nos o transtorno.",
"Atenção");
// showAttributeSearchScreen();
}
if (posX > 52 && posX <= 64) {
treeController.setCurrentTheme((CustomNode) parent
.getParent());
ScaleView.getInstance();
TreePath viewPath = new TreePath(treeController
.getNodeView(parent).getPath());
tree.setSelectionPath(viewPath);
}
}
}
if (parent.getNodeType().isTheme()) {
treeController.setCurrentTheme(parent);
int clickPosition = positionClicked.x
- ((parent.getLevel() - 1) * 20);
boolean isSelectedTheme = parent.isSelected();
if (LookAndFeelService.isNimbusActivated()) {
if (clickPosition > 14 && clickPosition < 28) { // click
// sobre o
// ícone do
// tema na
// árvore
// caso seja
// nimbus
parent.setSelected(!isSelectedTheme);
if (!isSelectedTheme) {
// despachar themeSelectedEvent
treeController.dispatch(new SelectedThemeEvent(
this, parent.getTheme()));
} else {
treeController.dispatch(new UnselectedThemeEvent(
this, parent.getName()));
}
} else { // click sobre um título de tema na árvore caso
// seja nimbus
if (parent.isSelected()) {
treeController.dispatch(new FocusedThemeEvent(this,
parent.getName()));
}
}
} else {
if (clickPosition > 21 && clickPosition < 36) { // click
// sobre o
// ícone do
// tema na
// árvore
// caso não
// seja
// nimbus
parent.setSelected(!isSelectedTheme);
if (!isSelectedTheme) {
treeController.dispatch(new SelectedThemeEvent(
this, parent.getTheme()));
} else {
treeController.dispatch(new UnselectedThemeEvent(
this, parent.getName()));
}
} else { // click sobre um título de tema na árvore caso não
// seja nimbus
if (parent.isSelected()) {
treeController.dispatch(new FocusedThemeEvent(this,
parent.getName()));
}
}
}
}
/*
* Verifies if the user clicked twice, in that case, nothing is done
*/
if (evt.getClickCount() > 1) {
tree.setSelectionPath(null);
return;
}
if (evt.getButton() == 1) {
if (parent == null)
return;
if (parent != null && parent.getNodeType() != NodeType.VIEW) {
int X = positionClicked.x - ((parent.getLevel() - 1) * 20);
tree.setComponentPopupMenu(null);
treeView.setPopMenu(treeView.createPopupTheme(parent));
tree.setComponentPopupMenu(treeView.getPopMenu());
treeController.setCurrentView(treeController
.getNodeView(parent));
if (X >= 33 && X <= 49) {
treeController.setCurrentTheme(parent);
}
treeController.setCurrentView(treeController
.getNodeView(parent));
treeController.setCurrentView(treeController
.getNodeView(parent));
} else {
/*
* Verifies if the user clicked on an selected view, in that
* case set's the clicked view as unselected
*/
if (parent.getNodeType() == NodeType.VIEW) {
tree.setComponentPopupMenu(null);
treeView.setPopMenu(treeView.createPopupView());
tree.setComponentPopupMenu(treeView.getPopMenu());
treeController.setCurrentView(treeController
.getNodeView(parent));
tree.setSelectionPath(new TreePath(parent.getPath()));
treeController.setCurrentView(treeController
.getNodeView(parent));
tree.repaint();
PlotterController.getInstance().startPlotter();
} else {
treeController.setCurrentView(parent);
PlotterController.getInstance().startPlotter();
}
}
}
if (evt.getButton() == 3) {
if ((parent.getNodeType() != NodeType.TOOLBAR
&& parent.getNodeType() != NodeType.VIEW && parent
.getNodeType() != NodeType.ROOT)) {
tree.setComponentPopupMenu(null);
treeView.setPopMenu(treeView.createPopupTheme(parent));
tree.setComponentPopupMenu(treeView.getPopMenu());
treeController.setCurrentView(treeController
.getNodeView(parent));
/*
* adjust to prevent moving node when the user clicks with
* the left button right after this event
*/
nodeSource = null;
nodeTarget = null;
} else if (parent.getNodeType() == NodeType.VIEW) {
/*
* adjust to prevent moving node when the user clicks with
* the left button right after this event
*/
nodeSource = null;
nodeTarget = null;
tree.setComponentPopupMenu(null);
treeView.setPopMenu(treeView.createPopupView());
tree.setComponentPopupMenu(treeView.getPopMenu());
treeController.setCurrentView(treeController
.getNodeView(parent));
}
}
} else { // raiz da vista
tree.setComponentPopupMenu(null);
treeView.setPopMenu(treeView.createPopupDefault());
tree.setComponentPopupMenu(treeView.getPopMenu());
}
//treeController.dispachLastTheme();
}
@Override
public void mouseReleased(MouseEvent evt) {
tree.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (nodeSource == null)
return;
treeController.setNodeSource(nodeSource);
if (nodeSource.getNodeType() == NodeType.TOOLBAR
|| nodeSource.getNodeType() == NodeType.ROOT) {
return;
}
Point pt = evt.getPoint();
TreePath parentPath = tree.getPathForLocation(pt.x, pt.y);
CustomNode targetView = null;
CustomNode sourceView = null;
if (parentPath == null) {
return;
}
nodeTarget = (CustomNode) parentPath.getLastPathComponent();
treeView.getTree().setSelectionPath(new TreePath(nodeTarget.getPath()));
if (nodeTarget == nodeSource)
return;
if (evt.isShiftDown()) {
treeController.pasteNode();
return;
}
sourceView = treeController.getNodeView(nodeSource);
targetView = treeController.getNodeView(nodeTarget);
int index = ((CustomNode) nodeTarget.getParent()).getIndex(nodeTarget);
if (nodeTarget.equals(treeController.getNodeView(nodeSource)))
return;
// Move a node
if (evt.getButton() == 1) {
if (nodeSource.getNodeType() == NodeType.VIEW
&& nodeTarget.getNodeType() == NodeType.VIEW) {
treeController.rearrange(index, treeView.getRoot(), nodeSource);
} else if (targetView.getName().equals(sourceView.getName())) {
treeController.rearrange(index, targetView, nodeSource);
return;
} else {
treeController.moveNode(targetView, sourceView);
return;
}
}
}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource().equals(treeView.getRenameTheme())) {
treeController.renameNode();
}
if (evt.getSource().equals(treeView.getDeleteTheme())) {
treeController.deleteNode();
}
if (evt.getSource().equals(treeView.getRenameTheme())) {
treeController.setSelectedNode((CustomNode) tree
.getLastSelectedPathComponent());
treeController.getSelectedNode().setHiddenExpanded(true);
if (treeController.getSelectedNode().getNodeType() != NodeType.NETWORK_THEME)
return;
tree.expandPath(new TreePath(treeController.getSelectedNode()
.getPath()));
}
// export theme
if (evt.getSource().equals(treeView.getExportTheme())) {
LookAndFeelService.changeLookAndFeelForNimbus();
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Exportar...");
FileFilter type1 = new FileNameExtensionFilter("SHP", "shp");
FileFilter type2 = new FileNameExtensionFilter("SHX", "shx");
FileFilter type3 = new FileNameExtensionFilter("XML", "xml");
chooser.addChoosableFileFilter(type1);
chooser.addChoosableFileFilter(type2);
chooser.addChoosableFileFilter(type3);
chooser.showSaveDialog(null);
File file = chooser.getSelectedFile();
if (file == null)
return;
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
CustomNode node = (CustomNode) tree
.getLastSelectedPathComponent();
bw.write(node.getName());
bw.newLine();
if (node.isSelected())
bw.write("true");
else
bw.write("false");
bw.newLine();
if (node.isScaleVisible())
bw.write("true");
else
bw.write("false");
bw.newLine();
bw.write(node.getNodeType().toString());
bw.newLine();
for (@SuppressWarnings("unchecked")
Enumeration<CustomNode> e = ((CustomNode) tree
.getLastSelectedPathComponent()).children(); e
.hasMoreElements();) {
node = e.nextElement();
if (node.getNodeType() == NodeType.TOOLBAR) {
if (e.hasMoreElements()) {
node = e.nextElement();
}
} else {
bw.write(node.getName());
bw.newLine();
if (node.isSelected())
bw.write("true");
else
bw.write("false");
bw.newLine();
if (node.isScaleVisible())
bw.write("true");
else
bw.write("false");
bw.newLine();
bw.write(node.getNodeType().toString());
bw.newLine();
}
bw.flush();
bw.close();
file.createNewFile();
}
} catch (IOException exc) {
exc.printStackTrace();
}
LookAndFeelService.changeLookAndFeelForDefault();
}
// collapse
if (evt.getSource().equals(treeView.getCollapse())) {
treeController.setSelectedNode((CustomNode) tree
.getLastSelectedPathComponent());
treeController.getSelectedNode().setHiddenExpanded(false);
if (treeController.getSelectedNode().getNodeType() != NodeType.NETWORK_THEME)
return;
tree.collapsePath(new TreePath(treeController.getSelectedNode()
.getPath()));
}
// create theme
if (evt.getSource().equals(treeView.getCreateChildTheme())) {
CustomNode parent = (CustomNode) tree
.getLastSelectedPathComponent();
/*
* If the node selected is a toolbar node receives the toolbar's
* selectedNode
*/
if (parent.getNodeType() == NodeType.TOOLBAR) {
parent = (CustomNode) parent.getParent();
}
if (!parent.isAllowsChildren()) {
LocalOptionPane.getInstance("Este tema não pode ter subtemas ",
"Glue - Criar Tema");
return;
}
ThemeOptionsView.getInstance(parent);
}
// properties theme
if (evt.getSource().equals(treeView.getPropertiesTheme())) {
System.out.println("Busca por propriedades.");
}
// srchAtribTheme
if (evt.getSource().equals(treeView.getSrchAtribTheme())) {
/*
* LookAndFeelService.changeLookAndFeelForNimbus();
* Metodos.resetReferences(); DataBaseConnection db =
* Metodos.openConnection(); JFrame frame = new
* JFrame("Consulta por Atributo"); Metodos.setFrmAttribute(frame);
* DynamicPanel pnlConsultaAtributo = new DynamicPanel(db, 139);
* Metodos.setThemeName(treeController.getCurrentTheme().getName());
* Metodos.setThemeId(treeController.getCurrentTheme().getId());
* Metodos.setViewName(treeController.getCurrentView().getName());
* try { Metodos.enabledComponents(pnlConsultaAtributo, db); } catch
* (SQLException e) { } frame.setUndecorated(true); DragPanel drag =
* new DragPanel(frame); frame.addMouseListener(drag);
* frame.addMouseMotionListener(drag);
* frame.setBounds(pnlConsultaAtributo.getBounds());
* frame.add(pnlConsultaAtributo);
* frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
* frame.setLocationRelativeTo(null); frame.setResizable(false);
* frame.setVisible(true);/* } // create theme if
* (evt.getSource().equals(treeView.getCreateTheme())) { if
* (treeController.getSelectedNode() == null) { return; }
*
* /* If the node selected is a toolbar node receives the toolbar's
* selectedNode
*/
if (treeController.getSelectedNode().getNodeType() == NodeType.TOOLBAR) {
treeController.setSelectedNode((CustomNode) treeController
.getSelectedNode().getParent());
}
if (!treeController.getSelectedNode().isAllowsChildren()) {
LocalOptionPane.getInstance("Este tema não pode ter subtemas ",
"Glue - Criar Tema");
return;
}
ThemeOptionsView.getInstance(treeController.getSelectedNode());
}
if (evt.getSource().equals(treeView.getRenameView())) {
treeController.renameNode();
}
if (evt.getSource().equals(treeView.getDeleteView())) {
treeController.deleteNode();
}
if (evt.getSource().equals(treeView.getImportView())) {
LookAndFeelService.changeLookAndFeelForNimbus();
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Importar...");
FileFilter type1 = new FileNameExtensionFilter("SHP", "shp");
FileFilter type2 = new FileNameExtensionFilter("SHX", "shx");
FileFilter type3 = new FileNameExtensionFilter("XML", "xml");
chooser.addChoosableFileFilter(type1);
chooser.addChoosableFileFilter(type2);
chooser.addChoosableFileFilter(type3);
chooser.showOpenDialog(null);
chooser.getSelectedFile();
LookAndFeelService.changeLookAndFeelForDefault();
}
if (evt.getSource().equals(treeView.getPersist())) {
if (treeController.getSelectedNode() == null)
return;
treeController.createViewUpdator(false, false, false);
}
if (evt.getSource().equals(treeView.getRevert())) {
if (treeController.getSelectedNode() == null)
return;
if (treeController.getSelectedNode().getId() > 0l) {
if (treeController.getSelectedNode().isApplied()) {
treeController.createViewUpdator(true, true, false);
} else {
treeController.createViewUpdator(true, false, false);
}
} else if (treeController.getSelectedNode().getId() < 0l) {
treeController.createViewUpdator(true, true, false);
}
}
if (evt.getSource().equals(treeView.getProperties())) {
if (treeController.getSelectedNode() == null) {
return;
}
String message = new String("Nome: "
+ treeController.getSelectedNode().getName()
+ "\n"
+ "Projeção: "
+ treeController.getSelectedNode().getView()
.getProjection().getName());
JOptionPane.showMessageDialog(null, message,
"Propriedades da vista", 1);
}
if (evt.getSource().equals(treeView.getCreateTheme())){
LookAndFeelService.changeLookAndFeelForNimbus();
CustomNode parent = treeController.getLastSelectedPathComponent();
if (parent == null) {
parent = treeController.getCurrentView();
if (parent == null)
return;
}
if (parent.getNodeType() == NodeType.TOOLBAR) {
parent = (CustomNode) parent.getParent();
}
ThemeOptionsView.getInstance(parent);
}
if (evt.getSource().equals(treeView.getCreateView())) {
LookAndFeelService.changeLookAndFeelForNimbus();
String name = JOptionPane
.showInputDialog("Digite o nome da nova vista: ");
LookAndFeelService.changeLookAndFeelForDefault();
CustomNode root = treeController.getRoot();
if (name == null || name.trim().equals(""))
return;
CustomNode compare = new CustomNode(0l, name, true, treeController
.getSelectedNode().getNodeType());
if (treeController.checkAllNodes(root, compare)) {
LocalOptionPane.getInstance("Este nome já existe",
"Glue - Criar Vista");
} else {
CustomNode node = new CustomNode(0l, name, false, NodeType.VIEW);
root.add(node);
node.setApplied(false);
node.setPersisted(false);
}
treeController.getDefaultTreeModel().reload(root);
}
}
public JTree getTree() {
return tree;
}
public void setTree(JTree tree) {
this.tree = tree;
}
}
|
package domain;
public class Estudiante {
private int id;
private String nombre;
private String carrera;
public Estudiante() {
}
public Estudiante(int id, String nombre, String carrera) {
this.id = id;
this.nombre = nombre;
this.carrera = carrera;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCarrera() {
return carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
@Override
public String toString() {
return "Estudiante [id=" + id + ", nombre=" + nombre + ", carrera=" + carrera + "]";
}
}
|
package Project;
//________________________________IMPORTACIONES_________________________________
import java.sql.*;
import javax.swing.*;
//_____________________________CONSTRUCTOR______________________________________
public class BaseDeDatos {
//__________________________________ATRIBUTOS___________________________________
String sql;
private static final String url = "jdbc:postgresql://localhost/accidentes";
private static final String clavePostgres = "root";
public static Connection con;
public static Statement stmt;
//___________________________________METODOS____________________________________
public static void conectarse() {
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url, "postgres", clavePostgres);
stmt = con.createStatement();
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
//______________________________________________________________________________
public static void desconectarse() {
try {
stmt.execute("END");
stmt.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
//______________________________________________________________________________
|
package com.jlgproject.model;
import java.io.Serializable;
import java.util.List;
/**
* @author 王锋 on 2017/6/15.
*/
public class DebtPerson implements Serializable{
private String idCode;//身份证号
private String name;//债事人姓名
private String provinceCode;//所属省
private String cityCode;//所属市
private String prCode;//所属区
private String phoneNumber;//联系电话
private String contactAddress;//联系地址
private String email;//电子邮箱
private String qq;//
private String weChat;
private List<String> picList;
public DebtPerson() {
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
public String getPrCode() {
return prCode;
}
public void setPrCode(String prCode) {
this.prCode = prCode;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getContactAddress() {
return contactAddress;
}
public void setContactAddress(String contactAddress) {
this.contactAddress = contactAddress;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWeChat() {
return weChat;
}
public void setWeChat(String weChat) {
this.weChat = weChat;
}
public List<String> getPicList() {
return picList;
}
public void setPicList(List<String> picList) {
this.picList = picList;
}
}
|
package application.gui;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JanelaBaskaraSwing extends JFrame {
private JButton btCalcular;
private JButton btLimpar;
private JTextField tfA;
private JTextField tfB;
private JTextField tfC;
private JLabel lbA;
private JLabel lbB;
private JLabel lbC;
private JLabel lbX1;
private JLabel lbX2;
private JLabel lbResultX1;
private JLabel lbResultX2;
private JMenuBar barraMenu;
private JMenu mnArquivo;
private JMenu mnAjuda;
private JMenuItem miNovo;
private JMenuItem miSair;
private JMenuItem miSobre;
private Container container;
public JanelaBaskaraSwing() {
super("Fórmula de Baskara");
container = this.getContentPane();//recupera o container da tela
container.setLayout(new FlowLayout());//Layout de fluxo
btCalcular = new JButton("Calcular");
btLimpar = new JButton("Limpar");
tfA = new JTextField(10);
tfB = new JTextField(10);
tfC = new JTextField(10);
lbResultX1 = new JLabel("0.0");
lbResultX2 = new JLabel("0.0");
barraMenu = new JMenuBar();
mnArquivo = new JMenu("Arquivo");
mnAjuda = new JMenu("Ajuda");
miNovo = new JMenuItem("Novo");
miSair = new JMenuItem("Sair");
miSobre = new JMenuItem("Sobre...");
barraMenu.add(mnArquivo);
barraMenu.add(mnAjuda);
mnArquivo.add(miNovo);
mnArquivo.add(miSair);
mnAjuda.add(miSobre);
this.setJMenuBar(barraMenu);
container.add(new JLabel("A:"));
container.add(tfA);
container.add(new JLabel("B:"));
container.add(tfB);
container.add(new JLabel("C:"));
container.add(tfC);
container.add(btCalcular);
container.add(new JLabel("X':"));
container.add(lbResultX1);
container.add(new JLabel("X'':"));
container.add(lbResultX2);
container.add(btLimpar);
container.setBackground(Color.green);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Implementando o metodo ActionListener.*/
btCalcular.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btCalcularAction();
}
});
btLimpar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btLimparAction();
}
});
miNovo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
miNovoAction();
}
});
miSair.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
miSairAction();
}
});
miSobre.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
miSobreAction();
}
});
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
private void btCalcularAction() {
if (isCamposConsistentes()) {
//entrada
double a = Double.parseDouble(getTfA().getText());
double b = Double.parseDouble(getTfB().getText());
double c = Double.parseDouble(getTfC().getText());
//processamento
double delta = Math.pow(b, 2) - 4 * a * c;
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
//saida
getLbResultX1().setText(String.valueOf(x1));
getLbResultX2().setText(String.valueOf(x2));
} else {
JOptionPane.showMessageDialog(this, "Campos Inconsistentes.");
}
}
private void btLimparAction() {
limpar();
}
private void limpar() {
getTfA().setText("");
getTfB().setText("");
getTfC().setText("");
getLbResultX1().setText("0.0");
getLbResultX2().setText("0.0");
}
private void miNovoAction() {
limpar();
}
private void miSairAction() {
System.exit(0);
}
private void miSobreAction(){
new JanelaSobre(this);
}
/* Tratando Inconsistencias.*/
private boolean isCamposConsistentes() {
String a = getTfA().getText().trim();
String b = getTfB().getText().trim();
String c = getTfC().getText().trim();
if (a.equals("")) {
getTfA().requestFocus();//deixara o o campo com erro piscando
return false;
} else if (b.equals("")) {
getTfB().requestFocus();//deixara o o campo com erro piscando
return false;
} else if (c.equals("")) {
getTfC().requestFocus();//deixara o o campo com erro piscando
return false;
}
try {
Double.parseDouble(a);
} catch (Exception e) {
getTfA().requestFocus();//deixara o o campo com erro piscando
return false;
}
try {
Double.parseDouble(b);
} catch (Exception e) {
getTfB().requestFocus();//deixara o o campo com erro piscando
return false;
}
try {
Double.parseDouble(c);
} catch (Exception e) {
getTfC().requestFocus();//deixara o o campo com erro piscando
return false;
}
return true;
}
/* Metodos acessores*/
public JTextField getTfA() {
return tfA;
}
/**
* @param tfA the tfA to set
*/
public void setTfA(JTextField tfA) {
this.tfA = tfA;
}
/**
* @return the tfB
*/
public JTextField getTfB() {
return tfB;
}
/**
* @param tfB the tfB to set
*/
public void setTfB(JTextField tfB) {
this.tfB = tfB;
}
/**
* @return the tfC
*/
public JTextField getTfC() {
return tfC;
}
/**
* @param tfC the tfC to set
*/
public void setTfC(JTextField tfC) {
this.tfC = tfC;
}
/**
* @return the lbResultX1
*/
public JLabel getLbResultX1() {
return lbResultX1;
}
/**
* @param lbResultX1 the lbResultX1 to set
*/
public void setLbResultX1(JLabel lbResultX1) {
this.lbResultX1 = lbResultX1;
}
/**
* @return the lbResultX2
*/
public JLabel getLbResultX2() {
return lbResultX2;
}
/**
* @param lbResultX2 the lbResultX2 to set
*/
public void setLbResultX2(JLabel lbResultX2) {
this.lbResultX2 = lbResultX2;
}
public static void main(String[] args) {
new JanelaBaskaraSwing();
}
}
|
package com.fnsvalue.skillshare.dto;
public class Question {
private int ask_no_pk;
private String user_tb_user_id_pk;
private String ask_tit;
private String ask_con;
private String ask_dt;
private int page;
private int perPageNum;
private int totalCount;
private int startPage;
private int endPage;
private boolean prev;
private boolean next;
public int getAsk_no_pk() {
return ask_no_pk;
}
public void setAsk_no_pk(int ask_no_pk) {
this.ask_no_pk = ask_no_pk;
}
public String getUser_tb_user_id_pk() {
return user_tb_user_id_pk;
}
public void setUser_tb_user_id_pk(String user_tb_user_id_pk) {
this.user_tb_user_id_pk = user_tb_user_id_pk;
}
public String getAsk_tit() {
return ask_tit;
}
public void setAsk_tit(String ask_tit) {
this.ask_tit = ask_tit;
}
public String getAsk_con() {
return ask_con;
}
public void setAsk_con(String ask_con) {
this.ask_con = ask_con;
}
public String getAsk_dt() {
return ask_dt;
}
public void setAsk_dt(String ask_dt) {
this.ask_dt = ask_dt;
}
//-----------------------------page
public Question() { //페이지 초기설정
this.page=1; // 처음에는 첫페이지
perPageNum=10; //게시물 10개씩
}
public void setPage(int page) { //페이지 set
if(page<=0){ //페이지 오류시
this.page =1; //페이지번호 1로
return;
}
this.page=page;
}
public void setPerPageNum(int perPageNum) { //게시물갯수 set
if(perPageNum <=0 || perPageNum>100){
this.perPageNum=10;
return;
}
this.perPageNum = perPageNum;
}
public int getPage() { //page get
return page;
}
//method for MyBatis SQL Mapper-
public int getPageStart(){ // 해당 페이지의 게시물들 get
return (this.page-1)*perPageNum;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getPerPageNum() {
return perPageNum;
}
@Override
public String toString(){
return "Criteria [page="+page+","+"perPageNum"+perPageNum+"]";
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) //전체게시물 받음
{
this.totalCount=totalCount; //전체게시물 받고
calcData(); //끝페이지, 시작페이지, 앞으로, 뒤로 설정
}
private void calcData()
{
endPage=(int)(Math.ceil(this.getPage()/(double)perPageNum)*perPageNum);
startPage=(endPage-perPageNum)+1;
int tempEndPage=(int) (Math.ceil(totalCount/(double)this.getPerPageNum()));
if(endPage>tempEndPage)
{
endPage=tempEndPage;
}
prev=startPage == 1?false :true;
next=endPage * this.getPerPageNum()>=totalCount?false :true;
}
public boolean isPrev() {
return prev;
}
public void setPrev(boolean prev) {
this.prev = prev;
}
public boolean isNext() {
return next;
}
public void setNext(boolean next) {
this.next = next;
}
}
|
package com.bunny.taskapi.service;
import com.bunny.taskapi.domain.Tasks;
import com.bunny.taskapi.repository.TasksRepository;
import org.springframework.stereotype.Service;
@Service
public class TaskCommandServiceImpl implements TaskCommandService
{
private final TasksRepository tasksRepository;
public TaskCommandServiceImpl(TasksRepository tasksRepository) {
this.tasksRepository = tasksRepository;
}
@Override
public Tasks upsertTasks(Tasks tasks) {
return tasksRepository.save(tasks);
}
}
|
package com.lizogub.LabWork9.test;
import com.lizogub.LabWork9.pages.DashboardPage;
import com.lizogub.LabWork9.pages.DictionaryPage;
import com.lizogub.LabWork9.pages.LoginPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
public class LinguaLeoAddWordTest {
@Test
public void addWordTest() {
String word = "narrow";
System.setProperty("webdriver.gecko.driver","C:\\Users\\vadim\\IdeaProjects\\stdyHillel\\src\\com\\lizogub\\LabWork9\\geckodriver.exe");
// System.setProperty("webdriver.gecko.driver","/opt/geckodriver");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,10);
DashboardPage dashboardPage = new DashboardPage(driver);
DictionaryPage dictionaryPage = new DictionaryPage(driver);
login(driver);
wait.until(dashboardPage.isLoggedIn());
dashboardPage.checkCurrentPage();
dashboardPage.openDictionary();
wait.until(dictionaryPage.dictionaryLoaded());
dictionaryPage.checkSearchBoxVisibility();
dictionaryPage.enterTextToSearchBox(word);
// wait.until(dictionaryPage.checkAddButtonClickable());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
dictionaryPage.clickAddButton();
wait.until(dictionaryPage.translationLoaded());
dictionaryPage.clickTranslationWord();
driver.quit();
}
protected static void login(WebDriver driver){
LoginPage loginPage = new LoginPage(driver);
driver.get("https://lingualeo.com/ru");
driver.findElement(By.id("headEnterBtn")).click();
loginPage.enterEmail("vadlvadl789@gmail.com");
loginPage.enterPassword("pAsSw04dR");
loginPage.clickSendButton();
}
}
|
package tk.martijn_heil.elytraoptions.command;
import com.sk89q.intake.Command;
import com.sk89q.intake.Require;
import org.bukkit.command.CommandSender;
import tk.martijn_heil.elytraoptions.EPlayer;
import tk.martijn_heil.elytraoptions.ElytraOptions;
import tk.martijn_heil.elytraoptions.command.common.Sender;
import tk.martijn_heil.elytraoptions.command.common.TargetOrSender;
public class ElytraOptionsCommands
{
@Command(aliases = "status", desc = "Show your player status", usage = "<value> <player=self>")
@Require("elytraoptions.command.status")
public void status(@Sender CommandSender sender, @TargetOrSender("elytraoptions.command.status.other")EPlayer about)
{
double remainingAirtime = ElytraOptions.getInstance().getConfig().getInt("airtime.max") - about.getAirTime();
sender.sendMessage("Status information for player " + about.getPlayer().getName() + ":");
sender.sendMessage( String.format("Using infinite: %s", about.isUsingInfinite()));
sender.sendMessage(String.format("Using boost: %s", about.isUsingBoost()));
sender.sendMessage(String.format("Using sound: %s", about.isUsingSound()));
sender.sendMessage(String.format("Using trail: %s", about.isUsingTrail()));
sender.sendMessage(String.format("Airtime remaining: %s", ((Double) remainingAirtime).toString()));
sender.sendMessage(String.format("Current airtime: %s", ((Integer) about.getAirTime()).toString()));
}
@Command(aliases = "boost", desc = "Show your player status", usage = "<value> <player=self>")
@Require("elytraoptions.command.boost")
public void boost(boolean value, @TargetOrSender("elytraoptions.command.boost.other") EPlayer ep)
{
ep.setUsingBoost(value);
}
@Command(aliases = "infinite", desc = "Show your player status", usage = "<value> <player=self>")
@Require("elytraoptions.command.infinite")
public void infinite(boolean value, @TargetOrSender("elytraoptions.command.infinite.other") EPlayer ep)
{
ep.setUsingInfinite(value);
}
@Command(aliases = "trail", desc = "Show your player status", usage = "<value> <player=self>")
@Require("elytraoptions.command.trail")
public void trail(boolean value, @TargetOrSender("elytraoptions.command.trial.other") EPlayer ep)
{
ep.setUsingTrail(value);
}
@Command(aliases = "sound", desc = "Show your player status", usage = "<value> <player=self>")
@Require("elytraoptions.command.sound")
public void sound(boolean value, @TargetOrSender("elytraoptions.command.sound.other") EPlayer ep)
{
ep.setUsingSound(value);
}
}
|
package com.nju.edu.cn.constant;
/**
* Created by shea on 2018/9/10.
*/
public class ContractBackTestHead {
//yield,max_drawdown,win_rate,profit_loss_ratio,position,
// today_profit_loss,average_trading_price,do_adjust_warehouse,trade_id,back_futures_position,
// nearby_futures_position,market_capital_capacity,creat_time
private int yield = 0;
private int max_drawdown = 1;
private int win_rate = 2;
private int profit_loss_ratio = 3;
private int position = 4;
private int today_profitloss = 5;
private int average_trading_price = 6;
private int do_adjust = 7;
private int tradeid = 8;
private int backposition = 9;
private int nearbyposition = 10;
private int market_capial_capacity = 11;
private int creattime = 12;
// private int fileBeginT = 101;
// private int tableBeginT = 109;
// private int gap = 109-101;
public ContractBackTestHead(String path) {
if(path.split("/")[path.split("/").length-1].equals("contract_back_test_xu.csv")){
yield = 3;
max_drawdown = 4;
win_rate = 5;
market_capial_capacity = 6;
profit_loss_ratio = 7;
position = 8;
today_profitloss = 9;
average_trading_price = 12;
do_adjust = 13;
nearbyposition = 14;
backposition = 15;
creattime = 16;
tradeid = 18;
// fileBeginT = 1;
// tableBeginT = 1;
// gap = 0;
}
}
public int getYield() {
return yield;
}
public int getMax_drawdown() {
return max_drawdown;
}
public int getWin_rate() {
return win_rate;
}
public int getProfit_loss_ratio() {
return profit_loss_ratio;
}
public int getPosition() {
return position;
}
public int getToday_profitloss() {
return today_profitloss;
}
public int getAverage_trading_price() {
return average_trading_price;
}
public int getDo_adjust() {
return do_adjust;
}
public int getTradeid() {
return tradeid;
}
public int getNearbyposition() {
return nearbyposition;
}
public int getBackposition() {
return backposition;
}
public int getMarket_capial_capacity() {
return market_capial_capacity;
}
public int getCreattime() {
return creattime;
}
// public int getGap() {
// return gap;
// }
}
|
/*
* 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 shifu.view.panel;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import shifu.core.Singleton;
import shifu.model.Emprunt;
import shifu.model.Mediatheque;
import shifu.model.dao.ShifuDAOFactory;
import shifu.view.DialogException;
/**
*
* @author user
*/
public class PanelGestionEmprunts extends javax.swing.JPanel {
List<Emprunt> listEmprunts;
Emprunt empruntSelect;
/**
* Creates new form PanelEmprunt
*/
public PanelGestionEmprunts() {
initComponents();
this.btnRetourEmprunt.setEnabled( false );
}
public JButton getBtnAjouterEmprunt() {
return btnAjouterEmprunt;
}
public JButton getBtnRetourEmprunt() {
return btnRetourEmprunt;
}
/**
* 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() {
panelSearchEmprunt = new shifu.view.panel.PanelSearch();
jScrollPane1 = new javax.swing.JScrollPane();
tableEmprunt = new javax.swing.JTable();
btnAjouterEmprunt = new javax.swing.JButton();
btnRetourEmprunt = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setBorder(new javax.swing.border.LineBorder(new java.awt.Color(102, 102, 102), 3, true));
tableEmprunt.setAutoCreateRowSorter(true);
tableEmprunt.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"Titre oeuvre emprunter", "Nom Emprunteur", "Prénom Emprunteur", "Téléphone Emprunteur", "Date de debut d'emprunt", "Renouvelé", "Date de fin au plus tard", "Retard"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Object.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tableEmprunt.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableEmpruntMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tableEmprunt);
if (tableEmprunt.getColumnModel().getColumnCount() > 0) {
tableEmprunt.getColumnModel().getColumn(0).setResizable(false);
tableEmprunt.getColumnModel().getColumn(1).setResizable(false);
tableEmprunt.getColumnModel().getColumn(2).setResizable(false);
tableEmprunt.getColumnModel().getColumn(3).setResizable(false);
tableEmprunt.getColumnModel().getColumn(4).setResizable(false);
tableEmprunt.getColumnModel().getColumn(5).setResizable(false);
tableEmprunt.getColumnModel().getColumn(6).setResizable(false);
tableEmprunt.getColumnModel().getColumn(7).setResizable(false);
}
btnAjouterEmprunt.setText("Ajouter un emprunt");
btnAjouterEmprunt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAjouterEmpruntActionPerformed(evt);
}
});
btnRetourEmprunt.setText("Valider un retour");
btnRetourEmprunt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRetourEmpruntActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel1.setText("Gestion des Emprunts");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(btnAjouterEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 367, Short.MAX_VALUE)
.addComponent(btnRetourEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(panelSearchEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panelSearchEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAjouterEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnRetourEmprunt, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(27, 27, 27)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void btnRetourEmpruntActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRetourEmpruntActionPerformed
ShifuDAOFactory.getEmpruntDAO().delete( empruntSelect );
try {
Mediatheque.getInstance().setListAdherents(
ShifuDAOFactory.getAdherentDAOC().findAll()
);
listEmprunts = ShifuDAOFactory.getEmpruntDAO().findAll();
refreshTableEmprunts();
} catch ( Exception ex ) {
new DialogException(ex );
}
}//GEN-LAST:event_btnRetourEmpruntActionPerformed
private void btnAjouterEmpruntActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAjouterEmpruntActionPerformed
}//GEN-LAST:event_btnAjouterEmpruntActionPerformed
private void tableEmpruntMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableEmpruntMouseClicked
int selectedRow = this.tableEmprunt.rowAtPoint( evt.getPoint() );
this.empruntSelect = listEmprunts.get( selectedRow );
this.btnRetourEmprunt.setEnabled( true );
}//GEN-LAST:event_tableEmpruntMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAjouterEmprunt;
private javax.swing.JButton btnRetourEmprunt;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private shifu.view.panel.PanelSearch panelSearchEmprunt;
private javax.swing.JTable tableEmprunt;
// End of variables declaration//GEN-END:variables
public void setEmprunts( List<Emprunt> listEmprunts ) {
this.listEmprunts = listEmprunts;
refreshTableEmprunts();
}
private void refreshTableEmprunts() {
DefaultTableModel model = ( DefaultTableModel ) this.tableEmprunt.getModel();
model.setRowCount( 0 );
Calendar c = Calendar.getInstance();
for ( Emprunt e : listEmprunts ) {
boolean retard = false;
c.setTime( e.getDateEmprunt() );
c.add( Calendar.DATE, 14 );
Date dateRetour = new Date( c.getTimeInMillis() );
if ( Date.valueOf( LocalDate.now() ).after( dateRetour ) ) {
retard = true;
}
model.addRow( new Object[]{
e.getOuvrage().getTitre(),
e.getAbonne().getNom(),
e.getAbonne().getPrenom(),
e.getAbonne().getTel(),
e.getDateEmprunt(),
e.isIsRenouvele(),
dateRetour,
retard
} );
}
this.btnRetourEmprunt.setEnabled( false );
this.tableEmprunt = new JTable( model );
}
public List<Emprunt> getListEmprunts() {
return listEmprunts;
}
}
|
package com.example.kevin.weatherclothingapp;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.amazon.device.associates.AssociatesAPI;
import com.amazon.device.associates.LinkService;
import com.amazon.device.associates.NotInitializedException;
import com.amazon.device.associates.OpenSearchPageRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONObject;
import java.util.ArrayList;
// code on retrieval of user's current location is modified from this page: http://developer.android.com/training/location/retrieve-current.html and https://github.com/googlesamples/android-play-location/blob/master/BasicLocationSample/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.java
public class WeatherClothingActivity extends ListActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final String TAG = "WeatherClothingActivity";
private final String BUNDLE = "com.example.kevin.weatherclothingapp";
private final int RESULT_OK = 1;
public final int AMAZON = 0;
public final int ETSY = 1;
public final String STORE = "store";
public final String CATEGORY = "category";
public final String ITEM = "item";
public final int SETTINGS = 0;
public final int LOCATION = 1;
ListView weatherList;
int chosenStore;
String chosenCategory;
String chosenItems;
String amazonSearchTerm;
String amazonCategory;
String temperatureDescription;
String weatherDescription;
private static final int CHANGE_LOCATION_REQUEST_CODE = 0;
private Button mChangeLocationButton;
private static final String KEY_INDEX = "index";
Activity a;
ArrayList<String> temperatureDescriptionList = new ArrayList<>();
ArrayList<String> iconNameArrayList = new ArrayList<>();
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected static Location mLastLocation;
String latitude;
String longitude;
private String newCityName;
private String newCityZMW;
private boolean isNewCity = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_clothing);
buildGoogleApiClient();
chosenStore = AMAZON;
chosenCategory = "mens";
chosenItems = "hats";
a = this;
APICreator apic = new APICreator(a);
String APPLICATION_KEY = apic.getKeyFromRawResource("APPLICATION_KEY");
AssociatesAPI.initialize(new AssociatesAPI.Config(APPLICATION_KEY, this));
// todo The getWunderGroundJSONData() method in APICreator is currently hardcoded to return Minneapolis. Instead, it should be changed so that if (isNewCity = false) it uses the latitude and longitude variables grabbed by getLastLocation() to request the user's own local forecast, and if (isNewCity = true) it instead uses the ZMW variable pulled by the ChangeLocationActivity request.
JSONObject wunderGroundJSONData = apic.getWunderGroundJSONData();
ArrayList<Bitmap> weatherIconArrayList = apic.getWeatherIconArrayList(wunderGroundJSONData);
ArrayList<String> forecastDayArrayList = apic.getWunderGroundStringInfo(wunderGroundJSONData, "title");
ArrayList<String> forecastConditionsArrayList = apic.getWunderGroundStringInfo(wunderGroundJSONData, "fcttext");
iconNameArrayList = apic.getWunderGroundStringInfo(wunderGroundJSONData, "icon");
temperatureDescriptionList = apic.getTemperatureDescription(wunderGroundJSONData);
//sets the list Adapter.
CustomListAdapter adapter = new CustomListAdapter(this, forecastDayArrayList, weatherIconArrayList, forecastConditionsArrayList, temperatureDescriptionList);
weatherList = (ListView) findViewById(android.R.id.list);
weatherList.setAdapter(adapter);
weatherList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent returnedIntent = getIntent();
onActivityResult(SETTINGS, RESULT_OK, returnedIntent);
if (chosenStore == AMAZON) {
if (chosenItems.equals("Shoes")) {
chosenCategory = chosenCategory + " Shoes";
} else {
chosenCategory = chosenCategory + " Clothing And Accessories";
}
APICreator apic = new APICreator(a);
temperatureDescription = temperatureDescriptionList.get(position); // this variable has four possibilities based on the temperature forecast from wunderground. <32 freezing, 32-50 cold, 50-75 warm, and >75 hot. Will need to create a @getTemperatureDescription method to convert wunderground into temperatureDescription
weatherDescription = apic.getWeatherDescription(iconNameArrayList.get(position)); // this variable has four possibilities based on the weatherIcon from the wunderground forecast: mild, rainy, snowy, and stormy. stormy and rainy are probably the same thing. Will need to create @getweatherDescription method to convert wunderground icon into correct weatherDescription
String amazonString = apic.createAmazonSearchTerm(weatherDescription, temperatureDescription, chosenItems, chosenCategory);
Log.e(TAG, amazonString);
// the category and search terms will change depending on what the user has chosen to search for. Categories available for the Amazon Mobile Associates API are found here https://developer.amazon.com/public/apis/earn/mobile-associates/docs/available-search-categories
//This is from https://developer.amazon.com/public/apis/earn/mobile-associates/docs/direct-linking
Toast t = Toast.makeText(WeatherClothingActivity.this, amazonString, Toast.LENGTH_LONG);
t.show();
OpenSearchPageRequest request = new OpenSearchPageRequest(chosenCategory, amazonString);
try {
LinkService linkService = AssociatesAPI.getLinkService();
linkService.openRetailPage(request);
} catch (NotInitializedException e) {
Log.v(TAG, "NotInitializedException error");
}
}
else if (chosenStore == ETSY){
Intent i = new Intent(WeatherClothingActivity.this, EtsyActivity.class);
Bundle b = new Bundle();
b.putSerializable(CATEGORY, chosenCategory);
b.putSerializable(ITEM, chosenItems);
i.putExtra(BUNDLE, b);
startActivity(i);
}
}
});
// this button launches ChangeLocationActivity, to change the location called by weather underground.
mChangeLocationButton = (Button)findViewById(R.id.change_location_button);
mChangeLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent launchChangeLocationActivity = new Intent(WeatherClothingActivity.this, ChangeLocationActivity.class);
// this means we expect some result to be returned to the activity
startActivityForResult(launchChangeLocationActivity, CHANGE_LOCATION_REQUEST_CODE);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
public void openSettings(MenuItem menuItem){
Intent i = new Intent(WeatherClothingActivity.this, SettingsActivity.class);
startActivityForResult(i, SETTINGS);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// todo this will need its own requestcode so that it can be differentiated from CHANGE_LOCATION_REQUEST_CODE. also RESULT_OK should be a resultCode, not a requestCode.
if (requestCode == RESULT_OK){
String store = data.getStringExtra(STORE);
if (store.equals("Etsy")){
chosenStore = ETSY;
}
else if (store.equals("Amazon")){
chosenStore = AMAZON;
}
chosenCategory = data.getStringExtra(CATEGORY);
chosenItems = data.getStringExtra(ITEM);
Log.e(TAG,"chosenStore: " + chosenStore + "; chosenCategory: " + chosenCategory + "; chosenItems: " + chosenItems);
}
if (requestCode == CHANGE_LOCATION_REQUEST_CODE && resultCode == RESULT_OK) {
// get data from extra needed to change city
newCityZMW = data.getStringExtra(ChangeLocationActivity.EXTRA_NEW_LOCATION_ZMW);
newCityName = data.getStringExtra(ChangeLocationActivity.EXTRA_NEW_LOCATION_CITYNAME);
isNewCity = true;
if (isNewCity) { // this if statement toggles whether forecast is pulled from user's own location, or the newly chosen location
// todo Create new forecast based on this new data
}
}
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
class MAAWebViewClient extends WebViewClient {
private final String TAG = "MAAWebViewClient";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
LinkService linkService = AssociatesAPI.getLinkService();
return linkService.overrideLinkInvocation(view, url);
} catch (NotInitializedException e) {
Log.v(TAG, "NotInitializedException error");
}
return false;
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
// todo - do we need to put any data in here?
// savedInstanceState.putString(KEY_INDEX, latitude);
// savedInstanceState.putString(KEY_INDEX, longitude);
}
@Override
public void onConnected(Bundle bundle) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = String.valueOf(mLastLocation.getLatitude());
longitude = String.valueOf(mLastLocation.getLongitude());
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
}
|
package Test;
import org.junit.*;
import Componentes.Jugador;
import Compuestos.Escudo;
import Compuestos.Mina;
import Compuestos.Provision;
import Principal.Juego;
public class JuegoTest {
@Test
public void seCreaElJuego() throws Exception {
Juego juego = new Juego();
Assert.assertNotNull(juego);
}
@Test
public void elJugadorSeSeteaEnLaPosicionDeEntrada() {
}
}
|
package com.zhowin.miyou.recommend.activity;
import android.content.Context;
import android.content.Intent;
import androidx.fragment.app.Fragment;
import com.zhowin.base_library.adapter.HomePageAdapter;
import com.zhowin.base_library.utils.ConstantValue;
import com.zhowin.miyou.R;
import com.zhowin.miyou.base.BaseBindActivity;
import com.zhowin.miyou.databinding.ActivityKickOutTheRoomBinding;
import com.zhowin.miyou.recommend.fragment.KickOutRoomFragment;
import java.util.ArrayList;
import java.util.List;
/**
* 踢出房间 ,和 禁言共用
* <p>
* type 1:踢出 2: 禁言 3:禁麦
*/
public class KickOutTheRoomActivity extends BaseBindActivity<ActivityKickOutTheRoomBinding> {
private int classType;
private String[] mTitle;
public static void start(Context context, int type) {
Intent intent = new Intent(context, KickOutTheRoomActivity.class);
intent.putExtra(ConstantValue.TYPE, type);
context.startActivity(intent);
}
@Override
public int getLayoutId() {
return R.layout.activity_kick_out_the_room;
}
@Override
public void initView() {
classType = getIntent().getIntExtra(ConstantValue.TYPE, -1);
}
@Override
public void initData() {
switch (classType) {
case 1:
mBinding.titleView.setTitle("踢出房间");
mTitle = new String[]{"踢出房间", "踢出记录",};
break;
case 2:
mBinding.titleView.setTitle("禁言");
mTitle = new String[]{"禁言", "禁言记录",};
break;
case 3:
mBinding.titleView.setTitle("禁麦");
mTitle = new String[]{"禁麦", "禁麦记录",};
break;
default:
throw new IllegalStateException("Unexpected value: " + classType);
}
List<Fragment> mFragments = new ArrayList<>();
for (int i = 0; i < mTitle.length; i++) {
mFragments.add(KickOutRoomFragment.newInstance(classType, i));
}
HomePageAdapter homePageAdapter = new HomePageAdapter(getSupportFragmentManager(), mFragments, mTitle);
mBinding.noScrollViewPager.setAdapter(homePageAdapter);
mBinding.noScrollViewPager.setScroll(true);
mBinding.slidingTabLayout.setViewPager(mBinding.noScrollViewPager);
}
}
|
package test.pong;
import gfx.BitmapFont;
import java.io.IOException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector2f;
import core.AppContainer;
import core.AppContext;
import core.AppState;
import core.StateBasedApp;
public class PongStartState extends AppState {
private BitmapFont rules;
public PongStartState(int id) {
super(id);
}
@Override
public void init(AppContainer appContainer, StateBasedApp app) {
try {
rules = new BitmapFont(AppContext.textureManager.get("Consolas"), new Vector2f(32, 32));
rules.setPosition(new Vector2f(appContainer.getWidth() / 3.5f, appContainer.getHeight() - (appContainer.getHeight() / 3)));
rules.setFontSize(15);
}
catch (IOException e) {
e.printStackTrace();
}
super.init(appContainer, app);
}
@Override
public void update(int delta) {
super.update(delta);
}
@Override
public void render() {
rules.renderText("Player 1: Z (Up) X (Down)\nPlayer 2: Up Arrow (Up) Down Arrow (Down)\n\nPress P to PLAY!\nPress ESC to Exit");
}
@Override
public void input() {
if (!Keyboard.getEventKeyState()) {
if (Keyboard.getEventKey() == Keyboard.KEY_P) {
app.enterNextState();
}
}
}
}
|
package com.ts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.SQLQuery;
import com.rest.dto.Review;
import com.rest.dto.Submit;
import com.rest.dto.Tasks;
import com.ts.db.HibernateTemplate;
public class ReviewDAO {
private SessionFactory factory = null;
private static SessionFactory sessionFactory;
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public int register(Review review) {
//java.util.Date utilDate = new java.sql.Date(employee.getJoinDate().getTime());
return HibernateTemplate.addObject(review);
}
public List<Review> getAllReviews() {
List<Review> reviews=(List)HibernateTemplate.getObjectListByQuery("From Review");
System.out.println("Inside All Review ..."+reviews);
return reviews;
}
public Review getReview(int id) {
return (Review)HibernateTemplate.getObject(Review.class,id);
}
public List<Review> getReviewsByStudentId(int studentId) {
String query= "from Review where studentId=:studentId";
Query query1 = sessionFactory.openSession().createQuery(query);
query1.setParameter("studentId",studentId);
List <Review> obj = query1.list();
for(Object review: obj){
Review reviews = (Review)review;
System.out.println(reviews.getReviewId());
}
return obj;
}
public void getReviewsByTaskId(int taskId) {
String query= "from Review where taskId=:taskId";
Query query1 = sessionFactory.openSession().createQuery(query);
query1.setParameter("tastId",taskId);
List <Review> obj = query1.list();
for(Object review: obj){
Review reviews = (Review)review;
System.out.println(reviews.getReviewId());
}
}
public Review getReview1(int taskId, int studentId) {
String query= "from Review where taskId=:taskId and studentId=:studentId";
Query query1 = sessionFactory.openSession().createQuery(query);
query1.setParameter("taskId",taskId);
query1.setParameter("studentId",studentId);
System.out.println(taskId);
//Faculty obj = query1.list();
Object queryResult = query1.uniqueResult();
Review review = (Review)queryResult;
return review;
}
}
|
package response.helpers.classes;
public class Description {
private String description;
public Description() {
super();
}
public Description(String content) {
this();
description = content;
}
public static Description createSuccess(String resource, int id, String action) {
return create(resource + " with id (" + id + ") was successfully " + action + ".");
}
public static Description createNotFound(String resource, String field, int value) {
return create(resource + " with " + field + " (" + value + ") was not found.");
}
public static Description create(String descriptionContent) {
return new Description(descriptionContent);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.example.mibrahiem.commonplaces;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.database.DatabaseReference;
public class RegisterActivity extends AppCompatActivity {
Spinner spinner;
EditText etMail,etPassword;
String email,password;
private FirebaseAuth mAuth;
Button btReg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etMail= (EditText) findViewById(R.id.et_regMail);
etPassword = (EditText) findViewById(R.id.et_regpass);
mAuth = FirebaseAuth.getInstance();
btReg= (Button) findViewById(R.id.bt_register);
btReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rgister();
}
});
}
private void rgister() {
email=etMail.getText().toString();
password=etPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(RegisterActivity.this, "Done", Toast.LENGTH_SHORT).show();
}
else
{
FirebaseAuthException e = (FirebaseAuthException )task.getException();
Toast.makeText(RegisterActivity.this, " failed."+e.getMessage(),Toast.LENGTH_SHORT).show();
Log.i("aaa",e.getMessage());
}
}
});
}
}
|
package dev.amoeba.moexplorer.model;
import android.content.ContentProviderClient;
import android.database.Cursor;
import java.io.Closeable;
import dev.amoeba.moexplorer.libcore.io.IoUtils;
import dev.amoeba.moexplorer.misc.ContentProviderClientCompat;
import static dev.amoeba.moexplorer.BaseActivity.State.MODE_UNKNOWN;
import static dev.amoeba.moexplorer.BaseActivity.State.SORT_ORDER_UNKNOWN;
public class DirectoryResult implements Closeable {
public ContentProviderClient client;
public Cursor cursor;
public Exception exception;
public int mode = MODE_UNKNOWN;
public int sortOrder = SORT_ORDER_UNKNOWN;
@Override
public void close() {
IoUtils.closeQuietly(cursor);
ContentProviderClientCompat.releaseQuietly(client);
cursor = null;
client = null;
}
}
|
package org.mge.algos.dp;
public class NthFibonacciNumber {
static int[] memTable = new int[90];
public static void main(String[] args) {
int n = 50;
long startTime = System.currentTimeMillis();
System.out.println(getNthFN(n));
System.out.println("Time taken for recursion: "
+ (System.currentTimeMillis() - startTime) / 1000d + " Sec");
startTime = System.currentTimeMillis();
for (int i = 0; i < 90; i++) {
memTable[i] = -1;
}
System.out.println(getNthFNMem(n));
System.out.println("Time taken for memoization: "
+ (System.currentTimeMillis() - startTime) / 1000d + " Sec");
startTime = System.currentTimeMillis();
System.out.println(getNthFNTab(n));
System.out.println("Time taken for tabulation: "
+ (System.currentTimeMillis() - startTime) / 1000d + " Sec");
}
public static int getNthFN(int n) {
if (n <= 1) {
return n;
}
return getNthFN(n - 1) + getNthFN(n - 2);
}
public static int getNthFNMem(int n) {
if (memTable[n] == -1) {
if (n <= 1) {
memTable[n] = n;
} else {
memTable[n] = getNthFNMem(n - 1) + getNthFNMem(n - 2);
}
}
return memTable[n];
}
public static int getNthFNTab(int n) {
int[] table = new int[n+1];
table[0] = 0;
table[1] = 1;
for(int i = 2; i <= n; i++) {
table[i] = table[i-1] + table[i-2];
}
return table[n];
}
}
|
package com.bright.website.shiro;
public class Contans {
public static final String CURRENT_USER = "user";
}
|
import java.io.Serializable;
/**
* Created by gcc on 13/04/17.
*/
public class SNP implements Serializable {
String rsID;
String alleleA;
String alleleB;
String maf;
String chrNr;
String pos;
double overallZscore;
public String getRsID() {
return rsID;
}
public void setRsID(String rsID) {
this.rsID = rsID;
}
public String getAlleleA() {
return alleleA;
}
public void setAlleleA(String alleleA) {
this.alleleA = alleleA;
}
public String getAlleleB() {
return alleleB;
}
public void setAlleleB(String alleleB) {
this.alleleB = alleleB;
}
public String getMaf() {
return maf;
}
public void setMaf(String maf) {
this.maf = maf;
}
public String getChrNr() {
return chrNr;
}
public void setChrNr(String chrNr) {
this.chrNr = chrNr;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public double getOverallZscore() {
return overallZscore;
}
public void setOverallZscore(double overallZscore) {
this.overallZscore = overallZscore;
}
@Override
public String toString() {
return "SNP{" +
"rsID='" + rsID + '\'' +
", alleleA='" + alleleA + '\'' +
", alleleB='" + alleleB + '\'' +
", maf=" + maf +
", chrNr='" + chrNr + '\'' +
", pos='" + pos + '\'' +
'}';
}
}
|
package com.github.ezauton.recorder;
import com.github.ezauton.core.action.ActionGroup;
import com.github.ezauton.core.action.BackgroundAction;
import com.github.ezauton.core.action.PurePursuitAction;
import com.github.ezauton.core.localization.estimators.TankRobotEncoderEncoderEstimator;
import com.github.ezauton.core.pathplanning.Path;
import com.github.ezauton.core.pathplanning.purepursuit.Lookahead;
import com.github.ezauton.core.pathplanning.purepursuit.LookaheadBounds;
import com.github.ezauton.core.pathplanning.purepursuit.PPWaypoint;
import com.github.ezauton.core.pathplanning.purepursuit.PurePursuitMovementStrategy;
import com.github.ezauton.core.robot.implemented.TankRobotTransLocDriveable;
import com.github.ezauton.core.simulation.SimulatedTankRobot;
import com.github.ezauton.core.simulation.TimeWarpedSimulation;
import com.github.ezauton.core.trajectory.geometry.ImmutableVector;
import com.github.ezauton.recorder.base.PurePursuitRecorder;
import com.github.ezauton.recorder.base.RobotStateRecorder;
import com.github.ezauton.recorder.base.TankDriveableRecorder;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class RecorderTest {
public static void main(String[] args) throws IOException, TimeoutException, ExecutionException {
ImmutableVector immutableVector = new ImmutableVector(0, 0);
immutableVector.isFinite();
Path path = new PPWaypoint.Builder()
.add(0, 0, 16, 13, -12)
.add(0, 4, 16, 13, -12)
.add(-0.5, 8.589, 16, 13, -12)
.add(-0.5, 12.405, 13, 13, -12)
.add(-0.5, 17, 8.5, 13, -12)
.add(1.5, 19.4, 0, 13, -12)
.buildPathGenerator()
.generate(0.05);
PurePursuitMovementStrategy ppMoveStrat = new PurePursuitMovementStrategy(path, 0.001);
// Not a problem
TimeWarpedSimulation simulation = new TimeWarpedSimulation(1);
// Might be a problem
SimulatedTankRobot robot = new SimulatedTankRobot(1, simulation.getClock(), 40, 0.3, 30D);
TankRobotEncoderEncoderEstimator locEstimator = robot.getDefaultLocEstimator();
locEstimator.reset();
Lookahead lookahead = new LookaheadBounds(1, 7, 2, 10, locEstimator);
TankRobotTransLocDriveable tankRobotTransLocDriveable = robot.getDefaultTransLocDriveable();
PurePursuitAction purePursuitAction = new PurePursuitAction(20, TimeUnit.MILLISECONDS, ppMoveStrat, locEstimator, lookahead, tankRobotTransLocDriveable);
Recording recording = new Recording();
RobotStateRecorder posRec = new RobotStateRecorder("robotstate", simulation.getClock(), locEstimator, locEstimator, robot.getLateralWheelDistance(), 1.5);
PurePursuitRecorder ppRec = new PurePursuitRecorder("pp", simulation.getClock(), path, ppMoveStrat);
TankDriveableRecorder tankRobot = new TankDriveableRecorder("td", simulation.getClock(), tankRobotTransLocDriveable);
recording.addSubRecording(posRec);
recording.addSubRecording(ppRec);
recording.addSubRecording(tankRobot);
BackgroundAction recAction = new BackgroundAction(10, TimeUnit.MILLISECONDS, recording::update);
BackgroundAction updateKinematics = new BackgroundAction(2, TimeUnit.MILLISECONDS, robot::update);
ActionGroup group = new ActionGroup()
.with(updateKinematics)
.with(recAction)
.addSequential(purePursuitAction);
simulation.add(group);
// run the simulator with a timeout of 20 seconds
simulation.runSimulation(30, TimeUnit.SECONDS);
// System.out.println("locEstimator.estimateLocation() = " + locEstimator.estimateLocation());
recording.save("loggy.json");
}
}
|
package model.impl;
import java.util.Vector;
import model.AccessPoint;
import model.GridPoint;
import model.PathLossModel;
import model.Room;
import model.Trajectory;
import model.TxRadioImpl;
import model.Wall;
public class TransTxRadioImpl extends TxRadioImpl {//this is the transmit radio (DL) (of the transmitter)
protected AccessPoint parentAP=null;
protected TransReceiverCardImpl rcard=null;
//Xu added
protected boolean powerOn=true;
public TransTxRadioImpl(String type, String model, int gain, double pt,int freqband, int frequency, AccessPoint ap) {
super();
this.type = type;
this.model = model;
this.gain = gain;
this.Pt = pt; //Xu: only getPt()
this.freqband = freqband;
this.frequency = frequency;
this.parentAP=ap;
this.rcard=new TransReceiverCardImpl(type,model, freqband, this);
//System.out.println("HIER RECEIVER VOOR AP MAKEN "+this.getReceivercard().getName());
if(type.equalsIgnoreCase("WiFi")) {
/*if(model.equalsIgnoreCase("DLink")){
this.Pt=14;
this.gain=2;
this.freqband = 2400;
this.frequency = frequency;
}*/
}
/*else if(type.equalsIgnoreCase("sensor")){
this.freqband = 2400;
this.frequency = frequency;
if(model.equalsIgnoreCase("CC2420")||model.equalsIgnoreCase("JN516x")){
this.rcard=new TransReceiverCardImpl(type,model,freqband,this);
}
}
else if(type.equalsIgnoreCase("UMTS")){
if(model.equalsIgnoreCase("Huawei femtocell")){
this.freqband = 1800;
this.frequency = frequency;
}
else if(model.equalsIgnoreCase("LTE")){
this.freqband = 2600;
this.frequency = frequency;
}
}*/
}
public TransReceiverCardImpl getReceivercard() {
return rcard;
}
public void setReceivercard(TransReceiverCardImpl rcard) {
this.rcard = rcard;
}
public AccessPoint getParentAP() {
return parentAP;
}
public void setParentAP(AccessPoint parentAP) {
this.parentAP = parentAP;
}
/*public void setRoomRange(RecReceiverCardImpl rectype, ParameterSet par, int HRX) {
if(rectype==null){
//roomrange=0;
return;
}
PathLossModel plmodel=this.getAPmodel();
double max_PL=this.getPt()-this.getParentAP().getRoom().getMin_DLP_req(rectype)+rectype.getRec_gain()+this.getGain()-par.getFade_margin()-par.getInterference()-par.getShad_margin();
roomrange=plmodel.calculateMaxDist(max_PL, this.getParentAP(), HRX);
}*/
public double getRoomrange(RecReceiverCardImpl rectype, int HRX) {
PathLossModel plmodel=this.getAPmodel();
//double max_PL=this.getPt()-this.getParentAP().getRoom().getMin_DLP_req(rectype)+rectype.getRec_gain()+this.getGain()-total_margin;
double roomrange=plmodel.calculateMaxDist(this.getParentAP().getRoom().getMin_DLP_req(rectype), this,this.getParentAP().getHeight(), HRX,rectype);
return roomrange;
}
public int getMaxEIRP(int safetydist_cm,double Emax,int HRX) {
GridPoint g=new GridPointImpl();
g.setRxHeight(HRX);
PathLossModel plmodel=this.getAPmodel();
double PL_diss=plmodel.getDistanceloss(safetydist_cm, this.getParentAP(), g);
//System.out.println("path loss op "+safetydist_cm+" cm is "+PL_diss);
double EIRPtest=43.15+PL_diss+20*Math.log10(Emax/this.getFrequency());
//System.out.println("EIRP voor "+safetydist_cm+" cm is "+EIRPtest);
if(this.getFreqband()==2400)
if (EIRPtest>20)
EIRPtest=20;
if(this.getFreqband()==5000)
if (EIRPtest>23)
EIRPtest=23;
return (int) Math.floor(EIRPtest);
}
public String toString() {
if(this==null)
return "null-radio";
StringBuffer sb = new StringBuffer();
sb.append("Radio type="+this.getType()+" model="+this.getModel()+" power="+this.getPt()+" gain="+this.getGain()+" frequencyband=" +this.getFreqband()+" frequency="+this.getFrequency());
if(this.getParentAP().getLevel()==null&&this.getParentAP().getCoordinates()==null)
sb.append("\n\tAccesspoint type= Accesspoint without coordinates, not attached to a level; height="+this.getParentAP().getHeight()+"\n");
else
sb.append("\n\tAccesspoint level="+this.getParentAP().getLevel().getNumber()+" ["+this.getParentAP().getCoordinates()+"] height="+this.getParentAP().getHeight()+"\n");
return sb.toString();
}
public double calculate_Pathloss(Room r, GridPoint Rx,Vector<Wall> w, Trajectory posbestpath, double max_PL,Trajectory t) {
//System.out.println(this.getAPmodel()==null);
return this.getAPmodel().calculate_Pathloss(r, this, Rx,w, posbestpath, max_PL, t);
}
//Xu added
public void setPowerOn(boolean b) {
this.powerOn = b;
}
public boolean getPowerOn() {
return this.powerOn;
}
}
|
package com.j2.io;
public class Tazza extends Coproduction { //공동제작한영화
public Tazza(Movie movie) {
this.movie = movie;
}
public String getDescription() {
return movie.getDescription() + ", tazza";
}
public int rate() {
return 800 + movie.rate();//타짜관객수에 영화관객수를 더함
}
}
|
/*
* 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 frsmanagementclient;
import ejb.session.stateless.AircraftConfigurationSessionBeanRemote;
import ejb.session.stateless.FlightRouteSessionBeanRemote;
import ejb.session.stateless.FlightSchedulePlanSessionBeanRemote;
import ejb.session.stateless.FlightScheduleSessionBeanRemote;
import ejb.session.stateless.FlightSessionBeanRemote;
import entity.CabinClass;
import entity.Employee;
import entity.Fare;
import entity.Flight;
import entity.FlightSchedule;
import entity.FlightSchedulePlan;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
import util.enumeration.CabinClassType;
import util.enumeration.FlightScheduleType;
import util.exception.AircraftConfigurationNotFoundException;
import util.exception.DeleteFlightException;
import util.exception.DeleteFlightScheduleException;
import util.exception.DeleteFlightSchedulePlanException;
import util.exception.FareExistException;
import util.exception.FlightExistException;
import util.exception.FlightNotFoundException;
import util.exception.FlightRouteDisabledException;
import util.exception.FlightRouteNotFoundException;
import util.exception.FlightScheduleExistException;
import util.exception.FlightSchedulePlanExistException;
import util.exception.FlightSchedulePlanNotFoundException;
import util.exception.GeneralException;
import util.exception.UpdateFlightSchedulePlanException;
/**
*
* @author Administrator
*/
public class FlightOperationModule {
private FlightSessionBeanRemote flightSessionBeanRemote;
private FlightRouteSessionBeanRemote flightRouteSessionBeanRemote;
private AircraftConfigurationSessionBeanRemote aircraftConfigurationSessionBeanRemote;
private FlightScheduleSessionBeanRemote flightScheduleSessionBeanRemote;
private FlightSchedulePlanSessionBeanRemote flightSchedulePlanSessionBeanRemote;
private Employee employee;
public FlightOperationModule() {
}
public FlightOperationModule(FlightSessionBeanRemote flightSessionBeanRemote, FlightRouteSessionBeanRemote flightRouteSessionBeanRemote,
AircraftConfigurationSessionBeanRemote aircraftConfigurationSessionBeanRemote, FlightScheduleSessionBeanRemote flightScheduleSessionBeanRemote,
FlightSchedulePlanSessionBeanRemote flightSchedulePlanSessionBeanRemote, Employee employee) {
this.flightSessionBeanRemote = flightSessionBeanRemote;
this.flightRouteSessionBeanRemote = flightRouteSessionBeanRemote;
this.aircraftConfigurationSessionBeanRemote = aircraftConfigurationSessionBeanRemote;
this.flightScheduleSessionBeanRemote = flightScheduleSessionBeanRemote;
this.flightSchedulePlanSessionBeanRemote = flightSchedulePlanSessionBeanRemote;
this.employee = employee;
}
public void menuFlightOperation() {
Scanner scanner = new Scanner(System.in);
Integer response = 0;
while (true) {
System.out.println("*** FRS Management :: Flight Operation Module ***\n");
System.out.println("1: Create Flight ");
System.out.println("2: View All Flights");
System.out.println("3: View Flight Details");
System.out.println("-----------------------");
System.out.println("4: Create Flight Schedule Plan");
System.out.println("5: View All Flight Schedule Plans");
System.out.println("6: View Flight Schedule Plan Details");
System.out.println("-----------------------");
System.out.println("7: Logout\n");
response = 0;
while (response < 1 || response > 7) {
System.out.print("> ");
response = scanner.nextInt();
if (response == 1) {
doCreateNewFlight();
} else if (response == 2) {
viewAllFlights();
} else if (response == 3) {
viewFlightDetails();
} else if (response == 4) {
doCreateNewFlightSchedulePlan();
} else if (response == 5) {
doViewAllFlightSchedulePlans();
} else if (response == 6) {
viewFlightSchedulePlanDetails();
} else if (response == 7) {
break;
} else {
System.out.println("Invalid option, please try again!\n");
}
}
if (response == 7) {
break;
}
}
}
private void doCreateNewFlight() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: Create New Flight ***\n");
System.out.print("Enter Flight Number> ");
String flightNumber = scanner.nextLine().trim();
Flight newFlight = new Flight(flightNumber);
System.out.print("Enter Origin Airport IATA code> ");
String originCode = scanner.nextLine().trim();
System.out.print("Enter Destination Airport IATA code> ");
String destinationCode = scanner.nextLine().trim();
System.out.print("Enter Aircraft Configuration Name> ");
String aircraftConfigurationName = scanner.nextLine().trim();
Long newFlightId = flightSessionBeanRemote.createNewFlight(newFlight, originCode, destinationCode, aircraftConfigurationName);
System.out.println("Flight with ID: " + newFlightId + " is created!\n");
if (flightRouteSessionBeanRemote.checkIfComplementaryFlightRouteExist(originCode, destinationCode)) {
System.out.print("Create a complementary return flight? (Y/N)> ");
String createOption = scanner.nextLine().trim();
if (createOption.equals("Y")) {
System.out.print("Enter Complementary Flight Number> ");
String complementaryFlightNumber = scanner.nextLine().trim();
Flight newComplementaryFlight = new Flight(complementaryFlightNumber);
Long newComplementaryReturnFlightId = flightSessionBeanRemote.createNewFlight(newComplementaryFlight, destinationCode, originCode, aircraftConfigurationName);
flightSessionBeanRemote.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
System.out.println("Complementary Flight with ID: " + newComplementaryReturnFlightId + " is created!\n");
}
}
} catch (FlightExistException | GeneralException | FlightRouteNotFoundException | AircraftConfigurationNotFoundException | FlightRouteDisabledException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void viewAllFlights() {
System.out.println("*** FRSManagement :: Flight Operation Module :: View All Flights ***\n");
List<Flight> flights = flightSessionBeanRemote.retrieveAllFlights();
if (flights.isEmpty()) {
System.out.println("No Available Flights!\n");
}
for (Flight flight : flights) {
System.out.println(flight);
if (flight.getComplementaryReturnFlight() != null) {
System.out.println("Complementary Flight = [" + flight.getComplementaryReturnFlight() + "]");
}
}
System.out.println();
}
private void viewFlightDetails() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: View Flight Details ***\n");
System.out.print("Enter Flight Number> ");
String flightNumber = scanner.nextLine().trim();
Flight flight = flightSessionBeanRemote.retrieveFlightByFlightNumber(flightNumber);
System.out.println(flight);
System.out.println(flight.getFlightRoute());
for (CabinClass cabinClass : flight.getAircraftConfiguration().getCabinClasses()) {
System.out.println(cabinClass.getCabinClassType());
System.out.println("Available seats = " + cabinClass.getCabinClassConfiguration().getCabinClassCapacity());
}
System.out.println();
System.out.print("Update details of this flight? (Y/N)> ");
if (scanner.nextLine().trim().equals("Y")) {
updateFlight(flight);
}
System.out.print("Delete this flight? (Y/N)> ");
if (scanner.nextLine().trim().equals("Y")) {
flightSessionBeanRemote.deleteFlight(flight);
}
} catch (FlightNotFoundException | DeleteFlightException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void updateFlight(Flight flight) {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: Update Flight ***\n");
System.out.print("Enter New Aircraft Configuration Name> ");
String newAircraftConfigurationName = scanner.nextLine().trim();
try {
flightSessionBeanRemote.updateFlight(flight, newAircraftConfigurationName);
} catch (AircraftConfigurationNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void doCreateNewFlightSchedulePlan() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: Create New Flight Schedule Plan ***\n");
System.out.print("Enter Flight Number> ");
String flightNumber = scanner.nextLine().trim();
Flight flight = flightSessionBeanRemote.retrieveFlightByFlightNumber(flightNumber);
if (flight.getDisabled() == true) {
System.out.println("This flight is disabled, not able to create a schedule plan!");
}
System.out.println("Select Type of Flight Schedule Plan> ");
System.out.println("1: Single");
System.out.println("2: Multiple");
System.out.println("3: Recurrent schedule every n day");
System.out.println("4: Recurrent schedule every week");
System.out.print("> ");
Integer response = Integer.valueOf(scanner.nextLine().trim());
String departureDateString;
String departureTimeString;
DateFormat departureTimeFormat = new SimpleDateFormat("hh:mm aa");
DateFormat departureDateFormat = new SimpleDateFormat("dd MMM yy");
Date departureDate;
Date departureTime;
String durationString;
DateFormat durationFormat = new SimpleDateFormat("hh Hours mm Minute");
Date durationTime;
List<Fare> fares = new ArrayList<>();
boolean option = true;
Long firstDepartureTimeLong = Long.MIN_VALUE;
FlightSchedulePlan newFlightSchedulePlan = new FlightSchedulePlan();
Date startDateTime;
Date endDateTime;
Integer recurrence = 0;
switch (response) {
case (1):
System.out.println("*** Create Single Flight Schedule ***\n");
System.out.print("Enter Departure Date (day MONTH year) > ");
departureDateString = scanner.nextLine().trim();
departureDate = departureDateFormat.parse(departureDateString);
System.out.print("Enter Departure Time (hr:min AM/PM)> ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureTimeFormat.parse(departureTimeString);
System.out.print("Enter Flight Duration (xx Hours xx Minute)> ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
System.out.println("*** Create Single Flight Schedule :: Enter Fares ***\n");
option = true;
while (option) {
System.out.print("Enter Cabin Class Code> ");
String cabinClassCode = scanner.nextLine().trim();
System.out.print("Enter Fare Basis Code> ");
String fareBasisCode = scanner.nextLine().trim();
System.out.print("Enter Amount> $ ");
Double fareAmount = Double.valueOf(scanner.nextLine().trim());
CabinClassType cabinClassType;
if (cabinClassCode.charAt(0) == 'F') {
cabinClassType = CabinClassType.FIRSTCLASS;
} else if (cabinClassCode.charAt(0) == 'J') {
cabinClassType = CabinClassType.BUSINESSCLASS;
} else if (cabinClassCode.charAt(0) == 'W') {
cabinClassType = CabinClassType.PREMIUMECONOMYCLASS;
} else {
cabinClassType = CabinClassType.ECONOMYCLASS;
}
Fare fare = new Fare(fareBasisCode, cabinClassType, fareAmount);
fares.add(fare);
System.out.print("Continue to create more fare? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
newFlightSchedulePlan = new FlightSchedulePlan(FlightScheduleType.SINGLE, fares, departureTime.getTime()); //rmb to merge flight
newFlightSchedulePlan = flightSchedulePlanSessionBeanRemote.createNewSingleFlightSchedulePlan(newFlightSchedulePlan, flight, departureDate, departureTime, durationTime);
System.out.println("Flight Schedule Plan with ID: " + newFlightSchedulePlan.getFlightSchedulePlanId() + " is created successfully!\n");
break;
case (2):
System.out.println("*** Create Multiple Flight Schedule ***\n");
System.out.println("*** Create Single Flight Schedule :: Enter Schedules ***\n");
List<Date> departureDates = new ArrayList<>();
List<Date> departureTimes = new ArrayList<>();
List<Date> durationTimes = new ArrayList<>();
option = true;
while (option) {
System.out.print("Enter Departure Date (day MONTH year) > ");
departureDateString = scanner.nextLine().trim();
departureDate = departureDateFormat.parse(departureDateString);
System.out.print("Enter Departure Time (hr:min AM/PM) > ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureTimeFormat.parse(departureTimeString);
if (departureDates.isEmpty()) {
firstDepartureTimeLong = departureDate.getTime() + departureTime.getTime();
}
departureDates.add(departureDate);
departureTimes.add(departureTime);
System.out.print("Enter Flight Duration (xx Hours xx Minute) > ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
durationTimes.add(durationTime);
System.out.print("Continue to create more schedules? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
System.out.println("*** Create Multiple Flight Schedule :: Enter Fares ***\n");
option = true;
while (option) {
System.out.print("Enter Cabin Class Code> ");
String cabinClassCode = scanner.nextLine().trim();
System.out.print("Enter Fare Basis Code> ");
String fareBasisCode = scanner.nextLine().trim();
System.out.print("Enter Amount> $ ");
Double fareAmount = Double.valueOf(scanner.nextLine().trim());
CabinClassType cabinClassType;
if (cabinClassCode.charAt(0) == 'F') {
cabinClassType = CabinClassType.FIRSTCLASS;
} else if (cabinClassCode.charAt(0) == 'J') {
cabinClassType = CabinClassType.BUSINESSCLASS;
} else if (cabinClassCode.charAt(0) == 'W') {
cabinClassType = CabinClassType.PREMIUMECONOMYCLASS;
} else {
cabinClassType = CabinClassType.ECONOMYCLASS;
}
Fare fare = new Fare(fareBasisCode, cabinClassType, fareAmount);
fares.add(fare);
System.out.print("Continue to create more fare? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
newFlightSchedulePlan = new FlightSchedulePlan(FlightScheduleType.MULTIPLE, fares, firstDepartureTimeLong); //rmb to merge flight
newFlightSchedulePlan = flightSchedulePlanSessionBeanRemote.createNewMultipleFlightSchedulePlan(newFlightSchedulePlan, flight, departureDates, departureTimes, durationTimes);
System.out.println("Flight Schedule Plan with ID: " + newFlightSchedulePlan.getFlightSchedulePlanId() + " is created successfully!\n");
break;
case (3):
System.out.println("*** Create Recurrent by Day Schedule ***\n");
System.out.print("Recurrence by how many days> ");
recurrence = Integer.valueOf(scanner.nextLine().trim());
System.out.print("Enter Departure Time (hr:min AM/PM) > ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureTimeFormat.parse(departureTimeString);
System.out.print("Enter Flight Duration (hr:min)> ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
System.out.print("Enter Start Date (day MONTH year)> ");
String startDateString = scanner.nextLine().trim();
DateFormat startDateFormat = new SimpleDateFormat("dd MMM yy");
startDateTime = startDateFormat.parse(startDateString);
System.out.print("Enter End Date (day MONTH year))> ");
String endDateString = scanner.nextLine().trim();
DateFormat endDateFormat = new SimpleDateFormat("dd MMM yy");
endDateTime = endDateFormat.parse(endDateString);
System.out.println("*** Create Recurrent by Day Flight Schedule :: Enter Fares ***\n");
option = true;
while (option) {
System.out.print("Enter Cabin Class Code> ");
String cabinClassCode = scanner.nextLine().trim();
System.out.print("Enter Fare Basis Code> ");
String fareBasisCode = scanner.nextLine().trim();
System.out.print("Enter Amount> $ ");
Double fareAmount = Double.valueOf(scanner.nextLine().trim());
CabinClassType cabinClassType;
if (cabinClassCode.charAt(0) == 'F') {
cabinClassType = CabinClassType.FIRSTCLASS;
} else if (cabinClassCode.charAt(0) == 'J') {
cabinClassType = CabinClassType.BUSINESSCLASS;
} else if (cabinClassCode.charAt(0) == 'W') {
cabinClassType = CabinClassType.PREMIUMECONOMYCLASS;
} else {
cabinClassType = CabinClassType.ECONOMYCLASS;
}
Fare fare = new Fare(fareBasisCode, cabinClassType, fareAmount);
fares.add(fare);
System.out.print("Continue to create more fare? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
newFlightSchedulePlan = new FlightSchedulePlan(FlightScheduleType.RECURRENTBYDAY, fares, departureTime.getTime()); //rmb to merge flight
newFlightSchedulePlan = flightSchedulePlanSessionBeanRemote.createNewRecurrentFlightSchedulePlan(newFlightSchedulePlan, flight,
departureTime, durationTime, recurrence, startDateTime, endDateTime);
System.out.println("Flight Schedule Plan with ID: " + newFlightSchedulePlan.getFlightSchedulePlanId() + " is created successfully!\n");
break;
case (4):
System.out.println("*** Create Recurrent by Week Schedule ***\n");
System.out.print("Enter Recurrent Day in a week (Monday - Sunday)> ");
String dayOfWeekString = scanner.nextLine().trim();
DateFormat dayOfWeekFormat = new SimpleDateFormat("EEE");
Date dayOfWeek = dayOfWeekFormat.parse(dayOfWeekString);
System.out.print("Enter Departure Time (hr:min AM/PM) > ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureTimeFormat.parse(departureTimeString);
System.out.print("Enter Flight Duration (hr:min)> ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
System.out.print("Enter Start Date (day MONTH year)> ");
startDateString = scanner.nextLine().trim();
startDateFormat = new SimpleDateFormat("dd MMM yy");
startDateTime = startDateFormat.parse(startDateString);
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(startDateTime);
// int weekday = calendar.get(Calendar.DAY_OF_WEEK);
// int days = Calendar.WEDNESDAY - weekday;
// if (days < 0)
// {
// days += 7;
// }
// calendar.add(Calendar.DAY_OF_YEAR, days);
// System.out.println(sdf.format(calendar.getTime()));
System.out.print("Enter End Date (day MONTH year))> ");
endDateString = scanner.nextLine().trim();
endDateFormat = new SimpleDateFormat("dd MMM yy");
endDateTime = endDateFormat.parse(endDateString);
System.out.println("*** Create Recurrent by Week Flight Schedule :: Enter Fares ***\n");
option = true;
while (option) {
System.out.print("Enter Cabin Class Code> ");
String cabinClassCode = scanner.nextLine().trim();
System.out.print("Enter Fare Basis Code> ");
String fareBasisCode = scanner.nextLine().trim();
System.out.print("Enter Amount> $ ");
Double fareAmount = Double.valueOf(scanner.nextLine().trim());
CabinClassType cabinClassType;
if (cabinClassCode.charAt(0) == 'F') {
cabinClassType = CabinClassType.FIRSTCLASS;
} else if (cabinClassCode.charAt(0) == 'J') {
cabinClassType = CabinClassType.BUSINESSCLASS;
} else if (cabinClassCode.charAt(0) == 'W') {
cabinClassType = CabinClassType.PREMIUMECONOMYCLASS;
} else {
cabinClassType = CabinClassType.ECONOMYCLASS;
}
Fare fare = new Fare(fareBasisCode, cabinClassType, fareAmount);
fares.add(fare);
System.out.print("Continue to create more fare? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
recurrence = 7;
newFlightSchedulePlan = new FlightSchedulePlan(FlightScheduleType.RECURRENTBYDAY, fares, departureTime.getTime()); //rmb to merge flight
newFlightSchedulePlan = flightSchedulePlanSessionBeanRemote.createNewRecurrentFlightSchedulePlan(newFlightSchedulePlan, flight,
departureTime, durationTime, 7, startDateTime, endDateTime);
System.out.println("Flight Schedule Plan with ID: " + newFlightSchedulePlan.getFlightSchedulePlanId() + " is created successfully!\n");
break;
default:
break;
}
//complementary flight schedule plan
if (flight.getComplementaryReturnFlight() != null) {
System.out.print("Create a complementary return flight schedule plan? (Y/N)> ");
if (scanner.nextLine().trim().equals("Y")) {
System.out.print("Enter Layover Duration (hr:min)> ");
String layoverDurationString = scanner.nextLine().trim();
durationFormat = new SimpleDateFormat("hr:min");
Date layoverDurationTime = durationFormat.parse(layoverDurationString);
Long returnFLightSchedulePlanId = flightSchedulePlanSessionBeanRemote.createReturnFlightSchedulePlan(newFlightSchedulePlan, flight, layoverDurationTime);
System.out.println("Return Flight Schedule Plan with ID: " + returnFLightSchedulePlanId + " is created successfully!\n");
}
}
} catch (FlightNotFoundException | ParseException | FlightSchedulePlanExistException | GeneralException | FlightScheduleExistException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void doViewAllFlightSchedulePlans() {
System.out.println("*** FRSManagement :: Flight Operation Module :: View All Flight Schedule Plans ***\n");
List<FlightSchedulePlan> flightSchedulePlans = flightSchedulePlanSessionBeanRemote.retrieveAllFlightSchedulePlans();
if (flightSchedulePlans.isEmpty()) {
System.out.println("No Available Flight Schedule Plans!\n");
} else {
for (FlightSchedulePlan flightSchedulePlan : flightSchedulePlans) {
System.out.println(flightSchedulePlan);
if (flightSchedulePlan.getComplementaryReturnSchedulePlan() != null) {
System.out.println("Complementary return schedule plan [ " + flightSchedulePlan.getComplementaryReturnSchedulePlan() + " ]");
}
}
System.out.println();
}
}
private void viewFlightSchedulePlanDetails() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: View Flight Schedule Plan Details ***\n");
System.out.print("Enter Flight Number of the Flight Schedule Plan> ");
String flightNumber = scanner.nextLine().trim();
List<FlightSchedulePlan> flightSchedulePlans = flightSchedulePlanSessionBeanRemote.retrieveFlightSchedulePlansByFlightNumber(flightNumber);
Integer selection = 1;
for (FlightSchedulePlan flightSchedulePlan : flightSchedulePlans) {
System.out.println("No." + selection + " " + flightSchedulePlan);
selection++;
}
System.out.print("Enter no. to view details> ");
Integer userSelection = Integer.valueOf(scanner.nextLine().trim());
FlightSchedulePlan flightSchedulePlanSelected = flightSchedulePlans.get(userSelection - 1);
System.out.println("\nFlight O-D pair=[" + flightSchedulePlanSelected.getFlight() + "]");
System.out.println("Flight schedule: ");
for (FlightSchedule flightSchedule : flightSchedulePlanSelected.getFlightSchedules()) {
System.out.println("\t" + flightSchedule);
}
System.out.println("Fare: ");
for (Fare fare : flightSchedulePlanSelected.getFares()) {
System.out.println("\t" + fare);
}
System.out.print("Update details of this flight schedule plan? (Y/N)> ");
if (scanner.nextLine().trim().equals("Y")) {
updateFlightSchedulePlan(flightSchedulePlanSelected);
}
System.out.print("Delete this flight schedule plan? (Y/N)> ");
if (scanner.nextLine().trim().equals("Y")) {
flightSchedulePlanSessionBeanRemote.deleteFlightSchedulePlan(flightSchedulePlanSelected);
System.out.println("Flight Schedule Plan deleted Successfully!");
}
} catch (FlightSchedulePlanNotFoundException | DeleteFlightScheduleException | ParseException | FlightScheduleExistException
| GeneralException | FareExistException | FlightNotFoundException | DeleteFlightSchedulePlanException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void updateFlightSchedulePlan(FlightSchedulePlan flightSchedulePlanSelected) throws DeleteFlightScheduleException, ParseException,
FlightScheduleExistException, GeneralException, FareExistException, FlightNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.println("*** FRSManagement :: Flight Operation Module :: Update Flight Schedule Plan ***\n");
System.out.print("Enter New Flight Number> ");
String flightNumber = scanner.nextLine().trim();
Flight flight = flightSessionBeanRemote.retrieveFlightByFlightNumber(flightNumber);
List<Fare> fares = new ArrayList<>();
System.out.println("Select Type of Flight Schedule Plan> ");
System.out.println("1: Update Fares");
System.out.println("2: Update Flight Schedules");
System.out.print("> ");
Integer response = Integer.valueOf(scanner.nextLine().trim());
if (response == 1) {
System.out.println("*** FRSManagement :: Flight Operation Module :: Update Flight Schedule Plan :: Update Fares***\n");
boolean option = true;
while (option) {
System.out.print("Enter Cabin Class Code> ");
String cabinClassCode = scanner.nextLine().trim();
System.out.print("Enter Fare Basis Code> ");
String fareBasisCode = scanner.nextLine().trim();
System.out.print("Enter Amount> $ ");
Double fareAmount = Double.valueOf(scanner.nextLine().trim());
CabinClassType cabinClassType;
if (cabinClassCode.charAt(0) == 'F') {
cabinClassType = CabinClassType.FIRSTCLASS;
} else if (cabinClassCode.charAt(0) == 'J') {
cabinClassType = CabinClassType.BUSINESSCLASS;
} else if (cabinClassCode.charAt(0) == 'W') {
cabinClassType = CabinClassType.PREMIUMECONOMYCLASS;
} else {
cabinClassType = CabinClassType.ECONOMYCLASS;
}
Fare fare = new Fare(fareBasisCode, cabinClassType, fareAmount);
fares.add(fare);
System.out.print("Continue to create more fare? (Y/N)> ");
String optionString = scanner.nextLine().trim();
if (optionString.charAt(0) == 'N') {
option = false;
}
}
} else if (response == 2) {
System.out.println("*** FRSManagement :: Flight Operation Module :: Update Flight Schedule Plan :: Update Flight Schedules***\n");
String departureDateString;
String departureTimeString;
DateFormat departureTimeFormat = new SimpleDateFormat("hh:mm aa");
DateFormat departureDateFormat = new SimpleDateFormat("dd MMM yy");
Date departureDate;
Date departureTime;
String durationString;
DateFormat durationFormat = new SimpleDateFormat("hh Hours mm Minute");
Date durationTime;
boolean option = true;
Long firstDepartureTimeLong = Long.MIN_VALUE;
FlightSchedulePlan newFlightSchedulePlan = new FlightSchedulePlan();
Date endDateTime;
Integer recurrence = 0;
if (flightSchedulePlanSelected.getFlightScheduleType().equals(FlightScheduleType.SINGLE)) {
try {
System.out.println("*** Update Single Flight Schedule ***\n");
System.out.print("Enter New Departure Date > ");
departureDateString = scanner.nextLine().trim();
departureDate = departureTimeFormat.parse(departureDateString);
System.out.print("Enter New Departure Time > ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureDateFormat.parse(departureTimeString);
System.out.print("Enter Flight Duration (hr:min)> ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
flightSchedulePlanSessionBeanRemote.updateSingleFlightSchedule(flightSchedulePlanSelected,
flightSchedulePlanSelected.getFlightSchedules().get(0), departureDate, departureTime, durationTime);
System.out.println("Flight Schedule Plan with ID: " + flightSchedulePlanSelected.getFlightSchedulePlanId() + " is created successfully!\n");
} catch (UpdateFlightSchedulePlanException ex) {
System.out.println("Error: " + ex.getMessage());
}
} else if (flightSchedulePlanSelected.getFlightScheduleType().equals(FlightScheduleType.MULTIPLE)) {
try {
System.out.println("*** Update Multiple Flight Schedule ***\n");
System.out.println("*** Current Flight schedules Under The Plan ***\n");
Integer selection = 1;
for (FlightSchedule flightSchedule : flightSchedulePlanSelected.getFlightSchedules()) {
System.out.println("No." + selection + " " + flightSchedule);
selection++;
}
System.out.print("Enter no. to update the flight schedule> ");
Integer userSelection = Integer.valueOf(scanner.nextLine().trim());
FlightSchedule flightScheduleSelected = flightSchedulePlanSelected.getFlightSchedules().get(userSelection - 1);
System.out.print("Enter New Departure Date > ");
departureDateString = scanner.nextLine().trim();
departureDate = departureTimeFormat.parse(departureDateString);
System.out.print("Enter New Departure Time > ");
departureTimeString = scanner.nextLine().trim();
departureTime = departureDateFormat.parse(departureTimeString);
System.out.print("Enter Flight Duration (hr:min)> ");
durationString = scanner.nextLine().trim();
durationTime = durationFormat.parse(durationString);
flightSchedulePlanSessionBeanRemote.updateSingleFlightSchedule(flightSchedulePlanSelected, flightScheduleSelected, departureDate, departureTime, durationTime);
System.out.println("Flight Schedule Plan with ID: " + flightSchedulePlanSelected.getFlightSchedulePlanId() + " is created successfully!\n");
} catch (UpdateFlightSchedulePlanException ex) {
System.out.println("Error: " + ex.getMessage());
}
} else if (flightSchedulePlanSelected.getFlightScheduleType().equals(FlightScheduleType.RECURRENTBYDAY)) {
try {
System.out.print("Recurrence by how many days> ");
recurrence = Integer.valueOf(scanner.nextLine().trim());
System.out.print("Enter End Date (day MONTH year))> ");
String endDateString = scanner.nextLine().trim();
DateFormat endDateFormat = new SimpleDateFormat("dd MMM yy");
endDateTime = endDateFormat.parse(endDateString);
flightSchedulePlanSessionBeanRemote.updateRecurrentDayFlightSchedule(flightSchedulePlanSelected, recurrence, endDateTime);
System.out.println("Flight Schedule Plan with ID: " + flightSchedulePlanSelected.getFlightSchedulePlanId() + " is created successfully!\n");
} catch (UpdateFlightSchedulePlanException ex) {
System.out.println("Error: " + ex.getMessage());
}
} else if (flightSchedulePlanSelected.getFlightScheduleType().equals(FlightScheduleType.RECURRENTBYWEEK)) {
try {
System.out.print("Enter End Date (day MONTH year))> ");
String endDateString = scanner.nextLine().trim();
DateFormat endDateFormat = new SimpleDateFormat("dd MMM yy");
endDateTime = endDateFormat.parse(endDateString);
flightSchedulePlanSessionBeanRemote.updateRecurrentWeekFlightSchedule(flightSchedulePlanSelected, endDateTime);
System.out.println("Flight Schedule Plan with ID: " + flightSchedulePlanSelected.getFlightSchedulePlanId() + " is created successfully!\n");
} catch (UpdateFlightSchedulePlanException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
}
}
}
|
import java.util.Arrays;
//Given an array of integers, every element appears twice except for one.
//Find that single one.
public class Solution {
public static int singleNumber(int[] A){
int x = 0;
for(int i = 0; i < A.length; i++){
x ^= A[i];
}
return x;
}
public static int singleNumber2(int[] A){
//sort the array
Arrays.sort(A);
//for(int i = 0; i < A.length; i++){
//System.out.println(A[i]);
//}
for(int i = 0; i < A.length - 1; ) {
if(A[i] != A[i+1]) {
return A[i];
}
i = i + 2;
}
return A[A.length - 1];
}
public static void main(String[] args){
int[] a = {
2, 1, 3, 1, 5, 4, 3, 4, 5
};
System.out.println("singleNumber:" + singleNumber(a));
System.out.println("singleNumber2:" + singleNumber2(a));
}
}
|
package machine;
import org.junit.Before;
import org.junit.Test;
public class GameMachineTest {
Table table;
GameAgainstMachine game;
// A - Ally
// E - Enemy
// O - Test
//
// ___________________
// |\|0|1|2|3|4|5|6|7|
// |0|_|_|K|_|_|_|_|_|
// |1|_|_|_|_|_|_|_|_|
// |2|_|_|_|_|_|_|R|_|
// |3|_|_|_|_|_|_|_|_|
// |4|_|_|_|_|B|_|_|_|
// |5|_|_|_|_|_|_|_|_|
// |6|_|_|_|_|_|_|_|_|
// |7|_|_|_|_|_|_|_|_|
@Before
public void setUp() {
game = new GameAgainstMachine();
table = game.table;
clearTable(table);
}
@Test
public void attemptTest() {
TestWriter.writeTestTitle("Attempt Test");
table.placePiece(new Piece(PieceKind.BISHOP, Color.WHITE), 4, 4);
table.placePiece(new Piece(PieceKind.KNIGHT, Color.BLACK), 0, 2);
table.placePiece(new Piece(PieceKind.ROOK, Color.BLACK), 2, 6);
TestWriter.writeTable(table);
int[] bestMove = new int[4];
double state = GameAgainstMachine.findBestMove(2, bestMove, table);
TestWriter.writeString("best move: " + " [" + bestMove[0] + ", " + bestMove[1] + "] -> [" + bestMove[2] + ", " + bestMove[3] + "]");
TestWriter.writeString("\tvalue: " + state);
TestWriter.writeString(game.table.whoTurns + " turns");
}
// ___________________
// |\|0|1|2|3|4|5|6|7|
// |0|_|_|_|_|_|_|_|_|
// |1|_|_|_|_|_|_|_|_|
// |2|_|K|_|_|_|P|_|_|
// |3|_|_|_|_|_|_|R|_|
// |4|_|_|_|_|_|_|_|_|
// |5|_|_|_|_|Q|_|_|_|
// |6|_|_|_|_|_|_|_|_|
// |7|_|_|_|_|_|_|_|_|
@Test
public void makeMoveTest1() {
TestWriter.writeTestTitle("Make Move Test");
table.placePiece(new Piece(PieceKind.QUEEN, Color.WHITE), 5, 4);
table.placePiece(new Piece(PieceKind.KNIGHT, Color.BLACK), 2, 1);
table.placePiece(new Piece(PieceKind.ROOK, Color.BLACK), 3, 6);
table.placePiece(new Piece(PieceKind.PAWN, Color.BLACK), 2, 5);
TestWriter.writeString("before making a move:");
TestWriter.writeTable(table);
game.makeMove(1);
TestWriter.writeString("after making a move:");
TestWriter.writeTable(table);
}
// ___________________
// |\|0|1|2|3|4|5|6|7|
// |0|_|_|_|_|_|_|_|_|
// |1|_|_|_|_|_|_|_|_|
// |2|_|B|_|_|_|P|_|_|
// |3|_|_|_|_|_|_|R|_|
// |4|_|_|_|_|_|_|_|_|
// |5|_|_|_|_|Q|_|_|_|
// |6|_|_|_|_|_|_|_|_|
// |7|_|_|_|_|_|_|_|_|
@Test
public void makeMoveTest2() {
TestWriter.writeTestTitle("Make Move Test 2");
table.placePiece(new Piece(PieceKind.QUEEN, Color.WHITE), 5, 4);
table.placePiece(new Piece(PieceKind.BISHOP, Color.BLACK), 2, 1);
table.placePiece(new Piece(PieceKind.ROOK, Color.BLACK), 3, 6);
table.placePiece(new Piece(PieceKind.PAWN, Color.BLACK), 2, 5);
TestWriter.writeString("before making a move:");
TestWriter.writeTable(table);
game.makeMove(2);
TestWriter.writeString("after making a move:");
TestWriter.writeTable(table);
}
private void clearTable(Table table) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
table.fields[i][j] = null;
}
}
}
}
|
package com.example.demo_boot.dao;
import java.io.Serializable;
public class ExtendedRepositoryImpl<T, ID extends Serializable>
{
/* extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {
private EntityManager entityManager;
public ExtendedRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}*/
}
|
package org.fuserleer.ledger.messages;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import org.fuserleer.crypto.Hash;
import org.fuserleer.network.messaging.Message;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.DsonOutput.Output;
import org.fuserleer.utils.Numbers;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public abstract class InventoryMessage extends Message
{
public final static int MAX_INVENTORY = 64;
@JsonProperty("inventory")
@DsonOutput(Output.ALL)
@JsonDeserialize(as=LinkedHashSet.class)
private Set<Hash> inventory;
InventoryMessage()
{
super();
}
InventoryMessage(final Collection<Hash> inventory)
{
super();
Objects.requireNonNull(inventory, "Inventory is null");
Numbers.greaterThan(inventory.size(), InventoryMessage.MAX_INVENTORY, "Too many inventory items");
if (inventory.isEmpty() == true)
throw new IllegalArgumentException("Inventory is empty");
this.inventory = new LinkedHashSet<Hash>(inventory);
}
public Set<Hash> getInventory()
{
if (this.inventory == null)
return Collections.emptySet();
return Collections.unmodifiableSet(this.inventory);
}
}
|
package com.pay.database.mybatis.config;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
@Repository
public interface BaseMapper<T> extends Mapper<T>,MySqlMapper<T> {
}
|
package com.cnk.travelogix.core.livesupporti.facade.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.cnk.travelogix.core.livesupporti.client.BannedVisitorRestClient;
import com.cnk.travelogix.core.livesupporti.client.dto.BannedVisitor;
import com.cnk.travelogix.core.livesupporti.client.dto.BannedVisitors;
import com.cnk.travelogix.core.livesupporti.facade.BannedVisitorsFacade;
public class BannedVisitorsFacadeImpl implements BannedVisitorsFacade {
private static final Logger LOG = LoggerFactory
.getLogger(BannedVisitorsFacadeImpl.class);
@Autowired
private BannedVisitorRestClient bannedVisitorRestClient;
@Override
public BannedVisitors getAllBannedVisitors(String page) {
BannedVisitors bannedVisitors = new BannedVisitors();
try {
bannedVisitors = bannedVisitorRestClient.getAllBannedVisitors(page);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return bannedVisitors;
}
@Override
public BannedVisitor getBannedVisitorById(int bannedVisitorId) {
BannedVisitor bannedVisitor = new BannedVisitor();
try {
bannedVisitor = bannedVisitorRestClient.getBannedVisitorById(bannedVisitorId);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return bannedVisitor;
}
@Override
public List<String> getBannedIPAddresses() {
List<String> response = null;
try {
response = bannedVisitorRestClient.getBannedIPAddresses();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return response;
}
@Override
public BannedVisitor createBannedVisitor(BannedVisitor bannedVisitor) {
BannedVisitor response = null;
try {
response = bannedVisitorRestClient
.createBannedVisitor(bannedVisitor);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return response;
}
@Override
public void deleteBannedVisitor(int bannedVisitorId) {
try {
bannedVisitorRestClient.deleteBannedVisitor(bannedVisitorId);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public BannedVisitorRestClient getBannedVisitorRestClient() {
return bannedVisitorRestClient;
}
public void setBannedVisitorRestClient(
BannedVisitorRestClient bannedVisitorRestClient) {
this.bannedVisitorRestClient = bannedVisitorRestClient;
}
}
|
package code._3_in_class;
public class Main{
public static void main(String[] args){
//primitive:
//numere
//caractere
//boolean
//referinte/obiecte
//este o colectie/grup/gramada de primitive
Masina m=new Masina();
m.start();
m.steer();
m.stop();
Date d=m.getDataFabricatie();
d.setYear(1800);
}
}
|
package hirondelle.web4j;
import hirondelle.web4j.security.SafeText;
import hirondelle.web4j.model.ModelCtorException;
import hirondelle.web4j.readconfig.ConfigReader;
import java.util.*;
import java.lang.reflect.*;
import java.util.logging.*;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.model.ConvertParam;
import hirondelle.web4j.BuildImpl;
/**
Scan Model Objects for Cross-Site Scripting vulnerabilities, and use of unsupported base objects.
<P>Here, 'base object' refers to <tt>Integer</tt>, <tt>Date</tt>,
and so on -- the basic building blocks passed to a Model Object constructor.
<P>Model Objects are defined as public concrete classes having a constructor that throws
{@link hirondelle.web4j.model.ModelCtorException}.
<P>The checks performed by this class are :
<ul>
<li>any <tt>public</tt> <tt>getXXX</tt> methods that return a <tt>String</tt> are identified as
Cross-Site Scripting vulnerabilities. Model Objects that return text in general should use {@link SafeText} instead
of {@link String}.
<li>any constructors taking an argument whose class is not supported according to
{@link hirondelle.web4j.model.ConvertParam#isSupported(Class)} are identified as errors.
</ul>
<P>When one of these checks fails, the incident is logged as a warning.
*/
final class CheckModelObjects {
/** Performs checks on all Model Objects. */
void performChecks(){
fLogger.config("Performing checks on Model Objects for Cross-Site Scripting vulnerabilities and unsupported constructor arguments.");
Set<Class> allClasses = ConfigReader.fetchConcreteClasses();
for (Class implClass: allClasses){
if ( isPublicModelObject(implClass) ){
scanForMethodsReturningString(implClass);
scanForUnsupportedCtorArgs(implClass);
}
}
logResults();
}
// PRIVATE //
private final ConvertParam fConvertParam = BuildImpl.forConvertParam();
private static final Logger fLogger = Util.getLogger(CheckModelObjects.class);
private int fCountXSS;
private int fCountUnsupportedCtorArg;
private boolean isPublicModelObject(Class aConcreteClass){
boolean result = false;
if ( isPublic(aConcreteClass) ) {
Constructor[] ctors = aConcreteClass.getDeclaredConstructors();
for (Constructor ctor : ctors){
List<Class> exceptionClasses = Arrays.asList(ctor.getExceptionTypes());
if (exceptionClasses.contains(ModelCtorException.class)) {
result = true;
break;
}
}
}
return result;
}
private boolean isPublic(Class aClass){
return Modifier.isPublic(aClass.getModifiers());
}
private boolean isPublic(Method aMethod){
return Modifier.isPublic(aMethod.getModifiers());
}
private void scanForMethodsReturningString(Class aModelObject){
Method[] methods = aModelObject.getDeclaredMethods();
for(Method method : methods){
if( isVulnerableMethod(method) ) {
fLogger.warning("Public Model Object named " + aModelObject.getName() + " has a public method named " + Util.quote(method.getName()) + " that returns a String. Should it return SafeText instead? Possible vulnerability to Cross-Site Scripting attack.");
fCountXSS++;
}
}
}
private boolean isVulnerableMethod(Method aMethod){
return isPublic(aMethod) && aMethod.getName().startsWith("get") && aMethod.getReturnType().equals(String.class);
}
private void scanForUnsupportedCtorArgs(Class aClass){
Constructor[] ctors = aClass.getDeclaredConstructors();
for (Constructor ctor : ctors){
List<Class> argClasses = Arrays.asList(ctor.getParameterTypes());
for(Class argClass: argClasses){
if( ! fConvertParam.isSupported(argClass) ){
fLogger.warning("Model Object: " + aClass + ". Constructor has argument not supported by ConvertParam: " + argClass);
fCountUnsupportedCtorArg++;
}
}
}
}
private void logResults(){
if(fCountXSS == 0){
fLogger.config("** SUCCESS *** : Scanned Model Objects for Cross-Site Scripting vulnerabilities. Found 0 incidents.");
}
else {
fLogger.warning("Scanned Model Objects for Cross-Site Scripting vulnerabilities. Found " + fCountXSS + " incident(s).");
}
if( fCountUnsupportedCtorArg == 0 ) {
fLogger.config("** SUCCESS *** : Scanned Model Objects for unsupported constructor arguments. Found 0 incidents.");
}
else {
fLogger.warning("Scanned Model Objects for unsupported constructor arguments. Found " + fCountUnsupportedCtorArg + " incident(s).");
}
}
}
|
package com.paytechnologies.cloudacar;
import java.util.ArrayList;
import java.util.HashMap;
import com.paytechnologies.DTO.NavDrawerItems;
import com.paytechnologies.cloudacar.AsynTask.InboxTask;
import com.paytechnologies.cloudacar.adapters.AdapterListForNavGrid;
import com.paytechnologies.cloudacar.interfaces.INavigationHandler;
import com.paytechnologies.cloudacar.parsetask.Message;
import com.paytechnologies.util.Constants;
import com.paytechnologies.util.FontFactory;
import com.paytechnologies.util.NavigationDrawerSetup;
import com.paytechnologies.util.SessionManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
@SuppressLint("NewApi")
public class TripPendingRequest extends Activity implements OnClickListener,
INavigationHandler {
private String TAG = "TripPendingRequest";
ListView listPendingRequest;
SessionManager session;
String[] msglist;
public static ArrayList<Message> msgArrAll = new ArrayList<Message>();
PendingRequestAdapter pra;
// private ListView mDrawerList;
// private DrawerLayout mDrawer;
// private CustomActionBarDrawerToggle mDrawerToggle;
// private String[] menuItems;
private GridView mDrawerList;
private DrawerLayout mDrawer;
private NavigationDrawerSetup navDrawerSetup;
private TextView txtPayout, txtTrip, txtHowItWorks, txtHeaderName;
private ImageView imgHeaderName;
private LinearLayout linearDrawerLayout;
public void linearHeaderLayoutOnClickListener (View v) {
Log.d (TAG, "##### linearHeaderLayoutOnClickListener called...");
return;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listpendingrequest);
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String userId = user.get(SessionManager.KEY_USERID);
// getActionBar().setDisplayHomeAsUpEnabled(true);
// getActionBar().setHomeButtonEnabled(true);
// mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
// // set a custom shadow that overlays the main content when the drawer
// // opens
// mDrawer.setDrawerShadow(R.drawable.drawer_shadow,
// GravityCompat.START);
// _initMenu();
// mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
// mDrawer.setDrawerListener(mDrawerToggle);
listPendingRequest = (ListView) findViewById(R.id.listViewTripPendingRequest);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
linearDrawerLayout = (LinearLayout) findViewById(R.id.main_drawer_linear);
mDrawerList = (GridView) findViewById(R.id.main_lst_leftdrawer);
txtHeaderName = (TextView) findViewById(R.id.main_txt_gridheader);
txtHeaderName.setTypeface(FontFactory.getRobotoCondensedBold(this));
imgHeaderName = (ImageView) findViewById(R.id.drawergridheader_img_user);
txtPayout = (TextView) findViewById(R.id.main_txtpayout);
txtPayout.setOnClickListener(this);
txtPayout.setTypeface(FontFactory.getRobotoCondensedBold(this));
txtTrip = (TextView) findViewById(R.id.main_txttrips);
txtTrip.setOnClickListener(this);
txtTrip.setTypeface(FontFactory.getRobotoCondensedBold(this));
txtHowItWorks = (TextView) findViewById(R.id.main_txthowitworks);
txtHowItWorks.setOnClickListener(this);
txtHowItWorks.setTypeface(FontFactory.getRobotoCondensedBold(this));
navDrawerSetup = new NavigationDrawerSetup(this, getActionBar(),
mDrawerList, mDrawer, getResources()
.getString(R.string.Inbox),linearDrawerLayout,txtHeaderName,imgHeaderName);
navDrawerSetup.setNavigationHandler(this);
navDrawerSetup.InitializeDrawer();
// if (subscribed.equalsIgnoreCase("true")) {
navDrawerSetup.setIntentExtra("bookTrip");
// }
navDrawerSetup.setCurrentCategoryAndPosition(Constants.CATEGORY_TRIPS,
3);
txtTrip.performClick();
AdapterListForNavGrid adapter = (AdapterListForNavGrid) mDrawerList
.getAdapter();
((NavDrawerItems) adapter.getItem(3)).setSelected(true);
adapter.notifyDataSetChanged();
new InboxTask(TripPendingRequest.this).execute(userId);
}
// private void _initMenu() {
// // TODO Auto-generated method stub
//
// NsMenuAdapter mAdapter = new NsMenuAdapter(this);
//
// mAdapter.addProfile(R.string.ns_menu_main_header_Profile);
//
// // ------------------------------------ Add Header list1
// ------------------------------------------------------------------
// mAdapter.addHeader(R.string.ns_menu_main_header_Payout);
// // mAdapter.addItem(R.drawable.secured);
//
// // Add first block
// menuItems = getResources().getStringArray(
// R.array.ns_menu_items_one);
// String[] menuItemsIcon = getResources().getStringArray(
// R.array.ns_menu_items_icon_one);
//
// int res = 0;
// for (String item : menuItems) {
//
// int id_title = getResources().getIdentifier(item, "string",
// this.getPackageName());
// int id_icon = getResources().getIdentifier(menuItemsIcon[res],
// "drawable", this.getPackageName());
//
// NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon);
//
// mAdapter.addItem(mItem);
// res++;
// }
// //--------------------------------------------------- next header
// -----------------------------------------------------------------
// mAdapter.addHeader(R.string.ns_menu_main_header_trips);
//
// menuItems = getResources().getStringArray(
// R.array.ns_menu_items_two);
//
// String[] menuItemsIcon1 = getResources().getStringArray(
// R.array.ns_menu_items_icon_two);
//
// int res1=0;
// for (String item : menuItems) {
//
// int id_title = getResources().getIdentifier(item, "string",
// this.getPackageName());
// int id_icon = getResources().getIdentifier(menuItemsIcon1[res1],
// "drawable", this.getPackageName());
// Log.d("id icomn", ""+id_icon);
//
// NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon);
// mAdapter.addItem(mItem);
// res1++;
// }
//
// //--------------------------------------------------- next header
// -----------------------------------------------------------------
// mAdapter.addHeader(R.string.ns_menu_main_header_cac);
//
// menuItems = getResources().getStringArray(
// R.array.ns_menu_items_three);
//
// String[] menuItemsIcon2= getResources().getStringArray(
// R.array.ns_menu_items_icon_three);
//
// int res3=0;
// for (String item : menuItems) {
//
// int id_title = getResources().getIdentifier(item, "string",
// this.getPackageName());
// int id_icon = getResources().getIdentifier(menuItemsIcon2[res3],
// "drawable", this.getPackageName());
// Log.d("id icomn", ""+id_icon);
//
// NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon);
// mAdapter.addItem(mItem);
// res3++;
// }
//
// mDrawerList = (ListView) findViewById(R.id.drawer);
// if (mDrawerList != null)
// mDrawerList.setAdapter(mAdapter);
//
// mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// }
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
navDrawerSetup.getDrawerToggle().syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
navDrawerSetup.getDrawerToggle().onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (navDrawerSetup.getDrawerToggle().onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
// private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
//
// public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout
// mDrawerLayout){
// super(
// mActivity,
// mDrawerLayout,
// R.drawable.ic_drawer,
// R.string.ns_menu_open,
// R.string.ns_menu_close);
// }
//
// @Override
// public void onDrawerClosed(View view) {
// getActionBar().setTitle(getString(R.string.Inbox));
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
// }
//
// @Override
// public void onDrawerOpened(View drawerView) {
// getActionBar().setTitle(getString(R.string.Inbox));
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
// }
// }
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
if (position == 0) {
Intent myPlans = new Intent(TripPendingRequest.this,
UploadPic.class);
startActivity(myPlans);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 2) {
Intent myPlans = new Intent(TripPendingRequest.this,
NewModifiedCacPlans.class);
startActivity(myPlans);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 3) {
Intent myPlans = new Intent(TripPendingRequest.this,
MyPlan.class);
startActivity(myPlans);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 6) {
Intent inbox = new Intent(TripPendingRequest.this,
ManageTrip.class);
startActivity(inbox);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 7) {
Intent booktrip = new Intent(TripPendingRequest.this,
BookTrip.class);
startActivity(booktrip);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 8) {
TextView tv = (TextView) mDrawerList.getChildAt(9)
.findViewById(R.id.menurow_title);
tv.setTextColor(getResources().getColor(R.color.Blue));
}
if (position == 9) {
Intent liveListTrack = new Intent(TripPendingRequest.this,
LiveTripUsersList.class);
startActivity(liveListTrack);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 10) {
Intent liveListChat = new Intent(TripPendingRequest.this,
DashBoard.class);
startActivity(liveListChat);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 5) {
Intent tripsDashBoard = new Intent(TripPendingRequest.this,
TripsDashboard.class);
startActivity(tripsDashBoard);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 12) {
Intent howItWorks = new Intent(TripPendingRequest.this,
MyTestActivity.class);
howItWorks.putExtra("fromIntent", "bookTrip");
startActivity(howItWorks);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 13) {
Intent callTobook = new Intent(TripPendingRequest.this,
CallToBook.class);
callTobook.putExtra("fromIntent", "bookTrip");
startActivity(callTobook);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 16) {
String mailTo = "info@cloudacar.com";
Intent email_intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts("mailto", mailTo, null));
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"CAC Comments");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(email_intent,
"Send email..."));
}
if (position == 14) {
Intent benifits = new Intent(TripPendingRequest.this,
Benifits.class);
benifits.putExtra("fromIntent", "bookTrip");
startActivity(benifits);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 15) {
Intent features = new Intent(TripPendingRequest.this,
Features.class);
features.putExtra("fromIntent", "bookTrip");
startActivity(features);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
if (position == 17) {
Intent logOut = new Intent(TripPendingRequest.this,
LogOut.class);
startActivity(logOut);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
mDrawer.closeDrawer(mDrawerList);
}
}
@Override
public void InvalidateMenu() {
// TODO Auto-generated method stub
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtHowItWorks.setTextColor(Color.parseColor("#a7a9ac"));
txtPayout.setTextColor(Color.parseColor("#a7a9ac"));
txtTrip.setTextColor(Color.parseColor("#a7a9ac"));
switch (v.getId()) {
case R.id.main_txtpayout:
navDrawerSetup.LoadPayout();
txtHowItWorks.setTextColor(Color.parseColor("#a7a9ac"));
txtTrip.setTextColor(Color.parseColor("#a7a9ac"));
((TextView) v).setTextColor(Color.parseColor("#0399cd"));
break;
case R.id.main_txttrips:
navDrawerSetup.LoadTrips();
txtHowItWorks.setTextColor(Color.parseColor("#a7a9ac"));
txtPayout.setTextColor(Color.parseColor("#a7a9ac"));
((TextView) v).setTextColor(Color.parseColor("#0399cd"));
break;
case R.id.main_txthowitworks:
navDrawerSetup.LoadHowItWorks();
AdapterListForNavGrid adapter = (AdapterListForNavGrid) mDrawerList
.getAdapter();
NavDrawerItems item = ((NavDrawerItems) adapter.getItem(5));
// ((NavDrawerItems) adapter.getItem(1)).setSelected(true);
item.setItemName(getString(R.string.logout));
item.setIcon(R.drawable.signout);
item.setSelectedIcon(R.drawable.signout_selected);
item.setPressesIcon(R.drawable.signout_selected);
item.setSelected(false);
adapter.notifyDataSetChanged();
txtPayout.setTextColor(Color.parseColor("#a7a9ac"));
txtTrip.setTextColor(Color.parseColor("#a7a9ac"));
((TextView) v).setTextColor(Color.parseColor("#0399cd"));
break;
}
}
}
|
package razerdp.basepopup;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import java.lang.ref.WeakReference;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import razerdp.widget.QuickPopup;
/**
* Created by 大灯泡 on 2018/8/23.
* <p>
* 快速建立Popup的builder
*/
public class QuickPopupBuilder implements LifecycleObserver {
private QuickPopupConfig mConfig;
private WeakReference<Object> ownerAnchorParent;
private int width = 0;
private int height = 0;
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy() {
ownerAnchorParent = null;
}
private QuickPopupBuilder(Object obj) {
ownerAnchorParent = new WeakReference<>(obj);
mConfig = QuickPopupConfig.generateDefault();
Activity activity = BasePopupHelper.findActivity(obj, false);
if (activity instanceof LifecycleOwner) {
((LifecycleOwner) activity).getLifecycle().addObserver(this);
} else {
if (activity != null) {
activity.getWindow().getDecorView().addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
}
@Override
public void onViewDetachedFromWindow(View v) {
v.removeOnAttachStateChangeListener(this);
onDestroy();
}
});
}
}
}
public static QuickPopupBuilder with(Context context) {
return new QuickPopupBuilder(context);
}
public static QuickPopupBuilder with(Fragment fragment) {
return new QuickPopupBuilder(fragment);
}
public static QuickPopupBuilder with(Dialog dialog) {
return new QuickPopupBuilder(dialog);
}
public QuickPopupBuilder contentView(int resId) {
mConfig.contentViewLayoutid(resId);
return this;
}
public QuickPopupBuilder width(int width) {
this.width = width;
return this;
}
public QuickPopupBuilder height(int height) {
this.height = height;
return this;
}
@Deprecated
public QuickPopupBuilder wrapContentMode() {
return width(ViewGroup.LayoutParams.WRAP_CONTENT)
.height(ViewGroup.LayoutParams.WRAP_CONTENT);
}
public final QuickPopupConfig getConfig() {
return mConfig;
}
public QuickPopupBuilder config(QuickPopupConfig quickPopupConfig) {
if (quickPopupConfig == null) return this;
if (quickPopupConfig != mConfig) {
quickPopupConfig.contentViewLayoutid(mConfig.contentViewLayoutid);
}
this.mConfig = quickPopupConfig;
return this;
}
public QuickPopup build() {
Object anchor = ownerAnchorParent == null ? null : ownerAnchorParent.get();
if (anchor instanceof Context) {
return new QuickPopup((Context) anchor, width, height, mConfig);
}
if (anchor instanceof Fragment) {
return new QuickPopup((Fragment) anchor, width, height, mConfig);
}
if (anchor instanceof Dialog) {
return new QuickPopup((Dialog) anchor, width, height, mConfig);
}
throw new NullPointerException("宿主已经被销毁");
}
public QuickPopup show() {
return show(null);
}
@Deprecated
public QuickPopup show(int anchorViewResid) {
QuickPopup quickPopup = build();
quickPopup.showPopupWindow(anchorViewResid);
return quickPopup;
}
public QuickPopup show(View anchorView) {
QuickPopup quickPopup = build();
quickPopup.showPopupWindow(anchorView);
return quickPopup;
}
public QuickPopup show(int x, int y) {
QuickPopup quickPopup = build();
quickPopup.showPopupWindow(x, y);
return quickPopup;
}
}
|
package com.rui.cn.config;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import com.rui.cn.annotation.AvoidScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* ribbon负载均衡策略
*
* @author zhangrl
* @time 2018/11/13
**/
@Configuration
@AvoidScan
public class RibbonConfig {
@Autowired
private IClientConfig iClientConfig;
@Bean
public IRule RibonRule(IClientConfig iClientConfig) {
return new RandomRule();
// RandomRule 随机策略:随机选择server
// RoundRobinRule 轮训策略:按顺序循环选择server
// RetryRule 重试策略:在一个配置时间段内当选择的server不成功,则尝试选择一个可用的server
// BestAvailableRule 最低并发策略:逐个考察server,若server断路器打开则忽略,在选择其中连接最低的server
// AvailabilityFilteringRule 可用过滤策略:过滤掉一直连接失败并标记为circuit tripped的server,过滤掉高并发的的server
// WeightedResponseTimeRule 响应时间加权策略:根据server响应时间分配权重,响应时间越长权重越低,被选择的概率越低,反之越高。这个策略很贴切,结合了各种因素,如网络,磁盘的直接影响响应时间
// ZoneAvoidanceRule 区域权重策略:综合判断server所在区域的性能和server的可用性轮询选择server,并且判断一个AWS zone的运行性能是否可用,提出不可用zone中的所有server
}
}
|
package com.chuxin.family.models;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.chuxin.family.utils.CxLog;
import android.content.Context;
/***
* 记账明细月数据存储
* @author shichao
*
*/
public class ChargeMonthDetail extends Model{
private static final String TAG_DAY = "day"; // 日期
private static final String TAG_RECORD = "record"; // 月记录
private static final String TAG_ID = "id"; // 月份
private static final String TAG_TYPE = "type"; // 月收入
private static final String TAG_MONEY = "money"; // 月支出
private static final String TAG_CATEGORY = "category"; // 月结余
private static final String TAG_FROM = "from"; // 月结余
private static final String TAG_DESC = "desc"; // 月结余
private static final String TABLE_NAME = "chargemonthdetail";
private JSONArray mMothDetailArray;
private JSONObject mMonthDetailJsonObj;
public ChargeMonthDetail(){
super();
mMonthDetailJsonObj = null;
mTable = TABLE_NAME;
}
public ChargeMonthDetail(JSONObject data, String id,Context ctx){
super();
mMonthDetailJsonObj = null;
mId = id;
mTable = TABLE_NAME;
mContext = ctx;
if(null != data){
mData = data;
} else {
init();
}
}
public String getChargeMonthDetailDay() {
try {
if(mData.has(TAG_DAY)){
return mData.getString(TAG_DAY);
}
} catch (JSONException e) {
CxLog.e("getChargeMonthDetailDay", ""+e.getMessage());
assert (false);
}
return null;
}
}
|
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.omod.web.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motechproject.server.omod.PersonAttributeTypeEnum;
import org.motechproject.server.omod.web.model.WebStaff;
import org.motechproject.server.svc.OpenmrsBean;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.MotechConstants;
import org.openmrs.PersonAttribute;
import org.openmrs.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import static org.motechproject.server.omod.web.model.StaffRegistrationMode.EDIT;
import static org.motechproject.server.omod.web.model.StaffRegistrationMode.NEW;
@Controller
@RequestMapping("/module/motechmodule/staff")
public class StaffController {
protected final Log log = LogFactory.getLog(StaffController.class);
@Autowired
@Qualifier("registrarBean")
private RegistrarBean registrarBean;
@Autowired
@Qualifier("openmrsBean")
private OpenmrsBean openmrsBean;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder
.registerCustomEditor(String.class, new StringTrimmerEditor(
true));
}
@ModelAttribute("staff")
public WebStaff getWebStaff() {
return new WebStaff();
}
@RequestMapping(method = RequestMethod.GET)
public String viewStaffForm(@RequestParam(value = "staffId", required = false) String staffId, ModelMap model) {
if (staffId != null) {
User staff = openmrsBean.getStaffBySystemId(staffId);
PersonAttribute phoneNumberAttr = staff.getAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeName());
PersonAttribute staffTypeAttr = staff.getAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_STAFF_TYPE.getAttributeName());
String phoneNumber = initializeDefaults(phoneNumberAttr);
String staffType = initializeDefaults(staffTypeAttr);
WebStaff webStaff = new WebStaff(staff.getPersonName().getGivenName(), staff.getPersonName().getFamilyName(), phoneNumber, staffType, staffId);
model.addAttribute("staff", webStaff);
}
model.addAttribute("staffTypes", registrarBean.getStaffTypes());
return "/module/motechmodule/staff";
}
private String initializeDefaults(PersonAttribute personAttribute) {
String value = "";
if (personAttribute != null) {
value = personAttribute.getValue();
}
return value;
}
@RequestMapping(method = RequestMethod.POST)
public String registerStaff(@ModelAttribute("staff") WebStaff staff,
Errors errors, ModelMap model) {
log.debug("Register Staff");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"motechmodule.firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"motechmodule.lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type",
"motechmodule.staffType.required");
validateTextLength(errors, "firstName", staff.getFirstName(),
MotechConstants.MAX_STRING_LENGTH_OPENMRS);
validateTextLength(errors, "lastName", staff.getLastName(),
MotechConstants.MAX_STRING_LENGTH_OPENMRS);
validateTextLength(errors, "phone", staff.getPhone(),
MotechConstants.MAX_STRING_LENGTH_OPENMRS);
if (staff.getPhone() != null
&& !staff.getPhone().matches(
MotechConstants.PHONE_REGEX_PATTERN)) {
errors.rejectValue("phone", "motechmodule.phoneNumber.invalid");
}
if (!errors.hasErrors()) {
User user = registrarBean.registerStaff(staff.getFirstName(), staff
.getLastName(), staff.getPhone(), staff.getType(), staff.getStaffId());
model.addAttribute("successMsg", (staff.isNew() ? NEW : EDIT).message(user));
}
model.addAttribute("staffTypes", registrarBean.getStaffTypes());
return "/module/motechmodule/staff";
}
void validateTextLength(Errors errors, String fieldname, String fieldValue,
int lengthLimit) {
if (fieldValue != null && fieldValue.length() > lengthLimit) {
errors.rejectValue(fieldname, "motechmodule.string.maxlength",
new Integer[]{lengthLimit},
"Specified text is longer than max characters.");
}
}
public void setRegistrarBean(RegistrarBean registrarBean) {
this.registrarBean = registrarBean;
}
public void setOpenmrsBean(OpenmrsBean openmrsBean) {
this.openmrsBean = openmrsBean;
}
}
|
package ru.biv.msgSystem;
import java.util.HashMap;
import java.util.Map;
import ru.biv.base.Abonent;
import ru.biv.base.Address;
import ru.biv.base.AddressService;
public class AddressServiceImpl implements AddressService{
private Map<Class<?>, Address> addresses = new HashMap<Class<?>,Address>();
public Address getAddress(Class<?> abonentClass) {
return addresses.get(abonentClass);
}
public void setAddress(Abonent abonent){
addresses.put(abonent.getClass(), abonent.getAddress());
}
}
|
package example;
import java.util.List;
class Geometric {
}
class Circle extends Geometric {
double radius;
}
class Rectangle extends Geometric {
double width;
double height;
}
class Triangle extends Geometric {
double firstSide;
double secondSide;
double thirdSide;
}
public class AreaGeometricDisplay {
public void showArea(List<Geometric> geometricList) {
for (Geometric geometric : geometricList) {
if (geometric instanceof Circle) {
Circle circle = (Circle) geometric;
double area = Math.PI * circle.radius * circle.radius;
System.out.println(area);
}
if (geometric instanceof Rectangle) {
Rectangle rectangle = (Rectangle) geometric;
double area = rectangle.width * rectangle.height;
System.out.println(area);
}
if (geometric instanceof Triangle) {
Triangle triangle = (Triangle) geometric;
double halfOfPerimeter = triangle.firstSide + triangle.secondSide + triangle.thirdSide;
double area = Math.sqrt(
halfOfPerimeter
* (halfOfPerimeter - triangle.firstSide)
* (halfOfPerimeter - triangle.secondSide)
* (halfOfPerimeter - triangle.thirdSide)
);
System.out.println(area);
}
// Nếu yêu cầu bao gồm thêm việc tính diện tích cho một geometric mới thì ta phải sửa lại method này
}
}
}
|
package app.integro.sjbhs.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Sjbhs_videos2List {
private String message;
public List<Sjbhs_videos2> getSjbhs_videos2Lists() {
return sjbhs_videos2Lists;
}
public void setSjbhs_videos2Lists(List<Sjbhs_videos2> sjbhs_videos2Lists) {
this.sjbhs_videos2Lists = sjbhs_videos2Lists;
}
@SerializedName("videos")
List<Sjbhs_videos2> sjbhs_videos2Lists;
private String success;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
|
package genscript.defaultops.factories;
import genscript.defaultops.OpConst;
import genscript.execution.ExecuterTreeElem;
import genscript.parse.ExecTreeElemFactory;
import genscript.syntax.tokens.Tokenizer;
import scriptinterface.execution.ExecutionScope;
import scriptinterface.execution.returnvalues.ExecutionResult;
public class StdConstFactory<ScopeType extends ExecutionScope, ReaderType extends Tokenizer> implements
ExecTreeElemFactory<ScopeType, ReaderType> {
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public ExecuterTreeElem<ScopeType, ReaderType> createElem(ReaderType source) {
return new OpConst((ExecutionResult) source.pollTokenValue()).init(source);
}
@Override
public String toString() {
return "Constant";
}
}
|
package com.shopify.order.popup;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* 주문 합배송 컨트롤러
* @author : 심윤
* @since : 2020-02-27
* @desc : 주문 합배송 컨트롤러
*/
@Controller
@RequestMapping("/order/popup")
public class OrderCombineController{
private Logger LOGGER = LoggerFactory.getLogger(OrderCombineController.class);
@Autowired private OrderCombineService orderCombineService;
//@Autowired private OrderService orderService;
//@Autowired private OrderPopupService orderPopupService;
//@Autowired private UtilFn util;
/**
* 주문 > 합배송 팝업 > 주문번호 확인 Step1
* @return ModelAndView(model)
*/
@GetMapping(value="/popOrderCombine")
public ModelAndView popOrderCombine(Model model, @ModelAttribute OrderPopupData orderPopupData, HttpSession sess) {
ModelAndView mav = new ModelAndView("order/popup/popOrderCombine");
Map<String, Object> map = orderCombineService.orderCombineCheck(orderPopupData, sess);
model.addAttribute("status", map.get("checkCode"));
model.addAttribute("orderCodeList", map.get("list"));
model.addAttribute("arrOrderCode", map.get("arrOrderCode"));
model.addAttribute("arrShopIdx", map.get("arrShopIdx"));
return mav;
}
/**
* 주문 > 합배송 팝업 > 관세정보 Step2
* @return ModelAndView(model)
*/
@GetMapping(value="/popOrderCombineInput")
public ModelAndView popOrderCombineInput(Model model, @ModelAttribute OrderPopupData orderPopupData, HttpSession sess) {
ModelAndView mav = new ModelAndView("order/popup/popOrderCombineInput");
Map<String, Object> map = orderCombineService.orderCombineAddr(orderPopupData, sess);
model.addAttribute("arrOrderCode", map.get("arrOrderCode"));
model.addAttribute("arrShopIdx", map.get("arrShopIdx"));
model.addAttribute("address", map.get("address"));
model.addAttribute("sellerAddrList", map.get("seller"));
model.addAttribute("boxList", map.get("boxList"));
model.addAttribute("skuList", map.get("skuList"));
model.addAttribute("status", map.get("status"));
return mav;
}
/**
* 주문 > 합배송 팝업 > 배송서비스 선택 Step3
* @return ModelAndView(model)
*/
@GetMapping(value="/popOrderCombineDelivery")
public ModelAndView popOrderCombinedelivery(Model model, @ModelAttribute OrderPopupData orderPopupData, HttpSession sess) {
Map<String, Object> map = orderCombineService.orderCombineDeliveryService(orderPopupData, sess);
ModelAndView mav = new ModelAndView("order/popup/popOrderCombineDelivery");
model.addAttribute("list", map.get("list"));
model.addAttribute("courier", map.get("courier"));
model.addAttribute("status", map.get("status"));
model.addAttribute("address", map.get("address")); //yr추가[2020.05.26]
return mav;
}
/**
* 주문 > 합배송 팝업 > 합배송 저장 proc Step4
* @return ModelAndView(jsonView)
*/
@PostMapping(value="/popOrderCombineProc")
public ModelAndView popOrderCombineProc(Model model, @RequestBody Map<String, String> request, HttpSession sess) {
int chk = orderCombineService.orderCombineDeliveryProc(request, sess);
ModelAndView mav = new ModelAndView("jsonView");
if(chk == 0) {
model.addAttribute("result", chk);
model.addAttribute("errCode", false);
model.addAttribute("errMsg", "실패");
}else {
model.addAttribute("result", chk);
model.addAttribute("errCode", true);
model.addAttribute("errMsg", "성공");
}
return mav;
// ShopData sessionData = (ShopData) sess.getAttribute(SpConstants.HTTP_SESSION_KEY);
//
// if(orderIdxChk != null) {
// //합배송 주문번호 임의생성(오늘날짜+임의수4자리)
// String orderCode = util.getDateElement("full").substring(2,12)+util.randomNumber(4,4);
// //합배송 주문일자 생성
// String orderDate = util.getDateElement("today");
// OrderData combineOrder = new OrderData();
// combineOrder.setShopIdx(sessionData.getShopIdx());
// combineOrder.setOrderCode(orderCode);
// combineOrder.setHideYn("N");
// combineOrder.setOrderDate(orderDate);
// combineOrder.setCombineYn("Y");
// combineOrder.setEmail(sessionData.getEmail());
//
// OrderDeliveryData delivery = new OrderDeliveryData();
// delivery.setShopIdx(sessionData.getShopIdx());
// delivery.setOrderCode(orderCode);
// delivery.setOrderDate(orderDate);
//
// //합배송용 주문생성
// //orderService.insertOrder(combineOrder);
// int chk = 0;
// Map<String, Object> map = orderPopupService.createDelivery(delivery, sess);
// if(map != null) {
// chk = (int) map.get("chk");
// masterCode = (String) map.get("masterCode");
// }
// LOGGER.debug("###############popOrderCombineProc=chk=>/"+chk);
//
// if(chk == 1) {
// //생성된 합배송idx 구하기
// OrderData combinedChkOrder = orderService.selectOneOrder(combineOrder);
//
// //받아온 주문 합배송처리
// String[] orderAry = orderIdxChk.split(",");
// //LOGGER.debug("###############1aaaaaaaaaaaa=orderIdx=>/"+orderIdxChk);
// List<OrderData> orderIdxList = new ArrayList<OrderData>();
// OrderData od = new OrderData();
// for(String el : orderAry) {
// int orderIdx = orderPopupService.selectOrderIdx(el);
// if(el != "" && el != null) {
// /**/
// //orderIdxList.add(od);
// //orderPopupService.updateOrderCodeMerge(orderIdxList);
// od.setOrderCode(el);
// od.setOrderIdx(orderIdx);
// od.setShopIdx(sessionData.getShopIdx());
// od.setCombineYn("Y");
// //od.setCombineOrderIdx(combinedChkOrder.getOrderIdx());
// od.setCombineOrderCode(orderIdxChk);
// od.setParentCode(masterCode);
// od.setChildCode(orderIdx+"");
// LOGGER.debug("###############popOrderCombineProc=masterCode=>/"+masterCode);
// LOGGER.debug("###############popOrderCombineProc=orderIdx=>/"+orderIdx);
// LOGGER.debug("###############popOrderCombineProc=od=>/"+od);
// int cnt= orderPopupService.selectDeliveryCombineCount(od);
// LOGGER.debug("###############popOrderCombineProc=cnt=>/"+cnt);
// if(cnt == 0) {
// cnt = orderPopupService.insertDeliveryCombine(od);
// LOGGER.debug("###############popOrderCombineProc=chkMap=>/"+cnt);
// }
// }
//
// }
//
// LOGGER.debug("###############1aaaaaaaaaaaa=orderIdxList=>/"+orderIdxList);
//
//// model.addAttribute("status", "ok");
// mav.addObject("status", "ok");
// }else {
// mav.addObject("status", "fail");
// }
//
// }else {
//// model.addAttribute("status", "no");
// mav.addObject("status", "no");
//
// }
}
}
|
package stream.object.step1.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/*
* ===========Serialization(직렬화):: Data Unpack============
* Person객체의 정보를(필드값) 다른곳(Sink::person.obj)으로 날리는 로직을 작성
* 1. Stream 객체를 생성 - - - ObjectOutputStream | FileOutputStream
* 2. 날린다..뿌린다..출력한다 - - - ObjectOutputStream의 기능을 사용 (writeObject(object))
*/
public class PersonObjectOuputTest1 {
public static void main(String[] args) throws IOException {
File f = new File("c:"+File.separator+"objfile"+File.separator+"person.obj");
f.getParentFile().mkdirs();
//1.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
//2.
Person p = new Person("김연아", 30, "2233", "여의도");
oos.writeObject(p);//sink쪽으로 정보들이 날라감...출력됨..
//3.
oos.close();//열어서 사용한 자원을 닫아준다.
System.out.println("person.obj 파일이 생성...확인...");
System.out.println("정보가 정확하게 출력되었는지는... 추후에 역직렬화해서 정보를 확인해보겠다..");
}
}
|
package com.tt.option.e;
import org.json.JSONObject;
public interface k {
JSONObject buildErrorMsg(String paramString);
void invokeHandler(String paramString);
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\e\k.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.