text
stringlengths 10
2.72M
|
|---|
package com.grability.test.dlmontano.grabilitytest.fragment;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.grability.test.dlmontano.grabilitytest.R;
import com.grability.test.dlmontano.grabilitytest.comparator.ApplicationComparatorByName;
import com.grability.test.dlmontano.grabilitytest.custom.adapter.ApplicationArrayAdapter;
import com.grability.test.dlmontano.grabilitytest.dao.database.ApplicationDatabaseSource;
import com.grability.test.dlmontano.grabilitytest.interfaces.ApplicationDataSource;
import com.grability.test.dlmontano.grabilitytest.model.Application;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
/**
* A simple {@link Fragment} subclass.
*/
public class AppSelectionListFragment extends Fragment {
public static String F_TAG = "ASLF";
private static String LOG_TAG = "ASLF";
private static long NO_CATEGORY_ID = -1;
private ListView appsListView;
private ApplicationArrayAdapter listViewAdapter;
private ArrayList<Application> listValues;
private ApplicationDataSource appsLocalSource;
private Application selectedApp;
private int lastItemCheckedPosition;
private View myFragmentView;
private OnAppSelectedListener activityCallback;
public interface OnAppSelectedListener {
void onAppSelected(Application application);
}
public AppSelectionListFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lastItemCheckedPosition = -1;
if (savedInstanceState != null) {
lastItemCheckedPosition = savedInstanceState
.getInt("lastItemCheckedPosition") - 1;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_app_selection_list,
container, false);
appsListView = (ListView) myFragmentView.findViewById(R.id.appsListView);
return myFragmentView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
Activity activity = (Activity) context;
activityCallback = (OnAppSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnAppSelectedListener");
}
}
@Override
public void onResume() {
super.onResume();
populateAppsList(NO_CATEGORY_ID);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (appsListView.getChildCount() > 0) {
outState.putInt("lastItemCheckedPosition", lastItemCheckedPosition + 1);
}
}
@Override
public void onDetach() {
super.onDetach();
activityCallback = null;
}
private void populateAppsList(long categoryId) {
appsLocalSource = new ApplicationDatabaseSource(getContext());
appsLocalSource.open();
if (appsLocalSource.defaultSourceContentHasApplications()) {
listValues = new ArrayList<Application>();
Map<Long, Application> appsTemp = appsLocalSource.getAllApplications();
if (categoryId == NO_CATEGORY_ID) {
appsTemp = appsLocalSource.getAllApplications();
} else {
appsTemp = appsLocalSource.getApplicationsByCategoryId(categoryId);
}
for (Long key: appsTemp.keySet()) {
Application app = appsTemp.get(key);
listValues.add(app);
}
Collections.sort(listValues, new ApplicationComparatorByName());
Application[] apps = new Application[listValues.size()];
listViewAdapter = new ApplicationArrayAdapter(getActivity(),
listValues.toArray(apps));
appsListView.setAdapter(listViewAdapter);
appsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lastItemCheckedPosition = position;
selectedApp = listValues.get(position);
activityCallback.onAppSelected(selectedApp);
}
});
}
appsLocalSource.close();
}
public void updateApplicationsList(long categoryId) {
populateAppsList(categoryId);
}
public void setAppsListViewEnabledState(boolean isEnabled) {
appsListView.setEnabled(isEnabled);
}
public void updateSelectedApplication() {
int visiblePosition = appsListView.getFirstVisiblePosition();
View view = appsListView.getChildAt(lastItemCheckedPosition
- visiblePosition);
listViewAdapter
.getView(lastItemCheckedPosition, view, appsListView);
}
}
|
package com.tencent.mm.plugin.emoji.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View.MeasureSpec;
import com.tencent.mm.view.SmileySubGrid;
public class EmojiDetailGridView extends SmileySubGrid {
private String iiv;
private EmojiDetailScrollView ilZ;
private volatile boolean ima = true;
public EmojiDetailGridView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public void onMeasure(int i, int i2) {
super.onMeasure(i, MeasureSpec.makeMeasureSpec(536870911, Integer.MIN_VALUE));
}
protected void setScrollEnable(boolean z) {
if (this.ilZ != null) {
this.ilZ.setScrollEnable(z);
}
}
public void setEmojiDetailScrollView(EmojiDetailScrollView emojiDetailScrollView) {
this.ilZ = emojiDetailScrollView;
}
protected final int getSkewingY$3c7ec8d0() {
return 0;
}
protected int getLongTouchTime() {
return 200;
}
public String getProductId() {
return this.iiv;
}
public void setProductId(String str) {
this.iiv = str;
}
}
|
import accountbook.*;
import java.awt.Color;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jfree.chart.*;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.DefaultPieDataset;
/**
* ショッピングサイトへのユーザ認証や商品選択に関する処理を担当するサーブレット
*/
public class AccountBookServlet extends HttpServlet {
private static String DB_NAME = "account_book"; // DB名
private static String DB_USER = "root"; // DBのユーザ名
private static String DB_PASS = "root"; // DBのパスワード
// ログインのビューを担当
private static String LOGIN_JSP = "/WEB-INF/Login.jsp";
// トップページのビューを担当
private static String SHOW_CALENDAR_JSP = "/WEB-INF/ShowCalendar.jsp";
// 収入の入力のビューを担当
private static String INPUT_REVENUE_JSP = "/WEB-INF/InputRevenue.jsp";
// 支出の入力のビューを担当
private static String INPUT_SPENDING_JSP = "/WEB-INF/InputSpending.jsp";
private static String INPUT_REVENUE_UPDATE_JSP = "WEB-INF/InputRevenueUpdate.jsp";
private static String INPUT_SPENDING_UPDATE_JSP = "WEB-INF/InputSpendingUpdate.jsp";
// 収入の円グラフのビューを担当
private static String SHOW_MONTHLY_PIE_CHART_JSP = "/WEB-INF/ShowMonthlyPieChart.jsp";
// 棒グラフのビューを担当
private static String SHOW_MONTHLY_BAR_CHART_JSP = "/WEB-INF/ShowMonthlyBarChart.jsp";
private static String SHOW_YEARLY_BAR_CHART_JSP = "/WEB-INF/ShowYearlyBarChart.jsp";
private static String SHOW_YEARLY_PIE_CHART_JSP = "/WEB-INF/ShowYearlyPieChart.jsp";
private static String SHOW_DAILY_DATA_JSP = "/WEB-INF/ShowDailyData.jsp";
/**
* サーブレットがPOSTメソッドでアクセスされた際に呼ばれる.
*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// doProcessを呼ぶことでGET/POSTのどちらでアクセスされても同じ処理を実行
doProcess(req, res);
}
/**
* サーブレットがGETメソッドでアクセスされた際に呼ばれる.
*/
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// doProcessを呼ぶことでGET/POSTのどちらでアクセスされても同じ処理を実行
doProcess(req, res);
}
/**
* クライアントから要求された処理をactionから判別し実行する
*/
protected void doProcess(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String nextView = ""; // 処理結果の表示を委託するJSPのパス
DatabaseConnector dc = null; // データベースへの接続を行うオブジェクト
UserManager um = null; // ユーザ認証や登録に関する処理を担当
SpendingManager sm = null; // 支出に関する処理を担当
RevenueManager rm = null; // 収入に関する処理を担当
try {
dc = new DatabaseConnector(DB_NAME, DB_USER, DB_PASS);
dc.openConnection(); // DBへ接続
um = new UserManager(dc);
sm = new SpendingManager(dc);
rm = new RevenueManager(dc);
// 前のページから渡される値を「UTF-8」に設定
req.setCharacterEncoding("UTF-8");
// これから表示するページのMIMEを設定
res.setContentType("text/html;charset=UTF-8");
// アクセスしたユーザのユーザオブジェクトを取得
HttpSession session = req.getSession(true);
User user = (User) session.getAttribute("user");
/*
* ユーザからの要求はURLの後方に付加された「?」
* 以降にGETメソッドのactionパラメータとして付加される
*/
String action = req.getParameter("action");
if (action == null) {
action = "";
}
/**
* 以下のif文でユーザからの要求を判別し,適切処理を行う
*/
if (user == null) {
if (action.equals("") || action.equals("loginPage")) {
nextView = LOGIN_JSP; // ログイン用のページを表示
} else if (action.equals("login")) {
// 認証の処理を実行
if (login(um, req)) {
user = (User) session.getAttribute("user");
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
// nextView = showItems(im, req); // ログイン成功
} else {
nextView = LOGIN_JSP; // ログイン失敗
}
} else if (action.equals("registration")) {
// 新規ユーザの登録処理を実行
nextView = registration(um, req);
} else {
/*
* ユーザオブジェクトが無い場合はログインしていないと判断し,
* 強制的にログインページへ遷移
*/
req.setAttribute("error", "先にログインしてください");
nextView = LOGIN_JSP;
}
} else if (action.equals("logout")) {
// ログアウトの処理を実行
nextView = logout(req);
} else if (action.equals("show_calendar") || action.equals("")) {
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
// 商品一覧を表示
// nextView = showItems(im, req);
} else if (action.equals("show_monthly_rev_pie")) {
nextView = createMonthlyPieChart(user, rm, sm, req);
} else if (action.equals("show_monthly_spe_pie")) {
nextView = createMonthlyPieChart(user, rm, sm, req);
} else if (action.equals("show_yearly_rev_pie")) {
nextView = createYearlyPieChart(user, rm, sm, req);
} else if (action.equals("show_yearly_spe_pie")) {
nextView = createYearlyPieChart(user, rm, sm, req);
} else if (action.equals("show_monthly_rev_bar")) {
nextView = createMonthlyBarChart(user, rm, sm, req);
} else if (action.equals("show_monthly_spe_bar")) {
nextView = createMonthlyBarChart(user, rm, sm, req);
} else if (action.equals("show_yearly_rev_bar")) {
nextView = createYearlyBarChart(user, rm, sm, req);
} else if (action.equals("show_yearly_spe_bar")) {
nextView = createYearlyBarChart(user, rm, sm, req);
} else if (action.equals("input_rev")) {
setRevenueItemKindMap(rm, req);
nextView = INPUT_REVENUE_JSP;
} else if (action.equals("input_spe")) {
setSpendingItemKindMap(sm, req);
nextView = INPUT_SPENDING_JSP;
} else if (action.equals("input_rev_u")) {
setRevenueItemKindMap(rm, req);
nextView = getRevenueBlock(user, rm, sm, req);
} else if (action.equals("input_spe_u")) {
setSpendingItemKindMap(sm, req);
nextView = getSpendingBlock(user, rm, sm, req);
} else if (action.equals("register_rev")) {
registerRevenue(user, rm, req, 0);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("register_spe")) {
registerSpending(user, sm, req, 0);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("update_rev")) {
updateRevenue(user, rm, req);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("update_spe")) {
updateSpending(user, sm, req);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("delete_rev")) {
deleteRevenue(user, rm, req);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("delete_spe")) {
deleteSpending(user, sm, req);
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} else if (action.equals("withdraw")) {
nextView = withdraw(user, um, req);
} else if (action.equals("show_daily")) {
nextView = setDailyData(rm, sm, user, req);
} else {
// 要求に該当する処理が無い場合
nextView = "";
}
if (nextView.equals("")) {
// actionパラメータの指定が無い,または不明な処理が要求された場合
req.setAttribute("error", "不正なアクションが要求されました("
+ req.getParameter("action") + ")");
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
}
dc.closeConnection(); // データベースへの接続を切断
} catch (Exception e) {
// 例外の詳細を/usr/tomcat/logs/catalina.outへ出力
// 問題が発生した際に参考にすると良い
e.printStackTrace();
req.setAttribute("error", "例外が発生しました:" + e.toString());
User user = (User) req.getSession(true).getAttribute("user");
if (user == null) {
nextView = LOGIN_JSP;
} else {
try {
setDateArray(rm, sm, user, req);
nextView = SHOW_CALENDAR_JSP;
} catch(Exception ex) {
req.getSession(true).invalidate();
e.printStackTrace();
nextView = LOGIN_JSP;
}
}
} finally {
/*
* 正常に処理された場合も,エラーの場合もビューとして指定されたJSP
* へフォワードし,クライアントに結果を返す
*/
req.getRequestDispatcher(nextView).forward(req, res);
}
}
/**
* ユーザが入力したユーザ名とパスワードを検証し,ログインの処理を行う
*/
private boolean login(UserManager um, HttpServletRequest req)
throws Exception {
String userName = req.getParameter("uname"); // ユーザ名
String password = req.getParameter("pass"); // パスワード
if (!isValid(userName) || !isValid(password)) {
req.setAttribute("error", "記入漏れがあります");
return false;
} else if (um.authenticate(userName, password) == false) {
req.setAttribute("error", "ユーザ名またはパスワードが違います");
return false;
} else {
// ログインに成功した場合
HttpSession session = req.getSession(true);
// セッションにユーザ名と新しいユーザオブジェクトをセットする
User user = um.getUser(userName);
session.setAttribute("user", user);
req.setAttribute("success", "認証に成功しました");
}
return true;
}
/**
* 新規ユーザの登録処理を行う
*/
private String registration(UserManager um, HttpServletRequest req)
throws Exception {
String userName = req.getParameter("uname"); // ユーザ名
String password = req.getParameter("pass"); // パスワード
String password2 = req.getParameter("pass2"); // パスワード(確認)
if (!isValid(userName) || !isValid(password) || !isValid(password2)) {
req.setAttribute("error", "記入漏れがあります");
} else if (!password.equals(password2)) {
req.setAttribute("error", "パスワードが確認用と一致しません");
} else if (!userName.matches("^([a-zA-Z0-9]{6,})$") || !password.matches("^([a-zA-Z0-9]{6,})$") || !password2.matches("^([a-zA-Z0-9]{6,})$")) {
req.setAttribute("error", "半角英数字で6文字以上入力してください");
} else if (um.registration(userName, password)) {
req.setAttribute("success", "登録に成功しました");
} else {
req.setAttribute("error", "すでに登録されています");
}
return LOGIN_JSP;
}
/**
* セッションを無効化し,ログアウトの処理を行う
*/
private String logout(HttpServletRequest req) {
HttpSession session = req.getSession(false); // セッションを取得
if (session != null) {
// セッションの無効化
// (D) セッションを無効化するための記述を追加し,下記のreq.setAttributeを適切なものに置き換える
session.invalidate();
req.setAttribute("success", "ログアウトしました");
}
// ログイン画面へ移動させる
return LOGIN_JSP;
}
private String withdraw(User user, UserManager um, HttpServletRequest req) throws Exception {
HttpSession session = req.getSession(true);
int userId = user.getUserId();
um.withdraw(userId);
session.invalidate();
req.setAttribute("success", "退会しました");
return LOGIN_JSP;
}
private void setDateArray(RevenueManager rm, SpendingManager sm, User user, HttpServletRequest req) throws Exception {
Calendar calendar = Calendar.getInstance();
AccountBookCalendar abc = new AccountBookCalendar();
int year;
int month;
int day = calendar.get(Calendar.DATE);
String param = req.getParameter("year");
if (!isValid(param)) {
year = -999;
} else if (!isDate(param, "yyyy")) {
year = -999;
req.setAttribute("error", "不正なパラメータです");
} else {
try {
year = Integer.parseInt(param);
} catch (NumberFormatException e) {
year = -999;
}
}
param = req.getParameter("month");
if (!isValid(param)) {
month = -999;
} else if (!isDate(param, "MM", "M")) {
month = -999;
req.setAttribute("error", "不正なパラメータです");
} else {
try {
month = Integer.parseInt(param);
} catch (NumberFormatException e) {
month = -999;
}
}
if (year == -999 || month == -999) {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
} else {
month = (month + 11) % 12;
}
calendar.set(year, month, 1);
int startWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.set(year, month, 0);
int beforeMonthLastDay = calendar.get(Calendar.DATE);
calendar.set(year, month + 1, 0);
int thisMonthLastDay = calendar.get(Calendar.DATE);
List<DailyData> dayList = new ArrayList<DailyData>();
for (int i = startWeek - 2; i >= 0; i--) {
dayList.add(new DailyData(beforeMonthLastDay - i + 35));
}
for (int i = 1; i <= thisMonthLastDay; i++) {
dayList.add(new DailyData(i));
}
int nextMonthDay = 1;
while (dayList.size() % 7 != 0) {
dayList.add(new DailyData(35 + nextMonthDay++));
}
rm.setDayListRevenue(user, year, month + 1, dayList);
sm.setDayListSpending(user, year, month + 1, dayList);
abc.setYear(year);
abc.setMonth(month);
abc.setDay(day);
abc.setDayList(dayList);
req.setAttribute("abc", abc);
}
public void setRevenueItemKindMap(RevenueManager rm, HttpServletRequest req) throws Exception {
Map<Integer, String> revenueItemKindMap = rm.getRevenueKindMap();
req.setAttribute("kind", revenueItemKindMap);
}
public void setSpendingItemKindMap(SpendingManager sm, HttpServletRequest req) throws Exception {
Map<Integer, String> spendingItemKindMap = sm.getSpendingKindMap();
req.setAttribute("kind", spendingItemKindMap);
}
private void registerRevenue(User user, RevenueManager rm, HttpServletRequest req, int blockId) throws Exception {
RevenueBlock rb = new RevenueBlock();
if (!isDate(req.getParameter("date"), "yyyy-MM-dd", "yyyy-M-dd", "yyyy-MM-d", "yyyy-M-d")) {
req.setAttribute("error", "不正なパラメータです");
return;
}
rb.setDate(req.getParameter("date"));
rb.setPlace(req.getParameter("place"));
List<RevenueItem> revenueItemList = new ArrayList<RevenueItem>();
for (int i = 0; req.getParameter("kind[" + i + "]") != null; i++) {
String name = req.getParameter("item_name[" + i + "]");
int kind = Integer.parseInt(req.getParameter("kind[" + i + "]"));
int price = Integer.parseInt(req.getParameter("price[" + i + "]"));
int count = Integer.parseInt(req.getParameter("count[" + i + "]"));
if (kind < 1 || kind > rm.getRevenueKindMap().size() || price < 0 || count < 1) {
req.setAttribute("error", "不正なパラメータです");
return;
}
RevenueItem ri = new RevenueItem();
ri.setItemName(name);
ri.setKindId(kind);
ri.setPrice(price);
ri.setCount(count);
revenueItemList.add(ri);
}
rb.setRevenueItemList(revenueItemList);
rm.registerRevenueBlock(user.getUserId(), blockId, rb);
req.setAttribute("success", "登録が完了しました");
}
private void registerSpending(User user, SpendingManager sm, HttpServletRequest req, int blockId) throws Exception {
SpendingBlock sb = new SpendingBlock();
if (!isDate(req.getParameter("date"), "yyyy-MM-dd", "yyyy-M-dd", "yyyy-MM-d", "yyyy-M-d")) {
req.setAttribute("error", "不正なパラメータです");
return;
}
sb.setDate(req.getParameter("date"));
sb.setPlace(req.getParameter("place"));
List<SpendingItem> spendingItemList = new ArrayList<SpendingItem>();
for (int i = 0; req.getParameter("kind[" + i + "]") != null; i++) {
String name = req.getParameter("item_name[" + i + "]");
int kind = Integer.parseInt(req.getParameter("kind[" + i + "]"));
int price = Integer.parseInt(req.getParameter("price[" + i + "]"));
int count = Integer.parseInt(req.getParameter("count[" + i + "]"));
if (kind < 1 || kind > sm.getSpendingKindMap().size() || price < 0 || count < 1) {
req.setAttribute("error", "不正なパラメータです");
return;
}
SpendingItem si = new SpendingItem();
si.setItemName(name);
si.setKindId(kind);
si.setPrice(price);
si.setCount(count);
spendingItemList.add(si);
}
sb.setSpendingItemList(spendingItemList);
sm.registerSpendingBlock(user.getUserId(), blockId, sb);
req.setAttribute("success", "登録が完了しました");
}
private String getRevenueBlock(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
int blockId = Integer.parseInt(req.getParameter("block_id"));
RevenueBlock rb = rm.getRevenueBlock(user.getUserId(), blockId);
if (rb == null) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
req.setAttribute("rb", rb);
return INPUT_REVENUE_UPDATE_JSP;
}
private String getSpendingBlock(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
int blockId = Integer.parseInt(req.getParameter("block_id"));
SpendingBlock sb = sm.getSpendingBlock(user.getUserId(), blockId);
if (sb == null) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
req.setAttribute("sb", sb);
return INPUT_SPENDING_UPDATE_JSP;
}
private boolean deleteRevenue(User user, RevenueManager rm, HttpServletRequest req) throws Exception {
int blockId = Integer.parseInt(req.getParameter("block_id"));
if (rm.deleteRevenue(user.getUserId(), blockId)) {
req.setAttribute("success", "削除が完了しました");
return true;
}
req.setAttribute("error", "不正な操作です");
return false;
}
private boolean deleteSpending(User user, SpendingManager sm, HttpServletRequest req) throws Exception {
int blockId = Integer.parseInt(req.getParameter("block_id"));
if (sm.deleteSpending(user.getUserId(), blockId)) {
req.setAttribute("success", "削除が完了しました");
return true;
}
req.setAttribute("error", "不正な操作です");
return false;
}
private void updateRevenue(User user, RevenueManager rm, HttpServletRequest req) throws Exception {
if (deleteRevenue(user, rm, req)) {
registerRevenue(user, rm, req, Integer.parseInt(req.getParameter("block_id")));
req.setAttribute("success", "更新が完了しました");
}
}
private void updateSpending(User user, SpendingManager sm, HttpServletRequest req) throws Exception {
if (deleteSpending(user, sm, req)) {
registerSpending(user, sm, req, Integer.parseInt(req.getParameter("block_id")));
req.setAttribute("success", "更新が完了しました");
}
}
private String createMonthlyPieChart(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
List<PieChartItem> pieChartItemList = null;
String date = req.getParameter("date");
if (date == null) {
java.util.Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
date = sdf.format(d);
}
if (!isDate(date, "yyyy-MM", "yyyy-M")) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
if (req.getParameter("action").equals("show_monthly_rev_pie")) {
pieChartItemList = rm.getPieChartItemList(user, date);
} else if (req.getParameter("action").equals("show_monthly_spe_pie")) {
pieChartItemList = sm.getPieChartItemList(user, date);
}
ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
DefaultPieDataset objDpd = new DefaultPieDataset();
for (PieChartItem pci : pieChartItemList) {
objDpd.setValue(Integer.toString(pci.getKindId()), pci.getPrice());
}
JFreeChart objCht = ChartFactory.createPieChart3D("", objDpd, true, true, true);
objCht.setBackgroundPaint(Color.WHITE);
// クリッカブル・マップ用のリンクを生成
PiePlot objPp = (PiePlot) objCht.getPlot();
objPp.setURLGenerator(new StandardPieURLGenerator("?action=" + (req.getParameter("action").equals("show_monthly_rev_pie") ? "show_monthly_rev_bar" : "show_monthly_spe_bar") + "&date=" + date));
// マップ用に生成された画像を保存するためにダミー・ファイルを生成
File objFl = File.createTempFile("tips", ".jpg");
objFl.deleteOnExit();
// イメージを生成
ChartRenderingInfo objCri = new ChartRenderingInfo(new StandardEntityCollection());
ChartUtilities.saveChartAsJPEG(objFl, objCht, 600, 400, objCri);
// リクエスト属性"map"に<map>タグを含む文字列データをセット
req.setAttribute("map", ChartUtilities.getImageMap("map", objCri));
// this.getServletContext().getRequestDispatcher("/chart.jsp").forward(req, response);
req.setAttribute("date", date);
return SHOW_MONTHLY_PIE_CHART_JSP;
}
private String createYearlyPieChart(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
List<PieChartItem> pieChartItemList = null;
String date = req.getParameter("date");
if (date == null) {
java.util.Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
date = sdf.format(d);
}
if (!isDate(date, "yyyy")) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
if (req.getParameter("action").equals("show_yearly_rev_pie")) {
pieChartItemList = rm.getYearlyPieChartItemList(user, date);
} else if (req.getParameter("action").equals("show_yearly_spe_pie")) {
pieChartItemList = sm.getYearlyPieChartItemList(user, date);
}
ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
DefaultPieDataset objDpd = new DefaultPieDataset();
for (PieChartItem pci : pieChartItemList) {
objDpd.setValue(Integer.toString(pci.getKindId()), pci.getPrice());
}
JFreeChart objCht = ChartFactory.createPieChart3D("", objDpd, true, true, true);
objCht.setBackgroundPaint(Color.WHITE);
// クリッカブル・マップ用のリンクを生成
PiePlot objPp = (PiePlot) objCht.getPlot();
objPp.setURLGenerator(new StandardPieURLGenerator("?action=" + (req.getParameter("action").equals("show_yearly_rev_pie") ? "show_yearly_rev_bar" : "show_yearly_spe_bar") + "&date=" + date));
// マップ用に生成された画像を保存するためにダミー・ファイルを生成
File objFl = File.createTempFile("tips", ".jpg");
objFl.deleteOnExit();
// イメージを生成
ChartRenderingInfo objCri = new ChartRenderingInfo(new StandardEntityCollection());
ChartUtilities.saveChartAsJPEG(objFl, objCht, 600, 400, objCri);
// リクエスト属性"map"に<map>タグを含む文字列データをセット
req.setAttribute("map", ChartUtilities.getImageMap("map", objCri));
// this.getServletContext().getRequestDispatcher("/chart.jsp").forward(req, response);
req.setAttribute("date", date);
return SHOW_YEARLY_PIE_CHART_JSP;
}
private String createMonthlyBarChart(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
String date = req.getParameter("date");Map<Integer, String> itemKindMap = null;
if (date == null) {
java.util.Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
date = sdf.format(d);
}
if (req.getParameter("action").equals("show_monthly_rev_bar")) {
itemKindMap = rm.getRevenueKindMap();
} else {
itemKindMap = sm.getSpendingKindMap();
}
int category = Integer.parseInt(req.getParameter("category"));
if (!isDate(date, "yyyy-MM", "yyyy-M") || category < 0 || category > itemKindMap.size()) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
req.setAttribute("date", date);
req.setAttribute("category", itemKindMap);
return SHOW_MONTHLY_BAR_CHART_JSP;
}
private String createYearlyBarChart(User user, RevenueManager rm, SpendingManager sm, HttpServletRequest req) throws Exception {
String date = req.getParameter("date");
if (date == null) {
java.util.Date d = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
date = sdf.format(d);
}
Map<Integer, String> itemKindMap = null;
if (req.getParameter("action").equals("show_yearly_rev_bar")) {
itemKindMap = rm.getRevenueKindMap();
} else {
itemKindMap = sm.getSpendingKindMap();
}
int category = Integer.parseInt(req.getParameter("category"));
if (!isDate(date, "yyyy") || category < 0 || category > itemKindMap.size()) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
req.setAttribute("date", date);
req.setAttribute("category", itemKindMap);
return SHOW_YEARLY_BAR_CHART_JSP;
}
private String setDailyData(RevenueManager rm, SpendingManager sm, User user, HttpServletRequest req) throws Exception {
String date = req.getParameter("date");
if (!isDate(date, "yyyy-MM-dd", "yyyy-M-dd", "yyyy-MM-d", "yyyy-M-d")) {
req.setAttribute("error", "不正なパラメータです");
setDateArray(rm, sm, user, req);
return SHOW_CALENDAR_JSP;
}
List<RevenueBlock> rList = rm.setDailyDataSet(user, date);
List<SpendingBlock> sList = sm.setDailyDataSet(user, date);
req.setAttribute("rList", rList);
req.setAttribute("sList", sList);
return SHOW_DAILY_DATA_JSP;
}
private boolean isDate(String date, String... formats) {
for (String f : formats) {
try {
SimpleDateFormat d = new SimpleDateFormat(f);
d.setLenient(false);
Date result = d.parse(date);
if (date.equals(d.format(result))) {
return true;
}
} catch (ParseException e) {
continue;
}
}
return false;
}
/**
* 引数で与えられた文字列が空でないかを判定する.引数で与えられたstr
* (文字列)がnullではなく,かつ空でない場合はtrueを,それ以外はfalseを返す.
*/
protected boolean isValid(String str) {
if (str != null && !str.equals("")) {
return true;
} else {
return false;
}
}
}
|
package com.cos.oauth2jwt.web;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.cos.oauth2jwt.config.auth.PrincipalDetails;
import com.cos.oauth2jwt.domain.user.User;
import com.cos.oauth2jwt.service.FollowService;
import com.cos.oauth2jwt.service.UserService;
import com.cos.oauth2jwt.web.dto.follow.FollowRespDto;
import com.cos.oauth2jwt.web.dto.user.LoginRespDto;
import com.cos.oauth2jwt.web.dto.user.ProfileImageRespDto;
import com.cos.oauth2jwt.web.dto.user.UserProfileRespDto;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@RestController
public class UserRestController {
private final UserService userService;
private final FollowService followService;
@GetMapping("/user/{pageUserId}/follow") // data 리턴하는 것
public ResponseEntity<?> followList(@AuthenticationPrincipal PrincipalDetails principalDetails, @PathVariable Long pageUserId){
List<FollowRespDto> followRespDto = followService.팔로우리스트(principalDetails.getUser().getId(), pageUserId);
return new ResponseEntity<>(followRespDto, HttpStatus.OK);
}
@GetMapping("/user/{id}")
public ResponseEntity<?> profile(@PathVariable Long id, @AuthenticationPrincipal PrincipalDetails principalDetails) {
UserProfileRespDto userProfileRespDto = userService.회원프로필(id, principalDetails.getUser().getId());
return new ResponseEntity<>(userProfileRespDto, HttpStatus.OK);
}
@GetMapping("/user/load")
public ResponseEntity<?> loadUser(@AuthenticationPrincipal PrincipalDetails principalDetails){
if(principalDetails != null) { // 사용자가 있을 경우 사용자 정보를 리턴
User user = principalDetails.getUser();
LoginRespDto loginRespDto = LoginRespDto.builder()
.id(user.getId())
.username(user.getUsername())
.name(user.getName())
.profileImageUrl(user.getProfileImageUrl())
.role(user.getRole())
.build();
return new ResponseEntity<>(loginRespDto, HttpStatus.OK);
}else { // null일 경우 401 리턴
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
@PutMapping("/user/{id}/profileImageUrl")
public ResponseEntity<?> profileImageUrlUpdate(@PathVariable int id, MultipartFile profileImageFile, @AuthenticationPrincipal PrincipalDetails principalDetails){
// id값이랑 principal id 비교(다르면 익셉션), 나중에 처리
User userEntity = userService.회원사진변경(profileImageFile, principalDetails);
// 바뀐 프로필 부분만 리턴
ProfileImageRespDto respDto = new ProfileImageRespDto();
respDto.setProfileImageUrl(userEntity.getProfileImageUrl());
return new ResponseEntity<>(respDto, HttpStatus.OK);
}
@PutMapping("/user/{id}")
public ResponseEntity<?> profileImageUrlUpdate(@PathVariable Long id,@RequestBody User user, @AuthenticationPrincipal PrincipalDetails principalDetails){
// id값이랑 principal id 비교(다르면 익셉션), 나중에 처리
User userEntity = userService.회원수정(id, user);
principalDetails.setUser(userEntity);
return new ResponseEntity<>(HttpStatus.OK); // 프로필페이지로 이동 200만 리턴
}
}
|
/*
* 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 jsscController;
import jsscGuiTest.JUsartReadWrite;
import jssctest.*;
/**
*
* @author eth
*/
public class JsscController {
private COMHandler comport_model;
private JUsartReadWrite gui_view;
public JsscController(COMHandler input_model){
this.comport_model = input_model;
gui_view = new JUsartReadWrite(input_model, this);
gui_view.setVisible(true);
}
public void connectToCom(){
try{
comport_model.connect("COM4", 0, 0, 0, 0);
}catch(Exception e){
System.out.println("controller says: unable to connect");
}
}
public void disconnectFromCom(){
try{
comport_model.disconnect();
}catch(Exception e){
System.out.println("controller says: unable to disconnect");
}
}
public void setCOMWriteString(String str){
comport_model.setCOMWriteString(str);
}
}
|
/*
* MainFrame.java
*
* Created on 21 november 2007, 21:10
*/
package be.tiwi.woordenboek.gui;
import be.tiwi.woordenboek.data.Woordenboek;
import be.tiwi.woordenboek.data.WoordenboekDAO;
import be.tiwi.woordenboek.impl.WoordenboekDAODummy;
import java.util.List;
import java.util.Vector;
/**
*
* @author Wijnand
*/
public class WoordenboekFrame extends javax.swing.JFrame {
WoordenboekDAO woordenboekDAO;
List<Woordenboek> woordenboeken;
/**
* Creates new form MainFrame
*/
public WoordenboekFrame() {
initComponents();
try {
woordenboekDAO = new WoordenboekDAODummy();
woordenboeken = woordenboekDAO.getWoordenboeken();
woordenboekLijst.setListData(new Vector(woordenboeken));
if (woordenboeken.size() > 0) {
woordenboekLijst.setSelectedIndex(0);
}
woordenLijst.setListData(new Vector<String>());
definitieLijst.setListData(new Vector<String>());
} catch (Exception e) {
System.out.println("Applicatie kan niet opstraten:" + e.getMessage());
throw new RuntimeException();
}
}
/**
* 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
woordenboekLijst = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
woordVeld = new javax.swing.JTextField();
zoekKnop = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
woordenLijst = new javax.swing.JList();
jScrollPane3 = new javax.swing.JScrollPane();
definitieLijst = new javax.swing.JList();
definitieKnop = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
woordenboekLijst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(woordenboekLijst);
jLabel1.setText("woord:");
zoekKnop.setText("zoek op prefix:");
zoekKnop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoekKnopActionPerformed(evt);
}
});
woordenLijst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(woordenLijst);
definitieLijst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
definitieLijst.setEnabled(false);
jScrollPane3.setViewportView(definitieLijst);
definitieKnop.setText("definitie:");
definitieKnop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
definitieKnopActionPerformed(evt);
}
});
jLabel2.setText("woordenboeken:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(zoekKnop)
.addComponent(woordVeld, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
.addComponent(definitieKnop, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(64, 64, 64)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(45, 45, 45))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(woordVeld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(zoekKnop)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(definitieKnop)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void zoekKnopActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_zoekKnopActionPerformed
{//GEN-HEADEREND:event_zoekKnopActionPerformed
String woord = woordVeld.getText();
if (woord.equals("")) {
return;
}
Vector<String> woorden = new Vector<>();
int[] indices = woordenboekLijst.getSelectedIndices();
for (int i : indices) {
String id = woordenboeken.get(i).getID();
try {
woorden.addAll(woordenboekDAO.zoekWoorden(woord, id));
} catch (Exception e) {
System.out.println("Probleem met zoeken woorden "+ e.getMessage());
}
woordenLijst.setListData(woorden);
if (!woorden.isEmpty()) {
woordenLijst.setSelectedIndex(0);
}
}
}//GEN-LAST:event_zoekKnopActionPerformed
private void definitieKnopActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_definitieKnopActionPerformed
{//GEN-HEADEREND:event_definitieKnopActionPerformed
int[] indices = (int[]) woordenLijst.getSelectedIndices();
Vector<String> definities = new Vector<String>();
for (int i : indices) {
String woord = (String) woordenLijst.getModel().getElementAt(i);
int[] indices2 = woordenboekLijst.getSelectedIndices();
for (int j : indices2) {
String id = woordenboeken.get(j).getID();
definities.addAll(woordenboekDAO.getDefinities(woord, id));
}
}
definitieLijst.setListData(definities);
}//GEN-LAST:event_definitieKnopActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new WoordenboekFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton definitieKnop;
private javax.swing.JList definitieLijst;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField woordVeld;
private javax.swing.JList woordenLijst;
private javax.swing.JList woordenboekLijst;
private javax.swing.JButton zoekKnop;
// End of variables declaration//GEN-END:variables
}
|
package com.neo1946.todolist.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.SignUpCallback;
import com.neo1946.todolist.R;
/**
* @author ouyangzhaoxian on 2019/03/12
*/
public class LoginActivity extends BaseActivity {
private EditText et_username;
private EditText et_password;
private Button bt_login;
private Button bt_register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
et_username = findViewById(R.id.et_name);
et_password = findViewById(R.id.et_password);
bt_login = findViewById(R.id.bt_login);
bt_register = findViewById(R.id.bt_register);
bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if("".equals(et_username.getText().toString()) || "".equals(et_password.getText().toString())){
Toast.makeText(LoginActivity.this, "用户名/密码 不能为空", Toast.LENGTH_SHORT).show();
return;
}
String username = et_username.getText().toString();
String password = et_password.getText().toString();
AVUser.logInInBackground(username, password, new LogInCallback<AVUser>() {
@Override
public void done(AVUser avUser, AVException e) {
if (e == null) {
Intent intent = new Intent();
LoginActivity.this.setResult(1, intent);
LoginActivity.this.finish();
} else {
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
bt_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if("".equals(et_username.getText().toString()) || "".equals(et_password.getText().toString())){
Toast.makeText(LoginActivity.this, "用户名/密码 不能为空", Toast.LENGTH_SHORT).show();
return;
}
String username = et_username.getText().toString();
String password = et_password.getText().toString();
AVUser user = new AVUser();// 新建 AVUser 对象实例
user.setUsername(username);// 设置用户名
user.setPassword(password);// 设置密码
// user.setEmail(email);//设置邮箱
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(AVException e) {
if (e == null) {
Intent intent = new Intent();
LoginActivity.this.setResult(1, intent);
LoginActivity.this.finish();
Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
LoginActivity.this.setResult(0, intent);
LoginActivity.this.finish();
}
}
|
/*
* CS 349 Java Code Examples
*
* TransConDemo Demo of different concatenation orders of matrix transforms.
Click the window to change the order.
*
*/
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.JButton;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.vecmath.*;
import java.lang.Math.*;
import java.util.Random;
import java.awt.event.*;
// create the window and run the demo
public class TransConDemo {
public static void main(String[] args) {
// create the window
Canvas canvas = new Canvas();
JFrame f = new JFrame("TransConDemo"); // jframe is the app window
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400); // window size
f.setContentPane(canvas); // add canvas to jframe
f.setVisible(true); // show the window
}
}
class Canvas extends JComponent {
// the house shape
private MyShape shape;
// a larger font for displaying the concatenation order
private Font font = new Font("SansSerif", Font.PLAIN, 30);
// the concatenation order
private int order = 0;
Canvas()
{
shape = new MyShape();
shape.setPoints(new double[][] {
{ 0, 0 } , {100, 0}, { 100, 100 }, { 50, 150 }, { 0, 100 }
} );
shape.setIsClosed(true);
shape.setIsFilled(false);
// using a mouse adapter with an anonymous class to get
// only mouse clicked events
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
order = (order + 1) % 6;
repaint();
}
});
System.out.println("click to change transformation order");
}
// custom graphics drawing
public void paintComponent(Graphics g) {
super.paintComponent(g); // JPanel paint
Graphics2D g2 = (Graphics2D)g;
// antialiasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// save the current transform matrix
AffineTransform M = g2.getTransform();
// you can move (0,0) to the bottom left using these
g2.translate(0, getHeight());
g2.scale(1, -1);
// draw the original shape in "model" coordinates
shape.setColour(Color.BLACK);
shape.paint(g2);
// create transformation matrices
AffineTransform R = AffineTransform.getRotateInstance(Math.toRadians(30));
AffineTransform T = AffineTransform.getTranslateInstance(100, 0);
AffineTransform S = AffineTransform.getScaleInstance(2, 1.2);
// concatenate the matrices in 1 of 6 orders
String s = "p'=";
switch (order)
{
case 0:
s += "TRS";
g2.transform(T);
g2.transform(R);
g2.transform(S);
break;
case 1:
s += "TSR";
g2.transform(T);
g2.transform(S);
g2.transform(R);
break;
case 2:
s += "RST";
g2.transform(R);
g2.transform(S);
g2.transform(T);
break;
case 3:
s += "RTS";
g2.transform(R);
g2.transform(T);
g2.transform(S);
break;
case 4:
s += "SRT";
g2.transform(S);
g2.transform(R);
g2.transform(T);
break;
case 5:
s += "STR";
g2.transform(S);
g2.transform(T);
g2.transform(R);
break;
}
s += "p";
// the shape will get transformed into "world" coordinates
shape.setColour(Color.RED);
shape.paint(g2);
// reset to transform before we did the T, R, and S
g2.setTransform(M);
// display the order text
g2.setColor(Color.BLACK);
g2.setFont(font);
g2.drawString(s, getWidth() / 3, getHeight() - 40);
}
}
|
package exception.myexception;
public class MainClass {
public static void main(String[] args) {
try {
Account ac = new Account(20000);
ac.deposit(10000);
ac.withDraw(300000);
ac.getBalance();
} catch (MyException e) {
System.out.println(e.getMessage());
//System.out.println(e.getClass());
}
}
}
|
package com.hesoyam.pharmacy.integration.medicine;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hesoyam.pharmacy.feedback.dto.EmployeeComplaintCreateDTO;
import com.hesoyam.pharmacy.feedback.dto.PharmacyComplaintCreateDTO;
import com.hesoyam.pharmacy.medicine.dto.ReservationCodeDTO;
import com.hesoyam.pharmacy.user.model.User;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
//import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.LocalDateTime;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MedicineReservationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private MockMvc mvc;
private static ObjectMapper objectMapper;
private static ObjectWriter objectWriter;
@BeforeAll
public static void initAll(){
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
}
@BeforeEach
public void init(){
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
@WithUserDetails(value = "hesoyampharmacy+mila@gmail.com")
void cancelInvalidReservationCode() throws Exception {
mvc.perform(post("/medicine-reservation/cancel-pickup").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(getInvalidCodeJSON()).with(user(getUserDetails()))).andExpect(status().is(404));
}
@Test
@WithUserDetails(value = "hesoyampharmacy+mila@gmail.com")
void confirmInvalidReservationCode() throws Exception {
mvc.perform(post("/medicine-reservation/confirm-pickup").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(getInvalidCodeJSON()).with(user(getUserDetails()))).andExpect(status().is(404));
}
private User getUserDetails(){
UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext (). getAuthentication ();
return (User) authentication.getPrincipal ();
}
private String getInvalidCodeJSON() throws JsonProcessingException {
ReservationCodeDTO reservationCodeDTO = new ReservationCodeDTO();
reservationCodeDTO.setReservationCode("abv");
return objectWriter.writeValueAsString(reservationCodeDTO);
}
}
|
package com.polsl.edziennik.desktopclient.view.common.dialogs;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.polsl.edziennik.desktopclient.controller.utils.LangManager;
import com.polsl.edziennik.desktopclient.controller.utils.factory.GuiComponentFactory;
import com.polsl.edziennik.desktopclient.controller.utils.factory.IGuiComponentAbstractFactory;
import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.ILabel;
import com.polsl.edziennik.desktopclient.properties.Properties;
public class SimpleDialog extends JOptionPane {
private String labelName;
private JLabel label;
private JLabel label2;
private JTextField text;
private JTextField text2;
private ILabel Ilabel;
private IGuiComponentAbstractFactory factory = GuiComponentFactory.getInstance();
private JPanel panel;
private ResourceBundle bundle = LangManager.getResource(Properties.Component);
private String[] options = new String[] { bundle.getString("saveTextButton"), bundle.getString("cancelTextButton") };
public SimpleDialog(String labelName, String label2Name) {
this.labelName = labelName;
Ilabel = factory.createLabel();
label = Ilabel.getLabel(labelName);
label2 = Ilabel.getLabel(label2Name);
panel = new JPanel();
text = new JTextField(20);
text2 = new JTextField(10);
panel.add(label);
panel.add(text);
panel.add(label2);
panel.add(text2);
}
public SimpleDialog(String labelName) {
this.labelName = labelName;
Ilabel = factory.createLabel();
label = Ilabel.getLabel(labelName);
panel = new JPanel();
text = new JTextField(20);
panel.add(label);
panel.add(text);
}
public int showDialog() {
return this.showOptionDialog(null, panel, bundle.getString(labelName), JOptionPane.DEFAULT_OPTION,
JOptionPane.YES_NO_OPTION, new ImageIcon(), options, options[0]);
}
public void clear() {
text.setText("");
if (text2 != null) text2.setText("");
}
public String getText() {
return text.getText();
}
public Float getWeight() {
return new Float(text2.getText());
}
}
|
/*
* Copyright © 2019 The GWT Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gwtproject.dom.builder.shared;
import org.gwtproject.safehtml.shared.SafeUri;
import org.gwtproject.safehtml.shared.annotations.IsSafeUri;
import org.gwtproject.safehtml.shared.annotations.IsTrustedResourceUri;
import org.gwtproject.safehtml.shared.annotations.SuppressIsTrustedResourceUriCastCheck;
/** HTML-based implementation of {@link FrameBuilder}. */
public class HtmlFrameBuilder extends HtmlElementBuilderBase<FrameBuilder> implements FrameBuilder {
HtmlFrameBuilder(HtmlBuilderImpl delegate) {
super(delegate, true);
}
@Override
public FrameBuilder frameBorder(int frameBorder) {
return trustedAttribute("frameBorder", frameBorder);
}
@Override
public FrameBuilder longDesc(SafeUri longDesc) {
return longDesc(longDesc.asString());
}
@Override
public FrameBuilder longDesc(@IsSafeUri String longDesc) {
return trustedAttribute("longDesc", longDesc);
}
@Override
public FrameBuilder marginHeight(int marginHeight) {
return trustedAttribute("marginHeight", marginHeight);
}
@Override
public FrameBuilder marginWidth(int marginWidth) {
return trustedAttribute("marginWidth", marginWidth);
}
@Override
public FrameBuilder name(String name) {
return trustedAttribute("name", name);
}
@Override
public FrameBuilder noResize() {
return trustedAttribute("noresize", "noresize");
}
@Override
public FrameBuilder scrolling(String scrolling) {
return trustedAttribute("scrolling", scrolling);
}
@Override
@SuppressIsTrustedResourceUriCastCheck
public FrameBuilder src(@IsTrustedResourceUri SafeUri src) {
return src(src.asString());
}
@Override
public FrameBuilder src(@IsTrustedResourceUri String src) {
return trustedAttribute("src", src);
}
}
|
package com.huawei.esdk.csdemo.view.panel;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.huawei.esdk.csdemo.common.ComponentBoundsTool;
import com.huawei.esdk.csdemo.common.ItemObject;
import com.huawei.esdk.csdemo.common.LabelText;
import com.huawei.esdk.csdemo.common.Table;
import com.huawei.esdk.csdemo.enums.ContinuousPresenceMode;
import com.huawei.esdk.csdemo.memorydb.DataBase;
public class ConfControlBottomPan extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private Rectangle rectangle;
private int xx = 10;
private int yy = 10;
private JPanel leftPanel = new JPanel();
private JLabel siteUriLabel = new JLabel();
private JTextField siteUriText = new JTextField();
private JLabel videoSourceUriLabel = new JLabel();
private JTextField videoSourceUriText = new JTextField();
private JButton leftSettingBut = new JButton();
private List<JComponent> leftComponents = new ArrayList<JComponent>();
private JPanel rightPanel = new JPanel();
private JLabel duohuamianUriLabel = new JLabel();
private JTextField duohuamianUriText = new JTextField("0");
private JLabel duohuamianTypeLabel = new JLabel();
private JComboBox duohuamianTypeText = new JComboBox();
private JButton rightSettingBut = new JButton();
private List<JComponent> rightComponents = new ArrayList<JComponent>();
public ConfControlBottomPan(Rectangle rectangle) {
this.rectangle = rectangle;
this.setLayout(null);
}
public void repaintCompomentName() {
leftPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), LabelText.confCtol_bottom_leftPanel_border[DataBase.getInstance().getLanguageFlag()]));
siteUriLabel.setText(LabelText.confCtol_bottom_siteUriLabel[DataBase.getInstance().getLanguageFlag()]);
videoSourceUriLabel.setText(LabelText.confCtol_bottom_videoSourceUriLabel[DataBase.getInstance().getLanguageFlag()]);
leftSettingBut.setText(LabelText.confCtol_bottom_leftSetBut[DataBase.getInstance().getLanguageFlag()]);
rightPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), LabelText.confCtol_bottom_rightPanel_border[DataBase.getInstance().getLanguageFlag()]));
duohuamianUriLabel.setText(LabelText.confCtol_bottom_duohuamianUriLabel[DataBase.getInstance().getLanguageFlag()]);
duohuamianTypeLabel.setText(LabelText.confCtol_bottom_duohuamianTypeLabel[DataBase.getInstance().getLanguageFlag()]);
rightSettingBut.setText(LabelText.confCtol_bottom_rightSetBut[DataBase.getInstance().getLanguageFlag()]);
}
public void initCompomentBouds() {
int widgetWidth = (this.rectangle.width - 10 - 2 * xx) / 2;
int widgetHeight = this.rectangle.height - 2 * yy;
leftPanel.setBounds(xx, yy, widgetWidth, widgetHeight);
rightPanel.setBounds(xx + widgetWidth + 10, yy, widgetWidth,widgetHeight);
int lbwidth = 0;
if(0 == DataBase.getInstance().getLanguageFlag()){
lbwidth = 90;
}else{
lbwidth = 180;
}
Table table1 = new Table(widgetWidth,widgetHeight, 3, 4, new String[]{"40","40","40"}, new String[]{String.valueOf(lbwidth),"0","40","130"});
List< Integer[]> bounds1 = new ArrayList< Integer[]>();
bounds1.add( new Integer[]{0,0,1,1});
bounds1.add( new Integer[]{0,2,1,2});
bounds1.add( new Integer[]{1,0,1,1});
bounds1.add( new Integer[]{1,2,1,2});
bounds1.add( new Integer[]{2,3,1,1});
new ComponentBoundsTool().getInitedBoundsComponent(this.leftComponents, bounds1, table1);
new ComponentBoundsTool().getInitedBoundsComponent(this.rightComponents, bounds1, table1);
}
public void addCompomentToPanel() {
this.setBounds(this.rectangle);
this.add(leftPanel);
leftPanel.setLayout(null);
for(JComponent jcpt: leftComponents){
leftPanel.add(jcpt);
}
siteUriText.setEditable(false);
int i = 0;
for(ContinuousPresenceMode item :ContinuousPresenceMode.values()){
ItemObject selectItem = new ItemObject();
selectItem.setKey(String.valueOf(i));
selectItem.setValue(item.value());
duohuamianTypeText.addItem(selectItem);
i++;
}
this.add(rightPanel);
rightPanel.setLayout(null);
for(JComponent jcpt : rightComponents){
rightPanel.add(jcpt);
}
}
public void repaintComponentVal() {
}
public void createPanel() {
addComponentToList();
repaintCompomentName();
initCompomentBouds();
addCompomentToPanel();
repaintComponentVal();
}
private void addComponentToList(){
leftComponents.add(siteUriLabel);
leftComponents.add(siteUriText);
leftComponents.add(videoSourceUriLabel);
leftComponents.add(videoSourceUriText);
leftComponents.add(leftSettingBut);
rightComponents.add(duohuamianUriLabel);
rightComponents.add(duohuamianUriText);
rightComponents.add(duohuamianTypeLabel);
rightComponents.add(duohuamianTypeText);
rightComponents.add(rightSettingBut);
}
public Rectangle getRectangle() {
return rectangle;
}
public JPanel getLeftPanel() {
return leftPanel;
}
public JLabel getSiteUriLabel() {
return siteUriLabel;
}
public JTextField getSiteUriText() {
return siteUriText;
}
public JLabel getVideoSourceUriLabel()
{
return videoSourceUriLabel;
}
public JTextField getVideoSourceUriText()
{
return videoSourceUriText;
}
public List<JComponent> getLeftComponents()
{
return leftComponents;
}
public List<JComponent> getRightComponents()
{
return rightComponents;
}
public JButton getLeftSettingBut() {
return leftSettingBut;
}
public JPanel getRightPanel() {
return rightPanel;
}
public JLabel getDuohuamianUriLabel() {
return duohuamianUriLabel;
}
public JTextField getDuohuamianUriText() {
return duohuamianUriText;
}
public JLabel getDuohuamianTypeLabel() {
return duohuamianTypeLabel;
}
public JComboBox getDuohuamianTypeText() {
return duohuamianTypeText;
}
public JButton getRightSettingBut() {
return rightSettingBut;
}
}
|
package com.codezjsos.base.impl;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import com.codezjsos.base.IBaseDao;
public class BaseDaoImpl extends HibernateDaoSupport implements IBaseDao {
private static final Logger logger=LoggerFactory.getLogger(BaseDaoImpl.class);
public void setSessionFacotry(SessionFactory sessionFacotry) {
super.setSessionFactory(sessionFacotry);
}
public <T> void save(T t) throws Exception {
getHibernateTemplate().save(t);
}
public <T> void update(T t) throws Exception {
getHibernateTemplate().update(t);
}
public <T> void delete(T t) throws Exception {
getHibernateTemplate().delete(t);
}
public <T> T findOne(Class<T> clz, Serializable unid) {
return getHibernateTemplate().get(clz, unid);
}
public <T> T load(Class<T> clz, Serializable unid) throws Exception{
// TODO Auto-generated method stub
return getHibernateTemplate().load(clz, unid);
}
private void setParamets(Query query,Object[] obj,int index){
for(Object o:(Object[])obj){
if(o instanceof Object[]){
setParamets(query,(Object[]) o, index);
}else{
query.setParameter(index,o);
}
index++;
}
}
private void setParamets(Object obj,Query query){
if(obj instanceof Map){
query.setProperties((Map<String,Object>)obj);
}else if(obj instanceof Object[]){
setParamets(query, (Object[]) obj,0);
}
}
public <T> T findOne(final String hql, final Object obj) throws Exception{
return getHibernateTemplate().execute(new HibernateCallback<T>() {
public T doInHibernate(Session arg0) throws HibernateException {
Query query=arg0.createQuery(hql);
setParamets(obj, query);
return (T) query.uniqueResult();
}
});
}
public <T> List<T> findAll(final String hql,final Object obj) throws Exception{
// TODO Auto-generated method stub
return getHibernateTemplate().execute(new HibernateCallback<List<T>>() {
public List<T> doInHibernate(Session arg0) throws HibernateException {
Query query=arg0.createQuery(hql);
setParamets(obj, query);
return (List<T>) query.list();
}
});
}
public <T> List<T> findPage(final String hql,final int first,final int max,final Object obj)throws Exception{
// TODO Auto-generated method stub
return getHibernateTemplate().execute(new HibernateCallback<List<T>>() {
public List<T> doInHibernate(Session arg0) throws HibernateException {
Query query=arg0.createQuery(hql);
query.setFirstResult(first);
query.setMaxResults(max);
setParamets(obj, query);
return (List<T>) query.list();
}
});
}
public <T> T findSql(final Class<T> clz,final String sql,final Object obj) throws Exception{
return getHibernateTemplate().execute(new HibernateCallback<T>() {
public T doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
return (T) query.addEntity(clz).uniqueResult();
}
});
}
public <T> List<T> findAllSql(final Class<T> clz,final String sql,final Object obj) throws Exception{
// TODO Auto-generated method stub
return getHibernateTemplate().execute(new HibernateCallback<List<T>>() {
public List<T> doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
return (List<T>) query.addEntity(clz).list();
}
});
}
public <T> List<T> findSqlPage(final Class<T> clz,final String sql, final int first,final int max,final Object obj) throws Exception{
// TODO Auto-generated method stub
return getHibernateTemplate().execute(new HibernateCallback<List<T>>() {
public List<T> doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
query.setFirstResult(first);
query.setMaxResults(max);
return (List<T>) query.addEntity(clz).list();
}
});
}
public void setSessionFactory2(SessionFactory sessionFactory){
setSessionFactory(sessionFactory);
}
public <T> T findSqlNo(final Class<T> clz,final String sql, final Object... obj)
throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<T>() {
public T doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
query.setResultTransformer(Transformers.aliasToBean(clz));
return (T) query.uniqueResult();
}
});
}
public Number findSqlNum(final String sql, final Object... obj)
throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<Number>() {
public Number doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
return (Number) query.uniqueResult();
}
});
}
public Number findSqlNum(final String sql, final Map<String,Object> obj)
throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<Number>() {
public Number doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=arg0.createSQLQuery(sql);
setParamets(obj, query);
return (Number) query.uniqueResult();
}
});
}
@Override
public int executeUpdate(String sql) throws Exception {
getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(sql).executeUpdate();
// List<ZMenu> os = findAllSql(ZMenu.class, "select p.* from z_menu p where EXISTS ( select 1 from z_menu_tmp where id = p.id )", null);
return 1;
}
@Override
public List<Map<String,Object>> findSqlPageResultTransformer(final String sql,
final int first, final int max,final Object obj) throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<List<Map<String,Object>>>() {
public List<Map<String,Object>> doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=(SQLQuery) arg0.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
setParamets(obj, query);
query.setFirstResult(first);
query.setMaxResults(max);
return (List<Map<String,Object>>) query.list();
}
});
}
@Override
public List<Map<String,Object>> findSqlPageResultTransformer(final String sql,final Object obj) throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<List<Map<String,Object>>>() {
public List<Map<String,Object>> doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=(SQLQuery) arg0.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
setParamets(obj, query);
return (List<Map<String,Object>>) query.list();
}
});
}
@Override
public Map<String,Object> findSqlOnePageResultTransformer(
final String sql,final Object obj) throws Exception {
return getHibernateTemplate().execute(new HibernateCallback<Map<String,Object>>() {
public Map<String,Object> doInHibernate(Session arg0) throws HibernateException {
SQLQuery query=(SQLQuery) arg0.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
setParamets(obj, query);
return (Map<String,Object>) query.uniqueResult();
}
});
}
}
|
package com.lqs.hrm.entity;
import java.util.Date;
/**
* 部门考勤统计实体类
* @author luckyliuqs
*
*/
public class CountAttendanceDepartmant {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.cad_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer cadId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.sign_date
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Date signDate;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.dept_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer deptId;
/**
* 部门名称
*/
private String deptName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.dept_emp_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer deptEmpNum;
/**
* 未签到职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.not_sign_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer notSignNum;
/**
* 签到且未签退职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.sign_not_logout_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer signNotLogoutNum;
/**
* 签到且早退职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.sign_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer signLeaveEarlyNum;
/**
* 迟到且未签退职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.late_not_leave_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer lateNotLeaveNum;
/**
* 迟到且早退职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.late_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer lateLeaveEarlyNum;
/**
* 到勤职工数量
* This field was generated by MyBatis Generator.
* This field corresponds to the database column count_attendance_departmant.normal_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
private Integer normalNum;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.cad_id
*
* @return the value of count_attendance_departmant.cad_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getCadId() {
return cadId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.cad_id
*
* @param cadId the value for count_attendance_departmant.cad_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setCadId(Integer cadId) {
this.cadId = cadId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.sign_date
*
* @return the value of count_attendance_departmant.sign_date
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Date getSignDate() {
return signDate;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.sign_date
*
* @param signDate the value for count_attendance_departmant.sign_date
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setSignDate(Date signDate) {
this.signDate = signDate;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.dept_id
*
* @return the value of count_attendance_departmant.dept_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getDeptId() {
return deptId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.dept_id
*
* @param deptId the value for count_attendance_departmant.dept_id
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.dept_emp_num
*
* @return the value of count_attendance_departmant.dept_emp_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getDeptEmpNum() {
return deptEmpNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.dept_emp_num
*
* @param deptEmpNum the value for count_attendance_departmant.dept_emp_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setDeptEmpNum(Integer deptEmpNum) {
this.deptEmpNum = deptEmpNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.not_sign_num
*
* @return the value of count_attendance_departmant.not_sign_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getNotSignNum() {
return notSignNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.not_sign_num
*
* @param notSignNum the value for count_attendance_departmant.not_sign_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setNotSignNum(Integer notSignNum) {
this.notSignNum = notSignNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.sign_not_logout_num
*
* @return the value of count_attendance_departmant.sign_not_logout_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getSignNotLogoutNum() {
return signNotLogoutNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.sign_not_logout_num
*
* @param signNotLogoutNum the value for count_attendance_departmant.sign_not_logout_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setSignNotLogoutNum(Integer signNotLogoutNum) {
this.signNotLogoutNum = signNotLogoutNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.sign_leave_early_num
*
* @return the value of count_attendance_departmant.sign_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getSignLeaveEarlyNum() {
return signLeaveEarlyNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.sign_leave_early_num
*
* @param signLeaveEarlyNum the value for count_attendance_departmant.sign_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setSignLeaveEarlyNum(Integer signLeaveEarlyNum) {
this.signLeaveEarlyNum = signLeaveEarlyNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.late_not_leave_num
*
* @return the value of count_attendance_departmant.late_not_leave_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getLateNotLeaveNum() {
return lateNotLeaveNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.late_not_leave_num
*
* @param lateNotLeaveNum the value for count_attendance_departmant.late_not_leave_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setLateNotLeaveNum(Integer lateNotLeaveNum) {
this.lateNotLeaveNum = lateNotLeaveNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.late_leave_early_num
*
* @return the value of count_attendance_departmant.late_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getLateLeaveEarlyNum() {
return lateLeaveEarlyNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.late_leave_early_num
*
* @param lateLeaveEarlyNum the value for count_attendance_departmant.late_leave_early_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setLateLeaveEarlyNum(Integer lateLeaveEarlyNum) {
this.lateLeaveEarlyNum = lateLeaveEarlyNum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column count_attendance_departmant.normal_num
*
* @return the value of count_attendance_departmant.normal_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public Integer getNormalNum() {
return normalNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column count_attendance_departmant.normal_num
*
* @param normalNum the value for count_attendance_departmant.normal_num
*
* @mbg.generated Tue May 26 23:34:06 CST 2020
*/
public void setNormalNum(Integer normalNum) {
this.normalNum = normalNum;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}
|
package propis;
public class Entrepa extends Propi{
int tipusPa;
boolean esCalent;
public Entrepa(int codi, float preuCost, float preuPublic, String nom, int tipusPa, boolean esCalent){
super(codi,preuCost,preuPublic,nom);
this.tipusPa=tipusPa;
this.esCalent=esCalent;
}
public Entrepa(int codi, float preuCost, float preuPublic, float q, int tipusPa, boolean esCalent){
super(codi, preuCost, preuPublic);
this.tipusPa=tipusPa;
this.esCalent=esCalent;
}
public String toString(){
return (super.toString()+" Entrepa: Tipus pa:"+tipusPa+", Es calent?:"+esCalent);
}
//Mètodes set i get
public int getTipusMassa(){return tipusPa;}
public boolean getEsCalent(){return esCalent;}
public void setTipusMassa(int tipusPa){this.tipusPa=tipusPa;}
public void setEsCalent(boolean esCalent){this.esCalent=esCalent;}
}
|
package com.github.sixro.minihabits.core.util.designpattern;
public interface Command {
void execute();
}
|
package com.yy.lite.brpc.protocol.codec;
import com.baidu.brpc.RpcMethodInfo;
import com.yy.anka.io.rpc.parse.RPCInfo;
/**
* @author donghonghua
* @date 2019/7/26
*/
public interface BrpcMetaConverter<T extends RPCInfo> {
RpcMethodInfo getRpcMethodInfoByReqRPCInfo(T req);
RpcMethodInfo getRpcMethodInfoByRespRPCInfo(T resp);
}
|
package org.fuserleer.network.discovery;
import java.util.Objects;
import org.fuserleer.Context;
import org.fuserleer.common.Agent;
import org.fuserleer.logging.Logger;
import org.fuserleer.logging.Logging;
import org.fuserleer.network.peers.Peer;
public class StandardDiscoveryFilter implements DiscoveryFilter
{
private static final Logger log = Logging.getLogger();
private Context context;
// TODO remove context and use dependency injection instead
public StandardDiscoveryFilter(Context context)
{
this.context = Objects.requireNonNull(context);
}
protected Context getContext()
{
return this.context;
}
public boolean filter(Peer peer)
{
try
{
if (this.context.getNetwork().isWhitelisted(peer.getURI()) == false)
return false;
if (peer.getNode() == null)
return false;
if (peer.getNode().getIdentity().equals(this.context.getNode().getIdentity()))
return false;
if (peer.getNode().getProtocolVersion() != 0 && peer.getNode().getProtocolVersion() < Agent.PROTOCOL_VERSION)
return false;
if (peer.getNode().getAgentVersion() != 0 && peer.getNode().getAgentVersion() <= Agent.REFUSE_AGENT_VERSION)
return false;
if (peer.isBanned())
return false;
return true;
}
catch (Exception ex)
{
log.error("Could not process filter on PeerFilter for Peer:"+peer.toString(), ex);
return false;
}
}
}
|
package com.septacore.ripple.preprocess;
import com.septacore.ripple.preprocess.PPBase;
import com.septacore.ripple.preprocess.types.PPType;
/**
* A constant value (an app with 0 arguments)
* @author rory
*/
public class PPConstantValue extends PPBase {
private final Object value;
/**
*
* @param type
* The type of the value
* @param value
* The value cast as an object
*/
public PPConstantValue(PPType type, final Object value) {
super(type);
this.value = value;
}
@Override
public Object getValue(int evalStep) {
return value;
}
}
|
package jp.personal.server.data.user;
import jp.personal.server.data.BaseVisitor;
import jp.personal.server.enums.LoginIdType;
import lombok.Data;
@Data
public class UserDto extends BaseVisitor {
private Integer userId;
private String loginId;
private String name;
private LoginIdType loginIdType;
private String discription;
private String eMail;
private String tel;
}
|
package com.eric.service;
import com.eric.bean.*;
import com.eric.dao.ApkMapper;
import com.eric.dao.AuthorityApkMapMapper;
import com.eric.dao.AuthorityMapper;
import com.eric.exception.MultipleDuplicateValuesInDatabaseException;
import com.eric.tools.AndroidManifestHelper.AndroidManifestAnalyze;
import com.eric.tools.MD5.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @ClassName: AuthorityService
* @Description: 权限
* @Author: Eric
* @Date: 2019/3/16 0016
* @Email: xiao_cui_vip@163.com
*/
@Service
public class AuthorityService {
@Autowired
AuthorityMapper authorityMapper;
@Autowired
ApkMapper apkMapper;
@Autowired
AuthorityApkMapMapper authorityApkMapMapper;
public void saveAuthority(String path, int apkAttribute) {
//设置线程池的大小为10
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "30");
List<String> amxList = getSimpleAndroidManifestXmlList(path);
if (amxList != null && amxList.size() > 0) {
amxList.parallelStream().forEach(xmlPath -> {
//当前线程名称
String currentThreadName = Thread.currentThread().getName();
System.out.println("-------------" + currentThreadName + "线程开始启动-----------");
List<String> authorityList = null;
try {
authorityList = AndroidManifestAnalyze.xmlHandle(xmlPath);
} catch (Exception e) {
System.out.println(currentThreadName + ":解析xml时出现异常....");
}
//包名
String packageName = "";
if (null != AndroidManifestAnalyze.findPackage(xmlPath)) {
packageName = AndroidManifestAnalyze.findPackage(xmlPath);
}
int apkId = -1;
try {
apkId = checkBeforeInsertAuthority(apkAttribute, packageName);
} catch (MultipleDuplicateValuesInDatabaseException e) {
e.printStackTrace();
}
insertAuthority(apkId, authorityList, packageName);
});
}
}
/**
* 向数据库中插入权限
*
* @param apkId 应用id
* @param authorityList 权限列表
* @param packageName 包名
*/
public void insertAuthority(int apkId, List<String> authorityList, String packageName) {
for (String au : authorityList) {
//获取权限的md5值
String auMd5 = MD5Utils.MD5Encode(au, "utf8");
//先查询数据库中有没有该权限
AuthorityExample authorityExample = getAuthorityExample(auMd5);
List<Authority> authorities = null;
if (null == authorityMapper) {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":authorityMapper为空");
} else {
authorities = authorityMapper.selectByExample(authorityExample);
}
if (authorities.size() > 1) {
//存在多余1条的权限,理论上不可能,出现则抛出异常
new MultipleDuplicateValuesInDatabaseException("数据库中存在" + authorities.size() + "条相同的权限信息");
}
if (authorities.size() == 1) {
//数据库中有1条权限记录
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库中已经存在1条该权限记录,正在查询权限-apk映射关系是否存在....");
Authority authority = authorities.get(0);
Integer authorityId = authority.getAuthorityId();
//查询映射关系是否在数据库中已经存在
AuthorityApkMapExample authorityApkMapExample = getAuthorityApkMapExample(authorityId, apkId);
List<AuthorityApkMap> authorityApkMaps = authorityApkMapMapper.selectByExample(authorityApkMapExample);
//数据库中没有该映射关系
if (checkBeforeInsertAuthorityApkMap(apkId, packageName, authorityId, authorityApkMaps)) {
return;
}
}
//数据库中没有该权限
if (authorities.size() == 0) {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库中没有该权限记录,正在执行插入操作....");
Authority authority = new Authority(au, auMd5);
authorityMapper.insertSelective(authority);
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":权限记录插入成功,正在插入权限-apk关系...");
Integer authorityId = authority.getAuthorityId();
AuthorityApkMap authorityApkMap = new AuthorityApkMap(apkId, authorityId);
authorityApkMapMapper.insertSelective(authorityApkMap);
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":权限-apk关系插入成功");
return;
}
}
}
public boolean checkBeforeInsertAuthorityApkMap(int apkId, String packageName, Integer authorityId, List<AuthorityApkMap> authorityApkMaps) {
if (authorityApkMaps.size() == 0) {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库中不存在权限-apk映射关系,正在插入该映射关系....");
//插入该映射关系
AuthorityApkMap authorityApkMap = new AuthorityApkMap(apkId, authorityId);
authorityApkMapMapper.insertSelective(authorityApkMap);
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":权限-apk映射关系插入完成");
return true;
}
if (authorityApkMaps.size() == 1) {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库中已经存在一条权限-apk映射关系记录,本次未执行插入操作");
return true;
}
if (authorityApkMaps.size() > 1) {
//理论上不可能大于1,出现则抛出异常
new MultipleDuplicateValuesInDatabaseException("数据库中存在" + authorityApkMaps.size() + "条相同的权限-apk映射关系");
}
return false;
}
/**
* 插入权限前进行检查是否存在相同记录
*
* @param apkAttribute 应用属性
* @param packageName 包名
*/
public synchronized int checkBeforeInsertAuthority(int apkAttribute, String packageName) throws MultipleDuplicateValuesInDatabaseException {
int apkId = -1;
Apk apk = new Apk(packageName, apkAttribute);
//在插入之前先判断数据库中有没有
ApkExample apkExample = getApkExample(packageName);
List<Apk> apks = apkMapper.selectByExample(apkExample);
if (apks.size() == 0) {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库中没有该apk记录,正在执行插入....");
//数据库中没有,插入
if (null != apkMapper) {
apkMapper.insertSelective(apk);
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":apk记录插入完成");
} else {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":apkMapper为空");
}
//获取id
if (apk.getApkId() != null) {
apkId = apk.getApkId();
} else {
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":返回的id是空");
}
} else if (apks.size() == 1) {
//数据库中已经存在一条相同的apk记录
System.out.println(Thread.currentThread().getName() + "当前正在提取权限的应用名称为:" + packageName + ":数据库已经存在该apk记录,记录数为:" + apks.size());
//获取Id
Apk apk1 = apks.get(0);
apkId = apk1.getApkId();
} else if (apks.size() >= 2) {
//理论上不可能,出现就抛出异常
throw new MultipleDuplicateValuesInDatabaseException("数据库中存在" + apks.size() + "条相同的apk记录");
}
return apkId;
}
/**
* 获取getAndroidManifestXml列表
*
* @param path 路径
* @return 权限清单列表
*/
public List<String> getAndroidManifestXmlList(String path) {
int total = 0;
System.out.println(">>>>>>开始获取AndroidManifest.xml文件列表........");
List<String> androidManifestXmlList = new ArrayList<>();
File file = new File(path);
if (file.exists()) {
LinkedList<File> list = new LinkedList<File>();
File[] files = file.listFiles();
for (File file2 : files) {
//搜寻xml文件的多线程名称
String finXmlThreadName = Thread.currentThread().getName();
total = addFile2List(total, androidManifestXmlList, list, file2, finXmlThreadName);
}
File temp_file;
while (!list.isEmpty()) {
temp_file = list.removeFirst();
files = temp_file.listFiles();
for (File file2 : files) {
//搜寻xml文件的多线程名称
String finXmlThreadName = Thread.currentThread().getName();
total = addFile2List(total, androidManifestXmlList, list, file2, finXmlThreadName);
}
}
System.out.println(">>>>>>获取AndroidManifest.xml文件列表完成........");
return androidManifestXmlList;
} else {
System.out.println("文件不存在!");
return null;
}
}
public List<String> getSimpleAndroidManifestXmlList(String path) {
int total = 0;
System.out.println(">>>>>>开始获取AndroidManifest.xml文件列表........");
List<String> androidManifestXmlList = new ArrayList<>();
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
File[] currentFiles = f.listFiles();
for (File currentFile : currentFiles) {
if (!currentFile.isDirectory()) {
String currentFileAbsolutePath = currentFile.getAbsolutePath();
String[] arr = currentFileAbsolutePath.split("\\\\");
if (arr[arr.length - 1].equals("AndroidManifest.xml")) {
androidManifestXmlList.add(currentFileAbsolutePath);
total++;
System.out.println("当前获取到的AndroidManifest.xml数量为:" + total);
}
}
}
}
}
}
return androidManifestXmlList;
}
public int addFile2List(int total, List<String> androidManifestXmlList, LinkedList<File> list, File file2, String finXmlThreadName) {
//当前搜寻路径
String file2AbsolutePath = file2.getAbsolutePath();
//System.out.println(finXmlThreadName + ":当前正在搜寻的路径为:" + file2AbsolutePath);
if (file2.isDirectory()) {
//是文件夹
list.add(file2);
} else {
//不是文件夹,判断是否是AndroidManifest.xml文件
//获取文件路径
total = getTotal(total, androidManifestXmlList, file2, finXmlThreadName);
}
return total;
}
/**
* 获取队列中的AndroidManifest.xml总数
*
* @param total xml文件总数
* @param androidManifestXmlList 文件列表
* @param file2 文件
* @return 返回总数
*/
public int getTotal(int total, List<String> androidManifestXmlList, File file2, String finXmlThreadName) {
//获取文件路径
String currentFilePath = file2.getAbsolutePath();
//按照斜线分割
String[] pathArr = currentFilePath.split("\\\\");
//判断是否是AndroidManifest.xml文件
if (pathArr[pathArr.length - 1].equals("AndroidManifest.xml") && !pathArr[pathArr.length - 2].equals("original")) {
androidManifestXmlList.add(currentFilePath);
total++;
System.out.println(finXmlThreadName + "当前获取到的AndroidManifest.xml文件总数为:" + total);
}
return total;
}
/**
* 获取id
*
* @param apks 应用list
* @return id
*/
public int getApkId(List<Apk> apks) {
int apkId;//数据库中已经存在
//获取Id
Apk apk1 = apks.get(0);
apkId = apk1.getApkId();
return apkId;
}
/**
* 获取根据id查询数据库中是否已经存在相应的权限记录的example
*
* @param authorityId 权限id
* @return example
*/
public AuthorityApkMapExample getAuthorityApkMapExample(Integer authorityId, int apkId) {
AuthorityApkMapExample authorityApkMapExample = new AuthorityApkMapExample();
AuthorityApkMapExample.Criteria authorityApkMapCriteria = authorityApkMapExample.createCriteria();
authorityApkMapCriteria.andAuthorityIdEqualTo(authorityId);
authorityApkMapCriteria.andApkIdEqualTo(apkId);
return authorityApkMapExample;
}
/**
* 获取根据权限内容md5值来查询数据库中是否存在相同记录的example
*
* @param auMd5 权限内容md5值
* @return example
*/
public AuthorityExample getAuthorityExample(String auMd5) {
AuthorityExample authorityExample = new AuthorityExample();
AuthorityExample.Criteria criteria = authorityExample.createCriteria();
criteria.andAuthorityMd5EqualTo(auMd5);
return authorityExample;
}
/**
* 获取格局包名来查询数据库中是否存在相同的apk记录的example
*
* @param packageName 包名
* @return example
*/
public ApkExample getApkExample(String packageName) {
ApkExample apkExample = new ApkExample();
ApkExample.Criteria apkCriteria = apkExample.createCriteria();
apkCriteria.andPackageNameEqualTo(packageName);
return apkExample;
}
/**
* 将TXT中的权限存入数据库中
*
* @param src TXT文件路径
*/
public void saveAuthority2DB(String src) {
int sum = 0;
try (FileReader reader = new FileReader(src);
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
//按照空格进行分割
String[] auArr = line.split("\\s+");
String au = auArr[1];
System.out.println(au);
String auMd5 = MD5Utils.MD5Encode(au, "UTF-8");
Authority authority = new Authority(au, auMd5);
//存入数据库
int i = authorityMapper.insertSelective(authority);
sum += i;
}
System.out.println("共插入了:" + sum + "条数据");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从TXT文件中获取到所有的权限
*
* @return
*/
public List<String> getAllAuthorityFromTxt(String path) {
List<String> auList = new ArrayList<>();
try (FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
//非空
if (!StringUtils.isEmpty(line)) {
auList.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return auList;
}
/**
* 遍历一个包含有多个txt文件的文件夹,将apk和权限的映射关系存入数据库中
* 操作的对象是正常APK
*
* @param src
*/
public void saveApkAuthorityApkMap(String src, int apkAttribute) {
File file = new File(src);
if (file.isDirectory()) {
File[] files = file.listFiles();
int i = 0;
for (File f : files) {
String path = f.getAbsolutePath();
String[] pathArr = path.split("\\\\");
//获取包名
String fileName = pathArr[pathArr.length - 1];
String packageName = fileName.substring(0, fileName.length() - 4);
Apk apk = new Apk(packageName, apkAttribute);
ApkExample apkExample = getApkExample(packageName);
List<Apk> apks = apkMapper.selectByExample(apkExample);
if (apks.size() <= 0) {
//插入
apkMapper.insertSelective(apk);
}
//获取当前apk的id 这个地方这么获得的话得到的值是null,改进后的结果如下:
apks = apkMapper.selectByExample(apkExample);
//如果数据库中只有一条记录
Integer apkId = -1;
if (apks.size() == 1) {
apkId = apks.get(0).getApkId();
}
List<String> list = getAllAuthorityFromTxt(path);
for (String a : list) {
//加密权限
String md5Encode = MD5Utils.MD5Encode(a, "UTF-8");
AuthorityExample authorityExample = getAuthorityExample(md5Encode);
List<Authority> authorities = authorityMapper.selectByExample(authorityExample);
//理论上数据库中存在该权限记录的话只有一条
//并且只处理只有一条记录的情况
//没有或者多余1条的都不处理
if (authorities.size() == 1) {
//获取权限id
Integer authorityId = authorities.get(0).getAuthorityId();
if (null != authorityId && apkId != -1) {
AuthorityApkMapExample authorityApkMapExample = getAuthorityApkMapExample(authorityId, apkId);
List<AuthorityApkMap> authorityApkMaps = authorityApkMapMapper.selectByExample(authorityApkMapExample);
//如果数据库中没有该映射关系则插入,其他情况不处理
if (authorityApkMaps.size() <= 0) {
AuthorityApkMap authorityApkMap = new AuthorityApkMap(apkId, authorityId);
authorityApkMapMapper.insertSelective(authorityApkMap);
}
}
}
}
i++;
System.out.println("已经完成" + i + "个");
}
}
}
/**
*
* 获取所有的权限
* @return 权限List
*/
public List<String> getAllAuthorityList() {
List<Authority> authorityList = authorityMapper.selectByExample(null);
List<String> aus = new ArrayList<>();
for (Authority authority : authorityList) {
aus.add(authority.getAuthorityContent());
}
return aus;
}
}
|
package com.example.animation;
import com.example.animation.widget.PieAnimation;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Created by ouyangshen on 2017/11/27.
*/
public class PieActivity extends AppCompatActivity implements OnClickListener {
private PieAnimation pa_circle; // 声明一个饼图动画对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pie);
// 从布局文件中获取名叫pa_circle的饼图动画
pa_circle = findViewById(R.id.pa_circle);
// 设置饼图动画的点击监听器
pa_circle.setOnClickListener(this);
// 开始播放饼图动画
pa_circle.start();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.pa_circle) {
if (!pa_circle.isRunning()) { // 判断饼图动画是否正在播放
// 不在播放,则开始播放饼图动画
pa_circle.start();
}
}
}
}
|
package com.sdl.webapp.common.api.model;
import java.util.Map;
/**
* <p>EntityModel interface.</p>
*/
public interface EntityModel extends ViewModel {
/**
* <p>getId.</p>
*
* @return a {@link java.lang.String} object.
*/
String getId();
/**
* <p>getXpmPropertyMetadata.</p>
*
* @return a {@link java.util.Map} object.
*/
Map<String, String> getXpmPropertyMetadata();
}
|
package View.Classes.Reservation;
import Controller.ChangePage;
import Controller.ChoseUserToResrvation;
import Model.Validations.EmailValidation;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by as on 2017-05-23.
*/
public class ChoseUserToReserwation {
private static JFrame window;
private JPanel reserwationForAdminPanel;
private JButton cancelButton;
private JButton nextButton;
private JTextField textFieldUserLogin;
void summaryPanel(){
window.dispose();
window.setVisible(false);
SummaryOfReserwation.main(null);
}
public ChoseUserToReserwation() {
nextButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
EmailValidation validation = new EmailValidation(textFieldUserLogin.getText());
if(validation.validateMail()) {
ChoseUserToResrvation user = new ChoseUserToResrvation(textFieldUserLogin.getText());
summaryPanel();
}
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ChangePage changePage = new ChangePage();
changePage.goToMainPersonPanel(window);
}
});
}
public static void main(String[] args) {
window = new JFrame("Choice User To reserwation");
window.setContentPane(new ChoseUserToReserwation().reserwationForAdminPanel);
window.setMinimumSize(new Dimension(800, 600));
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.pack();
window.setVisible(true);
}
private void createUIComponents() throws Exception {
reserwationForAdminPanel = new JPanel();
ImageIcon next= new ImageIcon("img/next_button.png");
ImageIcon cancel= new ImageIcon("img/cancel_button.png");
nextButton = new JButton(next);
cancelButton=new JButton(cancel);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main021433 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
List<Integer> arrA = Arrays.stream(br.readLine().split(" "))
.map(x -> Integer.parseInt(x))
.collect(Collectors.toList());
int m = Integer.parseInt(br.readLine());
List<Integer> arrB = Arrays.stream(br.readLine().split(" "))
.map(x -> Integer.parseInt(x))
.collect(Collectors.toList());
Map<Integer, Integer> subsetSumList = getSubsetSumList(arrB);
int count = getArraySum(T, subsetSumList, arrA);
System.out.println(count);
}
private static Map<Integer, Integer> getSubsetSumList(List<Integer> list) {
Map<Integer, Integer> subsetSumList = new HashMap<>();
int[] cache = new int[list.size() + 1];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size() - i; j++) {
cache[j] = cache[j] + list.get(j + i);
if (subsetSumList.get(cache[j]) == null) {
subsetSumList.put(cache[j], 1);
} else {
subsetSumList.put(cache[j], subsetSumList.get(cache[j]) + 1);
}
}
}
return subsetSumList;
}
private static int getArraySum(int N, Map<Integer, Integer> subsetSumMap, List<Integer> list) {
int count = 0;
int left = 0;
int right = 0;
int sum = 0;
while (true) {
if (right == list.size()) {
if (left < list.size() - 1) {
sum -= list.get(left++);
} else {
break;
}
} else if (sum >= N || sum + list.get(right) >= N) {
sum -= list.get(left++);
} else {
sum += list.get(right++);
}
if (sum < N) {
Integer subsetCount = subsetSumMap.get(N - sum);
if (subsetCount != null) {
count += subsetCount;
}
}
}
return count;
}
}
|
package com.lec.ex5_synchronize;
//못껴들게
//thread N개가 작업객체1개를 공유
/*threadA - 작업객체1
threadB - 작업객체1*/
public class ThreadEx implements Runnable {
private int num=0;//thread들이 공유하는 변수 //아무말하지 않으면 자동적으로0
@Override
//synchronized run() 수행 중에는 아무도 못 껴들어 //!!중요 !!
public synchronized void run() {
for(int i=0; i<10; i++) {
out();
try {
Thread.sleep(500);
} catch (InterruptedException e) { //num객체의private변수.A,B가 공유
}
}//for
}//main
private synchronized void out() { //out할때만 안껴들여. out다하고 대기걸때만 껴들 수 있어 // 여기에서만 호출할 method여서 private
String threadName = Thread.currentThread().getName();
if(threadName.equals("A")) {
System.out.println("~~~A수행중~~~");
num++;
} //만약에A가 이러면,B는 이렇게해라 //*********
System.out.println(threadName + "의num="+num); //B는 이것만함 //여기까지 못껴들게 !!중요!!//그러면 새로운 매소드 생성해야
}
}//A가 항상 먼저 나와. 아무도 껴들 수 없어
|
package graft.cpg;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.*;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import graft.traversal.CpgTraversalSource;
import graft.utils.SootUtil;
import graft.*;
import graft.traversal.CpgTraversal;
import static graft.Const.*;
import static graft.traversal.__.*;
import static graft.utils.DisplayUtil.*;
import static graft.utils.FileUtil.*;
/**
* Handles the actual construction of the CPG.
*
* @author Wim Keirsgieter
*/
public class CpgBuilder {
private Banner banner;
private static Logger log = LoggerFactory.getLogger(CpgBuilder.class);
public CpgBuilder() {
banner = new Banner("CPG construction summary");
}
/**
* Build a CPG for the program in the given target directory.
*
* @param targetDir the target directory of the program
*/
public void buildCpg(String targetDir) {
log.info("Building CPG");
log.info("Target directory: {})", targetDir);
long start = System.currentTimeMillis();
try {
// get class files in target director
File target = getTarget(targetDir);
List<File> classFiles = getClassFiles(target);
int nrClasses = classFiles.size();
if (nrClasses == 0) {
banner.println("- No class files in target dir");
banner.display();
return;
}
log.info("{} class(es) to load", nrClasses);
// get class names from class files
List<String> classNames = classFiles.stream()
.map(file -> getClassName(target, file))
.collect(Collectors.toList());
// load classes into Scene
log.info("Loading class(es)...");
SootUtil.loadClasses(classNames.toArray(new String[0]));
long loaded = System.currentTimeMillis();
// build CPGs for all classes
for (int i = 0; i < nrClasses; i++) {
String className = classNames.get(i);
File classFile = classFiles.get(i);
// load class from Scene
log.debug("Building CPG for class '{}'...", className);
SootClass cls = Scene.v().loadClassAndSupport(className);
// build class CPG
Vertex classNode = buildCpg(cls, classFile);
// class edge from root or package node to class node
log.debug("Adding class edge");
String packageName = cls.getPackageName();
Vertex packageNode = packageNodes(packageName);
Graft.cpg().traversal()
.addAstE(CLASS, CLASS)
.from(packageNode).to(classNode)
.iterate();
}
long built = System.currentTimeMillis();
// generate interproc edges
log.info("Individual CPGs loaded, adding interprocedural edges...");
Interproc.genInterprocEdges();
long interproc = System.currentTimeMillis();
banner.println("CPG constructed successfully!");
banner.println();
// performance stats
banner.println("Elapsed times:");
long timeToLoad = loaded - start;
long timeToBuild = built - loaded;
long timeToInter = interproc - built;
banner.println("* " + nrClasses + " class(es) loaded in " + displayTime(timeToLoad));
banner.println("* Intraprocedural CPGs built in " + displayTime(timeToBuild));
banner.println("* Interprocedural edges generated in " + displayTime(timeToInter));
banner.println("* TOTAL ELAPSED TIME: " + displayTime(timeToLoad + timeToBuild + timeToInter));
banner.println();
// CPG stats
banner.println("CPG info:");
long nrNodes = Graft.cpg().traversal().V().count().next();
long nrEdges = Graft.cpg().traversal().E().count().next();
long nrMethods = (long) Graft.cpg().traversal().entries().count().next();
banner.println("* " + nrMethods + " methods in " + nrClasses + " class(es)");
banner.println("* " + nrNodes + " nodes");
banner.println("* " + nrEdges + " edges");
} catch (GraftRuntimeException e) {
banner.println(e.getClass().getName() + " during CPG construction");
banner.println(e.getMessage());
}
banner.display();
}
/**
* Update the CPG given changes in the configured target directory.
*/
public void amendCpg() {
String targetDirName = Options.v().getString(OPT_TARGET_DIR);
File targetDir = new File(targetDirName);
banner = new Banner();
banner.println("Amending CPG");
banner.println("Target dir: " + targetDir);
List<File> classFiles = getClassFiles(targetDir);
if (classFiles.size() == 0) {
banner.println("No class files in target dir");
banner.display();
return;
}
List<File> amendedClasses = amendedClasses();
List<String> classNames = new ArrayList<>();
banner.println("Files changed:");
for (File classFile : amendedClasses) {
String className = getClassName(targetDir, classFile);
banner.println("- " + classFile.getName() + " (" + className + ")");
classNames.add(className);
}
if (amendedClasses.size() == 0) {
banner.println("No files changed - nothing to do");
banner.display();
return;
}
banner.println(amendedClasses.size() + " classes to amend");
long start = System.currentTimeMillis();
Vertex cpgRoot = Graft.cpg().traversal().V().hasLabel(CPG_ROOT).next();
SootUtil.loadClasses(classNames.toArray(new String[0]));
long prevNodes = Graft.cpg().nrV();
long prevEdges = Graft.cpg().nrE();
for (int i = 0; i < amendedClasses.size(); i++) {
log.debug("Amending CPG of class '{}'", classNames.get(i));
SootClass cls = Scene.v().loadClassAndSupport(classNames.get(i));
CpgBuilder.amendCpg(cpgRoot, cls, amendedClasses.get(i));
}
Graft.cpg().commit();
long end = System.currentTimeMillis();
banner.println("CPG amended successfully in " + displayTime(end - start));
banner.println("Nodes: " + Graft.cpg().nrV() + " (prev " + prevNodes + ")");
banner.println("Edges: " + Graft.cpg().nrE() + " (prev " + prevEdges + ")");
banner.display();
}
/**
* Get a list of all classes changed since CPG construction.
*
* @return a list of changed classes
*/
public static List<File> amendedClasses() {
String targetDirName = Options.v().getString(OPT_TARGET_DIR);
File targetDir = new File(targetDirName);
List<File> classFiles = getClassFiles(targetDir);
List<File> amendedClasses = new ArrayList<>();
for (File classFile : classFiles) {
String className = getClassName(targetDir, classFile);
try {
String hash = hashFile(classFile);
if (!hash.equals(CpgUtil.getClassHash(className))) {
amendedClasses.add(classFile);
}
} catch (GraftException e) {
log.warn("Could not hash file '{}'", classFile.getName(), e);
}
}
return amendedClasses;
}
private static Vertex buildCpg(SootClass cls, File classFile) {
String fileHash = UNKNOWN;
try {
fileHash = hashFile(classFile);
} catch (GraftException e) {
log.warn("Could not hash file '{}'", classFile.getName(), e);
}
Vertex classNode = (Vertex) Graft.cpg().traversal()
.addAstV(CLASS, cls.getShortName())
.property(SHORT_NAME, cls.getShortName())
.property(FULL_NAME, cls.getName())
.property(FILE_NAME, classFile.getName())
.property(FILE_PATH, classFile.getPath())
.property(FILE_HASH, fileHash)
.next();
log.debug("{} methods in class", cls.getMethodCount());
for (SootMethod method : cls.getMethods()) {
Body body;
try {
body = method.retrieveActiveBody();
} catch (RuntimeException e) {
// no active bodies for interface methods, abstract methods etc.
log.debug("No active body for method {}", method.getSignature());
continue;
}
if (body == null) continue;
try {
Vertex methodEntry = buildCpg(body);
if (method.isConstructor()) {
Graft.cpg().traversal()
.addAstE(CONSTRUCTOR, CONSTRUCTOR)
.from(classNode).to(methodEntry)
.iterate();
} else {
Graft.cpg().traversal()
.addAstE(METHOD, METHOD)
.from(classNode).to(methodEntry)
.iterate();
}
} catch (SootMethodRefImpl.ClassResolutionFailedException e) {
log.debug("Class resolution failed for method {}", method.getSignature());
}
}
Graft.cpg().commit();
return classNode;
}
private static Vertex buildCpg(Body body) {
UnitGraph unitGraph = new BriefUnitGraph(body);
CfgBuilder cfgBuilder = new CfgBuilder(unitGraph, new AstBuilder());
Vertex methodEntry = cfgBuilder.buildCfg();
PdgBuilder.buildPdg(unitGraph, cfgBuilder.generatedNodes());
return methodEntry;
}
private static void amendCpg(Vertex cpgRoot, SootClass cls, File classFile) {
CpgTraversalSource g = Graft.cpg().traversal();
g.V().hasLabel(AST_NODE)
.has(NODE_TYPE, CLASS)
.has(FULL_NAME, cls.getName())
.drop()
.iterate();
for (SootMethod method : cls.getMethods()) {
CpgUtil.dropMethod(method.getSignature());
}
CpgUtil.dropClass(cls.getName());
Vertex classNode = buildCpg(cls, classFile);
Graft.cpg().traversal()
.addAstE(CLASS, CLASS)
.from(cpgRoot).to(classNode)
.iterate();
// entry nodes of methods in amended classes
CpgTraversal entries = Graft.cpg().traversal().V()
.and(
V(classNode).astOut(METHOD).store("entries"),
V(classNode).astOut(CONSTRUCTOR).store("entries")
).cap("entries").unfold().dedup();
while (entries.hasNext()) {
Vertex entry = (Vertex) entries.next();
Interproc.genInterprocEdges(entry);
}
Graft.cpg().commit();
}
private static File getTarget(String targetDir) {
File target = new File(targetDir);
if (!target.exists()) {
throw new GraftRuntimeException("Target directory '" + targetDir + "' does not exist");
}
if (!target.isDirectory()) {
throw new GraftRuntimeException("Target directory '" + targetDir + "' is not a directory");
}
return target;
}
@SuppressWarnings("unchecked")
private static Vertex packageNodes(String packageName) {
String[] packages = packageName.split("\\.");
Vertex prev = Graft.cpg().root();
for (String pack : packages) {
if (pack.length() == 0) continue;
Vertex packNode = (Vertex) Graft.cpg().traversal().V()
.coalesce(
packageOf(pack),
addPackage(pack)
).next();
Graft.cpg().traversal()
.addAstE(PACKAGE, PACKAGE)
.from(prev).to(packNode)
.iterate();
prev = packNode;
}
return prev;
}
}
|
package edu.upc.util;
public enum MessageTypes {
local,
Remote,
System
}
|
package com.tencent.mm.plugin.setting.ui.fixtools;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.kernel.b;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.bg;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.setting.a.f;
import com.tencent.mm.plugin.setting.a.h;
import com.tencent.mm.plugin.setting.a.i;
import com.tencent.mm.plugin.setting.model.a$a;
import com.tencent.mm.plugin.setting.model.a.1;
import com.tencent.mm.plugin.setting.model.a.2;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMWizardActivity;
import com.tencent.mm.ui.base.a;
@a(3)
public class FixToolsUpLogUploadingUI extends MMWizardActivity {
private Button joh;
public a$a mOG = new 3(this);
private TextView mPo;
private ImageView mPp;
protected ProgressBar mPq;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (!getIntent().getExtras().getBoolean("WizardRootKillSelf", false)) {
setMMTitle(i.fix_tools_uplog);
this.mPo = (TextView) findViewById(f.fix_tools_uplog_uploading);
this.mPp = (ImageView) findViewById(f.fix_tools_uplog_logo);
this.joh = (Button) findViewById(f.fix_tools_uplog_finish);
this.mPq = (ProgressBar) findViewById(f.fix_tools_uplog_progress);
this.mPp.setImageResource(h.fix_tools_uplog);
this.mPo.setText(i.fix_tools_uplog_uploading);
this.joh.setOnClickListener(new 1(this));
setBackBtn(new 2(this));
this.mPq.setVisibility(0);
this.joh.setVisibility(8);
String stringExtra = getIntent().getStringExtra("date");
com.tencent.mm.plugin.setting.model.a btq = com.tencent.mm.plugin.setting.model.a.btq();
com.tencent.mm.plugin.setting.model.a.mOG = this.mOG;
x.i("MicroMsg.FixToolsUplogModel", "startUplog, date:%s, isUploading:%b", new Object[]{stringExtra, Boolean.valueOf(btq.egv)});
if (!btq.egv) {
btq.egv = true;
String str = "weixin";
if (g.Eg().Dx()) {
str = q.GF();
}
x.i("MicroMsg.FixToolsUplogModel", "startNewUplog, chooseTime:%d, time:%d", new Object[]{Long.valueOf(com.tencent.mm.plugin.setting.model.a.wy(new StringBuffer(stringExtra).append("000000").toString())), Integer.valueOf((int) ((((((bi.VF() / 86400000) * 86400000) + 57600000) - 1) - com.tencent.mm.plugin.setting.model.a.wy(new StringBuffer(stringExtra).append("000000").toString())) / 86400000))});
g.DF().a(new bg(new 1(btq, str, r1)), 0);
b.a(new 2(btq));
}
}
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i != 4) {
return super.onKeyDown(i, keyEvent);
}
DT(1);
return true;
}
protected final int getLayoutId() {
return com.tencent.mm.plugin.setting.a.g.fix_tools_uplog_uploading;
}
}
|
package com.example.autowiredemo;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Component
public class FileFortuneService implements FortuneService {
private String fileName="/Users/inouetakayuki/java_practice/spring_hibernate_for_beginners/springdemoannotations/src/main/resources/fortune-data.txt";
private List<String> theFortunes;
private Random myRandom = new Random();
public FileFortuneService() {
System.out.println(">> FileFortuneService: inside default constructor");
}
@PostConstruct
public void loadTheFortunesFile() {
System.out.println(">> FileFortuneService: inside method loadTheFortunesFile");
File theFile = new File(fileName);
System.out.println("Reading fortunes from file: " + theFile);
System.out.println("File exists: " + theFile.exists());
// initialize array list
theFortunes = new ArrayList<String>();
try(BufferedReader br = new BufferedReader(new FileReader(theFile))) {
String tempLine;
while ((tempLine = br.readLine()) != null) {
theFortunes.add(tempLine);
}
} catch(IOException e) {
e.printStackTrace();
}
}
@Override
public String getFortune() {
int index = myRandom.nextInt(theFortunes.size());
return theFortunes.get(index);
}
}
|
package backjoon.graph;
import java.io.*;
import java.util.*;
public class Backjoon2644 {
static class Index{
int value;
int depth;
public Index(int value, int depth){
this.value = value;
this.depth = depth;
}
}
static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int n, m;
static int x, y;
static boolean graph[][];
static int answer;
public static void main(String[] args) throws IOException{
n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
m = Integer.parseInt(br.readLine());
graph = new boolean[n + 1][n + 1];
for(int i = 0 ; i < m; i++){
st = new StringTokenizer(br.readLine());
int _x = Integer.parseInt(st.nextToken());
int _y = Integer.parseInt(st.nextToken());
graph[_x][_y] = graph[_y][_x] = true;
}
solve();
bw.write(answer + "\n");
bw.close();
br.close();
}
static void solve(){
boolean[] check = new boolean[n + 1];
Queue<Index> q = new LinkedList<>();
q.add(new Index(x, 0));
check[x] = true;
while(!q.isEmpty()){
Index curIdx = q.poll();
int curNum = curIdx.value;
int curDepth = curIdx.depth;
if(curNum == y) {
answer = curDepth;
return;
}
for(int i = 1; i <= n; i++){
if(graph[curNum][i] == false) continue;
if(check[i] == true) continue;
q.add(new Index(i, curDepth + 1));
check[i] = true;
}
}
answer = -1;
}
}
|
package com.example.codetribe1.constructionappsuite;
/**
* Created by CodeTribe1 on 2015-01-04.
*/
public class ZoomOutPageTransformerImpl extends ZoomOutPageTransformer {
}
|
package com.jackie.classbook.service.write.impl;
import com.jackie.classbook.common.ClassbookCodeEnum;
import com.jackie.classbook.common.ClassbookException;
import com.jackie.classbook.dao.AddressDao;
import com.jackie.classbook.dao.MateClassMapperDao;
import com.jackie.classbook.dao.MateDao;
import com.jackie.classbook.dao.NationDao;
import com.jackie.classbook.dto.request.BaseIdReqDTO;
import com.jackie.classbook.dto.request.MateAddReqDTO;
import com.jackie.classbook.dto.request.MateDeleteReqDTO;
import com.jackie.classbook.dto.request.MateUpdateReqDTO;
import com.jackie.classbook.entity.Mate;
import com.jackie.classbook.entity.MateClassMapper;
import com.jackie.classbook.process.AbstractService;
import com.jackie.classbook.process.Context;
import com.jackie.classbook.service.write.MateWriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author xujj
* @date 2018/6/29
*/
@Service
public class MateWriteServiceImpl extends AbstractService implements MateWriteService{
@Autowired
private MateDao mateDao;
@Autowired
private AddressDao addressDao;
@Autowired
private NationDao nationDao;
@Autowired
private MateClassMapperDao mateClassMapperDao;
@Override
public Context<MateAddReqDTO, Void> addMate(MateAddReqDTO reqDTO) {
//校验手机号、QQ、邮箱,三者不能重复
if (reqDTO.getMobile() != null){
Mate checkMobile = mateDao.queryMateByMobile(reqDTO.getMobile());
if (checkMobile != null){
throw new ClassbookException(ClassbookCodeEnum.MOBILE_EXIST);
}
}
if (reqDTO.getQq() != null){
Mate checkQq = mateDao.queryMateByQq(reqDTO.getQq());
if (checkQq != null){
throw new ClassbookException(ClassbookCodeEnum.QQ_EXIST);
}
}
if (!StringUtils.isEmpty(reqDTO.getEmail())){
Mate checkEmail = mateDao.queryMateByEmail(reqDTO.getEmail());
if (checkEmail != null){
throw new ClassbookException(ClassbookCodeEnum.EMAIL_EXIST);
}
}
Mate mate = new Mate();
//TODO 获取登录用户的id
mate.setAccountId(7L);
mate.setName(reqDTO.getName());
mate.setMobile(reqDTO.getMobile());
mate.setQq(reqDTO.getQq());
mate.setEmail(reqDTO.getEmail());
mate.setNation(getNation(reqDTO.getNationId()));
mate.setAge(reqDTO.getAge());
mate.setSex(reqDTO.getSex());
mate.setProvince(getAddress(reqDTO.getProvinceCode()));
mate.setCity(getAddress(reqDTO.getCityCode()));
mate.setCountry(getAddress(reqDTO.getCountryCode()));
mate.setTown(reqDTO.getTown());
mate.setVillage(reqDTO.getVillage());
mate.setLiveCity(reqDTO.getLiveCity());
mate.setImpression(reqDTO.getImpression());
mate.setValidFlag((byte)1);
mateDao.insert(mate);
Context<MateAddReqDTO, Void> context = new Context<>();
return context;
}
@Override
public Context<MateUpdateReqDTO, Void> updateMate(MateUpdateReqDTO reqDTO) {
if (reqDTO.getMobile() != null){
Mate checkMobile = mateDao.queryMateByMobile(reqDTO.getMobile());
if (checkMobile != null && !checkMobile.getId().equals(reqDTO.getId())){
throw new ClassbookException(ClassbookCodeEnum.MOBILE_EXIST);
}
}
if (reqDTO.getQq() != null){
Mate checkQq = mateDao.queryMateByQq(reqDTO.getQq());
if (checkQq != null && !checkQq.getId().equals(reqDTO.getId())){
throw new ClassbookException(ClassbookCodeEnum.QQ_EXIST);
}
}
if (!StringUtils.isEmpty(reqDTO.getEmail())){
Mate checkEmail = mateDao.queryMateByEmail(reqDTO.getEmail());
if (checkEmail != null && !checkEmail.getId().equals(reqDTO.getId())){
throw new ClassbookException(ClassbookCodeEnum.EMAIL_EXIST);
}
}
Mate mate = mateDao.queryById(reqDTO.getId());
mate.setName(reqDTO.getName());
mate.setMobile(reqDTO.getMobile());
mate.setQq(reqDTO.getQq());
mate.setEmail(reqDTO.getEmail());
mate.setNation(getNation(reqDTO.getNationId()));
mate.setAge(reqDTO.getAge());
mate.setSex(reqDTO.getSex());
mate.setProvince(getAddress(reqDTO.getProvinceCode()));
mate.setCity(getAddress(reqDTO.getCityCode()));
mate.setCountry(getAddress(reqDTO.getCountryCode()));
mate.setTown(reqDTO.getTown());
mate.setVillage(reqDTO.getVillage());
mate.setLiveCity(reqDTO.getLiveCity());
mate.setImpression(reqDTO.getImpression());
mateDao.update(mate);
//修改班级同学映射表
MateClassMapper mateClassMapper = new MateClassMapper();
mateClassMapper.setMateId(reqDTO.getId());
mateClassMapper.setMateName(reqDTO.getName());
mateClassMapper.setMateType(reqDTO.getAge());
mateClassMapperDao.update(mateClassMapper);
Context<MateUpdateReqDTO, Void> context = new Context<>();
return context;
}
@Override
public Context<MateDeleteReqDTO, Void> deleteMate(MateDeleteReqDTO reqDTO) {
Context<MateDeleteReqDTO, Void> context = new Context<>();
List<String> list = Arrays.asList(reqDTO.getIds().split(","));
List<Long> idList = new ArrayList<>();
for (String string : list){
idList.add(Long.valueOf(string));
}
mateDao.deleteByIdList(idList);
//删除班级同学映射表
Map filters = new HashMap();
filters.put("mateIdList", idList);
mateClassMapperDao.deleteByIdList(filters);
return context;
}
public String getAddress(Long codeId){
if (codeId == null){
return null;
}
return addressDao.queryAddressByCodeId(codeId).getName();
}
public String getNation(Long nationId){
if (nationId == null){
return null;
}
return nationDao.queryNationById(nationId).getNation();
}
}
|
package sample;
import java.io.Serializable;
public class Shield implements Serializable {
private int shieldCount=0;
public int getShieldCount() {
return shieldCount;
}
public void setShieldCount(int shieldCount) {
this.shieldCount = shieldCount;
}
public void updateShildCount(int shieldCount){
this.shieldCount += shieldCount;
}
}
|
package android.support.v7.widget;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
class SearchView$2 implements OnItemClickListener {
final /* synthetic */ SearchView UF;
SearchView$2(SearchView searchView) {
this.UF = searchView;
}
public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
SearchView.a(this.UF, i);
}
}
|
import java.util.*;
public class inverseNumber {
/*Inverse Of A Number*/
/*Points to remember while solving this question
Example 3 1 2 4
idx 4 3 2 1
1 Pr 4 Pada Hai
then 4 Par 1 Dale
Output
Inverse 1 4 2 3
idx 4 3 2 1
*/
public static void main(String[] args) {
// write your code here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int inverseNumber = 0;
int i = 1;
while(n > 0){
int digit = n%10;
n/=10;
inverseNumber += i*(int)Math.pow(10,digit-1);
i++;
}
System.out.println(inverseNumber);
}
}
|
package FolhaDePagamento;
public class TesteFolhaDePagameto {
}
|
package server;
import base.Constants;
import base.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import server.controller.HttpServerController;
/**
* @author guyue
* @date 2018/10/15
*/
public class MainServer {
public void start() {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(Constants.BOSS_THREAD_COUNT);
NioEventLoopGroup workerGroup = new NioEventLoopGroup(Constants.WORKER_THREAD_COUNT);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(
new HttpRequestDecoder(),
new HttpResponseEncoder(),
new HttpObjectAggregator(512 * 1024),
new HttpServerController()
);
}
})
.option(ChannelOption.SO_KEEPALIVE, Constants.SO_KEEP_ALIVE)
.bind(Constants.PORT)
.sync()
.channel()
.closeFuture()
.sync();
} catch (InterruptedException e) {
Logger.system.error(e);
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
|
package micro.auth._config.security.custom;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import com.digitalpersona.uareu.Engine;
import com.digitalpersona.uareu.Fmd;
import com.digitalpersona.uareu.UareUException;
import com.digitalpersona.uareu.UareUGlobal;
import dao.auth.fingerprint.FingerPrintFmdIndiceDerechoDao;
import dao.auth.fingerprint.FingerPrintFmdIndiceIzquierdoDao;
import dao.auth.fingerprint.FingerPrintFmdMedioDerechoDao;
import dao.auth.fingerprint.FingerPrintFmdMedioIzquierdoDao;
import dao.auth.fingerprint.FingerPrintFmdPulgarDerechoDao;
import dao.auth.fingerprint.FingerPrintFmdPulgarIzquierdoDao;
import dao.auth.usuarios.administradores.UsuarioAdministradorDao;
import dao.auth.usuarios.publicos.UsuarioPublicoDao;
import dto.main.MessageWebsocket;
import dto.main.Respuesta;
import micro.auth.services.externos.websocket.interfaces.IWebSocketService;
import model.auth.usuarios.administradores.UsuarioAdministrador;
import model.auth.usuarios.fingerprint.FingerPrintFmdIndiceDerecho;
import model.auth.usuarios.fingerprint.FingerPrintFmdIndiceIzquierdo;
import model.auth.usuarios.fingerprint.FingerPrintFmdMedioDerecho;
import model.auth.usuarios.fingerprint.FingerPrintFmdMedioIzquierdo;
import model.auth.usuarios.fingerprint.FingerPrintFmdPulgarDerecho;
import model.auth.usuarios.fingerprint.FingerPrintFmdPulgarIzquierdo;
import model.auth.usuarios.publicos.UsuarioPublico;
import utils.Converters;
import utils.StaticVariables;
import utils._config.language.Translator;
public class CustomDaoAuthenticationProvider implements AuthenticationProvider {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UsuarioAdministradorDao usuarioAdministradorDao;
@Autowired
public UsuarioPublicoDao usuarioPublicoDao;
@Autowired
private BCryptPasswordEncoder bcrypt;
@Autowired
FingerPrintFmdIndiceDerechoDao fingerPrintFmdIndiceDerechoDao;
@Autowired
FingerPrintFmdIndiceIzquierdoDao fingerPrintFmdIndiceIzquierdoDao;
@Autowired
FingerPrintFmdMedioDerechoDao fingerPrintFmdMedioDerechoDao;
@Autowired
FingerPrintFmdMedioIzquierdoDao fingerPrintFmdMedioIzquierdoDao;
@Autowired
FingerPrintFmdPulgarDerechoDao fingerPrintFmdPulgarDerechoDao;
@Autowired
FingerPrintFmdPulgarIzquierdoDao fingerPrintFmdPulgarIzquierdoDao;
@Autowired
IWebSocketService iWebSocketService;
@Autowired(required = false)
private HttpServletRequest request;
@Value("${websocket.topics.admin}")
private String topicAdmin;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getPrincipal().toString();
String password = authentication.getCredentials().toString();
String huella = null;
try {
huella = request.getParameter(StaticVariables.HUELLA);
} catch (Exception ex) {
}
List<GrantedAuthority> authorities = new ArrayList<>();
UsuarioAdministrador usuarioAdministrador = usuarioAdministradorDao.findByUsername(username);
UsuarioPublico usuarioPublico = usuarioPublicoDao.findByUsernameOrEmail(username, username);
if (usuarioPublico == null && usuarioAdministrador == null) {
throw new UsernameNotFoundException(String.format(Translator.toLocale("login.usuario.noexiste"), username));
}
if (usuarioPublico != null && usuarioAdministrador != null) {
throw new SessionAuthenticationException(
String.format(Translator.toLocale("login.usuario.same.users"), username));
}
// VALIDACION DE USUARIOS ADMINISTRADORES
if (usuarioAdministrador != null) {
if (!usuarioAdministrador.isEnabled()) {
throw new DisabledException(Translator.toLocale("login.usuario.deshabilitado"));
}
if (huella != null) {
if (usuarioAdministrador.getFingerPrintAuthentication() != null) {
if (!fingerPrintLogin(huella, usuarioAdministrador.getFingerPrintAuthentication().getId())) {
throw new BadCredentialsException(Translator.toLocale("login.huella.incorrecta"));
}
} else {
throw new BadCredentialsException(Translator.toLocale("login.huella.noenrollada"));
}
} else {
if (!bcrypt.matches(password, usuarioAdministrador.getPassword())) {
throw new BadCredentialsException(Translator.toLocale("login.password.incorrecto"));
}
}
usuarioAdministrador.getPermisos().forEach(permiso -> {
authorities.add(new SimpleGrantedAuthority(permiso.getEtiqueta()));
});
}
// VALIDACION DE USUARIOS PUBLICOS
if (usuarioPublico != null) {
if (!usuarioPublico.isEnabled()) {
throw new DisabledException(Translator.toLocale("login.usuario.publico.deshabilitado"));
}
if (huella != null) {
if (usuarioPublico.getFingerPrintAuthentication() != null) {
if (!fingerPrintLogin(huella, usuarioPublico.getFingerPrintAuthentication().getId())) {
throw new BadCredentialsException(Translator.toLocale("login.huella.incorrecta"));
}
} else {
throw new BadCredentialsException(Translator.toLocale("login.huella.noenrollada"));
}
} else {
if (!bcrypt.matches(password, usuarioPublico.getPassword())) {
throw new BadCredentialsException(Translator.toLocale("login.password.incorrecto"));
}
}
usuarioPublico.getPermisos().forEach(permiso -> {
authorities.add(new SimpleGrantedAuthority(permiso.getEtiqueta()));
});
}
try {
Respuesta<Boolean> respuesta = iWebSocketService.sendMessage(new MessageWebsocket(username,
Translator.toLocale("notification.login.init.session", new String[] { username }),
"Login", topicAdmin));
logger.info("respuesta iWebSocketService: " + respuesta.getCodigoHttp());
logger.info("respuesta iWebSocketService: " + respuesta.getMensaje());
logger.info("respuesta iWebSocketService: " + respuesta.getCuerpo());
} catch (Exception ex) {
logger.error("iWebSocketService: " + ex.getMessage());
}
Authentication auth = new UsernamePasswordAuthenticationToken(username, password, authorities);
return auth;
}
public boolean fingerPrintLogin(String huella, Long idAuthentication) {
try {
Engine engine = UareUGlobal.GetEngine();
Fmd fmdToIdentify = Converters.importImageString(huella);
List<FingerPrintFmdIndiceDerecho> fingersPrintFmdIndiceDerecho = fingerPrintFmdIndiceDerechoDao
.findByFingerPrintAuthentication(idAuthentication);
List<FingerPrintFmdIndiceIzquierdo> fingersPrintFmdIndiceIzquierdo = fingerPrintFmdIndiceIzquierdoDao
.findByFingerPrintAuthentication(idAuthentication);
List<FingerPrintFmdMedioDerecho> fingersPrintFmdMedioDerecho = fingerPrintFmdMedioDerechoDao
.findByFingerPrintAuthentication(idAuthentication);
List<FingerPrintFmdMedioIzquierdo> fingersPrintFmdMedioIzquierdo = fingerPrintFmdMedioIzquierdoDao
.findByFingerPrintAuthentication(idAuthentication);
List<FingerPrintFmdPulgarDerecho> fingersPrintFmdPulgarDerecho = fingerPrintFmdPulgarDerechoDao
.findByFingerPrintAuthentication(idAuthentication);
List<FingerPrintFmdPulgarIzquierdo> fingersPrintFmdPulgarIzquierdo = fingerPrintFmdPulgarIzquierdoDao
.findByFingerPrintAuthentication(idAuthentication);
List<byte[]> listHuellas = new ArrayList<byte[]>();
listHuellas.addAll(fingersPrintFmdIndiceDerecho.stream().map(FingerPrintFmdIndiceDerecho::getArchivo)
.collect(Collectors.toList()));
listHuellas.addAll(fingersPrintFmdIndiceIzquierdo.stream().map(FingerPrintFmdIndiceIzquierdo::getArchivo)
.collect(Collectors.toList()));
listHuellas.addAll(fingersPrintFmdMedioDerecho.stream().map(FingerPrintFmdMedioDerecho::getArchivo)
.collect(Collectors.toList()));
listHuellas.addAll(fingersPrintFmdMedioIzquierdo.stream().map(FingerPrintFmdMedioIzquierdo::getArchivo)
.collect(Collectors.toList()));
listHuellas.addAll(fingersPrintFmdPulgarDerecho.stream().map(FingerPrintFmdPulgarDerecho::getArchivo)
.collect(Collectors.toList()));
listHuellas.addAll(fingersPrintFmdPulgarIzquierdo.stream().map(FingerPrintFmdPulgarIzquierdo::getArchivo)
.collect(Collectors.toList()));
if (listHuellas.size() > 0) {
Fmd[] m_fmds = new Fmd[listHuellas.size()];
try {
for (int i = 0; i < listHuellas.size(); i++) {
m_fmds[i] = Converters.importImageBytes(listHuellas.get(i));
}
int falsepositive_rate = Engine.PROBABILITY_ONE / 100000;
Engine.Candidate[] vCandidates = engine.Identify(fmdToIdentify, 0, m_fmds, falsepositive_rate,
m_fmds.length);
if (0 != vCandidates.length) {
int falsematch_rate = engine.Compare(fmdToIdentify, 0, m_fmds[vCandidates[0].fmd_index],
vCandidates[0].view_index);
if (falsematch_rate < falsepositive_rate) {
logger.info("Fingerprints matched.");
String str = String.format("dissimilarity score: 0x%x.\n", falsematch_rate);
logger.info(str);
str = String.format("false match rate: %e.\n\n\n",
(double) (falsematch_rate / Engine.PROBABILITY_ONE));
logger.info(str);
return true;
}
}
} catch (UareUException e1) {
e1.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.Id;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import misc.AllPayCheckMacValue;
import misc.Parse;
import model.OrderBean;
import model.OrderService;
@WebServlet("/OrderReturn")
public class OrderReturnServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private OrderService service;
@Override
public void init() throws ServletException {
ServletContext application = this.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
service = (OrderService)context.getBean("OrderService");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String merchantID = req.getParameter("MerchantID");
String merchantTradeNo = req.getParameter("MerchantTradeNo");
String rtnCode = req.getParameter("RtnCode");
String rtnMsg = req.getParameter("RtnMsg");
String tradeNo = req.getParameter("TradeNo");
String tradeAmt = req.getParameter("TradeAmt");
String paymentDate = req.getParameter("PaymentDate");
String paymentType = req.getParameter("PaymentType");
String paymentTypeChargeFee = req.getParameter("PaymentTypeChargeFee");
String tradeDate = req.getParameter("TradeDate");
String simulatePaid = req.getParameter("SimulatePaid");
String checkMacValue = req.getParameter("CheckMacValue");
System.out.println("code="+checkMacValue);
if(AllPayCheckMacValue.merchantID.equals(merchantID)) {
if(Parse.convertInt(rtnCode) == 1) {//模擬付款
if(AllPayCheckMacValue.checkMacValueReturn(merchantTradeNo, rtnCode, rtnMsg,
tradeNo, tradeAmt, paymentDate, paymentType, paymentTypeChargeFee,
tradeDate, simulatePaid, checkMacValue)) {
OrderBean bean = new OrderBean();
bean.setOrderNo(merchantTradeNo);
bean.setPaymentType(paymentType);
bean.setPaymentTypeChargeFee(Parse.convertInt(paymentTypeChargeFee));
bean.setAllPayTradeNo(tradeNo);
bean.setOrderState("已結帳");
service.update2(bean);
out.print("1|OK");
return;
} else {
out.print("0|ErrorMessage");
return;
}
}
}
out.print("1|OK");
}
}
|
package com.tencent.mm.plugin.voip.model.a;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.protocal.c.bhz;
import com.tencent.mm.protocal.c.cas;
import com.tencent.mm.protocal.c.cat;
import com.tencent.mm.protocal.c.cau;
public final class l extends n<cat, cau> {
public l(String str, String str2, String str3, String str4, String str5) {
a aVar = new a();
aVar.dIG = new cat();
aVar.dIH = new cau();
aVar.uri = "/cgi-bin/micromsg-bin/voipstatreport";
aVar.dIF = 320;
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
cat cat = (cat) this.diG.dID.dIL;
cas cas = new cas();
bhz bhz = new bhz();
bhz.VO(str);
cas.spT = bhz;
cas cas2 = new cas();
bhz bhz2 = new bhz();
bhz2.VO(str2);
cas2.spT = bhz2;
cas cas3 = new cas();
bhz bhz3 = new bhz();
bhz3.VO(str3);
cas3.spT = bhz3;
cas cas4 = new cas();
bhz bhz4 = new bhz();
bhz4.VO(str4);
cas4.spT = bhz4;
cas cas5 = new cas();
bhz bhz5 = new bhz();
bhz5.VO(str5);
cas5.spT = bhz5;
cat.svJ = cas;
cat.sxe = cas2;
cat.sxd = cas3;
cat.sxf = cas4;
cat.sxg = cas5;
}
public final int getType() {
return 320;
}
public final e bLm() {
return new 1(this);
}
}
|
package com.lolRiver.river.models;
import com.lolRiver.river.bootstrap.TestAppConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* @author mxia (mxia@lolRiver.com)
* 9/28/13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestAppConfiguration.class})
@WebAppConfiguration
public class KassadinGameDeserializerTest {
@Test
public void dummyTest() {
// TODO xia replace this with real tests
}
}
|
package com.geekhelp.controller;
import com.geekhelp.beans.Page;
import com.geekhelp.entity.Question;
import com.geekhelp.entity.Tag;
import com.geekhelp.service.question.QuestionService;
import com.geekhelp.service.tag.TagService;
import com.geekhelp.util.QuestionUtil;
import com.geekhelp.util.TagUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
/**
* Created by V.Odahovskiy.
* Date 10.02.2015
* Time 12:34
* Package com.geekhelp.controller
*/
@Controller
@RequestMapping(value = {"","/"})
public class IndexController {
@Autowired
private QuestionService questionService;
@Autowired
private TagService tagService;
@Autowired
private QuestionUtil questionUtil;
@Autowired
private TagUtil tagUtil;
@RequestMapping(method = {RequestMethod.GET,RequestMethod.HEAD})
public String index(ModelMap model,
@RequestParam(value = "page",defaultValue = "1",required = false) Integer page,
@RequestParam(value = "results",defaultValue = "5",required = false)Integer recPerPage) {
int size = questionService.findAll().size();
int maxPages = (size % recPerPage == 0)? (size / recPerPage) : (size / recPerPage)+1;
page = (page > maxPages)? maxPages : page;
List<Question> list = questionService.findAll(page, recPerPage);
fillQuestions(list);
int current = page;
int begin = Math.max(1, current - recPerPage);
int end = maxPages;
Page<Question> questionPage = new Page<>(list, begin, current, size, maxPages, recPerPage, end);
model.addAttribute("page", questionPage);
List<Tag> tags = tagService.findAll();
fillTags(tags);
model.addAttribute("tags", tags);
return "index";
}
/**
* Fill questions by data
* @param questions
*/
private void fillQuestions(List<Question> questions){
for (Question question : questions){
questionUtil.fillQuestion(question);
}
}
private void fillTags(List<Tag> tags){
for (Tag tag : tags) {
tagUtil.fillTag(tag);
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2019 Bayu Dwiyan Satria
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import com.bayudwiyansatria.environment.apache.spark.SparkIO;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.mllib.clustering.BisectingKMeansModel;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
public class DistanceMeasureTest {
public static void main(String[] args){
double[][] data= new com.bayudwiyansatria.io.IO().readCSV_double("src/main/resources/bigdata");
int Interval = 10;
double[][] distanceMetric = new com.bayudwiyansatria.mat.Mat().getDistanceMetric(data);
int[] clusters = new int[data.length];
double[][] newData = new com.bayudwiyansatria.mat.Mat().copyArray(data);
int length = data.length;
int NumberOfCluster = 2;
int interval = Interval;
double[] V = new com.bayudwiyansatria.mat.Mat().initArray(Interval + 1, 0.0);
double[] density = new com.bayudwiyansatria.mat.Mat().initArray(Interval + 1, 0.0);
double[] variance;
double[] output = new double[2];
int[][] clusterTable = new int[Interval + 2][data.length];
for(int i = 0; i < data.length; i++) {
clusters[i] = i;
}
do {
int x = 1;
int y = 0;
double distance = distanceMetric[x - 1][y];
for(int i = 0; i < data.length - 1; ++i) {
for(int j = 0; j <= i; ++j) {
if (distance < 0.0 || distanceMetric[i][j] < distance && distanceMetric[i][j] > -1.0) {
distance = distanceMetric[i][j];
x = i + 1;
y = j;
}
}
}
int left;
int right;
if (clusters[x] < clusters[y]) {
left = clusters[y];
right = clusters[x];
} else {
left = clusters[x];
right = clusters[y];
}
int[] position = new com.bayudwiyansatria.utils.Utils().getFind(clusters, "=", left);
for (int value : position) {
clusters[value] = right;
}
clusters = new com.bayudwiyansatria.ml.ML().getNormalLabel(clusters);
position = new com.bayudwiyansatria.utils.Utils().getFind(clusters, "=", right);
--length;
for(int i = 0; i < position.length - 1; ++i) {
for(int j = i + 1; j < position.length; ++j) {
if (position[i] > position[j]) {
distanceMetric[position[i] - 1][position[j]] = -1.0;
} else {
distanceMetric[position[j] - 1][position[i]] = -1.0;
}
}
}
int[][] member = new int[length][];
int[] nMember = new int[length];
double[][] centroid = new double[length][data[0].length];
System.arraycopy(newData, 0, centroid, 0, right);
for(int i = 0; i < length; ++i) {
member[i] = new com.bayudwiyansatria.utils.Utils().getFind(clusters, "=", i);
nMember[i] = member[i].length;
}
double[][] tmp = new double[nMember[right]][];
for(int i = 0; i < nMember[right]; ++i) {
tmp[i] = data[member[right][i]];
}
centroid[right] = new com.bayudwiyansatria.ml.ML().getCentroid(tmp);
System.arraycopy(newData, right + 1, centroid, right + 1, left - right - 1);
System.arraycopy(newData, left + 1, centroid, left, length - left);
newData = centroid;
x = right;
for(y = 0; y < length; ++y) {
if (x != y) {
double DistanceBetweenCentroid = new com.bayudwiyansatria.mat.Mat().getDistance_Relative(newData[x], newData[y]);
for(int i = 0; i < nMember[x]; ++i) {
for(int j = 0; j < nMember[y]; ++j) {
if (member[x][i] > member[y][j]) {
distanceMetric[member[x][i] - 1][member[y][j]] = DistanceBetweenCentroid;
} else {
distanceMetric[member[y][j] - 1][member[x][i]] = DistanceBetweenCentroid;
}
}
}
}
}
if (length <= Interval + 1) {
variance = new com.bayudwiyansatria.ml.ML().getVariance(data, clusters);
V[interval] = variance[0] / variance[1];
clusterTable[interval + 1] = new com.bayudwiyansatria.mat.Mat().copyArray(clusters);
--interval;
}
} while (length > NumberOfCluster);
// Identify Global Optimum
for(int i = Interval - 1; i > 0; --i) {
if (V[i - 1] >= V[i] && V[i + 1] > V[i]) {
density[i] = V[i + 1] + V[i - 1] - 2.0 * V[i];
}
}
variance = new com.bayudwiyansatria.math.Math().getMax(density);
int optimum = (int) variance[1] + 1;
density[optimum - 1] = -1.0;
double globalOptimum;
if (variance[0] == 0.0) {
globalOptimum = 0.0;
} else {
globalOptimum = variance[0] / variance[0];
}
output[0] = optimum;
output[1] = globalOptimum;
new com.bayudwiyansatria.mat.Mat().print(clusterTable[optimum]);
}
public double getDistanceAbsolute(double[] p1, double[] p2) {
double distance = 0.0;
for(int i = 0; i < p1.length; ++i) {
double difference = p2[i] - p1[i];
distance += difference * difference;
}
return Math.sqrt(distance);
}
public static Vector[] getCentroid(JavaRDD<Vector> data){
int NumberOfClusters = 2;
org.apache.spark.mllib.clustering.BisectingKMeans bkm = new org.apache.spark.mllib.clustering.BisectingKMeans().setK(NumberOfClusters);
BisectingKMeansModel model = bkm.run(data);
Vector[] clusterCenters = model.clusterCenters();
for (int i = 0; i < clusterCenters.length; i++) {
System.out.println("Cluster Center " + i + ": " + clusterCenters[i]);
}
return clusterCenters;
}
}
|
package tsubulko.entity;
import tsubulko.entity.Employee;
import lombok.Data;
import java.util.Date;
import java.util.LinkedList;
@Data
abstract class Engineer extends Employee {
// private Project project;
private String project;
public Engineer(int id,Birth dateOfBirth, String name, String surname, Sex sex, String email, Adress adress, Position position, double salary, int experiense, Education education, String project) {
super(id,dateOfBirth, name, surname, sex, email, adress, position, salary, experiense, education);
this.project = project;
}
public Engineer() {
}
}
|
package com.myorg.banking.models;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class BankTransaction {
@Id
@GeneratedValue
private Long id;
private Long fromacct;
public BankTransaction() {}
public BankTransaction(Long id, Long fromacct, Long toacct, Double amounttransfered, Date dateoftransfer) {
super();
this.id = id;
this.fromacct = fromacct;
this.toacct = toacct;
this.amounttransfered = amounttransfered;
this.dateoftransfer = dateoftransfer;
}
private Long toacct;
private Double amounttransfered;
private Date dateoftransfer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getFromacct() {
return fromacct;
}
public void setFromacct(Long fromacct) {
this.fromacct = fromacct;
}
public Long getToacct() {
return toacct;
}
public void setToacct(Long toacct) {
this.toacct = toacct;
}
public Double getAmounttransfered() {
return amounttransfered;
}
public void setAmounttransfered(Double amounttransfered) {
this.amounttransfered = amounttransfered;
}
public Date getDateoftransfer() {
return dateoftransfer;
}
public void setDateoftransfer(Date dateoftransfer) {
this.dateoftransfer = dateoftransfer;
}
}
|
package board.command;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.model.AdminDAO;
import board.model.AdminDTO;
import util.StringUtil;
public class AdminListCmd implements Cmd {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
int pageno = Integer.parseInt(StringUtil.nchk(request.getParameter("pageno"), (String)request.getAttribute("pageno"), "1"));
String[] checked = request.getParameterValues("check");
if(checked == null){
checked = (String[])request.getAttribute("checked");
}
String searchKeyword =StringUtil.nchk(request.getParameter("searchKeyword"), (String)request.getAttribute("searchKeyword") , "");
AdminDAO dao = new AdminDAO();
int totalcnt = dao.AdminListTotalCnt(searchKeyword, checked);
ArrayList<AdminDTO> list = dao.AdminList(searchKeyword, pageno, totalcnt, checked);
request.setAttribute("pageno", String.valueOf(pageno));
request.setAttribute("checked", checked);
request.setAttribute("searchKeyword", searchKeyword);
request.setAttribute("adminList", list);
request.setAttribute("totalcnt", String.valueOf(totalcnt));
}
}
|
package tim.prune.function.estimate.jama;
/**
* QR Decomposition.
*
* For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
* orthogonal matrix Q and an n-by-n upper triangular matrix R so that A = Q*R.
*
* The QR decomposition always exists, even if the matrix does not have full
* rank, so the constructor will never fail. The primary use of the QR
* decomposition is in the least squares solution of nonsquare systems of
* simultaneous linear equations. This will fail if isFullRank() returns false.
*
* Original authors The MathWorks, Inc. and the National Institute of Standards and Technology
* The original public domain code has now been modified and reduced,
* and is placed under GPL2 with the rest of the GpsPrune code.
*/
public class QRDecomposition
{
/** Array for internal storage of decomposition */
private double[][] _QR;
/** Row and column dimensions */
private int _m, _n;
/** Array for internal storage of diagonal of R */
private double[] _Rdiag;
/**
* QR Decomposition, computed by Householder reflections.
*
* @param inA Rectangular matrix
* @return Structure to access R and the Householder vectors and compute Q.
*/
public QRDecomposition(Matrix inA)
{
// Initialize.
_QR = inA.getArrayCopy();
_m = inA.getNumRows();
_n = inA.getNumColumns();
_Rdiag = new double[_n];
// Main loop.
for (int k = 0; k < _n; k++)
{
// Compute 2-norm of k-th column without under/overflow.
double nrm = 0;
for (int i = k; i < _m; i++) {
nrm = Maths.pythag(nrm, _QR[i][k]);
}
if (nrm != 0.0)
{
// Form k-th Householder vector.
if (_QR[k][k] < 0) {
nrm = -nrm;
}
for (int i = k; i < _m; i++) {
_QR[i][k] /= nrm;
}
_QR[k][k] += 1.0;
// Apply transformation to remaining columns.
for (int j = k + 1; j < _n; j++)
{
double s = 0.0;
for (int i = k; i < _m; i++) {
s += _QR[i][k] * _QR[i][j];
}
s = -s / _QR[k][k];
for (int i = k; i < _m; i++) {
_QR[i][j] += s * _QR[i][k];
}
}
}
_Rdiag[k] = -nrm;
}
}
/*
* ------------------------ Public Methods ------------------------
*/
/**
* Is the matrix full rank?
* @return true if R, and hence A, has full rank.
*/
public boolean isFullRank()
{
for (int j = 0; j < _n; j++) {
if (_Rdiag[j] == 0)
return false;
}
return true;
}
/**
* Least squares solution of A*X = B
* @param B A Matrix with as many rows as A and any number of columns
* @return X that minimizes the two norm of Q*R*X-B
* @exception IllegalArgumentException if matrix dimensions don't agree
* @exception RuntimeException if Matrix is rank deficient.
*/
public Matrix solve(Matrix B)
{
if (B.getNumRows() != _m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!isFullRank()) {
throw new RuntimeException("Matrix is rank deficient.");
}
// Copy right hand side
int nx = B.getNumColumns();
double[][] X = B.getArrayCopy();
// Compute Y = transpose(Q)*B
for (int k = 0; k < _n; k++) {
for (int j = 0; j < nx; j++) {
double s = 0.0;
for (int i = k; i < _m; i++) {
s += _QR[i][k] * X[i][j];
}
s = -s / _QR[k][k];
for (int i = k; i < _m; i++) {
X[i][j] += s * _QR[i][k];
}
}
}
// Solve R*X = Y;
for (int k = _n - 1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= _Rdiag[k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j] * _QR[i][k];
}
}
}
return (new Matrix(X, _n, nx).getMatrix(0, _n - 1, 0, nx - 1));
}
}
|
package xyz.mijack.blog.csdn.html;
import com.mustafaferhan.debuglog.DebugLog;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import xyz.mijack.blog.csdn.constant.Constant;
import xyz.mijack.blog.csdn.db.DBUtil;
import xyz.mijack.blog.csdn.model.Author;
import xyz.mijack.blog.csdn.model.Blog;
import xyz.mijack.blog.csdn.model.BlogType;
import xyz.mijack.blog.csdn.model.Category;
import xyz.mijack.blog.csdn.model.SimpleBlog;
/**
* Created by MiJack on 2015/4/17.
*/
public class HTMLHandler {
/**
* 将从网页获取到的文本转化成相应Blog对象,其间包含着{@link xyz.mijack.blog.csdn.model.Author}对象的持久化<br/>
*
* @return 对应的Blog列表对象
* @see org.jsoup.nodes.Document
*/
public static List<Blog> getBlogList(Document document, Category category) {
Elements blogsHtml = document.getElementsByClass(HtmlTagList.class_blog_item);
List<Blog> list = new ArrayList<>();
for (Element element : blogsHtml) {
Blog blog = getBlogFromHtml(element, category);
list.add(blog);
}
return list;
}
public static Blog getBlogFromHtml(Element element, Category category) {
Blog blog = new Blog();
//设置Blog的类型
blog.setCategory(category.getName());
// 获取并设置Blog的标题、内容以及相应的URL
Elements atags = element.getElementsByTag(HtmlTagList.tag_a);
blog.setTitle(atags.get(0).text());
blog.setContent(element.getElementsByTag(HtmlTagList.tag_dd).first().text());
blog.setBlogUrl(atags.get(0).attr(HtmlTagList.attr_href));
//设置Blog的时间
try {
// 无法获取Blog的时间
Document document = Jsoup.parse(new URL(blog.getBlogUrl()), 10000);
String time = document.getElementsByClass(HtmlTagList.class_link_postdate).first().text();
blog.setTime(dateFormat.parse(time).getTime());
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
//设置Aothor的id
Author author = new Author();
Element dtElement = element.getElementsByTag(HtmlTagList.tag_dt).first();
author.setIconUrl(dtElement.getElementsByTag(HtmlTagList.tag_img).first().attr(HtmlTagList.attr_src));
Element userName = element.getElementsByClass(HtmlTagList.class_user_name).first();
author.setAuthorUrl(userName.attr(HtmlTagList.attr_href));
//author对象存入表中,获取对应的id
DBUtil.saveAuthor(author);
blog.setAuthorId(author.getId());
DebugLog.i(blog.toString() + "\n\t" + author.toString());
return blog;
}
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public static List<SimpleBlog> getBlogListFromAuthor(Document document) {
Element blogsHtml = document.getElementById(HtmlTagList.id_article_list);
List<SimpleBlog> list = new ArrayList<>();
for (Element element : blogsHtml.getElementsByClass(HtmlTagList.class_list_item)) {
SimpleBlog blog = getBlogFromAuthor(element);
list.add(blog);
}
return list;
}
private static SimpleBlog getBlogFromAuthor(Element element) {
//一个博客对应的div的class属性为list_item
SimpleBlog simpleBlog = new SimpleBlog();
//类型对应的class属性为ico,同时也可能带有ico_type_Repost、ico_type_Original、ico_type_Translated中的一个
simpleBlog.setBlogTpye(BlogType.getBlogType(element.getElementsByClass(HtmlTagList.class_ico)));
//title 为第一个a标签
Element titleElement = element.getElementsByTag(HtmlTagList.tag_a).first();
String blogUrl=titleElement.attr(HtmlTagList.attr_href);
if (!blogUrl.startsWith(Constant.WEB_ADDRESS)){
blogUrl= Constant.WEB_ADDRESS+blogUrl;
}
simpleBlog.setBlogUrl(blogUrl);
DebugLog.d("simpleBlog:" + simpleBlog.getBlogUrl());
//时间
try {
simpleBlog.setDate(dateFormat.parse(element.getElementsByClass(HtmlTagList.class_link_postdate).first().text()).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
//url
simpleBlog.setTitle(titleElement.text());
DebugLog.d(simpleBlog.toString());
return simpleBlog;
}
}
|
package com.tencent.mm.plugin.appbrand.task;
import com.tencent.mm.plugin.appbrand.ui.AppBrandEmbedUI;
final class a extends f {
final long gtc;
private String gtd;
a(long j) {
super(AppBrandEmbedUI.class, null);
this.gtc = j;
}
final void a(String str, int i, AppBrandRemoteTaskController appBrandRemoteTaskController) {
if (this.gtS.keySet().isEmpty()) {
this.gtd = str;
}
super.a(str, i, appBrandRemoteTaskController);
}
final void vu(String str) {
if (this.gtd.equals(str)) {
this.gtS.clear();
this.gtT.clear();
return;
}
super.vu(str);
}
}
|
package nl.tim.aoc.day15;
import nl.tim.aoc.Challenge;
public class Day15Challenge2 extends Challenge
{
private Day15Challenge1 base;
@Override
public void prepare()
{
base = new Day15Challenge1();
base.prepare();
}
@Override
public Object run(String alternative)
{
return base.run(true, 15);
}
}
|
package com.xuecheng.manage_course.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.CoursePublishResult;
import com.xuecheng.framework.domain.course.ext.CourseView;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.media.response.MediaCode;
import com.xuecheng.framework.exception.CustomerException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsPageClient;
import com.xuecheng.manage_course.config.CoursePublishProperties;
import com.xuecheng.manage_course.dao.*;
import com.xuecheng.manage_course.service.ICourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@EnableConfigurationProperties(CoursePublishProperties.class)
public class CourseService implements ICourseService {
@Autowired
private CoursePublishProperties prop;
@Autowired
private TeachplanMapper teachplanMapper;
@Autowired
private CourseBaseRepository courseBaseRepository;
@Autowired
private TeachplanRepository teachplanRepository;
@Autowired
private CourseMapper courseMapper;
@Autowired
private CourseMarketRepository courseMarketRepository;
@Autowired
private CoursePicRepository coursePicRepository;
@Autowired
private CmsPageClient cmsPageClient;
@Autowired
private CoursePubRepository coursePubRepository;
@Autowired
private TeachplanMediaRepository teachplanMediaRepository;
@Autowired
private TeachplanMediaPubRepository teachplanMediaPubRepository;
@Override
public TeachplanNode findTeachplanList(String courseId) {
if (StringUtils.isBlank(courseId)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
if (teachplanNode == null) {
throw new CustomerException(CourseCode.COURSE_TEACHPLANISNULL);
}
return teachplanMapper.selectList(courseId);
}
//添加课程计划
@Override
@Transactional
public ResponseResult addTeachplan(Teachplan teachplan) {
//检验参数
if (teachplan == null ||
StringUtils.isBlank(teachplan.getCourseid()) ||
StringUtils.isBlank(teachplan.getPname())) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
//取出课程id
String courseid = teachplan.getCourseid();
//取出parentid
String parentid = teachplan.getParentid();
//判断parentid是否为空
if (StringUtils.isBlank(parentid)) {
//为空,获取根节点(一级标题的id)
parentid = getTeachplanRoot(courseid);
}
//取出父结点信息
Optional<Teachplan> teachplanOptional = teachplanRepository.findById(parentid);
if (!teachplanOptional.isPresent()) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
//取出父节点
Teachplan teachplanParent = teachplanOptional.get();
//父节点级别
String parentGrade = teachplanParent.getGrade();
//子结点的级别,根据父结点来判断
teachplan.setParentid(parentid);
teachplan.setStatus("0");
if (parentGrade.equals("1")) {
teachplan.setGrade("2");
} else {
teachplan.setGrade("3");
}
//设置课程id
teachplan.setCourseid(teachplanParent.getCourseid());
teachplanRepository.save(teachplan);
return new ResponseResult(CommonCode.SUCCESS);
}
private String getTeachplanRoot(String courseid) {
//检验courseid
Optional<CourseBase> optional = courseBaseRepository.findById(courseid);
if (!optional.isPresent()) {
throw new CustomerException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
}
CourseBase courseBase = optional.get();
//取出课程计划根节点
List<Teachplan> teachplanList = teachplanRepository.findByCourseidAndParentid(courseid, "0");
if (CollectionUtils.isEmpty(teachplanList)) {
Teachplan teachplan = new Teachplan();
teachplan.setCourseid(courseid);
teachplan.setPname(courseBase.getName());
teachplan.setGrade("1");
teachplan.setParentid("0");
teachplan.setStatus("0");// 未发布
teachplanRepository.save(teachplan);
return teachplan.getId();
}
return teachplanList.get(0).getId();
}
//修改课程计划
@Override
@Transactional
public ResponseResult updateTeachplan(Teachplan teachplan) {
//检验参数
if (teachplan == null ||
StringUtils.isBlank(teachplan.getCourseid()) ||
StringUtils.isBlank(teachplan.getPname())) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
String parentid = teachplan.getParentid();
//取出父结点信息
Optional<Teachplan> teachplanOptional = teachplanRepository.findById(parentid);
if (!teachplanOptional.isPresent()) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
//取出父节点
Teachplan teachplanParent = teachplanOptional.get();
//父节点级别
String parentGrade = teachplanParent.getGrade();
//子结点的级别,根据父结点来判断
teachplan.setParentid(parentid);
teachplan.setStatus("0");
if (parentGrade.equals("1")) {
teachplan.setGrade("2");
} else {
teachplan.setGrade("3");
}
//设置课程id
teachplan.setCourseid(teachplanParent.getCourseid());
teachplanRepository.save(teachplan);
return new ResponseResult(CommonCode.SUCCESS);
}
//通过id查询课程计划
@Override
public Teachplan findTeachplanById(String id) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
Optional<Teachplan> optional = teachplanRepository.findById(id);
if (!optional.isPresent()) {
return null;
}
return optional.get();
}
//通过id删除课程计划
@Override
@Transactional
public ResponseResult deleteTeachplan(String id) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
teachplanRepository.deleteById(id);
return new ResponseResult(CommonCode.SUCCESS);
}
@Override
public QueryResponseResult<CourseInfo> findCourseList(int page, int size, CourseListRequest courseListRequest) {
if (courseListRequest == null) {
courseListRequest = new CourseListRequest();
}
if (size <= 0) {
size = 20;
}
//设置分页参数
PageHelper.startPage(page, size);
//分页查询
List<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
if (CollectionUtils.isEmpty(courseListPage)) {
throw new CustomerException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
}
PageInfo<CourseInfo> pageInfo = PageInfo.of(courseListPage);
QueryResult<CourseInfo> queryResult = new QueryResult<>();
queryResult.setList(courseListPage);
queryResult.setTotalPage(pageInfo.getPageSize());
queryResult.setTotal(pageInfo.getTotal());
return new QueryResponseResult<>(CommonCode.SUCCESS, queryResult);
}
/**
* 添加课程
*
* @param courseBase 新课程
* @return
*/
@Override
@Transactional
public AddCourseResult addCourseBase(CourseBase courseBase) {
courseBase.setStatus("202001");//未发布
courseBaseRepository.save(courseBase);
return new AddCourseResult(CommonCode.SUCCESS, courseBase.getId());
}
/**
* 根据id查询课程
*
* @param courseId 课程id
* @return
*/
@Override
public CourseBase getCoursebaseById(String courseId) {
if (StringUtils.isBlank(courseId)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
return optional.orElse(null);
}
/**
* 更新课程
*
* @param id 主键
* @param courseBase json串
* @return
*/
@Override
@Transactional
public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CourseBase one = this.getCoursebaseById(id);
BeanUtils.copyProperties(courseBase, one);
courseBaseRepository.save(one);
return new ResponseResult(CommonCode.SUCCESS);
}
/**
* 根据课程id查询课程营销数据
*
* @param courseId 课程id
* @return 课程营销数据
*/
@Override
public CourseMarket getCourseMarketById(String courseId) {
if (StringUtils.isBlank(courseId)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
Optional<CourseMarket> optional = courseMarketRepository.findById(courseId);
return optional.orElse(null);
}
/**
* 更新或添加课程营销数据
*
* @param id 主键 课程id
* @param courseMarket json
* @return 更新好的课程营销数据
*/
@Override
public CourseMarket updateCourseMarket(String id, CourseMarket courseMarket) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CourseMarket one = this.getCourseMarketById(id);
if (one != null) {
//更新
one.setCharge(courseMarket.getCharge());
one.setStartTime(courseMarket.getStartTime());//课程有效期,开始时间
one.setEndTime(courseMarket.getEndTime());//课程有效期,结束时间
one.setPrice(courseMarket.getPrice());
one.setQq(courseMarket.getQq());
one.setValid(courseMarket.getValid());
courseMarketRepository.save(one);
} else {
//添加
one = new CourseMarket();
BeanUtils.copyProperties(courseMarket, one);
one.setId(id);
courseMarketRepository.save(one);
}
return one;
}
/**
* 保存图片
*
* @param courseId 课程id
* @param pic 图片id
* @return
*/
@Override
@Transactional
public ResponseResult saveCoursePic(String courseId, String pic) {
if (StringUtils.isBlank(courseId) || StringUtils.isBlank(pic)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CoursePic coursePic = null;
Optional<CoursePic> optional = coursePicRepository.findById(courseId);
coursePic = optional.orElseGet(CoursePic::new);
coursePic.setCourseid(courseId);
coursePic.setPic(pic);
coursePicRepository.save(coursePic);
return new ResponseResult(CommonCode.SUCCESS);
}
/**
* 查询图片
*
* @param courseId 课程id
* @return
*/
@Override
public CoursePic findCoursepic(String courseId) {
if (StringUtils.isBlank(courseId)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
Optional<CoursePic> optional = coursePicRepository.findById(courseId);
return optional.orElse(null);
}
/**
* 删除课程图片
*
* @param courseId 课程id
* @return
*/
@Override
@Transactional
public ResponseResult deleteCoursePic(String courseId) {
if (StringUtils.isBlank(courseId)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
int count = coursePicRepository.deleteByCourseid(courseId);
if (count == 0) {
return new ResponseResult(CommonCode.FAIL);
}
return new ResponseResult(CommonCode.SUCCESS);
}
/**
* 查询课程视图数据
*
* @param id 课程id
* @return
*/
@Override
public CourseView getCourseView(String id) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CourseView courseView = new CourseView();
//查询课程基础信息
Optional<CourseBase> baseOptional = courseBaseRepository.findById(id);
if (baseOptional.isPresent()) {
CourseBase courseBase = baseOptional.get();
courseView.setCourseBase(courseBase);
}
//查询课程图片
Optional<CoursePic> picOptional = coursePicRepository.findById(id);
if (picOptional.isPresent()) {
CoursePic coursePic = picOptional.get();
courseView.setCoursePic(coursePic);
}
//查询课程营销信息
Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
if (marketOptional.isPresent()) {
CourseMarket courseMarket = marketOptional.get();
courseView.setCourseMarket(courseMarket);
}
//查询课程计划
TeachplanNode teachplanNode = teachplanMapper.selectList(id);
courseView.setTeachplanNode(teachplanNode);
return courseView;
}
/**
* 预览课程
*
* @param id 课程id
* @return
*/
@Override
public CoursePublishResult preview(String id) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CourseBase one = this.getCoursebaseById(id);
//发布课程预览页面
CmsPage cmsPage = new CmsPage();
cmsPage.setSiteId(prop.getSiteId());
cmsPage.setPageName(id + ".html");
cmsPage.setPageAliase(one.getName());
cmsPage.setTemplateId(prop.getTemplateId());
cmsPage.setPageWebPath(prop.getPageWebPath());
cmsPage.setPagePhysicalPath(prop.getPagePhysicalPath());
cmsPage.setDataUrl(prop.getDataUrlPre() + id);
//远程请求cms保存页面信息
CmsPageResult cmsPageResult = cmsPageClient.save(cmsPage);
if (!cmsPageResult.isSuccess()) {
return new CoursePublishResult(CommonCode.FAIL, null);
}
//页面id
String pageId = cmsPageResult.getCmsPage().getPageId();
//页面url
String url = prop.getPreviewUrl() + pageId;
return new CoursePublishResult(CommonCode.SUCCESS, url);
}
/**
* 发布页面
*
* @param id 课程id
* @return
*/
@Override
@Transactional
public CoursePublishResult publish(String id) {
//发布课程详情页面
CmsPostPageResult cmsPostPageResult = publishPage(id);
if (!cmsPostPageResult.isSuccess()) {
throw new CustomerException(CommonCode.FAIL);
}
//更新课程状态
CourseBase courseBase = saveCoursePubState(id);
if (courseBase == null) {
throw new CustomerException(CommonCode.FAIL);
}
//课程索引
CoursePub coursePub = createCoursePub(id);
//向数据库保存课程索引信息
CoursePub newCoursePub = saveCoursePub(id, coursePub);
if (newCoursePub == null) {
throw new CustomerException(CourseCode.COURSE_PUBLISH_CREATE_INDEX_ERROR);
}
//保存课程计划媒资信息到待索引表
saveTeachplanMediaPub(id);
//课程缓存
//页面url
String pageUrl = cmsPostPageResult.getPageUrl();
return new CoursePublishResult(CommonCode.SUCCESS, pageUrl);
}
//保存课程计划媒资信息
private void saveTeachplanMediaPub(String courseId) {
//查询课程媒资信息
List<TeachplanMedia> mediaList = teachplanMediaRepository.findByCourseId(courseId);
if (CollectionUtils.isEmpty(mediaList)) {
throw new CustomerException(CourseCode.COURSE_MEDIA_LISTISNULL);
}
//将课程计划媒资信息存储待索引表
//先删后插
int count = teachplanMediaPubRepository.deleteByCourseId(courseId);
List<TeachplanMediaPub> mediaPubList = new ArrayList<>();
for (TeachplanMedia teachplanMedia : mediaList) {
TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);
teachplanMediaPub.setTimestamp(new Date());
mediaPubList.add(teachplanMediaPub);
}
teachplanMediaPubRepository.saveAll(mediaPubList);
}
/**
* 课程计划保存视频信息
*
* @param teachplanMedia 保存的对象
* @return
*/
@Override
public ResponseResult saveMedia(TeachplanMedia teachplanMedia) {
//判断参数
if (teachplanMedia == null || StringUtils.isBlank(teachplanMedia.getTeachplanId())) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
Optional<Teachplan> optional = teachplanRepository.findById(teachplanMedia.getTeachplanId());
if (!optional.isPresent()) {
throw new CustomerException(CourseCode.COURSE_MEDIA_TEACHPLAN_ISNULL);
}
//得到教学计划
Teachplan teachplan = optional.get();
//得到等级
String grade = teachplan.getGrade();
//判断等级
if (!StringUtils.equals("3", grade)) {
throw new CustomerException(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
}
TeachplanMedia one = null;
//查询媒资教学计划表
Optional<TeachplanMedia> mediaOptional = teachplanMediaRepository.findById(teachplanMedia.getTeachplanId());
if (!mediaOptional.isPresent()) {
one = new TeachplanMedia();
}else{
one = mediaOptional.get();
}
one.setTeachplanId(teachplanMedia.getTeachplanId());
one.setMediaId(teachplanMedia.getMediaId());
one.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
one.setMediaUrl(teachplanMedia.getMediaUrl());
one.setCourseId(teachplan.getCourseid());
teachplanMediaRepository.save(one);
return new ResponseResult(CommonCode.SUCCESS);
}
private CourseBase saveCoursePubState(String id) {
CourseBase coursebase = this.getCoursebaseById(id);
//更新发布状态
coursebase.setStatus("202002");
CourseBase save = courseBaseRepository.save(coursebase);
return save;
}
private CmsPostPageResult publishPage(String id) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CourseBase one = this.getCoursebaseById(id);
//发布课程预览页面
CmsPage cmsPage = new CmsPage();
cmsPage.setSiteId(prop.getSiteId());
cmsPage.setPageName(id + ".html");
cmsPage.setPageAliase(one.getName());
cmsPage.setTemplateId(prop.getTemplateId());
cmsPage.setPageWebPath(prop.getPageWebPath());
cmsPage.setPagePhysicalPath(prop.getPagePhysicalPath());
cmsPage.setDataUrl(prop.getDataUrlPre() + id);
//发布页面
return cmsPageClient.postPageQuick(cmsPage);
}
public CoursePub saveCoursePub(String id, CoursePub coursePub) {
if (StringUtils.isBlank(id)) {
throw new CustomerException(CommonCode.INVALID_PARAM);
}
CoursePub coursePubNew = null;
Optional<CoursePub> coursePubOptional = coursePubRepository.findById(id);
coursePubNew = coursePubOptional.orElseGet(CoursePub::new);
//复制
BeanUtils.copyProperties(coursePub, coursePubNew);
//设置主键
coursePubNew.setId(id);
//更新时间戳为最新时间
coursePubNew.setTimestamp(new Date());
//发布时间
coursePubNew.setPubTime(new Date());
//保存
coursePubRepository.save(coursePubNew);
return coursePubNew;
}
private CoursePub createCoursePub(String id){
CoursePub coursePub = new CoursePub();
coursePub.setId(id);
//基础信息
Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
if(courseBaseOptional.isPresent()){
CourseBase courseBase = courseBaseOptional.get();
BeanUtils.copyProperties(courseBase, coursePub);
}
//查询课程图片
Optional<CoursePic> picOptional = coursePicRepository.findById(id);
if(picOptional.isPresent()){
CoursePic coursePic = picOptional.get();
BeanUtils.copyProperties(coursePic, coursePub);
}
//课程营销信息
Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
if(marketOptional.isPresent()){
CourseMarket courseMarket = marketOptional.get();
BeanUtils.copyProperties(courseMarket, coursePub);
}
//课程计划
TeachplanNode teachplanNode = teachplanMapper.selectList(id);
//将课程计划转成json
String teachplanString = JSON.toJSONString(teachplanNode);
coursePub.setTeachplan(teachplanString);
return coursePub;
}
}
|
package org.ubiquity.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to rename a property to a target class.
*
* If no target class is specified, then the rename will apply to any target class.
* This annotation must be placed on a getter or a setter.
*
* Date: 25/05/12
*
* @author François LAROCHE
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface CopyRename {
/**
* The name of the destination property
*
* @return The name of the destination property
*/
String propertyName();
/**
* The class of the objects matching this rename rule
* If Object.class is returned, then this rule will apply to any un-configured rule.
* This property can be safely omitted.
*
* @return the class matching this rule
*/
Class<?> targetClass() default Object.class;
}
|
import java.util.Scanner;
public class UI {
GradeSystems gradesystem=new GradeSystems();
Scanner s=new Scanner(System.in);
UI(){
System.out.println("輸入ID或 Q (結束使用)?");
String stuID=s.nextLine();
if(stuID=="Q"){
System.exit(0);
}
this.checkID(stuID);
}
public void checkID(String ID){
if(gradesystem.containsID(ID)){
while(true){
this.promptCommand();
char op=s.nextLine().charAt(0);
switch(op)
{
case 'G':
gradesystem.showGrade(ID);
break;
case 'R':
gradesystem.showRank(ID);
break;
case 'W':
gradesystem.updateWeights();
break;
case 'E':
System.exit(0);
break;
}
}
}else{
}
}
public void promptCommand(){
System.out.println("輸入指令 1) G 顯示成績 (Grade)");
System.out.println(" 2) R 顯示排名 (Rank)");
System.out.println(" 3) W 更新配分 (Weight)");
System.out.println(" 4) E 離開選單 (Exit)");
}
public void promptID(){
}
public void showFinishMsg(){
}
public void showWelcomeMsg(){
System.out.println("Welcome 李威廷");
//这里要修改!!!
}
}
|
package com.flutterwave.raveandroid.uk;
import com.flutterwave.raveandroid.ViewObject;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
import java.util.HashMap;
public class NullUkView implements UkUiContract.View {
@Override
public void showFetchFeeFailed(String s) {
}
@Override
public void onPaymentError(String message) {
}
@Override
public void showPollingIndicator(boolean active) {
}
@Override
public void showProgressIndicator(boolean active) {
}
@Override
public void onTransactionFeeFetched(String charge_amount, Payload payload, String fee) {
}
@Override
public void onAmountValidationSuccessful(String amountToPay) {
}
@Override
public void onPaymentFailed(String message, String responseAsJSONString) {
}
@Override
public void onValidationSuccessful(HashMap<String, ViewObject> dataHashMap) {
}
@Override
public void showFieldError(int viewID, String message, Class<?> viewType) {
}
@Override
public void onPaymentSuccessful(String status, String flwRef, String responseAsString) {
}
@Override
public void showTransactionPage(String amount, String paymentCode, String accountNumber, String sortCode, String flwRef, String txRef) {
}
}
|
package zystudio.cases.graphics.touch;
import zystudio.demo.R;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
* 我记得这个Case是用来试探多点触摸的..
*
*/
public class CaseForTouch {
private static CaseForTouch sCase;
private Activity mAct;
public static CaseForTouch obtain(Activity act) {
if (sCase == null) {
sCase = new CaseForTouch();
}
sCase.setActivity(act);
return sCase;
}
private void setActivity(Activity act) {
this.mAct = act;
}
public void work() {
mAct.setContentView(R.layout.casefortouch);
RelativeLayout rl = (RelativeLayout)
mAct.findViewById(R.id.casetouch_rl);
rl.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// printMotionEvent(event);
return false;
}
});
ImageView iv = (ImageView) mAct.findViewById(R.id.casetouch_iv);
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
printMotionEvent(event);
return false;
}
});
iv.setImageResource(R.drawable.motor);
}
public void work2(){
ImageView iv=new ImageView(mAct);
iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
iv.setImageResource(R.drawable.motor);
mAct.setContentView(iv);
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
printMotionEvent(event);
return false;
}
});
}
//work1 work2 work3 都不能实现多点触控
public void work3(){
LinearLayout ll=new LinearLayout(mAct);
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
ll.setBackgroundResource(R.drawable.motor);
mAct.setContentView(ll);
ll.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
printMotionEvent(event);
return false;
}
});
}
public void work4(){
CustImageView iv=new CustImageView(mAct);
iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
iv.setImageResource(R.drawable.motor);
mAct.setContentView(iv);
}
private static void printMotionEvent(MotionEvent event) {
//监测ImageView,完全没有检测出多点触摸的东西
Log.i("ertewu", "event 1:" + event.getAction());
Log.i("ertewu", "event 2:" + event.getActionIndex());
Log.i("ertewu", "event 3:" + event.getPointerCount());
Log.i("ertewu", "event 4:" + event.getPointerId(event.getActionIndex()));
final int actionMasked = event.getAction() & MotionEvent.ACTION_MASK;
Log.i("ertewu", "event 5:" +actionMasked);
Log.i("ertewu", "=====================");
}
private static class CustImageView extends ImageView{
public CustImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
printMotionEvent(event);
return super.onTouchEvent(event);
}
}
}
|
package com.croxx.hgwechat.res.didiumbrella;
import com.croxx.hgwechat.model.didiumbrella.DidiUmbrellaUser;
public class ResDidiUmbrellaWithUser extends ResDidiUmbrella {
private DidiUmbrellaUser user;
public ResDidiUmbrellaWithUser() {
}
public ResDidiUmbrellaWithUser(int errcode, String errmsg, DidiUmbrellaUser user) {
super(errcode, errmsg);
this.user = user;
}
/* Getters & Setters */
public DidiUmbrellaUser getUser() {
return user;
}
public void setUser(DidiUmbrellaUser user) {
this.user = user;
}
}
|
package com.qr_market.util;
import android.graphics.Bitmap;
import java.util.ArrayList;
import java.util.List;
/**
* @author Orxan
* @author Kemal Sami KARACA
* @since 07.03.2015
* @version v1.01
*
* @last 08.03.2015
*/
public class MarketProduct {
private String product_uid;
private String product_name;
private String product_price;
private String product_price_type;
private double product_amount;
private List<String> product_image_url;
private List<Bitmap> product_image;
private String p_detail;
private int image_id;
// Static Market Object
private static MarketProduct pInstance = null;
public static MarketProduct getProductInstance() {
if(pInstance == null) {
pInstance = new MarketProduct();
}
return pInstance;
}
// Constructor
public MarketProduct() {
setProduct_image_url(new ArrayList());
setProduct_image(new ArrayList());
}
public MarketProduct(String p_name,String p_detail, String product_price,int image_id) {
this.setProduct_name(p_name);
this.setImage_id(image_id);
this.setP_detail(p_detail);
this.setProduct_price(product_price);
}
@Override
public String toString() {
return "ProductInfo{" +
"product_name='" + getProduct_name() + '\'' +
"product_uid='" + getProduct_uid() + '\'' +
"product_price='" + getProduct_price() + '\'' +
"product_price_type='" + getProduct_price_type() + '\'' +
"product_imgURL='" + getProduct_image_url() + '\'' +
"product_imgSize='" + getProduct_image().size() + '\'' +
'}';
}
@Override
public MarketProduct clone(){
MarketProduct p = new MarketProduct();
p.setProduct_uid(pInstance.getProduct_uid());
p.setProduct_name(pInstance.getProduct_name());
p.setProduct_price(pInstance.getProduct_price());
p.setProduct_price_type(pInstance.getProduct_price_type());
p.setProduct_image_url(pInstance.getProduct_image_url());
p.setProduct_image(pInstance.getProduct_image());
return p;
}
public String getProduct_uid() {
return product_uid;
}
public void setProduct_uid(String product_uid) {
this.product_uid = product_uid;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_price() {
return product_price;
}
public void setProduct_price(String product_price) {
this.product_price = product_price;
}
public String getProduct_price_type() {
return product_price_type;
}
public void setProduct_price_type(String product_price_type) {
this.product_price_type = product_price_type;
}
public String getP_detail() {
return p_detail;
}
public void setP_detail(String p_detail) {
this.p_detail = p_detail;
}
public int getImage_id() {
return image_id;
}
public void setImage_id(int image_id) {
this.image_id = image_id;
}
public List<Bitmap> getProduct_image() {
return product_image;
}
public void setProduct_image(List<Bitmap> product_image) {
this.product_image = product_image;
}
public List<String> getProduct_image_url() {
return product_image_url;
}
public void setProduct_image_url(List<String> product_image_url) {
this.product_image_url = product_image_url;
}
public double getProduct_amount() {
return product_amount;
}
public void setProduct_amount(double product_amount) {
this.product_amount = product_amount;
}
}
|
package com.nmhung.controller;
import com.nmhung.constant.RoleConstant;
import com.nmhung.constant.WebConstant;
import com.nmhung.model.UserModel;
import com.nmhung.service.UserService;
import com.nmhung.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@Autowired
UserService userService;
@GetMapping("/login")
public ModelAndView login(
@RequestParam(name = "msg",defaultValue = "")String msg,
HttpSession session
){
ModelAndView modelAndView = new ModelAndView("login");
return modelAndView;
}
@PostMapping("/login")
public String login(UserModel model, HttpServletRequest request){
UserModel userLogin = userService.login(model.getUsername(), model.getPassword());
String redirect = "";
String msg = "";
if(userLogin == null) {
msg = "get-data-err";
redirect = "/login?msg=err";
// WebUtils.sendRedirect(response, request.getContextPath() + "/login?msg=err");
}else {
SessionUtil.getInstance().put(request, WebConstant.USER_LOGIN,userLogin);
if(userLogin.getRole().getCode().equalsIgnoreCase(RoleConstant.ADMIN)) {
redirect = "/admin/home";
}else if(userLogin.getRole().getCode().equalsIgnoreCase(RoleConstant.TEACHER)) {
redirect = "/teacher/home";
}else {
redirect = "/403";
}
}
return "redirect:" + redirect;
}
}
|
package cl.ufro.infocleta.core;
import java.util.LinkedList;
import java.util.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cl.ufro.infocleta.beans.Alumno;
import cl.ufro.infocleta.beans.ListaAlumnos;
import cl.ufro.infocleta.core.imp.linked.ListaEnlazada;
import cl.ufro.infocleta.gui.ControladorGUI;
/**
*
* @author c3sg
*/
public class SimpleControladorGUI implements ControladorGUI {
private static final Logger LOGGER = LoggerFactory
.getLogger(SimpleControladorGUI.class);
private ListaAlumnos lista;
private Queue<Alumno> cola;
public SimpleControladorGUI() {
lista = new ListaEnlazada();
cola = new LinkedList<>();
}
@Override
public void agregarAlumno(Alumno a) {
LOGGER.debug("Insertando Alumno {}: ", a);
lista.insertar(a);
}
@Override
public Alumno buscarAlumno(Alumno a) {
LOGGER.debug("# Buscando Alumno {}", a);
return lista.obtener(a.getMatricula());
}
@Override
public ListaAlumnos todosAlumnos() {
return lista;
}
@Override
public boolean borrarAlumno(Alumno a) {
LOGGER.debug("Eliminando Alumno {}", a);
return lista.eliminar(a);
}
@Override
public Alumno buscarAlumno(String codigo) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean borrarAlumno(String codigo) {
// TODO Auto-generated method stub
return false;
}
@Override
public void agregarACola(Alumno a) {
cola.add(a);
}
@Override
public Queue<Alumno> obtenerAlumnosEnCola() {
return cola;
}
}
|
package com.actual.batch;
import org.apache.flink.api.common.functions.MapPartitionFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.util.Collector;
/**
* @fileName: MapPartition.java
* @description: MapPartition.java类说明
* @author: by echo huang
* @date: 2020-04-05 11:25
*/
public class MapPartition {
public static void main(String[] args) throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
//产生数据
DataSource<Long> dataSource = env.generateSequence(1, 20);
dataSource.mapPartition(new MyMapPartition())
.print();
}
static class MyMapPartition implements MapPartitionFunction<Long, Long> {
@Override
public void mapPartition(Iterable<Long> values, Collector<Long> out) throws Exception {
long sum = 0;
for (Long value : values) {
sum += value;
}
out.collect(sum);
}
}
}
|
package zajaczkowski.adrian.exceptions;
public class TooBigItemExceptions extends RuntimeException {
private static final String MESSAGE = "Item is too big. It can not be load!";
public TooBigItemExceptions(){
super(MESSAGE);
}
}
|
package generateordernumber;
import generateordernumber.generator.Generator;
import java.util.Calendar;
/**
* <p> Date :2018/5/30 </p>
* <p> Module : </p>
* <p> Description : </p>
* <p> Remark : </p>
*
* @author yangdejun
* @version 1.0
* <p>--------------------------------------------------------------</p>
* <p>修改历史</p>
* <p> 序号 日期 修改人 修改原因 </p>
* <p> 1 </p>
*/
public class Test {
public static void main(String[] args) {
String orderNumber;
// System.out.println(Calendar.getInstance().getTimeInMillis());
for (int i = 0; i < 100000; i ++) {
orderNumber = Generator.generatorOrderNumber();
System.out.println(orderNumber);
}
System.out.println(Calendar.getInstance().getTimeInMillis());
}
}
|
package gov.samhsa.c2s.pcm.service.mapping;
import gov.samhsa.c2s.pcm.infrastructure.dto.FlattenedSmallProviderDto;
import gov.samhsa.c2s.pcm.service.dto.OrganizationDto;
import org.modelmapper.PropertyMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FlattenedSmallProviderDtoToOrganizationDtoMap extends PropertyMap<FlattenedSmallProviderDto, OrganizationDto> {
@Autowired
private FlattenedSmallProviderDtoToIdentifiersDtoConverter flattenedSmallProviderDtoToIdentifiersDtoConverter;
@Override
protected void configure() {
using(flattenedSmallProviderDtoToIdentifiersDtoConverter).map(source).setIdentifiers(null);
map().setName(source.getOrganizationName());
map().getAddress().setLine1(source.getFirstLinePracticeLocationAddress());
map().getAddress().setLine2(source.getSecondLinePracticeLocationAddress());
map().getAddress().setCity(source.getPracticeLocationAddressCityName());
map().getAddress().setState(source.getPracticeLocationAddressStateName());
map().getAddress().setPostalCode(source.getPracticeLocationAddressPostalCode());
map().getAddress().setCountry(source.getPracticeLocationAddressCountryCode());
map().setPhoneNumber(source.getPracticeLocationAddressTelephoneNumber());
}
}
|
public class Helper {
public static enum myCounter {
COUNTER,
SIZE
}
}
|
/**
* Copyright 2007 Jens Dietrich Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package nz.org.take.compiler;
import nz.org.take.AggregationFunction;
import nz.org.take.Predicate;
import nz.org.take.Query;
/**
* Service used to generate the names for artifacts (classes,methods)
* representing artefacts in the kb (predicates, facts, rules, ..).
*
* @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a>
*/
public interface NameGenerator {
/**
* Generate a class name.
* @param p a predicate
* @return a name
*/
public String getClassName(Predicate p);
/**
* Generate a method name for a query
* @param q a query
* @return a method name
*/
public String getMethodName(Query q);
/**
* Generate a method name for an aggregation function
* @param f an aggregation function
* @return a method name
*/
public String getMethodName(AggregationFunction f);
/**
* Generate the name of the class that has the methods
* generated for a query
* @param q a query
* @return a class name
*/
public String getKBFragementName(Query q);
/**
* Generate an accessor name for a slot.
* @param p a predicate
* @param slot a slot position
* @return a name
*/
public String getAccessorNameForSlot(Predicate p, int slot);
/**
* Generate a mutator name for a slot.
* @param p a predicate
* @param slot a slot position
* @return a name
*/
public String getMutatorNameForSlot(Predicate p, int slot);
/**
* Generate a variable name for a slot.
* @param p a predicate
* @param slot a slot position
* @return a name
*/
public String getVariableNameForSlot(Predicate p, int slot);
/**
* Get the (local, without package name) name of the registry class for the aggregation functions.
* @return
*/
public String getAggregationFunctionsRegistryClassName();
/**
* Get the (local, without package name) name of the registry class for the expressions.
* @return
*/
public String getExpressionRegistryClassName();
/**
* Get the (local, without package name) name of the registry class for the constants.
* @return
*/
public String getConstantRegistryClassName();
/**
* Get the (local, without package name) name of the registry class for fact stores.
* @return
*/
public String getFactStoreRegistryClassName();
/**
* Reset cached information. Thsi method should be called before reusing name generators.
*/
public void reset();
}
|
package in.hocg.defaults;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import static javax.swing.UIManager.getInt;
/**
* (๑`灬´๑)
*
* @author hocgin(admin@hocg.in)
* --------------------
* Created 16-8-24.
*/
public class Custom {
public interface RequestParams {
String JUMP = "jump"; // 回跳参数
}
/**
* 错误码翻译器
* @param code
* @return
*/
public static String _message(Integer code) {
switch (code) {
case 200:
return "成功";
case 500:
return "失败";
case 403:
return "文件格式/内容不符合规定";
case 404:
return "查找的数据不存在";
case 999:
default:
return "未知错误";
}
}
public static class Data extends HashMap<String, Object> implements Serializable {
{
put("code", 200);
put("message", "成功");
put("data", null);
}
public Data(Integer code) {
setCode(code);
}
public Data(Map<String, Object> map) {
super(map);
}
public Integer getCode() {
return getInt("code");
}
public Data setCode(Integer code) {
put("code", code);
setMessage(_message(code));
return this;
}
public String getMessage() {
return (String) get("message");
}
public Data setMessage(String message) {
if (message != null) {
put("message", message);
}
return this;
}
public Object getData() {
return get("data");
}
public Data setData(Object data) {
put("data", data);
return this;
}
public static Data NEW(Integer code) {
return new Data(code);
}
public static Data SUCCESS() {
return new Data(200);
}
}
}
|
package homework4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Library {
Library() {}
public void init() throws SQLException {
// Connection conn = DBConnector.getConnection();
// Statement query = conn.createStatement();
//
// query.executeUpdate(
// "CREATE TABLE `books` (" +
// " `id` INT NOT NULL AUTO_INCREMENT," +
// " `isbn` varchar(13) NOT NULL UNIQUE," +
// " `author_id` INT NOT NULL," +
// " `title_id` INT NOT NULL," +
// " PRIMARY KEY (`id`)" +
// ");"
// );
// query.executeUpdate(
// "CREATE TABLE `authors` (" +
// " `id` INT NOT NULL AUTO_INCREMENT," +
// " `name` varchar(100) NOT NULL UNIQUE," +
// " PRIMARY KEY (`id`)" +
// ");"
// );
// query.executeUpdate(
// "CREATE TABLE `titles` (" +
// "`id` INT NOT NULL AUTO_INCREMENT," +
// "`name` varchar(100) NOT NULL UNIQUE," +
// "PRIMARY KEY (`id`)" +
// ");"
// );
// query.executeUpdate(
// "ALTER TABLE `books`" +
// " ADD CONSTRAINT `books_fk0`" +
// " FOREIGN KEY (`author_id`) REFERENCES `authors`(`id`);"
// );
// query.executeUpdate(
// "ALTER TABLE `books`" +
// " ADD CONSTRAINT `books_fk1`" +
// " FOREIGN KEY (`title_id`) REFERENCES `titles`(`id`);"
// );
//
}
public static void main(String[] args) {
// try {
// Library lib = new Library();
// lib.init();
// System.out.println(lib.addAuthor("Ewan"));
// System.out.println(lib.addAuthor("McGregor"));
// System.out.println(lib.getAuthor("Ewan"));
// System.out.println(lib.getAuthor("McGregor"));
// System.out.println(Author.getByName("Ewan"));
// } catch (SQLException e) {
// System.out.println(e.getMessage());
// }
}
}
|
package com.bkSoft.evpn.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.bkSoft.evpn.R;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.AdSize;
import com.facebook.ads.AdView;
public class AboutUsActivity extends AppCompatActivity {
WebView webView_about_us;
Toolbar toolbar_about_us;
AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
toolbar_about_us = findViewById(R.id.toolbar_about_us);
setSupportActionBar(toolbar_about_us);
adView = new AdView(this, (getString(R.string.facebook_banner)), AdSize.BANNER_HEIGHT_50);
LinearLayout adContainer = (LinearLayout) findViewById(R.id.banner_container);
// Add the ad view to your activity layout
adContainer.addView(adView);
adView.setAdListener(new AdListener() {
@Override
public void onError(Ad ad, AdError adError) {
// Ad error callback
Toast.makeText(AboutUsActivity.this, "Error: " + adError.getErrorMessage(),
Toast.LENGTH_LONG).show();
}
@Override
public void onAdLoaded(Ad ad) {
// Ad loaded callback
}
@Override
public void onAdClicked(Ad ad) {
// Ad clicked callback
}
@Override
public void onLoggingImpression(Ad ad) {
// Ad impression logged callback
}
});
adView.loadAd();
toolbar_about_us.setTitle("About Us");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
webView_about_us = findViewById(R.id.webView_about_us);
webView_about_us.getSettings().setJavaScriptEnabled(true);
//todo:: do something
webView_about_us.loadUrl("file:///android_asset/about_us.html");
webView_about_us.setWebViewClient(new MyWebViewClient());
webView_about_us.setHorizontalScrollBarEnabled(false);
webView_about_us.requestFocus();
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.util.Date;
/**
* SClienthostinfoId generated by hbm2java
*/
public class SClienthostinfoId implements java.io.Serializable {
private String uniqueid;
private String hostIp;
private String operationId;
private String deptid;
private String creator;
private Date createtime;
private String notes;
public SClienthostinfoId() {
}
public SClienthostinfoId(String uniqueid, String hostIp, String operationId, String deptid, String creator,
Date createtime, String notes) {
this.uniqueid = uniqueid;
this.hostIp = hostIp;
this.operationId = operationId;
this.deptid = deptid;
this.creator = creator;
this.createtime = createtime;
this.notes = notes;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getHostIp() {
return this.hostIp;
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public String getOperationId() {
return this.operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof SClienthostinfoId))
return false;
SClienthostinfoId castOther = (SClienthostinfoId) other;
return ((this.getUniqueid() == castOther.getUniqueid()) || (this.getUniqueid() != null
&& castOther.getUniqueid() != null && this.getUniqueid().equals(castOther.getUniqueid())))
&& ((this.getHostIp() == castOther.getHostIp()) || (this.getHostIp() != null
&& castOther.getHostIp() != null && this.getHostIp().equals(castOther.getHostIp())))
&& ((this.getOperationId() == castOther.getOperationId())
|| (this.getOperationId() != null && castOther.getOperationId() != null
&& this.getOperationId().equals(castOther.getOperationId())))
&& ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null
&& castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid())))
&& ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null
&& castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null
&& castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getNotes() == castOther.getNotes()) || (this.getNotes() != null
&& castOther.getNotes() != null && this.getNotes().equals(castOther.getNotes())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getUniqueid() == null ? 0 : this.getUniqueid().hashCode());
result = 37 * result + (getHostIp() == null ? 0 : this.getHostIp().hashCode());
result = 37 * result + (getOperationId() == null ? 0 : this.getOperationId().hashCode());
result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode());
result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
result = 37 * result + (getNotes() == null ? 0 : this.getNotes().hashCode());
return result;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* TPrepareRelationId generated by hbm2java
*/
public class TPrepareRelationId implements java.io.Serializable {
private String prepareTaskuid;
private String taskuid;
public TPrepareRelationId() {
}
public TPrepareRelationId(String prepareTaskuid, String taskuid) {
this.prepareTaskuid = prepareTaskuid;
this.taskuid = taskuid;
}
public String getPrepareTaskuid() {
return this.prepareTaskuid;
}
public void setPrepareTaskuid(String prepareTaskuid) {
this.prepareTaskuid = prepareTaskuid;
}
public String getTaskuid() {
return this.taskuid;
}
public void setTaskuid(String taskuid) {
this.taskuid = taskuid;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TPrepareRelationId))
return false;
TPrepareRelationId castOther = (TPrepareRelationId) other;
return ((this.getPrepareTaskuid() == castOther.getPrepareTaskuid())
|| (this.getPrepareTaskuid() != null && castOther.getPrepareTaskuid() != null
&& this.getPrepareTaskuid().equals(castOther.getPrepareTaskuid())))
&& ((this.getTaskuid() == castOther.getTaskuid()) || (this.getTaskuid() != null
&& castOther.getTaskuid() != null && this.getTaskuid().equals(castOther.getTaskuid())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getPrepareTaskuid() == null ? 0 : this.getPrepareTaskuid().hashCode());
result = 37 * result + (getTaskuid() == null ? 0 : this.getTaskuid().hashCode());
return result;
}
}
|
package org.G2B.Games2BuyFrontEnd.Controller;
import org.G2B.Games2BuyEnd.DAO.CategoryDAO;
import org.G2B.Games2BuyEnd.DTO.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class pagecontroller {
@Autowired
private CategoryDAO categoryDAO;
@RequestMapping(value = { "/", "/home", "/index" })
public ModelAndView index() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "Home");
mv.addObject("categories", categoryDAO.list());
mv.addObject("userClickHome", true);
return mv;
}
@RequestMapping(value ="/aboutus")
public ModelAndView aboutus() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "About Us");
mv.addObject("userClickAbout", true);
return mv;
}
@RequestMapping(value ="/contactus")
public ModelAndView contactus() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "Contact Us");
mv.addObject("userClickContact", true);
return mv;
}
@RequestMapping(value ="/show/all/games")
public ModelAndView showAllProducts() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "Store");
mv.addObject("categories", categoryDAO.list());
mv.addObject("userClickAllGames", true);
return mv;
}
@RequestMapping(value ="/show/category/{id}/games")
public ModelAndView showCategoryProducts(@PathVariable("id") int id) {
ModelAndView mv = new ModelAndView("page");
Category category = null;
category = categoryDAO.get(id);
mv.addObject("title",category.getName());
mv.addObject("categories", categoryDAO.list());
mv.addObject("category", category);
mv.addObject("userClickCategoryGames", true);
return mv;
}
}
|
package org.gnunet.integration.internal.execute;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import akka.actor.Props;
import akka.actor.UntypedActor;
public class BoomExecutorWorker extends UntypedActor {
private final static Logger log = LoggerFactory.getLogger(BoomExecutorWorker.class);
// public static Map<String, Counter> counters = new HashMap<String, Counter>();
private static int msgReceivedCount = 0;
private static int startCount = 0;
private static int stopCount = 0;
public static final Long IO_EXCEPTION = 1L;
public static final Long ILLEGAL_ARGUMENT_EXCEPTION = 2L;
public static final Long NULL_POINTER_EXCEPTION = 3L;
public static final Long RUNTIME_EXCEPTION = -1L;
public static Props mkProps() {
return Props.create(BoomExecutorWorker.class);
}
public BoomExecutorWorker() {
super();
}
@Override
public void preStart() {
log.info("Starting BoomExecutorWorker instance # {} {}", self().hashCode(), self().path());
startCount++;
// counters.put(name, new Counter());
}
@Override
public void postStop() {
log.info("Stopping BoomExecutorWorker instance # {} {}", self().hashCode(), self().path());
stopCount++;
// counters.remove(name);
}
@Override
public void onReceive(final Object message) throws Exception {
msgReceivedCount++;
// counters.get(name).incMsg();
if (message instanceof CLIMsg) {
CLIMsg cmd = (CLIMsg) message;
if (cmd.getId().equals(IO_EXCEPTION)) {
log.warn("{}, receive message IOException msgReceivedCount={}",
self().path(),
msgReceivedCount);
throw new IOException();
} else if (cmd.getId().equals(ILLEGAL_ARGUMENT_EXCEPTION)) {
log.warn("{}, receive message IllegalArgumentException msgReceivedCount={}",
self().path(),
msgReceivedCount);
throw new IllegalArgumentException();
} else if (cmd.getId().equals(NULL_POINTER_EXCEPTION)) {
log.warn("{}, receive message NullPointerException msgReceivedCount={}",
self().path());
throw new NullPointerException();
} else {
log.warn("{}, bad bad bad !!!!!!! msgReceivedCount={}",
self().path(),
msgReceivedCount);
throw new RuntimeException("BoomExecutorWorker received an unknow message");
}
}
}
public static int getMsgReceivedCount() {
return msgReceivedCount;
}
public static int getStartCount() {
return startCount;
}
public static int getStopCount() {
return stopCount;
}
public static void resetCounter() {
msgReceivedCount = 0;
startCount = 0;
stopCount = 0;
// counters = new HashMap<String, Counter>();
}
}
|
package XMLSerialize;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class SerializeXML
{
public static void main(String[] args) throws Exception
{
Student st1=new Student();
st1.setRollno(102);
st1.setSname("Anindya");
Student st2=new Student();
st2.setRollno(76);
st2.setSname("Prakhar");
List<Student> s=new ArrayList<>();
s.add(st1);
s.add(st2);
College c=new College();
c.setStudents(s);
File f=new File("D:\\Programming\\JAVA\\Java Created Files\\CollegeList.xml");
XMLEncoder x=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(f)));
x.writeObject(c);
x.close();
}
}
|
package com.example.recycleview_withimage_f;
import androidx.recyclerview.widget.RecyclerView;
public class itemsadapter extends RecyclerView.Adapter {
}
|
package entities;
import physics.PhysObject;
import physics.PlayerPhysObject;
import java.awt.*;
public class Player {
private final String name;
private final PhysObject phys;
private int health = 100;
public Player(String name, Point pos) {
this.name = name;
this.phys = new PlayerPhysObject();
this.phys.setPosition(pos);
}
public void move() {
}
public void attack() {
}
public void takeDamage(int amount) {
health = Math.max(0, health - amount);
if (health == 0) {
die();
}
}
public void heal(int amount) {
health = Math.min(100, health + amount);
}
private void die() {
}
}
|
package it.polimi.ingsw.GC_21.CLIENT;
import java.io.Serializable;
import java.util.Scanner;
import it.polimi.ingsw.GC_21.GAMEMANAGEMENT.GameEndState;
import it.polimi.ingsw.GC_21.VIEW.InputForm;
import it.polimi.ingsw.GC_21.VIEW.LobbyInput;
import it.polimi.ingsw.GC_21.VIEW.PassInput;
import it.polimi.ingsw.GC_21.fx.FXMLGameController;
public class MessageToClient implements Serializable{
protected boolean result;
protected String description;
protected GameEndState gameEndState = GameEndState.Going;
protected boolean waiting; //if the message needs an input from the client!
protected InputForm inputForm;
protected Connections client;
public boolean isWaiting() {
return waiting;
}
public void setWaiting(boolean waiting) {
this.waiting = waiting;
}
public MessageToClient(boolean result, boolean waiting, String description) {
this.result = result;
this.waiting = waiting;
this.description = description;
}
public MessageToClient(boolean result, String description) {
this.result = result;
this.waiting = false;
this.description = description;
}
public InputForm executeCLI(Object LOCK) throws InterruptedException {//notifies the run CLI that there is a new Input form to fill
System.out.println(description);
synchronized (LOCK) {
LOCK.notifyAll();
}
if (inputForm != null) {
inputForm.inputFromCli();
}
return inputForm;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public GameEndState getGameEndState() {
return gameEndState;
}
public void setGameEndState(GameEndState gameEndState) {
this.gameEndState = gameEndState;
}
public void executeGUI(FXMLGameController gameController) {
gameController.printMessDescription(description);
}
public InputForm getInputForm() {
return inputForm;
}
public void setInputForm(InputForm inputForm) {
this.inputForm = inputForm;
}
public void setClient(Connections client) {
this.client = client;
}
}
|
package com.tencent.mm.plugin.bbom;
import com.tencent.mm.az.d;
import com.tencent.mm.kernel.a.c.a;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.model.p;
class k$1 extends a {
k$1() {
}
public final void execute(g gVar) {
p pVar = new p(d.class);
}
}
|
package com.avantir.qrcode.generator;
import java.util.HashMap;
import java.util.Map;
public abstract class EmvTlv {
protected abstract String encode();
protected Map decode(String qrCodeTlv){
Map<String, Object> tlvMap = new HashMap<>();
int index = 0;
String qrCodeTlvTmp = qrCodeTlv;
while (qrCodeTlvTmp.length() > 0 && index < 99){
String tag = qrCodeTlvTmp.substring(0, 2);
qrCodeTlvTmp = qrCodeTlvTmp.substring(2);
String len = qrCodeTlvTmp.substring(0, 2);
qrCodeTlvTmp = qrCodeTlvTmp.substring(2);
int lenInt = Integer.parseInt(len);
String value = qrCodeTlvTmp.substring(0, lenInt);
qrCodeTlvTmp = qrCodeTlvTmp.substring(lenInt);
System.out.println("Tag: " + tag + " Value: " + value);
tlvMap.put(tag, value);
}
return tlvMap;
}
}
|
package kodlamaio.hrms.entities.concretes.cv;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import kodlamaio.hrms.entities.concretes.Candidate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "cv_experience")
public class CvExperience {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "company_name")
private String companyName;
@Column(name = "position_name")
private String positionName;
@Column(name = "start_date")
private LocalDate startDate;
@Column(name = "end_date")
private LocalDate endDate;
@ManyToOne
@JoinColumn(name = "candidate_id")
private Candidate candidate;
}
|
package littleservantmod.entity;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.ai.EntityAITasks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public abstract class EntityLittleServantBlock extends EntityLittleServantBase {
/** (Usually one-shot) tasks used to select an use block target */
public final EntityAITasks targetBlockTasks;
/** The active target the Task system uses for tracking */
private BlockPos useTargetBlock = BlockPos.ORIGIN;
public EntityLittleServantBlock(World worldIn) {
super(worldIn);
this.targetBlockTasks = new EntityAITasks(worldIn != null && worldIn.profiler != null ? worldIn.profiler : null);
}
@Override
public void addBlockTargetAI(int priority, EntityAIBase task) {
this.targetBlockTasks.addTask(priority, task);
}
@Override
protected void updateAITasks() {
super.updateAITasks();
this.world.profiler.startSection("targetBlockSelector");
this.targetBlockTasks.onUpdateTasks();
this.world.profiler.endSection();
}
public BlockPos getUseTargetBlock() {
return useTargetBlock;
}
public void setUseTargetBlock(BlockPos useTargetBlock) {
this.useTargetBlock = useTargetBlock;
}
}
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package BPMN.impl;
import BPMN.BPMNEventErrorDefault;
import BPMN.BPMNPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Event Error Default</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class BPMNEventErrorDefaultImpl extends BPMNModelElementImpl implements BPMNEventErrorDefault {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BPMNEventErrorDefaultImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return BPMNPackage.Literals.BPMN_EVENT_ERROR_DEFAULT;
}
} //BPMNEventErrorDefaultImpl
|
package br.org.funcate.glue.model;
public class InfoClick {
private String selectedThemeName = "none";
private double xPosition;
private double yPosition;
public double getxPosition() {
return xPosition;
}
public void setxPosition(double xPosition) {
this.xPosition = xPosition;
}
public double getyPosition() {
return yPosition;
}
public void setyPosition(double yPosition) {
this.yPosition = yPosition;
}
public String getSelectedThemeName() {
return selectedThemeName;
}
public void setSelectedThemeName(String selectedTheme) {
this.selectedThemeName = selectedTheme;
}
}
|
package wx.realware.wx.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Arrays;
public class CheckForWX {
public static final String tooken = "joe_hqq168"; // 开发者自行定义Tooken
public static final String grant_type = "client_credential";
public static final String appid = "wx6b746c1803305e6e";//測試公眾號
public static final String appsecret = "2e6af3013a63dba54b34a29b593a0f13";//第三方用户唯一凭证密钥,即appsecret
public static String Access_token = "";
/**
*
返回码 说明
-1 系统繁忙,此时请开发者稍候再试
0 请求成功https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
40001 AppSecret错误或者AppSecret不属于这个公众号,请开发者确认AppSecret的正确性
40002 请确保grant_type字段值为client_credential
40164 调用接口的IP地址不在白名单中,请在接口IP白名单中进行设置。(小程序及小游戏调用不要求IP地址在白名单内。)
* @throws Exception
* @throws IOException
*/
public static String falshAccess_token() throws IOException, Exception
{
String url = "https://api.weixin.qq.com/cgi-bin/token?"
+ "grant_type=client_credential&appid="+CheckForWX.appid+"&secret="+CheckForWX.appsecret;
return reqestWXInterface(url);
//10__g0s1AgoAKMzKcMI7ySHbZMxSRNsYbVMWjoHWFOdTSXw7ir_MZrFSUAs7nthe9ShZJhzbFY8CpYdFqfuqSVVnYFNWr4Z65OwDol5TvlGR5CEvnOtVnUM3_LInUsu9vXYgwv44GhANIc2qcvmSULdADAYAR
}
public static String reqestWXInterface(String url) throws Exception
{
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
System.err.println(resultBuffer.toString());
return resultBuffer.toString();
}
public static boolean checkSignature(String signature,
String timestamp, String nonce) {
// 1.定义数组存放tooken,timestamp,nonce
String[] arr = { tooken, timestamp, nonce };
// 2.对数组进行排序
Arrays.sort(arr);
// 3.生成字符串
StringBuffer sb = new StringBuffer();
for (String s : arr) {
sb.append(s);
}
String temp = getSha1(sb.toString());
// 5.将加密后的字符串,与微信传来的加密签名比较,返回结果
return temp.equals(signature);
}
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
public static void main(String args[])
{
try {
CheckForWX.Access_token = falshAccess_token();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package control_de_versiones;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* @author donQ
*/
public class Vista extends JFrame implements ActionListener {
JTextField Nombre = new JTextField();
JTextField PrimerApellido = new JTextField();
JTextField SegundoApellido = new JTextField();
JTextField Edad = new JTextField();
JTextField Sexo = new JTextField();
JTextField DNI = new JTextField();
JLabel Int_Nombre = new JLabel("Introduce Nombre");
JLabel Int_PrimerApellido = new JLabel("Introduce primer Apellido");
JLabel Int_SegundoApellido = new JLabel("Introduce segundo Apellido");
JLabel Int_Edad = new JLabel("Introduce Edad");
JLabel Int_Sexo = new JLabel("Introduce Sexo");
JLabel Int_DNI = new JLabel("Introduce DNI");
JLabel Titulo = new JLabel("Añadir Usuario", JLabel.CENTER);
JButton buttonInsert = new JButton("Añadir");
JPanel contenedor = new JPanel();
Vista() {
this.setSize(1024, 130);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
contenedor = new JPanel(new GridLayout(2, 6));
contenedor.add(Int_DNI);
contenedor.add(Int_Nombre);
contenedor.add(Int_PrimerApellido);
contenedor.add(Int_SegundoApellido);
contenedor.add(Int_Edad);
contenedor.add(Int_Sexo);
contenedor.add(DNI);
contenedor.add(Nombre);
contenedor.add(PrimerApellido);
contenedor.add(SegundoApellido);
contenedor.add(Edad);
contenedor.add(Sexo);
add(contenedor, "Center");
buttonInsert.addActionListener(this);
add(buttonInsert, "South");
add(Titulo, "North");
}
@Override
public void actionPerformed(ActionEvent e) {
boolean ok=false;
try{
persona Persona = new persona(DNI.getText(), Nombre.getText(), PrimerApellido.getText(), SegundoApellido.getText(), Integer.parseInt(Edad.getText()), Sexo.getText());
Controlador controlador = new Controlador();
ok=controlador.Insertar(Persona);
if(ok==true){
Titulo.setText("Se ha insertado correctamente");
}else{
Titulo.setText("No se ha insertado correctamente");
}
}catch (Exception t){
Titulo.setText("Faltan Campos para llenar");
}
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.business.impl.elem;
import java.util.List;
import javax.persistence.EntityManager;
import net.nan21.dnet.core.api.session.Session;
import net.nan21.dnet.core.business.service.entity.AbstractEntityService;
import net.nan21.dnet.module.bd.business.api.elem.IElementCategoryService;
import net.nan21.dnet.module.bd.domain.impl.elem.ElementCategory;
import net.nan21.dnet.module.bd.domain.impl.elem.Engine;
/**
* Repository functionality for {@link ElementCategory} domain entity. It contains
* finder methods based on unique keys as well as reference fields.
*
*/
public class ElementCategory_Service
extends
AbstractEntityService<ElementCategory>
implements
IElementCategoryService {
public ElementCategory_Service() {
super();
}
public ElementCategory_Service(EntityManager em) {
super();
this.setEntityManager(em);
}
@Override
public Class<ElementCategory> getEntityClass() {
return ElementCategory.class;
}
/**
* Find by unique key
*/
public ElementCategory findByEngine_name(Engine engine, String name) {
return (ElementCategory) this
.getEntityManager()
.createNamedQuery(ElementCategory.NQ_FIND_BY_ENGINE_NAME)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("engine", engine).setParameter("name", name)
.getSingleResult();
}
/**
* Find by unique key
*/
public ElementCategory findByEngine_name(Long engineId, String name) {
return (ElementCategory) this
.getEntityManager()
.createNamedQuery(
ElementCategory.NQ_FIND_BY_ENGINE_NAME_PRIMITIVE)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("engineId", engineId).setParameter("name", name)
.getSingleResult();
}
/**
* Find by reference: engine
*/
public List<ElementCategory> findByEngine(Engine engine) {
return this.findByEngineId(engine.getId());
}
/**
* Find by ID of reference: engine.id
*/
public List<ElementCategory> findByEngineId(String engineId) {
return (List<ElementCategory>) this
.getEntityManager()
.createQuery(
"select e from ElementCategory e where e.clientId = :clientId and e.engine.id = :engineId",
ElementCategory.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("engineId", engineId).getResultList();
}
}
|
package br.com.ufmt.ic.wfd;
public class ItemListView {
private String texto;
private String ssid;
private int iconeRid;
public ItemListView(String texto, int iconeRid)
{
this.texto = texto;
this.iconeRid = iconeRid;
}
public String getSsid() {
return ssid;
}
public void setSsid(String ssid) {
this.ssid = ssid;
}
public int getIconeRid()
{
return iconeRid;
}
public void setIconeRid(int iconeRid)
{
this.iconeRid = iconeRid;
}
public String getTexto()
{
return texto;
}
public void setTexto(String texto)
{
this.texto = texto;
}
}
|
/*
* #%L
* Janus
* %%
* Copyright (C) 2014 KIXEYE, Inc
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.kixeye.janus;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import com.kixeye.janus.loadbalancer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.kixeye.janus.serverlist.ConfigServerList;
import com.kixeye.janus.serverlist.ConstServerList;
import com.kixeye.janus.serverlist.EurekaServerList;
import com.kixeye.janus.serverlist.ServerList;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicPropertyFactory;
/**
* This class provides the main entry point for retrieving the "best" server instance within a single service cluster.
* It coordinates the discovery of available server instances (via {@link ServerList})
* to produce the best candidate server instance.with a load balancing strategy {@link LoadBalancer}
* <p/>
* {@link Janus} will cache internally the server instances returned by the {@link ServerList} for a period of time, and will only ask
* the {@link ServerList} for server instances when the period has expired. By default, the service instances will be cached for 30 seconds,
* and this can be overridden by calling setRefreshIntervalInMillis OR by setting/updating the property "janus.refreshIntervalInMillis".
* <p/>
* {@link Janus} delegates the responsibility of service instance discovery to the {@link ServerList} provided to it, allowing for configurable
* discovery strategies. Janus provides some strategies out of the box:
*
* @author cbarry@kixeye.com
* @see {@link com.kixeye.janus.serverlist.ConfigServerList}
* @see {@link com.kixeye.janus.serverlist.ConstServerList}
* @see {@link com.kixeye.janus.serverlist.EurekaServerList}
* <p/>
* {@link Janus} also delegates the responsibility of service instance selection to the {@link LoadBalancer} provided to it, allowing for configurable
* load balancing strategies. Janus provides some strategies out of the box:
* @see {@link com.kixeye.janus.loadbalancer.RandomLoadBalancer}
* @see {@link com.kixeye.janus.loadbalancer.SessionLoadBalancer}
* @see {@link com.kixeye.janus.loadbalancer.ZoneAwareLoadBalancer}
* <p/>
* For clients using HTTP or WebSockets to talk to their services, the Janus library provides some clients which integrate {@link Janus} for invoking
* remote service endpoints.
* @see {@link com.kixeye.janus.client.rest.DefaultRestTemplateClient}
* @see {@link com.kixeye.janus.client.http.async.AsyncHttpClient}
* @see {@link com.kixeye.janus.client.websocket.SessionWebSocketClient}
* @see {@link com.kixeye.janus.client.websocket.StatelessWebSocketClient}
* @see {@link com.kixeye.janus.client.websocket.StatelessMessageClient}
*/
public class Janus {
private static final Logger logger = LoggerFactory.getLogger(Janus.class);
public static final String REFRESH_INTERVAL_IN_MILLIS = "janus.refreshIntervalInMillis";
public static final long DEFAULT_REFRESH_INTERVAL_IN_MILLIS = 30000;
private final String serviceName;
private final ServerList serverList;
private final LoadBalancer loadBalancer;
private final StatsFactory statsFactory;
private final DynamicLongProperty refreshInterval = DynamicPropertyFactory.getInstance().getLongProperty(REFRESH_INTERVAL_IN_MILLIS, DEFAULT_REFRESH_INTERVAL_IN_MILLIS);
// cache of server lists
private final Map<String, ServerStats> servers = new ConcurrentHashMap<>();
private final AtomicBoolean updatingServer = new AtomicBoolean(false);
private long nextUpdateTime = -1;
/**
* @param serviceName the name of the service cluster
* @param serverList the {@link ServerList} implementation
* @param loadBalancer the {@link LoadBalancer} implementation
* @param statsFactory factory class for the creation of {@link ServerStats}
*/
public Janus(String serviceName, ServerList serverList, LoadBalancer loadBalancer, StatsFactory statsFactory) {
this.serviceName = serviceName;
this.serverList = serverList;
this.loadBalancer = loadBalancer;
this.statsFactory = statsFactory;
initializeServerList();
}
/**
* @param serviceName the name of the service cluster
* @param serverList the {@link ServerList} implementation
* @param loadBalancer the {@link LoadBalancer} implementation
* @param statsFactory factory class for the creation of {@link ServerStats}
* @param refreshInterval the refresh interval (in millis) to refresh Janus's cache of servers.
*/
public Janus(String serviceName, ServerList serverList, LoadBalancer loadBalancer, StatsFactory statsFactory, long refreshInterval) {
this.serviceName = serviceName;
this.serverList = serverList;
this.loadBalancer = loadBalancer;
this.statsFactory = statsFactory;
setRefreshInterval(refreshInterval);
initializeServerList();
}
/**
* Sets the refresh interval of the internal server instance cache.
*
* @param refreshInterval the refreshInterval to set
*/
public void setRefreshInterval(long refreshInterval) {
ConfigurationManager.getConfigInstance().setProperty(REFRESH_INTERVAL_IN_MILLIS, refreshInterval);
}
/**
* Getter for refreshInteval
*
* @return the current refreshInterval
*/
public long getRefreshInterval() {
return refreshInterval.get();
}
/**
* Get the service cluster name associated with janus instance
*
* @return service name
*/
public String getServiceName() {
return serviceName;
}
/**
* Get a single server instance chosen through the {@link LoadBalancer}
*
* @return a server instance chosen through the load balancer.
*/
public ServerStats getServer() {
updateServerList();
Collection<ServerStats> serverStats = servers.values();
List<ServerStats> availableServerStats = new ArrayList<>(serverStats.size());
for (ServerStats s : serverStats) {
if (s.getServerInstance().isAvailable()) {
availableServerStats.add(s);
}
}
// done if no available servers
if (availableServerStats.isEmpty()) {
return null;
}
return loadBalancer.choose(availableServerStats);
}
private void initializeServerList() {
try {
for (ServerInstance s : serverList.getListOfServers()) {
ServerStats stat = statsFactory.createServerStats(s);
servers.put(s.getId(), stat);
}
} catch (Exception e) {
logger.error("Exception initializing the server list", e);
}
}
private void updateServerList() {
// only allow one thread to update the server list
if (!updatingServer.compareAndSet(false, true)) {
return;
}
try {
// has the update interval been met?
long now = System.currentTimeMillis();
if (getRefreshInterval() == 0 || nextUpdateTime > now) {
return;
} else {
nextUpdateTime = now + getRefreshInterval();
}
// update server stats with current availability
for (ServerInstance s : serverList.getListOfServers()) {
ServerStats stat = servers.get(s.getId());
if (stat != null) {
stat.getServerInstance().setAvailable(s.isAvailable());
} else {
stat = statsFactory.createServerStats(s);
servers.put(s.getId(), stat);
}
}
// tick all the servers and remove from list if requested
Iterator<Map.Entry<String, ServerStats>> iter = servers.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ServerStats> entry = iter.next();
ServerInstance s = entry.getValue().getServerInstance();
if (!s.tick()) {
logger.warn("Janus removing service instance <{}> due to discovery heartbeat timeout.", s.getId());
iter.remove();
}
}
} catch (Exception e) {
logger.error("Exception updating the server list", e);
} finally {
updatingServer.set(false);
}
}
/**
* Create an instance of {@link Builder}
*
* @param serviceName the service cluster name that the {@link Janus} will use
* @return the builder
*/
public static Builder builder(String serviceName) {
return new Builder(serviceName);
}
/**
* builder for create {@link Janus} instances. Provides
* defaults for components needed by {@link Janus} that can
* be overridden. Also provides convenience methods for configuring
* @{link Janus}.
*/
public static class Builder {
private String serviceName;
private ServerList serverList;
private LoadBalancer loadBalancer;
private StatsFactory statsFactory;
private MetricRegistry metricRegistry = new MetricRegistry();
private Long refreshIntervalInMillis = Janus.DEFAULT_REFRESH_INTERVAL_IN_MILLIS;
public Builder(String serviceName){
Preconditions.checkArgument(!Strings.isNullOrEmpty(serviceName), "'serviceName' cannot be null or empty.");
this.serviceName = serviceName;
}
/**
* constructs {@link Janus} with a {@link EurekaServerList}
* @param eurekaServiceUrl the url Eureka is listening on
* @param useSecure whether or not to communicate with discovered services in a secure manor.
* @param useInternalIp whether or not to communicate with discovered services using a private IP address.
* @return the Builder
*/
public Builder withEureka(String eurekaServiceUrl, boolean useSecure, boolean useInternalIp) {
this.serverList = new EurekaServerList(eurekaServiceUrl, serviceName, useSecure, useInternalIp);
return this;
}
/**
* constructs {@link Janus} with a pre-configured {@link EurekaServerList}
* @param serverList the pre-configured EurekaServerList to user for service discovery
* @return the builder
*/
public Builder withEureka(EurekaServerList serverList) {
this.serverList = serverList;
return this;
}
/**
* constructs {@link Janus} using the given urls with a {@link ConstServerList}.
* @param urls the urls of the service instances that {@link Janus} will discover.
* @return the Builder
*/
public Builder withServers(String...urls) {
Preconditions.checkNotNull(urls, "'urls cannot be null'");
this.serverList = new ConstServerList(serviceName, urls);
return this;
}
/**
* constructs {@link Janus} with a {@link RandomLoadBalancer}. This is the default {@link LoadBalancer} that
* the Builder will use if not overridden.
* @return the Builder
*/
public Builder withRandomLoadBalancing() {
this.loadBalancer = new RandomLoadBalancer();
return this;
}
/**
* constructs {@link Janus} with a {@link RandomLoadBalancer}. This is the default {@link LoadBalancer} that
* the Builder will use if not overridden.
* @return the Builder
*/
public Builder withServerSideLoadBalancing() {
this.loadBalancer = new ServerSideLoadBalancer();
this.refreshIntervalInMillis = 0L;
return this;
}
/**
* constructs {@link Janus} with a {@link SessionLoadBalancer}.
* @return the Builder
*/
public Builder withSessionLoadBalancing(){
this.loadBalancer = new SessionLoadBalancer();
return this;
}
/**
* constructs {@link Janus} with a {@link ZoneAwareLoadBalancer}.
*
* @param zone the zone that constructed {@link Janus} instance in running in.
* @return the Builder
*/
public Builder withZoneAwareLoadBalancing(String zone){
Preconditions.checkArgument(!Strings.isNullOrEmpty(zone), "'zone' cannot be null or empty.");
this.loadBalancer = new ZoneAwareLoadBalancer(serviceName, zone, metricRegistry);
return this;
}
/**
* constructs {@link Janus} with a {@link ServerList}
* @param serverList the {@link ServerList} to construct {@link Janus} with
* @return the Builder
*/
public Builder withServerList(ServerList serverList){
Preconditions.checkNotNull(serverList, "'serverList cannot be null'");
this.serverList = serverList;
return this;
}
/**
* constructs {@link Janus} with a {@link LoadBalancer}
* @param loadBalancer {@link LoadBalancer} to construct {@link Janus} with
* @return the Builder
*/
public Builder withLoadBalancer(LoadBalancer loadBalancer){
Preconditions.checkNotNull(loadBalancer, "'loadBalancer cannot be null'");
this.loadBalancer = loadBalancer;
return this;
}
/**
* constructs {@link Janus} with a {@link StatsFactory}.
* @param statsFactory the {@link StatsFactory} to construct {@link Janus} with
* @return the Builder
*/
public Builder withStatsFactory(StatsFactory statsFactory){
Preconditions.checkNotNull(statsFactory, "'statsFactory cannot be null'");
this.statsFactory = statsFactory;
return this;
}
/**
* constructs {@link Janus} with a {@link MetricRegistry}
* @param metricRegistry the {@link MetricRegistry} to construct {@link Janus} with
* @return the Builder
*/
public Builder withMetricRegistry(MetricRegistry metricRegistry){
Preconditions.checkNotNull(metricRegistry, "'metricRegistry cannot be null'");
this.metricRegistry = metricRegistry;
if(loadBalancer instanceof ZoneAwareLoadBalancer){
//need to re-create the ZoneAwareLoadBalancer with the new MetricRegistry
withZoneAwareLoadBalancing(((ZoneAwareLoadBalancer) loadBalancer).getZone());
}
return this;
}
/**
* constructs {@link Janus} with the given refreshIntervalInMillis
* @param refreshIntervalInMillis the interval to refresh {@link Janus}'s internal cache of server instances
* @return the Builder
*/
public Builder withRefreshIntervalInMillis(long refreshIntervalInMillis){
this.refreshIntervalInMillis = refreshIntervalInMillis;
return this;
}
/**
* Builds the {@link Janus} instance
* @return {@link Janus} instance
*/
public Janus build(){
setDefaults();
return new Janus(serviceName, serverList, loadBalancer, statsFactory, refreshIntervalInMillis);
}
private void setDefaults() {
if(serverList == null){
serverList = new ConfigServerList(serviceName);
}
if(loadBalancer == null){
loadBalancer = new RandomLoadBalancer();
}
if(statsFactory == null){
statsFactory = new ServerStatsFactory(ServerStats.class, metricRegistry);
}
}
}
}
|
package com.mysql.cj.jdbc.ha;
import com.mysql.cj.conf.ConnectionUrl;
import com.mysql.cj.conf.HostInfo;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.conf.RuntimeProperty;
import com.mysql.cj.jdbc.ConnectionImpl;
import com.mysql.cj.jdbc.JdbcConnection;
import com.mysql.cj.util.Util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;
public abstract class MultiHostConnectionProxy implements InvocationHandler {
private static final String METHOD_GET_MULTI_HOST_SAFE_PROXY = "getMultiHostSafeProxy";
private static final String METHOD_EQUALS = "equals";
private static final String METHOD_HASH_CODE = "hashCode";
private static final String METHOD_CLOSE = "close";
private static final String METHOD_ABORT_INTERNAL = "abortInternal";
private static final String METHOD_ABORT = "abort";
private static final String METHOD_IS_CLOSED = "isClosed";
private static final String METHOD_GET_AUTO_COMMIT = "getAutoCommit";
private static final String METHOD_GET_CATALOG = "getCatalog";
private static final String METHOD_GET_SCHEMA = "getSchema";
private static final String METHOD_GET_DATABASE = "getDatabase";
private static final String METHOD_GET_TRANSACTION_ISOLATION = "getTransactionIsolation";
private static final String METHOD_GET_SESSION_MAX_ROWS = "getSessionMaxRows";
List<HostInfo> hostsList;
protected ConnectionUrl connectionUrl;
boolean autoReconnect = false;
JdbcConnection thisAsConnection = null;
JdbcConnection parentProxyConnection = null;
JdbcConnection topProxyConnection = null;
JdbcConnection currentConnection = null;
boolean isClosed = false;
boolean closedExplicitly = false;
String closedReason = null;
protected Throwable lastExceptionDealtWith = null;
class JdbcInterfaceProxy implements InvocationHandler {
Object invokeOn = null;
JdbcInterfaceProxy(Object toInvokeOn) {
this.invokeOn = toInvokeOn;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName()))
return Boolean.valueOf(args[0].equals(this));
synchronized (MultiHostConnectionProxy.this) {
Object result = null;
try {
result = method.invoke(this.invokeOn, args);
result = MultiHostConnectionProxy.this.proxyIfReturnTypeIsJdbcInterface(method.getReturnType(), result);
} catch (InvocationTargetException e) {
MultiHostConnectionProxy.this.dealWithInvocationException(e);
}
return result;
}
}
}
MultiHostConnectionProxy() throws SQLException {
this.thisAsConnection = getNewWrapperForThisAsConnection();
}
MultiHostConnectionProxy(ConnectionUrl connectionUrl) throws SQLException {
this();
initializeHostsSpecs(connectionUrl, connectionUrl.getHostsList());
}
int initializeHostsSpecs(ConnectionUrl connUrl, List<HostInfo> hosts) {
this.connectionUrl = connUrl;
Properties props = connUrl.getConnectionArgumentsAsProperties();
this
.autoReconnect = ("true".equalsIgnoreCase(props.getProperty(PropertyKey.autoReconnect.getKeyName())) || "true".equalsIgnoreCase(props.getProperty(PropertyKey.autoReconnectForPools.getKeyName())));
this.hostsList = new ArrayList<>(hosts);
int numHosts = this.hostsList.size();
return numHosts;
}
protected JdbcConnection getProxy() {
return (this.topProxyConnection != null) ? this.topProxyConnection : this.thisAsConnection;
}
protected JdbcConnection getParentProxy() {
return this.parentProxyConnection;
}
protected final void setProxy(JdbcConnection proxyConn) {
if (this.parentProxyConnection == null)
this.parentProxyConnection = proxyConn;
this.topProxyConnection = proxyConn;
propagateProxyDown(proxyConn);
}
protected void propagateProxyDown(JdbcConnection proxyConn) {
this.currentConnection.setProxy(proxyConn);
}
JdbcConnection getNewWrapperForThisAsConnection() throws SQLException {
return new MultiHostMySQLConnection(this);
}
Object proxyIfReturnTypeIsJdbcInterface(Class<?> returnType, Object toProxy) {
if (toProxy != null &&
Util.isJdbcInterface(returnType)) {
Class<?> toProxyClass = toProxy.getClass();
return Proxy.newProxyInstance(toProxyClass.getClassLoader(), Util.getImplementedInterfaces(toProxyClass), getNewJdbcInterfaceProxy(toProxy));
}
return toProxy;
}
InvocationHandler getNewJdbcInterfaceProxy(Object toProxy) {
return new JdbcInterfaceProxy(toProxy);
}
void dealWithInvocationException(InvocationTargetException e) throws SQLException, Throwable, InvocationTargetException {
Throwable t = e.getTargetException();
if (t != null) {
if (this.lastExceptionDealtWith != t && shouldExceptionTriggerConnectionSwitch(t)) {
invalidateCurrentConnection();
pickNewConnection();
this.lastExceptionDealtWith = t;
}
throw t;
}
throw e;
}
abstract boolean shouldExceptionTriggerConnectionSwitch(Throwable paramThrowable);
abstract boolean isMasterConnection();
synchronized void invalidateCurrentConnection() throws SQLException {
invalidateConnection(this.currentConnection);
}
synchronized void invalidateConnection(JdbcConnection conn) throws SQLException {
try {
if (conn != null && !conn.isClosed())
conn.realClose(true, !conn.getAutoCommit(), true, null);
} catch (SQLException sQLException) {}
}
abstract void pickNewConnection() throws SQLException;
synchronized ConnectionImpl createConnectionForHost(HostInfo hostInfo) throws SQLException {
ConnectionImpl conn = (ConnectionImpl)ConnectionImpl.getInstance(hostInfo);
JdbcConnection topmostProxy = getProxy();
if (topmostProxy != this.thisAsConnection)
conn.setProxy(this.thisAsConnection);
conn.setProxy(topmostProxy);
return conn;
}
void syncSessionState(JdbcConnection source, JdbcConnection target) throws SQLException {
if (source == null || target == null)
return;
RuntimeProperty<Boolean> sourceUseLocalSessionState = source.getPropertySet().getBooleanProperty(PropertyKey.useLocalSessionState);
boolean prevUseLocalSessionState = ((Boolean)sourceUseLocalSessionState.getValue()).booleanValue();
sourceUseLocalSessionState.setValue(Boolean.valueOf(true));
boolean readOnly = source.isReadOnly();
sourceUseLocalSessionState.setValue(Boolean.valueOf(prevUseLocalSessionState));
syncSessionState(source, target, readOnly);
}
void syncSessionState(JdbcConnection source, JdbcConnection target, boolean readOnly) throws SQLException {
if (target != null)
target.setReadOnly(readOnly);
if (source == null || target == null)
return;
RuntimeProperty<Boolean> sourceUseLocalSessionState = source.getPropertySet().getBooleanProperty(PropertyKey.useLocalSessionState);
boolean prevUseLocalSessionState = ((Boolean)sourceUseLocalSessionState.getValue()).booleanValue();
sourceUseLocalSessionState.setValue(Boolean.valueOf(true));
target.setAutoCommit(source.getAutoCommit());
String db = source.getDatabase();
if (db != null && !db.isEmpty())
target.setDatabase(db);
target.setTransactionIsolation(source.getTransactionIsolation());
target.setSessionMaxRows(source.getSessionMaxRows());
sourceUseLocalSessionState.setValue(Boolean.valueOf(prevUseLocalSessionState));
}
abstract void doClose() throws SQLException;
abstract void doAbortInternal() throws SQLException;
abstract void doAbort(Executor paramExecutor) throws SQLException;
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if ("getMultiHostSafeProxy".equals(methodName))
return this.thisAsConnection;
if ("equals".equals(methodName))
return Boolean.valueOf(args[0].equals(this));
if ("hashCode".equals(methodName))
return Integer.valueOf(hashCode());
if ("close".equals(methodName)) {
doClose();
this.isClosed = true;
this.closedReason = "Connection explicitly closed.";
this.closedExplicitly = true;
return null;
}
if ("abortInternal".equals(methodName)) {
doAbortInternal();
this.currentConnection.abortInternal();
this.isClosed = true;
this.closedReason = "Connection explicitly closed.";
return null;
}
if ("abort".equals(methodName) && args.length == 1) {
doAbort((Executor)args[0]);
this.isClosed = true;
this.closedReason = "Connection explicitly closed.";
return null;
}
if ("isClosed".equals(methodName))
return Boolean.valueOf(this.isClosed);
try {
return invokeMore(proxy, method, args);
} catch (InvocationTargetException e) {
throw (e.getCause() != null) ? e.getCause() : e;
} catch (Exception e) {
Class<?>[] declaredException = method.getExceptionTypes();
for (Class<?> declEx : declaredException) {
if (declEx.isAssignableFrom(e.getClass()))
throw e;
}
throw new IllegalStateException(e.getMessage(), e);
}
}
abstract Object invokeMore(Object paramObject, Method paramMethod, Object[] paramArrayOfObject) throws Throwable;
protected boolean allowedOnClosedConnection(Method method) {
String methodName = method.getName();
return (methodName.equals("getAutoCommit") || methodName.equals("getCatalog") || methodName.equals("getSchema") || methodName
.equals("getDatabase") || methodName.equals("getTransactionIsolation") || methodName
.equals("getSessionMaxRows"));
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\ha\MultiHostConnectionProxy.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the license.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting;
/**
* Created by: dodge1 Date: Jan 27, 2005
*/
public class Limits {
public double getMin() {
return min;
}
public double getMax() {
return max;
}
private double min;
private double max;
public Limits(double min, double max) {
this.min = min;
this.max = max;
}
@Override
public String toString() {
return "Limits are " + min + " to " + max;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(max);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(min);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Limits other = (Limits) obj;
if (Double.doubleToLongBits(max) != Double.doubleToLongBits(other.max)) {
return false;
}
if (Double.doubleToLongBits(min) != Double.doubleToLongBits(other.min)) {
return false;
}
return true;
}
}
|
package com.designPattern.structural.decorator;
public class CNChannelPackage extends ChannelDecorator {
public CNChannelPackage(SetaliteTV setaliteTV) {
super(setaliteTV);
}
@Override
public String show(int channelNo) {
if(channelNo > 120 && channelNo <= 130)
return "Enjoy Cartoons.";
else
return this.getSetaliteTV().show(channelNo);
}
@Override
public int cost() {
return this.getSetaliteTV().cost() + 10;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build.VERSION;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.plugin.webview.ui.tools.LogoWebViewWrapper.b;
import com.tencent.mm.sdk.platformtools.BackwardSupportUtil;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.widget.MMWebView;
public final class f implements b {
static final int pXi = R.g.webview_pulldown_refresh;
private boolean YM = false;
public boolean fpo = false;
a pXe;
ImageView pXf;
LogoWebViewWrapper pXg;
int pXh = 0;
private boolean pXj = false;
private int pXk = 0;
private float pXl = 0.0f;
private ValueAnimator pXm;
private ViewPropertyAnimator pXn;
private float pXo;
private View pXp;
View pXq;
private TextView pXr;
private boolean pXs = true;
public boolean pXt = false;
public final void da(View view) {
String str;
this.pXg = (LogoWebViewWrapper) view.findViewById(R.h.logo_web_view_wrapper);
this.pXf = (ImageView) view.findViewById(R.h.webview_logo_refresh_iv);
this.pXp = view.findViewById(R.h.webview_logo_container);
if (this.pXp != null) {
this.pXq = this.pXp.findViewById(R.h.x5_logo);
this.pXr = (TextView) this.pXq.findViewById(R.h.x5_logo_url);
}
this.pXh = BackwardSupportUtil.b.b(this.pXg.getContext(), 72.0f);
String str2 = "MicroMsg.WebViewPullDownLogoDelegate";
String str3 = "refreshImage.id = %s, logoWrapper.id = %s";
Object[] objArr = new Object[2];
if (this.pXf == null) {
str = "null";
} else {
str = String.valueOf(this.pXf.getId());
}
objArr[0] = str;
if (this.pXg == null) {
str = "null";
} else {
str = String.valueOf(this.pXg.getId());
}
objArr[1] = str;
x.d(str2, str3, objArr);
x.d("MicroMsg.WebViewPullDownLogoDelegate", "LOADING_LOGO_HEIGHT = %d", new Object[]{Integer.valueOf(this.pXh)});
}
public final void b(MMWebView mMWebView) {
mMWebView.setCompetitorView(this.pXg);
mMWebView.cAy();
if (VERSION.SDK_INT <= 10) {
this.pXg.getWebViewContainer().setBackgroundColor(this.pXg.getResources().getColor(R.e.webview_logo_bg_color));
}
LogoWebViewWrapper logoWebViewWrapper = this.pXg;
logoWebViewWrapper.getWebViewContainer();
if (logoWebViewWrapper.pVp != null) {
logoWebViewWrapper.hNb = mMWebView;
logoWebViewWrapper.pVp.addView(logoWebViewWrapper.hNb);
}
CharSequence charSequence = "";
if (mMWebView.isXWalkKernel() || mMWebView.getIsX5Kernel()) {
this.pXs = true;
} else {
this.pXs = false;
}
if (!(this.pXq == null || mMWebView.getIsX5Kernel())) {
((ImageView) this.pXq.findViewById(R.h.x5_logo_img)).setVisibility(8);
((TextView) this.pXq.findViewById(R.h.info_txt)).setText(charSequence);
}
if (!this.pXs || this.pXt) {
jY(true);
return;
}
jY(false);
if (this.pXq != null) {
this.pXq.setVisibility(0);
}
}
public final void bVT() {
this.fpo = false;
stopLoading();
if (this.pXs && this.pXq != null && !this.pXt) {
jY(false);
this.pXg.setReleaseTargetHeight(0);
this.pXq.setVisibility(0);
}
}
public final void startLoading() {
if (!this.YM && this.pXf != null && this.pXg != null) {
this.YM = true;
this.pXg.jY(true);
this.pXf.clearAnimation();
if (this.pXm != null) {
this.pXm.cancel();
}
this.pXm = ObjectAnimator.ofFloat(this, "startLoadingStep", new float[]{this.pXl + 0.0f, this.pXl + 354.0f});
this.pXm.setDuration(960);
this.pXm.setRepeatMode(1);
this.pXm.setRepeatCount(-1);
this.pXm.setInterpolator(new LinearInterpolator());
this.pXm.start();
if (this.pXe != null) {
this.pXe.bVV();
}
}
}
public final void stopLoading() {
if (this.YM) {
x.d("MicroMsg.WebViewPullDownLogoDelegate", "stopLoading()");
this.pXj = true;
this.YM = false;
if (this.pXg != null && this.fpo) {
this.pXg.jY(false);
}
if (this.pXm != null) {
this.pXm.cancel();
}
if (this.pXg != null) {
this.pXg.P(0, 250);
}
if (this.pXf != null) {
x.d("MicroMsg.WebViewPullDownLogoDelegate", "refreshImage, alpha to 0f");
this.pXf.animate().alpha(0.0f).setDuration(500).start();
}
}
}
public final void release() {
if (this.pXg != null) {
LogoWebViewWrapper logoWebViewWrapper = this.pXg;
if (logoWebViewWrapper.pVp != null) {
logoWebViewWrapper.pVp.removeView(logoWebViewWrapper.hNb);
logoWebViewWrapper.hNb = null;
}
logoWebViewWrapper = this.pXg;
logoWebViewWrapper.pVz = null;
logoWebViewWrapper.pVy = null;
}
if (this.pXp != null) {
((ViewGroup) this.pXp).removeAllViews();
}
this.pXg = null;
this.pXf = null;
this.pXk = 0;
if (this.pXm != null) {
this.pXm.cancel();
this.pXm = null;
}
}
public final void AH(int i) {
if (this.pXp != null) {
this.pXp.setBackgroundColor(i);
}
}
public final void bVU() {
if (this.pXq != null) {
this.pXq.setVisibility(8);
}
}
public final void Y(int i, boolean z) {
String str;
String str2 = "MicroMsg.WebViewPullDownLogoDelegate";
String str3 = "onOverScrollOffset, offset = %d, pointerDown = %b, refreshImage.visibility = %s, refreshImage.drawable = %s, refreshImage.alpha = %s";
Object[] objArr = new Object[5];
objArr[0] = Integer.valueOf(i);
objArr[1] = Boolean.valueOf(z);
if (this.pXf == null) {
str = "null";
} else {
str = String.valueOf(this.pXf.getVisibility());
}
objArr[2] = str;
if (this.pXf == null) {
str = "null";
} else {
str = this.pXf.getDrawable().toString();
}
objArr[3] = str;
if (this.pXf == null) {
str = "null";
} else {
str = String.valueOf(this.pXf.getAlpha());
}
objArr[4] = str;
x.v(str2, str3, objArr);
if (this.fpo) {
if (i == 0) {
this.pXj = false;
}
if (this.pXf != null) {
if (z) {
if (Math.abs(i) >= this.pXh) {
if (this.pXg != null) {
this.pXg.setReleaseTargetHeight(this.pXh);
}
} else if (this.pXg != null) {
this.pXg.setReleaseTargetHeight(0);
}
} else if (Math.abs(i) > this.pXh && !this.YM) {
x.d("MicroMsg.WebViewPullDownLogoDelegate", "startLoading()");
startLoading();
return;
} else if (this.YM) {
return;
}
if (this.pXf != null && this.pXf.getAlpha() < 1.0f && this.pXn == null && z) {
x.d("MicroMsg.WebViewPullDownLogoDelegate", "refreshImage alpha to 1.0f");
this.pXn = this.pXf.animate().alpha(1.0f).setDuration(500);
this.pXn.setListener(new 1(this));
this.pXn.start();
}
if (!this.pXj) {
int i2 = (-i) - this.pXk;
if (Math.abs(i) >= this.pXh) {
i2 *= 5;
} else {
i2 *= 2;
}
this.pXk = -i;
float height = ((float) this.pXf.getHeight()) / 2.0f;
float width = ((float) this.pXf.getWidth()) / 2.0f;
this.pXl -= (float) i2;
this.pXf.setScaleType(ScaleType.MATRIX);
Matrix imageMatrix = this.pXf.getImageMatrix();
imageMatrix.postRotate((float) (-i2), width, height);
this.pXf.setImageMatrix(imageMatrix);
this.pXf.setImageResource(pXi);
}
this.pXf.invalidate();
}
}
}
public final float getStartLoadingStep() {
return this.pXo;
}
public final void setStartLoadingStep(float f) {
float f2 = 0.0f;
this.pXo = f;
this.pXf.setScaleType(ScaleType.MATRIX);
Matrix imageMatrix = this.pXf.getImageMatrix();
float width = this.pXf == null ? 0.0f : ((float) this.pXf.getWidth()) / 2.0f;
if (this.pXf != null) {
f2 = ((float) this.pXf.getHeight()) / 2.0f;
}
imageMatrix.setRotate(f, width, f2);
this.pXl = f;
this.pXf.invalidate();
}
public final void jY(boolean z) {
if (this.pXg != null && this.pXg.pVv != z) {
this.pXg.jY(z);
if (this.pXq != null) {
this.pXq.setVisibility(8);
}
this.pXt = z;
}
}
public final void setCurrentURL(String str) {
if (!this.pXs || this.pXt) {
jY(true);
if (this.pXq != null && this.pXq.getVisibility() == 0) {
this.pXq.setVisibility(8);
}
} else if (this.pXr != null) {
if (!bi.oW(str)) {
if (!bi.oW(Uri.parse(str).getHost())) {
CharSequence string = this.pXr.getContext().getString(R.l.webview_logo_url, new Object[]{r0});
this.pXr.setVisibility(0);
this.pXr.setText(string);
jY(false);
return;
}
}
this.pXr.setVisibility(8);
}
}
}
|
package com.jim.multipos.utils;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.Window;
import com.jim.mpviews.MpButton;
import com.jim.mpviews.RecyclerViewWithMaxHeight;
import com.jim.multipos.R;
import com.jim.multipos.data.DatabaseManager;
import com.jim.multipos.data.db.model.currency.Currency;
import com.jim.multipos.data.db.model.inventory.BillingOperations;
import com.jim.multipos.ui.billing_vendor.adapter.BillingInfoAdapter;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by developer on 04.12.2017.
*/
public class BillingInfoDialog extends Dialog {
private View dialogView;
@BindView(R.id.btnWarningYES)
MpButton btnWarningYES;
@BindView(R.id.btnWarningNO)
MpButton btnWarningNO;
@BindView(R.id.rvPayments)
RecyclerViewWithMaxHeight rvPayments;
BillingInfoAdapter adapter;
List<Object> billingOperations;
public interface BillingInfoCallback {
void onEdit(BillingOperations operations);
}
public BillingInfoDialog(@NonNull Context context, BillingOperations operations, DatabaseManager databaseManager, BillingInfoCallback billingInfoCallback) {
super(context);
dialogView = getLayoutInflater().inflate(R.layout.billing_info_dialog, null);
ButterKnife.bind(this, dialogView);
requestWindowFeature(Window.FEATURE_NO_TITLE);
rvPayments.setLayoutManager(new LinearLayoutManager(context));
billingOperations = new ArrayList<>();
Currency currency = databaseManager.getMainCurrency();
adapter = new BillingInfoAdapter(context, currency);
rvPayments.setAdapter(adapter);
operations.resetOperationsHistoryList();
if (operations.getOperationsHistoryList() != null && operations.getOperationsHistoryList().size() != 0) {
billingOperations.add(operations);
billingOperations.addAll(operations.getOperationsHistoryList());
adapter.setData(billingOperations);
} else {
billingOperations.add(operations);
adapter.setData(billingOperations);
}
btnWarningYES.setOnClickListener(view -> {
dismiss();
});
if (operations.getOperationType() == BillingOperations.PAID_TO_CONSIGNMENT) {
btnWarningNO.setVisibility(View.VISIBLE);
} else {
btnWarningNO.setVisibility(View.GONE);
}
btnWarningNO.setOnClickListener(view -> {
billingInfoCallback.onEdit(operations);
dismiss();
});
setContentView(dialogView);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
}
}
|
/****************************************************
* $Project: DinoAge
* $Date:: Mar 21, 2008
* $Revision:
* $Author:: khoanguyen
* $Comment::
**************************************************/
package org.ddth.dinoage.data;
import java.io.File;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ddth.blogging.Author;
import org.ddth.blogging.Blog;
import org.ddth.blogging.Comment;
import org.ddth.blogging.Entry;
import org.ddth.dinoage.data.exception.QueryDataException;
import org.ddth.dinoage.data.exception.UpdateDataException;
/**
* @author khoa.nguyen
*
*/
public class DataManager {
private static Log logger = LogFactory.getLog(DataManager.class);
private DataProvider provider;
public DataManager(File databaseFolder) {
boolean creation = !databaseFolder.exists();
String connectionURL = "jdbc:derby:" + databaseFolder.getAbsolutePath() + (creation ? ";create=true;" : ";");
String scriptResource = creation ? "dinoage_derby.sql" : null;
ConnectionManager manager = new ConnectionManager(
"org.apache.derby.jdbc.EmbeddedDriver", connectionURL, "", "", scriptResource);
provider = new DefaultDataProvider(manager);
}
public DataManager(DataProvider provider) {
this.provider = provider;
}
public void createAuthor(Author author) {
try {
provider.createAuthor(author);
} catch (UpdateDataException e) {
logger.error("Cannot create new author", e);
}
}
public void createBlog(Blog blog) {
try {
provider.createBlog(blog);
} catch (UpdateDataException e) {
logger.error("Cannot create blog", e);
}
}
public void createEntry(String blogId, Entry entry) {
try {
provider.createEntry(blogId, entry);
} catch (UpdateDataException e) {
logger.error("Cannot create entry", e);
}
}
public void createComment(long entryId, Comment comment) {
try {
provider.createComment(entryId, comment);
} catch (UpdateDataException e) {
logger.error("Cannot create comment", e);
}
}
public Author getAuthor(String userId) {
try {
return provider.getAuthor(userId);
}
catch (QueryDataException e) {
logger.error("Cannot load author", e);
}
return null;
}
public Blog getBlog(String blogId) {
try {
return provider.getBlog(blogId);
} catch (QueryDataException e) {
logger.error("Cannot load blog", e);
}
return null;
}
public List<Comment> getComments(long entryId) {
try {
return provider.getComments(entryId);
} catch (QueryDataException e) {
logger.error("Cannot load comments", e);
}
return null;
}
public List<Entry> getEntries(String blogId) {
try {
return provider.getEntries(blogId);
} catch (QueryDataException e) {
logger.error("Cannot load entries", e);
}
return null;
}
}
|
package jumpingalien.part3.programs.Expressions;
import jumpingalien.model.Tile;
import jumpingalien.model.World;
import jumpingalien.part3.programs.Program;
import jumpingalien.part3.programs.Expressions.Exceptions.IllegalOperandException;
public class GetTile extends BinaryExpression<Tile, Double> {
public GetTile(Expression<Double> left, Expression<Double> right)
throws IllegalOperandException {
super(left, right);
}
@Override
public Tile evaluate(Program program) {
int pixelX = getLeftOperand().evaluate(program).intValue();
int pixelY = getRightOperand().evaluate(program).intValue();
World world = program.getPossessedObject().getWorld();
int[] tilePos = world.getTilePosition(pixelX, pixelY);
return new Tile(tilePos[0],tilePos[1],world);
}
}
|
package com.perfectorial.dto;
/**
* @author Mohsen Ebrahimi
*/
public interface RequestDto {
}
|
/**
*
*/
package com.wds.spring.batch.partition;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.batch.item.ItemProcessor;
/**
*
* @author bruce.liu(mailto:jxta.liu@gmail.com)
* 2014-1-11下午02:38:01
*/
public class CreditBillProcessor implements
ItemProcessor<CreditBill, CreditBill> {
public CreditBill process(CreditBill bill) throws Exception {
System.out.println(bill.toString());
CreditBill destCreditBill = new CreditBill();
destCreditBill.setAccountID(bill.getAccountID());
destCreditBill.setAddress(bill.getAddress());
destCreditBill.setAmount(bill.getAmount());
destCreditBill.setDate(bill.getDate());
destCreditBill.setId(bill.getId() + 100);
destCreditBill.setName(bill.getName());
return destCreditBill;
}
}
|
package com.testiranje.rss;
import java.io.FileOutputStream;
import java.util.Iterator;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class RSSWriter {
private static String XML_BLOCK = "\n";
private static String XML_INDENT = "\t";
public static void write(RSSFeed rssfeed, String xmlfile) throws Exception {
XMLOutputFactory output = XMLOutputFactory.newInstance();
XMLEventWriter writer = output.createXMLEventWriter
(new FileOutputStream(xmlfile));
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent endSection = eventFactory.createDTD(XML_BLOCK);
StartDocument startDocument = eventFactory.createStartDocument();
writer.add(startDocument);
writer.add(endSection);
StartElement rssStart = eventFactory.createStartElement("", "", "rss");
writer.add(rssStart);
writer.add(eventFactory.createAttribute("version", "2.0"));
// writer.add(endSection);
writer.add(eventFactory.createStartElement("", "", "channel"));
// writer.add(endSection);
RSSHeader header = rssfeed.getHeader();
createNode(writer, "title", header.getTitle());
createNode(writer, "link", header.getLink());
createNode(writer, "description", header.getDescription());
createNode(writer, "language", header.getLanguage());
createNode(writer, "copyright", header.getCopyright());
createNode(writer, "pubDate", header.getPubDate());
Iterator<RSSEntry> iterator = rssfeed.getEntries().iterator();
while (iterator.hasNext()) {
RSSEntry entry = iterator.next();
writer.add(eventFactory.createStartElement("", "", "item"));
// writer.add(endSection);
createNode(writer, "title", entry.getTitle());
createNode(writer, "description", entry.getDescription());
createNode(writer, "link", entry.getLink());
createNode(writer, "guid", entry.getGuid());
createNode(writer, "pubDate", entry.getPubDate());
writer.add(eventFactory.createEndElement("", "", "item"));
//writer.add(endSection);
}
// writer.add(endSection);
writer.add(eventFactory.createEndElement("", "", "channel"));
// writer.add(endSection);
writer.add(eventFactory.createEndElement("", "", "rss"));
// writer.add(endSection);
writer.add(eventFactory.createEndDocument());
writer.close();
}
private static void createNode
(XMLEventWriter eventWriter, String name, String value)
throws XMLStreamException {
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent endSection = eventFactory.createDTD(XML_BLOCK);
XMLEvent tabSection = eventFactory.createDTD(XML_INDENT);
StartElement sElement = eventFactory.createStartElement("", "", name);
// eventWriter.add(tabSection);
eventWriter.add(sElement);
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
// eventWriter.add(endSection);
}
}
|
public class dxdxd {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.