text
stringlengths 10
2.72M
|
|---|
package network.nerve.swap.db;
import io.nuls.core.crypto.HexUtil;
import io.nuls.core.rockdb.manager.RocksDBManager;
import io.nuls.core.rockdb.model.Entry;
import network.nerve.swap.model.po.FarmPoolPO;
import network.nerve.swap.utils.SwapDBUtil;
import java.util.List;
/**
* @author Niels
*/
public class FarmStorageReader {
public static void main(String[] args) throws Exception {
String path = "/Users/niels/workspace/nerve-network/data/swap";
RocksDBManager.init(path);
List<Entry<byte[], byte[]>> list = RocksDBManager.entryList("sw_table_farm_5");
for (Entry<byte[], byte[]> entry : list) {
System.out.println(HexUtil.encode(entry.getKey()));
FarmPoolPO po = SwapDBUtil.getModel(entry.getValue(), FarmPoolPO.class);
System.out.println(po);
}
}
}
|
package com.online.web;
import java.io.IOException;
import java.io.PrintWriter;
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 com.online.dao.EmployeeDAO;
import com.online.model.Employee;
@WebServlet("/create.htm")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*int no = Integer.parseInt(request.getParameter("eno"));
String name = request.getParameter("ename");
String designation= request.getParameter("edesignation");
String gender = request.getParameter("egender");
double sal = Double.parseDouble(request.getParameter("esal"));
String uname = request.getParameter("eusername");
String pwd = request.getParameter("epassword");*/
EmployeeDAO eDao = new EmployeeDAO();
/*Employee employee = new Employee(no, name, designation, gender, sal, uname, pwd);*/
Employee employee = new Employee();
employee.setEno(Integer.parseInt(request.getParameter("eno")));
employee.setEname(request.getParameter("ename"));
employee.setEdesignation(request.getParameter("edesignation"));
employee.setEgender(request.getParameter("egender"));
employee.setEsal(Double.parseDouble(request.getParameter("esal")));
employee.setEusername(request.getParameter("eusername"));
employee.setEpassword(request.getParameter("epassword"));
int result = eDao.insertData(employee);
PrintWriter pw = response.getWriter();
String no = null;
if(result > 0){
//pw.println(no+" record is inserted");
response.sendRedirect("Login.jsp");
}
else
pw.println(no+" record is not inserted");
}
}
|
package com.icanit.app_v2.entity;
// default package
import java.util.List;
/**
* AppMerchantType entity. @author MyEclipse Persistence Tools
*/
public class AppMerchantType implements java.io.Serializable {
// Fields
public int id,parentId;
public String typeName,pic;
public List<AppMerchantType> subTypeList;
}
|
package items;
import board.blockingobject.Player;
import util.parameters.PlayerEventParameter;
public class FlagObserver implements ItemObserver {
private Flag flag;
/**
* Creates a new FlagObserver
* @param flag The flag to observe
*
* @throws IllegalArgumentException
* when the flag is null.
*/
public FlagObserver(Flag flag) throws IllegalArgumentException{
if(flag == null)
throw new IllegalArgumentException();
this.flag = flag;
}
@Override
public void update(Observable observed, PlayerEventParameter playerActionParameter) {
if(observed instanceof Player){
Player pl = (Player)observed;
if(playerActionParameter.hasPlayerDied()){
flag.drop(pl,pl.getPosition());
}
else{
flag.drop(pl,pl.getPosition().getRandomNonBlockingNeighbour());
}
}
}
@Override
public Item getObservedItem() {
return flag;
}
}
|
package com.wangzhu.service;
/**
* Created by wang.zhu on 2020-09-05 14:59.
**/
public interface IAllUserService extends IUserService {
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TimingLogger;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import webuters.com.geet_uttarakhand20aprilpro.R;
import webuters.com.geet_uttarakhand20aprilpro.Utils.Pref;
import webuters.com.geet_uttarakhand20aprilpro.Utils.StringUtils;
import webuters.com.geet_uttarakhand20aprilpro.Utils.TagUtils;
import webuters.com.geet_uttarakhand20aprilpro.adapter.AlbumRecyclerAdapter;
import webuters.com.geet_uttarakhand20aprilpro.adapter.CatagoryAdapter;
import webuters.com.geet_uttarakhand20aprilpro.adapter.LatestSongAdapter;
import webuters.com.geet_uttarakhand20aprilpro.adapter.ViewPagerAdapter;
import webuters.com.geet_uttarakhand20aprilpro.bean.AlbumListBean;
import webuters.com.geet_uttarakhand20aprilpro.bean.Catagory_calass_bean;
import webuters.com.geet_uttarakhand20aprilpro.bean.CategoryGetSetUrl;
import webuters.com.geet_uttarakhand20aprilpro.connection.NetworkCheckClass;
import webuters.com.geet_uttarakhand20aprilpro.holder.Holder;
import webuters.com.geet_uttarakhand20aprilpro.pojo.AlbumPOJO;
import webuters.com.geet_uttarakhand20aprilpro.pojo.LatestSongPOJO;
//import com.google.analytics.tracking.android.EasyTracker;
//import com.google.analytics.tracking.android.MapBuilder;
//import com.google.analytics.tracking.android.StandardExceptionParser;
public class MainActivity extends Activity{
RecyclerView rv_garwali, rv_kumauni, rv_jaunsari, rv_singers;
Timer timer;
int page = 0;
List<AlbumListBean> main_album_list = new ArrayList<>();
public static Set<String> listItem = new HashSet<>();
public ProgressDialog pDialog;
public static TextView catagory_see_all, see_all_singers, see_all_album;
static ArrayList<CategoryGetSetUrl> catagory_array_list1 = new ArrayList<CategoryGetSetUrl>();
String CatagoryName, CatId;
String Singer_First_Name, Singer_Last_Name, id, Latest_Image_Id, Latest_Song_Name, Detailes_caragory;
ImageView toolbar_main;
TextView toolbar_title, latest_song_title_main, title_singer, garwali_title, title_jonsari, title_kumaoni, garwali_see_all;
boolean flag = false;
LinearLayout linear_full;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private List<Catagory_calass_bean> itemInfoList = new ArrayList<>();
LinearLayout linear;
LinearLayout media_player_play;
ImageView back_arrow;
private ConnectionDetector cd;
public static String CATAGOARY_URL = "http://23.22.9.33/SongApi/singer.php?action_type=Catagory";
Boolean v = false;
String currentVersion = "";
private static final int REQUEST_WRITE_STORAGE = 112;
EditText edit_searchmain;
Button btn_searchmain;
Boolean boolSearch = false;
ListView list_search;
String FULL_NAME;
String album_id_not = "";
ArrayList<Catagory_calass_bean> add_allthree_arraylist = new ArrayList<Catagory_calass_bean>();
CatagoryAdapter catagoryAdapter;
private BroadcastReceiver mRegistrationBroadcastReceiver;
public static GoogleAnalytics analytics;
public static Tracker tracker;
public static boolean img_flag;
public static boolean blured_mediaplaying = false;
boolean nav_flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CountDownTimer(2000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
// showRewardedVideo();
}
}.start();
rv_garwali = findViewById(R.id.rv_garwali);
rv_kumauni = findViewById(R.id.rv_kumauni);
rv_jaunsari = findViewById(R.id.rv_jaunsari);
rv_singers = findViewById(R.id.rv_singers);
analytics = GoogleAnalytics.getInstance(this);
analytics.setLocalDispatchPeriod(1800);
tracker = analytics.newTracker("UA-18871205-2");
tracker.enableExceptionReporting(true);
tracker.enableAdvertisingIdCollection(true);
tracker.enableAutoActivityTracking(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.getBoolean("backup")) {
Intent intent = new Intent(MainActivity.this, SampleActivity.class);
intent.putExtra("backup", true);
startActivity(intent);
}
}
if (extras != null) {
if (extras.getBoolean("backup1")) {
Intent intent = new Intent(MainActivity.this, SampleActivity.class);
intent.putExtra("backup1", true);
startActivity(intent);
}
}
if (extras != null) {
if (extras.getBoolean("backup2")) {
Intent intent = new Intent(MainActivity.this, AlbumeSongs.class);
intent.putExtra("Album_id", extras.getString("album_back_id"));
intent.putExtra("SongImage123", extras.getString("album_back_cover"));
startActivity(intent);
}
}
Log.d("notification", "running");
if (extras != null) {
String message = extras.getString("message");
String title = extras.getString("title");
String albumid = extras.getString("album_id");
String albumname = extras.getString("album_name");
Log.d("notification", "message:-" + message);
Log.d("notification", "albumid:-" + albumid);
Log.d("notification", "albumname:-" + albumname);
Log.d("notification", "title:-" + title);
// Toast.makeText(getApplicationContext(), "album_id:-" + albumid, Toast.LENGTH_LONG).show();
}
SharedPreferences sp = getSharedPreferences("geet.txt", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
String album_id = sp.getString("album_id", "");
Log.d("notification", "album_id:-" + album_id);
editor.putString("album_id", "");
editor.commit();
if (album_id != null || album_id.length() > 0) {
album_id_not = album_id;
if (nav_flag) {
for (AlbumListBean album : main_album_list) {
if (album.getId().equals(album_id_not)) {
Intent i = new Intent(MainActivity.this, AlbumeSongs.class);
// String Singer_Song_path = catagory_array_listArray.get(3).getAlbumCover();
String SongImg = album.getAlbumCover();
String AlbumId = album.getId();
i.putExtra("Album_id", AlbumId);
i.putExtra("SongImage123", SongImg);
nav_flag = false;
startActivity(i);
}
}
}
}
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
//When the broadcast received
//We are sending the broadcast from GCMRegistrationIntentService
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)) {
String token = intent.getStringExtra("token");
Log.d("sunil", "Token:-" + token);
if (!AppConstant.getNotification(getApplicationContext())) {
}
// sendApiToken(token);
} else if (intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)) {
Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
}
}
};
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (ConnectionResult.SUCCESS != resultCode) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show();
GooglePlayServicesUtil.showErrorNotification(resultCode, getApplicationContext());
} else {
Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show();
}
} else {
Intent itent = new Intent(this, GCMRegistrationIntentService.class);
startService(itent);
}
try {
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
} catch (Exception e) {
}
try {
currentVersion = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
cd = new ConnectionDetector(getApplicationContext());
edit_searchmain = (EditText) findViewById(R.id.edit_searchmain);
btn_searchmain = (Button) findViewById(R.id.btn_searchmain);
garwali_title = (TextView) findViewById(R.id.garwali_title);
back_arrow = (ImageView) findViewById(R.id.back_arrow);
back_arrow.setVisibility(View.GONE);
toolbar_main = (ImageView) findViewById(R.id.toolbar_main);
toolbar_main.setVisibility(View.VISIBLE);
viewPager = (ViewPager) findViewById(R.id.viewpager);
title_singer = (TextView) findViewById(R.id.title_singer);
linear = (LinearLayout) findViewById(R.id.linear);
// searchArraylist = new ArrayList<String>();
// savesearcharraylist = new ArrayList<>(searchArraylist);
edit_searchmain = (EditText) findViewById(R.id.edit_searchmain);
btn_searchmain = (Button) findViewById(R.id.btn_searchmain);
list_search = (ListView) findViewById(R.id.list_search);
catagoryAdapter = new CatagoryAdapter(MainActivity.this, R.layout.activity_main, add_allthree_arraylist);
list_search.setAdapter(catagoryAdapter);
final InputMethodManager imma = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
edit_searchmain.setRawInputType(InputType.TYPE_CLASS_TEXT);
edit_searchmain.setTextIsSelectable(true);
btn_searchmain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!boolSearch) {
boolSearch = true;
edit_searchmain.setVisibility(View.VISIBLE);
toolbar_main.setVisibility(View.GONE);
toolbar_title.setVisibility(View.GONE);
//list_search.setVisibility(View.VISIBLE);
edit_searchmain.requestFocus();
imma.showSoftInput(edit_searchmain, InputMethodManager.SHOW_IMPLICIT);
} else {
edit_searchmain.setText("");
boolSearch = false;
edit_searchmain.setVisibility(View.GONE);
toolbar_main.setVisibility(View.VISIBLE);
toolbar_title.setVisibility(View.VISIBLE);
list_search.setVisibility(View.GONE);
linear_full.setVisibility(View.VISIBLE);
imma.hideSoftInputFromWindow(edit_searchmain.getWindowToken(), 0);
}
}
});
edit_searchmain.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
list_search.setVisibility(View.VISIBLE);
linear_full.setVisibility(View.GONE);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String filtered = edit_searchmain.getText().toString().toLowerCase(Locale.getDefault());
catagoryAdapter.filter(filtered);
}
});
/*VIEW PAGER CODE HERE AS MENTION */
linear_full = (LinearLayout) findViewById(R.id.linear_full);
media_player_play = (LinearLayout) findViewById(R.id.media_player_play);
scrollMethod();
pageSwitcher(3);
String cat_name;
catagory_see_all = (TextView) findViewById(R.id.catagory_see_all);
toolbar_title = (TextView) findViewById(R.id.toolbar_title);
see_all_singers = (TextView) findViewById(R.id.see_all_singers);
see_all_album = (TextView) findViewById(R.id.see_all_album);
toolbar_main = (ImageView) findViewById(R.id.toolbar_main);
garwali_see_all = (TextView) findViewById(R.id.garwali_see_all);
garwali_title = (TextView) findViewById(R.id.garwali_title);
title_kumaoni = (TextView) findViewById(R.id.title_kumaoni);
title_kumaoni.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ii = new Intent(MainActivity.this, Demo_kumanuni_albums.class);
startActivity(ii);
}
});
title_jonsari = (TextView) findViewById(R.id.title_jonsari);
title_jonsari.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Demo_jonsari_albums.class);
startActivity(i);
}
});
latest_song_title_main = (TextView) findViewById(R.id.latest_song_title_main);
garwali_title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent Garwali_Album_intent = new Intent(MainActivity.this, Demo_garwali_albums.class);
startActivity(Garwali_Album_intent);
}
});
title_singer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Singer_See_all.class);
startActivity(i);
}
});
//
// Step1 : create the RotateAnimation object
RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
// Step 2: Set the Animation properties
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
toolbar_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SampleActivity.class);
startActivity(i);
}
});
see_all_singers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("See all button clicked.." + "click tus");
Intent i = new Intent(MainActivity.this, Singer_See_all.class);
startActivity(i);
}
});
if (!cd.isConnectingToInternet()) {
Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
// finish();
} else {
checkPrefsongs();
new GetVersionCode().execute();
new Garwali_cat_Asyntask().execute();
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, "").length() > 0) {
new Singer_List_AsynTask(false).execute();
} else {
new Singer_List_AsynTask(true).execute();
}
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_TASK, "").length() > 0) {
new FetchingTask(false).execute();
} else {
new FetchingTask(true).execute();
}
new CatagoryUrlAsynTask().execute();
new Kumauni_cat_Asyntask().execute();
new junsari_cat_Asyntask().execute();
}
try {
Intent in = getIntent();
Uri data = in.getData();
Log.d(TagUtils.getTag(), "data to get:-" + data.toString());
// String url = "http://www.geetuttrakahand.com/album_id=133/image=singer_25_387893574.png";
String url = data.toString();
url = url.replace("http://www.geetuttrakahandpro.com/", "");
String[] split = url.split("/");
String a_id = split[0].split("=")[1];
String img_name = split[1].split("=")[1];
Intent i = new Intent(this, NewAlbumSongsActivity.class);
i.putExtra("Album_id", a_id);
i.putExtra("SongImage123", "http://23.22.9.33/Admin/GeetApp/includes/uploads/" + img_name);
startActivity(i);
Log.d(TagUtils.getTag(), "album_id:-" + a_id + ",image:-" + img_name);
} catch (Exception e) {
e.printStackTrace();
}
garwali_see_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Garwali_Album_intent = new Intent(MainActivity.this, Demo_garwali_albums.class);
startActivity(Garwali_Album_intent);
}
});
catagory_see_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Demo_kumanuni_albums.class);
startActivity(i);
}
});
see_all_album.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Demo_jonsari_albums.class);
startActivity(i);
}
});
}
public void checkPrefsongs() {
attachGarwaliAdapter();
attachKumauniAdapter();
attachJaunsariAdapter();
attachSingerList();
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_TASK, "").length() > 0) {
parseBannerImages(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_TASK, ""));
}
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_GARWALI_SONGS, "").length() > 0) {
parseGarwaliSongs(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_GARWALI_SONGS, ""));
}
Log.d(TagUtils.getTag(), "singer list:-" + Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, ""));
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, "").length() > 0) {
parseSingerList(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, ""));
}
//
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_CATEGORY_DATA, "").length() > 0) {
parseCategoryResponse(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_CATEGORY_DATA, ""));
}
//
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_KAMUANI_SONGS, "").length() > 0) {
parseKumauniResponse(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_KAMUANI_SONGS, ""));
}
//
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_JAUNSARI_SONGS, "").length() > 0) {
parseJaunsariResponse(Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_JAUNSARI_SONGS, ""));
}
}
private void showInterstitial() {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
}
private final String TAG = "notification";
public void sendApiToken(final String token) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://23.22.9.33/Admin/GeetApp/getapi/notification1.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Log.d("sunil","response:-"+response);
// try {
// JSONObject jsonObject=new JSONObject(response);
// String success=jsonObject.optString("success");
// if(success.equals("true")){
//// JSONObject result=""
// Toast.makeText(getApplicationContext(),"Gcm Registration Success",Toast.LENGTH_SHORT).show();
// AppConstant.setNotification(getApplicationContext(),true);
// //Log.d("sunil","success");
// }
// else{
// Toast.makeText(getApplicationContext(),"Gcm Registration Failed",Toast.LENGTH_SHORT).show();
// //Log.d("sunil","failed");
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Log.d("sunil", "" + error);
}
}) {
@Override
protected Map<String, String> getParams() {
SharedPreferences sp = getSharedPreferences("Fiyoore.txt", Context.MODE_PRIVATE);
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "AIzaSyDnLuEw-_lUKETi-W0l425a-208yr6Zr2I");
params.put("regtoken", token);
params.put("message", "hey this is sunil");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
public void onDestroy() {
// if (mAdView != null) {
// mAdView.destroy();
// }
super.onDestroy();
}
private long value(String string) {
string = string.trim();
if (string.contains(".")) {
final int index = string.lastIndexOf(".");
return value(string.substring(0, index)) * 100 + value(string.substring(index + 1));
} else {
return Long.valueOf(string);
}
}
// private void showInterstitial(){
// if(mInterstitialAd.isLoaded()){
// mInterstitialAd.show();
// }
// }
private void scrollMethod() {
}
private boolean checkInternetConenction() {
ConnectivityManager connec = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
// Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
// Intent i = new Intent(MainActivity.this, MainActivity.class);
//// oursong.stop();
// startActivity(i);
return true;
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
Intent i = new Intent(MainActivity.this, NetworkCheckClass.class);
// oursong.stop();
startActivity(i);
// Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
return false;
}
private class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... params) {
String newVersion = null;
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (onlineVersion != null && !onlineVersion.isEmpty()) {
if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
//show dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Update Available");
alertDialog.setMessage("Do you want to update it?");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
// mInterstitialAd.loadAd(adRequest);
}
});
alertDialog.show();
//Log.d("update","yess");
} else {
// mInterstitialAd.loadAd(adRequest);
}
}
//Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
// Toast.makeText(getApplicationContext(),"Current version " + currentVersion + "playstore version " + onlineVersion,Toast.LENGTH_LONG).show();
}
}
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1500); // delay
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
//Log.e("item click for event", "hii tushar");
// checkInternetConenction();
Intent i = new Intent(getApplicationContext(), SampleActivity.class);
i.putExtra(SampleActivity.ARG_LAYOUT, R.layout.sample);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
private class RemindTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (page > 10) {
// In my case the number of pages are 5
timer = new Timer();
} else {
viewPager.setCurrentItem(page++, true);
}
}
});
}
}
private class Garwali_cat_Asyntask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String url = "http://23.22.9.33/SongApi/singer.php?action_type=Catagorydetails&id=2";
String content = HttpULRConnect.getData(url);
return content;
}
@Override
protected void onPostExecute(String s) {
Log.d(TagUtils.getTag(), "garwali reponse:-" + s);
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_GARWALI_SONGS, "").length() == 0) {
parseGarwaliSongs(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_GARWALI_SONGS, s);
}
}
AlbumRecyclerAdapter garwaliAlbumAdapter;
List<AlbumPOJO> garwaliAlbumPOJOS = new ArrayList<>();
public void parseGarwaliSongs(final String s) {
final TimingLogger timings = new TimingLogger(TagUtils.getTag(), "garwali song split");
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
garwaliAlbumPOJOS.clear();
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray ar = new JSONArray(s);
int length = ar.length();
if (ar.length() > 4) {
for (int i = length - 1; i > length - 5; i--) {
Gson gson = new Gson();
AlbumPOJO albumPOJO = gson.fromJson(ar.optJSONObject(i).toString(), AlbumPOJO.class);
garwaliAlbumPOJOS.add(albumPOJO);
}
}
timings.addSplit("parsing");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
garwaliAlbumAdapter.notifyDataSetChanged();
timings.addSplit("finished");
timings.dumpToLog();
}
}.execute();
}
public void attachGarwaliAdapter() {
garwaliAlbumAdapter = new AlbumRecyclerAdapter(this, null, garwaliAlbumPOJOS);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
// layoutManager.setReverseLayout(true);
// layoutManager.setStackFromEnd(true);
rv_garwali.setHasFixedSize(true);
rv_garwali.setAdapter(garwaliAlbumAdapter);
rv_garwali.setLayoutManager(layoutManager);
rv_garwali.setItemAnimator(new DefaultItemAnimator());
}
private class FetchingTask extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog;
boolean isDialog;
public FetchingTask(boolean isDialog) {
this.isDialog = isDialog;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isDialog) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("http://23.22.9.33/SongApi/singer.php?action_type=Latest");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder lineRead = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
lineRead.append(line);
}
String responseString = lineRead.toString();
return responseString;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_TASK, "").length() == 0){
parseBannerImages(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_TASK, s);
}
}
public void parseBannerImages(final String s) {
if (!s.isEmpty()) {
new AsyncTask<Void, Void, Void>() {
List<Catagory_calass_bean> itemInfos = new ArrayList<>();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray jsonObject = new JSONArray(s);
int length = jsonObject.length();
if (length > 5) {
length = 5;
}
for (int i = 0; i < length; i++) {
Catagory_calass_bean itemInfo = new Catagory_calass_bean();
JSONObject jsObject = jsonObject.getJSONObject(i);
itemInfo.setId(jsObject.getString("id"));
Latest_Image_Id = jsObject.getString("id");
itemInfo.setAlbumCover(jsObject.getString("AlbumCover"));
itemInfo.setAlbumName(jsObject.getString("AlbumName"));
Latest_Song_Name = jsObject.getString("AlbumName");
itemInfos.add(itemInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
itemInfoList.clear();
itemInfoList.addAll(itemInfos);
adapter = new ViewPagerAdapter(MainActivity.this, itemInfoList);
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}.execute();
}
}
private class Kumauni_cat_Asyntask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String url = "http://23.22.9.33/SongApi/singer.php?action_type=Catagorydetails&id=1";
String content = HttpULRConnect.getData(url);
return content;
}
@Override
protected void onPostExecute(String s) {
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_KAMUANI_SONGS, "").length() == 0) {
parseKumauniResponse(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_KAMUANI_SONGS, s);
}
}
AlbumRecyclerAdapter kumauniAlbumAdapter;
List<AlbumPOJO> kumauniAlbumPOJOS = new ArrayList<>();
public void parseKumauniResponse(final String s) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
kumauniAlbumPOJOS.clear();
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray ar = new JSONArray(s);
// JSONArray newJsonArray = new JSONArray();
// for (int i = ar.length()-1; i>=0; i--) {
// newJsonArray.put(ar.get(i));
// }
// System.out.println("Array response is ---" + newJsonArray);
// //Log.e("Array response ids---", String.valueOf(ar));
// int length = newJsonArray.length();
// if (newJsonArray.length() > 4) {
// length = 4;
// }
for (int i = ar.length() - 1; i > ar.length() - 5; i--) {
Gson gson = new Gson();
AlbumPOJO albumPOJO = gson.fromJson(ar.optJSONObject(i).toString(), AlbumPOJO.class);
kumauniAlbumPOJOS.add(albumPOJO);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
kumauniAlbumAdapter.notifyDataSetChanged();
}
}.execute();
}
public void attachKumauniAdapter() {
kumauniAlbumAdapter = new AlbumRecyclerAdapter(this, null, kumauniAlbumPOJOS);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
// layoutManager.setReverseLayout(true);
// layoutManager.setStackFromEnd(true);
rv_kumauni.setHasFixedSize(true);
rv_kumauni.setAdapter(kumauniAlbumAdapter);
rv_kumauni.setLayoutManager(layoutManager);
rv_kumauni.setItemAnimator(new DefaultItemAnimator());
}
private class junsari_cat_Asyntask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String url = "http://23.22.9.33/SongApi/singer.php?action_type=Catagorydetails&id=3";
String content = HttpULRConnect.getData(url);
return content;
}
@Override
protected void onPostExecute(String s) {
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_JAUNSARI_SONGS, "").length() == 0) {
parseJaunsariResponse(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_JAUNSARI_SONGS, s);
}
}
AlbumRecyclerAdapter jaunsariAlbumAdapter;
List<AlbumPOJO> jaunsariAlbumPOJOS = new ArrayList<>();
public void parseJaunsariResponse(final String s) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
jaunsariAlbumPOJOS.clear();
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray ar = new JSONArray(s);
// JSONArray newJsonArray = new JSONArray();
// for (int i = ar.length()-1; i>=0; i--) {
// newJsonArray.put(ar.get(i));
// }
// System.out.println("Array response is ---" + newJsonArray);
//Log.e("Array response ids---", String.valueOf(ar));
int length = ar.length();
if (ar.length() > 4) {
length = 4;
}
for (int i = length - 1; i > length - 5; i--) {
Gson gson = new Gson();
AlbumPOJO albumPOJO = gson.fromJson(ar.optJSONObject(i).toString(), AlbumPOJO.class);
jaunsariAlbumPOJOS.add(albumPOJO);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
jaunsariAlbumAdapter.notifyDataSetChanged();
}
}.execute();
}
public void attachJaunsariAdapter() {
jaunsariAlbumAdapter = new AlbumRecyclerAdapter(this, null, jaunsariAlbumPOJOS);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
// layoutManager.setReverseLayout(true);
// layoutManager.setStackFromEnd(true);
rv_jaunsari.setHasFixedSize(true);
rv_jaunsari.setAdapter(jaunsariAlbumAdapter);
rv_jaunsari.setLayoutManager(layoutManager);
rv_jaunsari.setItemAnimator(new DefaultItemAnimator());
}
private class Singer_List_AsynTask extends AsyncTask<String, String, String> {
boolean is_dialog;
public Singer_List_AsynTask(boolean is_dialog) {
this.is_dialog = is_dialog;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (is_dialog) {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading .........");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
}
@Override
protected String doInBackground(String... params) {
String content = HttpULRConnect.getData(Holder.SINGERS_LIST_URL);
return content;
}
@Override
protected void onPostExecute(String s) {
try {
if (pDialog != null) {
pDialog.dismiss();
}
} catch (Exception e) {
}
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, "").length() == 0) {
parseSingerList(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_SINGER_LIST, s);
}
}
LatestSongAdapter latestSongAdapter;
List<LatestSongPOJO> latestSongPOJOS = new ArrayList<>();
public void parseSingerList(final String s) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
jaunsariAlbumPOJOS.clear();
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray ar = new JSONArray(s);
// JSONArray newJsonArray = new JSONArray();
// for (int i = ar.length()-1; i>=0; i--) {
// newJsonArray.put(ar.get(i));
// }
// System.out.println("Array response is ---" + newJsonArray);
//Log.e("Array response ids---", String.valueOf(ar));
int length = ar.length();
if (ar.length() > 4) {
length = 4;
}
for (int i = 0; i < length; i++) {
Gson gson = new Gson();
LatestSongPOJO latestSongPOJO = gson.fromJson(ar.optJSONObject(i).toString(), LatestSongPOJO.class);
latestSongPOJOS.add(latestSongPOJO);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
latestSongAdapter.notifyDataSetChanged();
getAlbums();
}
}.execute();
}
public void attachSingerList() {
latestSongAdapter = new LatestSongAdapter(this, null, latestSongPOJOS);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
// layoutManager.setReverseLayout(true);
// layoutManager.setStackFromEnd(true);
rv_singers.setHasFixedSize(true);
rv_singers.setAdapter(latestSongAdapter);
rv_singers.setLayoutManager(layoutManager);
rv_singers.setItemAnimator(new DefaultItemAnimator());
}
public void getAlbums() {
for (Catagory_calass_bean s : add_allthree_arraylist) {
////Log.d("sun", s.getAlbumName());
////Log.d("sun", s.getAlbumCover());
catagoryAdapter = new CatagoryAdapter(MainActivity.this, R.layout.catagory_class_layout, add_allthree_arraylist);
list_search.setAdapter(catagoryAdapter);
list_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* String albumID12 = add_allthree_arraylist.get(position).getId();
String AlbumImage = add_allthree_arraylist.get(position).getAlbumCover();
String album_name= add_allthree_arraylist.get(position).getAlbumName();
Intent i = new Intent(MainActivity.this, AlbumeSongs.class);
i.putExtra("SongImage123", AlbumImage);
i.putExtra("album_name", album_name);
i.putExtra("Album_id", albumID12);
startActivity(i);
*/
String SingerId = add_allthree_arraylist.get(position).getId();
String singerImage = add_allthree_arraylist.get(position).getImage();
int songIndex = position;
FULL_NAME = Singer_First_Name + Singer_Last_Name;
if (singerImage != null) {
Intent i1 = new Intent(getApplicationContext(), Singers_Details_class.class);
i1.putExtra("songIndex", songIndex);
i1.putExtra("ImageIs", singerImage);
i1.putExtra("Singer_id_put", SingerId);
i1.putExtra("FULL_Singer__NAME", FULL_NAME);
startActivity(i1);
} else {
String albumID12 = add_allthree_arraylist.get(position).getId();
String AlbumImage = add_allthree_arraylist.get(position).getAlbumCover();
String album_name = add_allthree_arraylist.get(position).getAlbumName();
Intent i = new Intent(MainActivity.this, AlbumeSongs.class);
i.putExtra("SongImage123", AlbumImage);
i.putExtra("album_name", album_name);
i.putExtra("Album_id", albumID12);
startActivity(i);
}
}
});
}
}
private class CatagoryUrlAsynTask extends AsyncTask<String, String, String> {
String id, catagoryName;
@Override
protected String doInBackground(String... params) {
String content = HttpULRConnect.getData(CATAGOARY_URL);
return content;
}
@Override
protected void onPostExecute(String s) {
if (Pref.GetStringPref(getApplicationContext(), StringUtils.FETCH_CATEGORY_DATA, "").length() == 0) {
parseCategoryResponse(s);
}
Pref.SetStringPref(getApplicationContext(), StringUtils.FETCH_CATEGORY_DATA, s);
}
}
public void parseCategoryResponse(String s) {
try {
JSONArray ar = new JSONArray(s);
System.out.println("Array response is ---" + ar);
for (int i = 0; i < ar.length(); i++) {
System.out.println("Array response is ---" + ar.length());
JSONObject jsonobject = ar.getJSONObject(ar.length() - 1 - i);
CategoryGetSetUrl catagory_bean = new CategoryGetSetUrl();
CatId = jsonobject.getString("id");
catagory_bean.setId(CatId);
System.out.println("Full URL is As iT is ---" + Detailes_caragory);
CatagoryName = jsonobject.getString("CatagoryName");
catagory_bean.setCatagoryName(CatagoryName);
latest_song_title_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, See_all_catagory.class);
i.putExtra("ID", CatId);
i.putExtra("NAME", CatagoryName);
startActivity(i);
}
});
catagory_array_list1.add(catagory_bean);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
if (flag) {
flag = false;
new AlertDialog.Builder(this)
//.setTitle("")
.setCancelable(false)
.setMessage("Are you Sure you want to Exit?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
} else {
flag = true;
edit_searchmain.setVisibility(View.GONE);
toolbar_main.setVisibility(View.VISIBLE);
toolbar_title.setVisibility(View.VISIBLE);
list_search.setVisibility(View.GONE);
linear_full.setVisibility(View.VISIBLE);
}
}
// this.moveTaskToBack(true);
@Override
public void onPause() {
super.onPause();
if ((pDialog != null) && pDialog.isShowing())
pDialog.dismiss();
pDialog = null;
Intent intent = new Intent(getApplicationContext(), BlurMediaPlayer.class);
startService(intent);
super.onPause();
Log.w("MainActivity", "onPause");
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
}
@Override
public void onResume() {
super.onResume();
Log.w("MainActivity", "onResume");
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));
}
int count = 0;
}
|
/*
* Can a static method be overridden? No.
* Instance methods could be overridden, but not class method.
* overriding is about runtime, how the methods are dynamically selected.
* so which overridden method is selected depends on the acutal instance.
*
*/
package Inheritance;
/**
*
* @author YNZ
*/
class BBase {
public static int id = 1;
//private static String name = this.toString(); this statment is not valid, for this ref. to an instance.
public static void whoAmI() {
System.out.println("A");
}
public static void doIt() {
System.out.println("do it");
}
public void doIt(int a) {
}
public float doIt(int a, float b) {
return a + b;
}
public int doIt(int a, int b) {
return a + b;
}
public void getInstance() {
System.out.println(this.hashCode());
}
}
class BBBBBbase1 extends BBase {
public static int id = 2;
public static void whoAmI() {
System.out.println("B");
}
public static void doIt() {
System.out.println("do it");
}
@Override
public void getInstance() {
System.out.println(this.hashCode());
}
}
class CanStaticOverridden {
public static void main(String... args) {
BBase.whoAmI();
BBBBBbase1.whoAmI();
BBase.doIt();
BBase a = new BBase();
BBBBBbase1 b = new BBBBBbase1();
System.out.println(BBase.id);
System.out.println(BBBBBbase1.id);
System.out.println(a.id);
System.out.println(((BBase) b).id);
a.getInstance();
b.getInstance();
}
}
|
/**********************************************************************
Copyright (c) 2014 Baris ERGUN and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.cassandra.query;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import java.util.Iterator;
import org.datanucleus.ExecutionContext;
import org.datanucleus.FetchPlan;
import org.datanucleus.api.ApiAdapter;
import org.datanucleus.store.query.Query;
import org.datanucleus.store.query.QueryManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class CassandraQueryResultWithResultCacheTest
{
private CQLQuery mockCqlQuery;
private ResultSet mockResultSet;
private CassandraQueryResult cqlQueryResult;
public CassandraQueryResultWithResultCacheTest()
{
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
mockCqlQuery = mock(CQLQuery.class);
mockResultSet = mock(ResultSet.class);
ExecutionContext mockExecutionContext = mock(ExecutionContext.class);
when(mockCqlQuery.getExecutionContext()).thenReturn(mockExecutionContext);
when(mockExecutionContext.getApiAdapter()).thenReturn(mock(ApiAdapter.class));
when(mockCqlQuery.getStringExtensionProperty(Query.EXTENSION_RESULT_SIZE_METHOD, "last")).thenReturn("resultSizeMethod");
when(mockCqlQuery.getBooleanExtensionProperty(Query.EXTENSION_LOAD_RESULTS_AT_COMMIT, true)).thenReturn(true);
when(mockCqlQuery.useResultsCaching()).thenReturn(true);
cqlQueryResult = new CassandraQueryResult(mockCqlQuery, mockResultSet);
verify(mockCqlQuery, times(1)).getExecutionContext();
verify(mockExecutionContext, times(1)).getApiAdapter();
verify(mockCqlQuery, times(1)).getStringExtensionProperty(eq(Query.EXTENSION_RESULT_SIZE_METHOD), eq("last"));
verify(mockCqlQuery, times(1)).getBooleanExtensionProperty(eq(Query.EXTENSION_LOAD_RESULTS_AT_COMMIT), eq(true));
verify(mockCqlQuery, times(1)).useResultsCaching();
verifyNoMoreInteractions(mockResultSet);
}
@After
public void tearDown()
{
}
@Test
public void shouldCloseResultsIfNoMoreElementsOnInitialize()
{
Iterator<Row> mockRowIter = mock(Iterator.class);
when(mockResultSet.iterator()).thenReturn(mockRowIter);
when(mockRowIter.hasNext()).thenReturn(false);
QueryManager mockQueryManager = mock(QueryManager.class);
when(mockCqlQuery.getQueryManager()).thenReturn(mockQueryManager);
FetchPlan mockFetchPlan = mock(FetchPlan.class);
when(mockCqlQuery.getFetchPlan()).thenReturn(mockFetchPlan);
when(mockFetchPlan.getFetchSize()).thenReturn(3);
cqlQueryResult.initialise();
verify(mockCqlQuery, times(1)).getFetchPlan();
verify(mockFetchPlan, times(1)).getFetchSize();
verify(mockResultSet, times(1)).iterator();
verify(mockRowIter, times(1)).hasNext();
verify(mockCqlQuery, times(1)).getQueryManager();
verify(mockQueryManager, times(1)).addQueryResult(eq(mockCqlQuery), anyMap(), anyList());
verifyNoMoreInteractions(mockResultSet, mockRowIter);
}
@Test
public void shouldProcessRowsOneByOneOnInitializeWithGreedyFetch()
{
Iterator<Row> mockRowIter = mock(Iterator.class);
when(mockResultSet.iterator()).thenReturn(mockRowIter);
when(mockRowIter.hasNext()).thenAnswer(new Answer()
{
int count = 0;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
return count++ < 5;
}
});
when(mockResultSet.one()).thenAnswer(new Answer()
{
int count = 0;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
if (count++ < 4)
{
return mock(Row.class);
}
return null;
}
});
FetchPlan mockFetchPlan = mock(FetchPlan.class);
when(mockCqlQuery.getFetchPlan()).thenReturn(mockFetchPlan);
when(mockFetchPlan.getFetchSize()).thenReturn(FetchPlan.FETCH_SIZE_GREEDY);
cqlQueryResult.initialise();
verify(mockCqlQuery, times(1)).getFetchPlan();
verify(mockFetchPlan, times(1)).getFetchSize();
verify(mockResultSet, times(2)).iterator();
verify(mockRowIter, times(6)).hasNext();
verify(mockResultSet, times(4)).one();
verifyNoMoreInteractions(mockResultSet, mockRowIter);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms.connection;
import jakarta.jms.Connection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSException;
import jakarta.jms.Session;
import jakarta.jms.TransactionRolledBackException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.ResourceTransactionManager;
import org.springframework.transaction.support.SmartTransactionObject;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
/**
* {@link org.springframework.transaction.PlatformTransactionManager} implementation
* for a single JMS {@link jakarta.jms.ConnectionFactory}. Binds a JMS
* Connection/Session pair from the specified ConnectionFactory to the thread,
* potentially allowing for one thread-bound Session per ConnectionFactory.
*
* <p>This local strategy is an alternative to executing JMS operations within
* JTA transactions. Its advantage is that it is able to work in any environment,
* for example a standalone application or a test suite, with any message broker
* as target. However, this strategy is <i>not</i> able to provide XA transactions,
* for example in order to share transactions between messaging and database access.
* A full JTA/XA setup is required for XA transactions, typically using Spring's
* {@link org.springframework.transaction.jta.JtaTransactionManager} as strategy.
*
* <p>Application code is required to retrieve the transactional JMS Session via
* {@link ConnectionFactoryUtils#getTransactionalSession} instead of a standard
* Jakarta EE-style {@link ConnectionFactory#createConnection()} call with subsequent
* Session creation. Spring's {@link org.springframework.jms.core.JmsTemplate}
* will autodetect a thread-bound Session and automatically participate in it.
*
* <p>Alternatively, you can allow application code to work with the standard
* Jakarta EE-style lookup pattern on a ConnectionFactory, for example for legacy code
* that is not aware of Spring at all. In that case, define a
* {@link TransactionAwareConnectionFactoryProxy} for your target ConnectionFactory,
* which will automatically participate in Spring-managed transactions.
*
* <p><b>The use of {@link CachingConnectionFactory} as a target for this
* transaction manager is strongly recommended.</b> CachingConnectionFactory
* uses a single JMS Connection for all JMS access in order to avoid the overhead
* of repeated Connection creation, as well as maintaining a cache of Sessions.
* Each transaction will then share the same JMS Connection, while still using
* its own individual JMS Session.
*
* <p>The use of a <i>raw</i> target ConnectionFactory would not only be inefficient
* because of the lack of resource reuse. It might also lead to strange effects
* when your JMS driver doesn't accept {@code MessageProducer.close()} calls
* and/or {@code MessageConsumer.close()} calls before {@code Session.commit()},
* with the latter supposed to commit all the messages that have been sent through the
* producer handle and received through the consumer handle. As a safe general solution,
* always pass in a {@link CachingConnectionFactory} into this transaction manager's
* {@link #setConnectionFactory "connectionFactory"} property.
*
* <p>Transaction synchronization is turned off by default, as this manager might
* be used alongside a datastore-based Spring transaction manager such as the
* JDBC {@link org.springframework.jdbc.datasource.DataSourceTransactionManager},
* which has stronger needs for synchronization.
*
* @author Juergen Hoeller
* @since 1.1
* @see ConnectionFactoryUtils#getTransactionalSession
* @see TransactionAwareConnectionFactoryProxy
* @see org.springframework.jms.core.JmsTemplate
*/
@SuppressWarnings("serial")
public class JmsTransactionManager extends AbstractPlatformTransactionManager
implements ResourceTransactionManager, InitializingBean {
@Nullable
private ConnectionFactory connectionFactory;
private boolean lazyResourceRetrieval = false;
/**
* Create a new JmsTransactionManager for bean-style usage.
* <p>Note: The ConnectionFactory has to be set before using the instance.
* This constructor can be used to prepare a JmsTemplate via a BeanFactory,
* typically setting the ConnectionFactory via setConnectionFactory.
* <p>Turns off transaction synchronization by default, as this manager might
* be used alongside a datastore-based Spring transaction manager like
* DataSourceTransactionManager, which has stronger needs for synchronization.
* Only one manager is allowed to drive synchronization at any point of time.
* @see #setConnectionFactory
* @see #setTransactionSynchronization
*/
public JmsTransactionManager() {
setTransactionSynchronization(SYNCHRONIZATION_NEVER);
}
/**
* Create a new JmsTransactionManager, given a ConnectionFactory.
* @param connectionFactory the ConnectionFactory to obtain connections from
*/
public JmsTransactionManager(ConnectionFactory connectionFactory) {
this();
setConnectionFactory(connectionFactory);
afterPropertiesSet();
}
/**
* Set the JMS ConnectionFactory that this instance should manage transactions for.
*/
public void setConnectionFactory(@Nullable ConnectionFactory cf) {
if (cf instanceof TransactionAwareConnectionFactoryProxy txAwareCFP) {
// If we got a TransactionAwareConnectionFactoryProxy, we need to perform transactions
// for its underlying target ConnectionFactory, else JMS access code won't see
// properly exposed transactions (i.e. transactions for the target ConnectionFactory).
this.connectionFactory = txAwareCFP.getTargetConnectionFactory();
}
else {
this.connectionFactory = cf;
}
}
/**
* Return the JMS ConnectionFactory that this instance should manage transactions for.
*/
@Nullable
public ConnectionFactory getConnectionFactory() {
return this.connectionFactory;
}
/**
* Obtain the ConnectionFactory for actual use.
* @return the ConnectionFactory (never {@code null})
* @throws IllegalStateException in case of no ConnectionFactory set
* @since 5.0
*/
protected final ConnectionFactory obtainConnectionFactory() {
ConnectionFactory connectionFactory = getConnectionFactory();
Assert.state(connectionFactory != null, "No ConnectionFactory set");
return connectionFactory;
}
/**
* Specify whether this transaction manager should lazily retrieve a JMS
* Connection and Session on access within a transaction ({@code true}).
* By default, it will eagerly create a JMS Connection and Session at
* transaction begin ({@code false}).
* @since 5.1.6
* @see JmsResourceHolder#getConnection()
* @see JmsResourceHolder#getSession()
*/
public void setLazyResourceRetrieval(boolean lazyResourceRetrieval) {
this.lazyResourceRetrieval = lazyResourceRetrieval;
}
/**
* Make sure the ConnectionFactory has been set.
*/
@Override
public void afterPropertiesSet() {
if (getConnectionFactory() == null) {
throw new IllegalArgumentException("Property 'connectionFactory' is required");
}
}
@Override
public Object getResourceFactory() {
return obtainConnectionFactory();
}
@Override
protected Object doGetTransaction() {
JmsTransactionObject txObject = new JmsTransactionObject();
txObject.setResourceHolder(
(JmsResourceHolder) TransactionSynchronizationManager.getResource(obtainConnectionFactory()));
return txObject;
}
@Override
protected boolean isExistingTransaction(Object transaction) {
JmsTransactionObject txObject = (JmsTransactionObject) transaction;
return txObject.hasResourceHolder();
}
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
throw new InvalidIsolationLevelException("JMS does not support an isolation level concept");
}
ConnectionFactory connectionFactory = obtainConnectionFactory();
JmsTransactionObject txObject = (JmsTransactionObject) transaction;
Connection con = null;
Session session = null;
try {
JmsResourceHolder resourceHolder;
if (this.lazyResourceRetrieval) {
resourceHolder = new LazyJmsResourceHolder(connectionFactory);
}
else {
con = createConnection();
session = createSession(con);
if (logger.isDebugEnabled()) {
logger.debug("Created JMS transaction on Session [" + session + "] from Connection [" + con + "]");
}
resourceHolder = new JmsResourceHolder(connectionFactory, con, session);
}
resourceHolder.setSynchronizedWithTransaction(true);
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
resourceHolder.setTimeoutInSeconds(timeout);
}
txObject.setResourceHolder(resourceHolder);
TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolder);
}
catch (Throwable ex) {
if (session != null) {
try {
session.close();
}
catch (Throwable ex2) {
// ignore
}
}
if (con != null) {
try {
con.close();
}
catch (Throwable ex2) {
// ignore
}
}
throw new CannotCreateTransactionException("Could not create JMS transaction", ex);
}
}
@Override
protected Object doSuspend(Object transaction) {
JmsTransactionObject txObject = (JmsTransactionObject) transaction;
txObject.setResourceHolder(null);
return TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
}
@Override
protected void doResume(@Nullable Object transaction, Object suspendedResources) {
TransactionSynchronizationManager.bindResource(obtainConnectionFactory(), suspendedResources);
}
@Override
protected void doCommit(DefaultTransactionStatus status) {
JmsTransactionObject txObject = (JmsTransactionObject) status.getTransaction();
Session session = txObject.getResourceHolder().getOriginalSession();
if (session != null) {
try {
if (status.isDebug()) {
logger.debug("Committing JMS transaction on Session [" + session + "]");
}
session.commit();
}
catch (TransactionRolledBackException ex) {
throw new UnexpectedRollbackException("JMS transaction rolled back", ex);
}
catch (JMSException ex) {
throw new TransactionSystemException("Could not commit JMS transaction", ex);
}
}
}
@Override
protected void doRollback(DefaultTransactionStatus status) {
JmsTransactionObject txObject = (JmsTransactionObject) status.getTransaction();
Session session = txObject.getResourceHolder().getOriginalSession();
if (session != null) {
try {
if (status.isDebug()) {
logger.debug("Rolling back JMS transaction on Session [" + session + "]");
}
session.rollback();
}
catch (JMSException ex) {
throw new TransactionSystemException("Could not roll back JMS transaction", ex);
}
}
}
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
JmsTransactionObject txObject = (JmsTransactionObject) status.getTransaction();
txObject.getResourceHolder().setRollbackOnly();
}
@Override
protected void doCleanupAfterCompletion(Object transaction) {
JmsTransactionObject txObject = (JmsTransactionObject) transaction;
TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
txObject.getResourceHolder().closeAll();
txObject.getResourceHolder().clear();
}
/**
* Create a JMS Connection via this template's ConnectionFactory.
* <p>This implementation uses JMS 1.1 API.
* @return the new JMS Connection
* @throws jakarta.jms.JMSException if thrown by JMS API methods
*/
protected Connection createConnection() throws JMSException {
return obtainConnectionFactory().createConnection();
}
/**
* Create a JMS Session for the given Connection.
* <p>This implementation uses JMS 1.1 API.
* @param con the JMS Connection to create a Session for
* @return the new JMS Session
* @throws jakarta.jms.JMSException if thrown by JMS API methods
*/
protected Session createSession(Connection con) throws JMSException {
return con.createSession(true, Session.AUTO_ACKNOWLEDGE);
}
/**
* Lazily initializing variant of {@link JmsResourceHolder},
* initializing a JMS Connection and Session on user access.
*/
private class LazyJmsResourceHolder extends JmsResourceHolder {
private boolean connectionInitialized = false;
private boolean sessionInitialized = false;
public LazyJmsResourceHolder(@Nullable ConnectionFactory connectionFactory) {
super(connectionFactory);
}
@Override
@Nullable
public Connection getConnection() {
initializeConnection();
return super.getConnection();
}
@Override
@Nullable
public <C extends Connection> C getConnection(Class<C> connectionType) {
initializeConnection();
return super.getConnection(connectionType);
}
@Override
@Nullable
public Session getSession() {
initializeSession();
return super.getSession();
}
@Override
@Nullable
public <S extends Session> S getSession(Class<S> sessionType) {
initializeSession();
return super.getSession(sessionType);
}
@Override
@Nullable
public <S extends Session> S getSession(Class<S> sessionType, @Nullable Connection connection) {
initializeSession();
return super.getSession(sessionType, connection);
}
private void initializeConnection() {
if (!this.connectionInitialized) {
try {
addConnection(createConnection());
}
catch (JMSException ex) {
throw new CannotCreateTransactionException(
"Failed to lazily initialize JMS Connection for transaction", ex);
}
this.connectionInitialized = true;
}
}
private void initializeSession() {
if (!this.sessionInitialized) {
Connection con = getConnection();
Assert.state(con != null, "No transactional JMS Connection");
try {
addSession(createSession(con), con);
}
catch (JMSException ex) {
throw new CannotCreateTransactionException(
"Failed to lazily initialize JMS Session for transaction", ex);
}
this.sessionInitialized = true;
}
}
}
/**
* JMS transaction object, representing a JmsResourceHolder.
* Used as transaction object by JmsTransactionManager.
* @see JmsResourceHolder
*/
private static class JmsTransactionObject implements SmartTransactionObject {
@Nullable
private JmsResourceHolder resourceHolder;
public void setResourceHolder(@Nullable JmsResourceHolder resourceHolder) {
this.resourceHolder = resourceHolder;
}
public JmsResourceHolder getResourceHolder() {
Assert.state(this.resourceHolder != null, "No JmsResourceHolder available");
return this.resourceHolder;
}
public boolean hasResourceHolder() {
return (this.resourceHolder != null);
}
@Override
public boolean isRollbackOnly() {
return (this.resourceHolder != null && this.resourceHolder.isRollbackOnly());
}
}
}
|
package vista.Proveedores;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import controlador.*;
public class FormAltaProveedor extends javax.swing.JFrame {
private JButton btnAceptar;
private JTextField txtDomicilio;
private JTextField txtCuit;
private JTextField txtRazonSocial;
private AbstractAction aceptarAccion;
private JLabel lblRazonSocial;
private JLabel jLabel2;
private JLabel jLabel1;
public FormAltaProveedor() {
super();
initGUI();
}
private void initGUI() {
try {
getContentPane().setLayout(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("Alta de Proveedores");
{
btnAceptar = new JButton();
getContentPane().add(btnAceptar);
btnAceptar.setText("ACEPTAR");
btnAceptar.setBounds(132, 225, 118, 34);
btnAceptar.setAction(getAceptarAccion());
}
{
txtCuit = new JTextField();
getContentPane().add(txtCuit);
txtCuit.setBounds(134, 12, 244, 34);
}
{
txtDomicilio = new JTextField();
getContentPane().add(txtDomicilio);
txtDomicilio.setBounds(134, 58, 244, 34);
}
{
txtRazonSocial = new JTextField();
getContentPane().add(txtRazonSocial);
txtRazonSocial.setBounds(134, 108, 244, 34);
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("Cuit");
jLabel1.setBounds(12, 13, 110, 33);
}
{
jLabel2 = new JLabel();
getContentPane().add(jLabel2);
jLabel2.setText("Domicilio");
jLabel2.setBounds(12, 59, 110, 33);
}
{
lblRazonSocial = new JLabel();
getContentPane().add(lblRazonSocial);
lblRazonSocial.setText("Razon Social");
lblRazonSocial.setBounds(12, 109, 110, 33);
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
private AbstractAction getAceptarAccion() {
if(aceptarAccion == null) {
aceptarAccion = new AbstractAction("ACEPTAR", null) {
public void actionPerformed(ActionEvent evt) {
Restaurante.getRestaurante().altaDeProveedor(txtCuit.getText(), txtRazonSocial.getText(), txtDomicilio.getText());
txtCuit.setText("");
txtRazonSocial.setText("");
txtDomicilio.setText("");
JOptionPane.showMessageDialog(null, "Proveedor creado con exito.", "Resultado", JOptionPane.INFORMATION_MESSAGE);
}
};
}
return aceptarAccion;
}
}
|
package com.osteching.litemongo;
public final class Operator {
private Operator() {
}
public static final String EQ = "=";
public static final String GT = "$gt";
public static final String LT = "$lt";
}
|
package business.model;
public interface CompTime {
public double calcularPreco(int hours);
}
|
/**
* 香港理工大学-中国科学院研究生院数据挖掘-PageRank算法实现
* @author chaoyu
* @right Copyright by PolyU team
* @github https://github.com/yuchao86/pagerank.git
* @date 2012-10-18
*/
package polyu.gucas.rawPagerank.UnitTest;
/**
* Tutorial 05: "Inverted File Indexing"
* compile and run with :
* WordUtil,MyHtmlTextHandler,HtmlWordExtractor,IndexBuilder
* together with your own code.
*/
/**
* This class demos how to use IndexBuilder
* @version jdk 1.6.0
*/
import java.io.*;
import java.util.*;
import polyu.gucas.rawPagerank.wordretrieve.IndexBuilder;
public class TestIndexBuilder {
public static final String[] urlArr={
"http://www.polyu.edu.hk/poc/abt.html",
"http://www.polyu.edu.hk/cpa/polyu/index.php",
"http://www.cs.cityu.edu.hk/news",
};
public static void main(String[] args) {
IndexBuilder ib=new IndexBuilder();
for(int i=0;i<urlArr.length;++i){
try {
ib.feedUrl(urlArr[i]);
} catch (IOException e) {
System.err.println("URL IS Not Accesible:"+urlArr[i]);
}
}
Iterator<String> it;
//Demo: Look up where a term appears
it=ib.lookUpDocForTerm("polyu");
System.out.println("Term \"polyu\" is in document:");
printIterator(it);
//Another Demo: Look up where a term appears
it=ib.lookUpDocForTerm("CMAO");
System.out.println("Term \"CMAO\" is in document:");
printIterator(it);
//Demo: Enumerate through all documents
it=ib.getDocIterator();
System.out.println("Document List:");
printIterator(it);
//Demo: Enumerate through all terms
it=ib.getTermIterator();
System.out.println("Term List:");
printIterator(it);
}
public static void printIterator(Iterator<String> it){
System.out.print("[");
while(it.hasNext()){
System.out.print(it.next());
System.out.print("; ");
}
System.out.println("]");
}
}
|
package cn.edu.pku.residents.schedule;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UploadServer {
private final static int SERVER_PORT = 1234;
public static void main(String[] args) throws Exception {
//1.创建ServerSocket, 在循环中接收客户端请求, 每接收到一个请求就开启新线程处理
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("服务已启动,绑定1234端口!");
while(true){
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
}
}
class ServerThread extends Thread{
Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
FileOutputStream fos = null;
try {
//3.获取输入输出流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
//7.接收文件, 查找是否存在. 如果存在, 给写一个消息给客户端, 服务端线程结束. 如果不存在, 写消息给客户端, 准备开始上传.
String fileName = br.readLine();
long fileLen = Long.parseLong(br.readLine());
File dir = new File("upload");
dir.mkdir();
File file = new File(dir,fileName);
if(file.exists() && file.length() == fileLen){ // 文件已存在, length()即为文件大小, 文件不存在length()为0
ps.println("已存在");
return;
}
else{
ps.println(file.length()); // 文件已存在, length()即为文件大小, 文件不存在length()为0
}
//10.从Socket的输入流中读取数据, 创建FileOutputStream写出到文件中
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String ip = socket.getInetAddress().getHostAddress();
System.out.println(time + " " + ip + (file.exists() ? " 开始断点续传: " : " 开始上传文件: ") + file.getName());
long start = System.currentTimeMillis();
InputStream in = socket.getInputStream();
fos = new FileOutputStream(file, true); // 文件存在就追加, 文件不存在则创建
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) != -1){ //这个地方会堵塞,如果客服端没有关闭socket.服务器端读不到流末尾(-1)
fos.write(buffer, 0, len);
if(file.length() == fileLen) // 文件大小等于客户端文件大小时, 代表上传完毕
break;
}
fos.close();
long end = System.currentTimeMillis();
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println(time + " " + ip + " 上传文件结束: " + file.getName() + ", 耗时: " + (end - start) + "毫秒");
ps.println("上传成功");
socket.close();
} catch (IOException e) {
if(fos != null)
try {
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
|
package cat_tests.appmanager;
import com.codeborne.selenide.Selenide;
public class TargetingHelper extends HelperBase {
public TargetingHelper(Selenide driver) {
super(driver);
}
public void setShowNever() {
click(getMarketEntityPage().show_never);
}
}
|
package com.cxc.viewanimationdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
Button btn_ani = (Button)findViewById(R.id.btn_ani);
//XML文件实现的动画
// Animation animation = AnimationUtils.loadAnimation(this,R.anim.animation_text);
// btn_ani.startAnimation(animation);
//代码实现的动画
AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
alphaAnimation.setDuration(2000);
btn_ani.startAnimation(alphaAnimation);
}
}
|
package de.cuuky.varo.version;
public enum BukkitVersion {
ONE_7(7),
ONE_8(8),
ONE_9(9),
ONE_10__ONE_11(10, 11),
ONE_12(12),
ONE_13__ONE__14(13, 14);
private int[] identifier;
private BukkitVersion(int... identifier) {
this.identifier = identifier;
}
public int[] getIdentifier() {
return identifier;
}
public boolean isHigherThan(BukkitVersion ver) {
return getIdentifier()[0] > ver.getIdentifier()[0];
}
public static BukkitVersion getVersion(String v) {
int versionNumber = Integer.valueOf(v.split("1_")[1].split("_")[0]);
for(BukkitVersion version : values())
for(int s : version.getIdentifier())
if(versionNumber == s)
return version;
if(versionNumber < values()[0].getIdentifier()[0])
return values()[0];
else if(versionNumber > values()[values().length - 1].getIdentifier()[values()[values().length - 1].getIdentifier().length - 1])
return values()[values().length - 1];
return null;
}
}
|
package com.git.cloud.vmrc.dao;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.vmrc.model.po.VmrcPo;
/**
* @ClassName: VmrcDao
* @Description: vmware remote console dao
* @author WangJingxin
* @date 2016年6月27日 下午2:22:02
*
*/
public class VmrcDao extends CommonDAOImpl {
/**
* @Title: queryVmrcInfoByVmId
* @Description: 查询 vmware remote console 连接所需的信息
* @param vmId
* @return VmrcPo
*/
public VmrcPo queryVmrcInfoByVmId(String vmId) throws Exception {
VmrcPo po = super.findObjectByID("queryVmrcInfoByVmId",vmId);
return po;
}
}
|
package com.esum.web.apps.dbc.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.esum.appetizer.config.Configurer;
import com.esum.appetizer.controller.AbstractController;
import com.esum.appetizer.util.PageUtil;
import com.esum.appetizer.util.RequestUtils;
import com.esum.web.apps.dbc.service.DbcInfoService;
import com.esum.web.apps.dbc.vo.DbcInfo;
@Controller
public class DbcInfoController extends AbstractController {
@Autowired
private DbcInfoService baseService;
/**
* DBC 컴포넌트 - 목록 화면
*/
@RequestMapping(value = "/service/dbc/dbcInfoList")
public String dbcInfoList(HttpServletRequest request, Model model) {
String interfaceId = request.getParameter("searchInterfaceId");
String jobName = request.getParameter("searchJobName");
String jobType = request.getParameter("searchJobType");
String nodeId = request.getParameter("searchNodeId");
int currentPage = RequestUtils.getParamInt(request, "currentPage", 1);
PageUtil pageUtil = new PageUtil(currentPage, Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10,
baseService.countList(interfaceId, nodeId, jobName, jobType));
List<DbcInfo> list = baseService.selectList(interfaceId, nodeId, jobName, jobType, pageUtil);
model.addAttribute("list", list);
model.addAttribute("pageUtil", pageUtil);
return "/service/dbc/dbcInfoList";
}
/**
* DBC 컴포넌트 - 등록 화면
*/
@RequestMapping(value = "/service/dbc/dbcInfoInsert")
public String dbcInfoInsert(HttpServletRequest request, Model model) {
// 초기값 설정
DbcInfo vo = new DbcInfo();
vo.setUseFlag("N");
vo.setJobType("J");
vo.setMaxThread(1);
vo.setPollingInterval(30);
vo.setUseComponentEvent("N");
model.addAttribute("vo", vo);
return "/service/dbc/dbcInfoInsert";
}
/**
* DBC 컴포넌트 - 상세 화면
*/
@RequestMapping(value = "/service/dbc/dbcInfoDetail")
public String dbcInfoDetail(HttpServletRequest request, Model model) {
String interfaceId = request.getParameter("interfaceId");
DbcInfo vo = baseService.select(interfaceId);
model.addAttribute("vo", vo);
return "/service/dbc/dbcInfoInsert";
}
}
|
package InternetTest;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 实现TCP的网络编程
* 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
*/
public class TCPTest1 {
//客户端
@Test
public void client(){
Socket socket=null;
OutputStream os=null;
try {
//1.创建Socket对象,指明服务器端的ip和端口号
InetAddress inet=InetAddress.getByName("127.0.0.1");
socket=new Socket(inet,8899);
//2.获取一个输出流,用于输出数据
os = socket.getOutputStream();
//3.写出数据的操作
os.write("gengzichen".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally { //4.资源的关闭
try {
if(os!=null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//服务端
@Test
public void server(){
ServerSocket ss=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream bos=null;
try {
//1.创建服务器端的ServerSocket,指明自己的端口号
ss=new ServerSocket(8899);
//2.调用accept()表示接收来自于客户端的socket
socket=ss.accept();
//3.获取输入流
is=socket.getInputStream();
//4.读取输入流中的数据
bos=new ByteArrayOutputStream();
byte[] buffer=new byte[5];
int len;
while((len=is.read(buffer))!=-1){
bos.write(buffer,0,len);
}
System.out.println(bos.toString());
System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据");
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bos != null){
//5.关闭资源
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package com.hjc.java_common_tools;
/**
* <pre>
* jstack输出的结果是:
*
* "Thread-0" prio=6 tid=0x0000000006735800 nid=0x1be0 waiting on condition [0x0000000006faf000]
* java.lang.Thread.State: TIMED_WAITING (sleeping)
* at java.lang.Thread.sleep(Native Method)
* at com.hjc.java_common_tools.ThreadB_3.run(ThreadStatus_jstack_3.java:58)
* - locked <0x00000000eaceffd0> (a com.hjc.java_common_tools.ThreadB_3)
*
* "main" prio=6 tid=0x00000000004db800 nid=0xed0 in Object.wait() [0x00000000026cf000]
* java.lang.Thread.State: BLOCKED (on object monitor)
* at java.lang.Object.wait(Native Method)
* - waiting on <0x00000000eaceffd0> (a com.hjc.java_common_tools.ThreadB_3)
* at java.lang.Object.wait(Object.java:485)
* at com.hjc.java_common_tools.ThreadStatus_jstack_3.main(ThreadStatus_jstack_3.java:37)
* - locked <0x00000000eaceffd0> (a com.hjc.java_common_tools.ThreadB_3)
* </pre>
*
* 可以看到:当主线程执行b.wait()之后,就进入了WAITING状态,但是新线程执行notifyAll()之后,
* 有一个瞬间主线程回到了RUNNABLE状态,但是好景不长,由于这个时候新线程还没有释放锁,所以主线程立刻进入了BLOCKED状态 。
*
* <h2>当在对象上调用wait()方法时,执行该代码的线程立即放弃它在对象上的锁。然而调用notify()时,并不意味着这时线程会放弃其锁。
* 如果线程仍然在完成同步代码,则线程在移出之前不会放弃锁。因此,只要调用notify()并不意味着这时该锁被释放</h2>
*
* @author hejianchao
*
*/
public class ThreadStatus_jstack_3 {
public static void main(String[] args) {
ThreadB_3 b = new ThreadB_3(); // ThreadB status: new
b.start(); // ThreadB status: runnable
synchronized (b) {
try {
System.out.println("wait b to cal 。。。");
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b result is:" + b.total);
}
}
}
class ThreadB_3 extends Thread {
int total;
public void run() {
synchronized (this) {
for (int i = 0; i < 101; i++) {
total += i;
}
notifyAll();
try {
System.out.println("子线程休息下。。");
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package ru.job4j.web;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Класс AttributeStorage реалиует сущность Хранилище атрибутов.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-05-28
* @since 2018-05-28
*/
public class AttributeStorage {
/**
* Атрибуты.
*/
private ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<>();
/**
* Установить хранилище атрибутов.
* @param req HTTP-запрос.
*/
public void set(HttpServletRequest req) {
// Mock setAttribute
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String key = invocation.getArgumentAt(0, String.class);
Object value = invocation.getArgumentAt(1, Object.class);
attributes.put(key, value);
//System.err.println("Storage <<< key: " + key + ", val:" + value);
return null;
}
}).when(req).setAttribute(Mockito.anyString(), Mockito.anyObject());
// Mock getAttribute
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String key = invocation.getArgumentAt(0, String.class);
Object value = attributes.get(key);
//System.err.println("Storage >>> key: " + key + ", val: " + value);
return value;
}
}).when(req).getAttribute(Mockito.anyString());
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.bittorrent;
import java.io.File;
import java.util.Date;
import org.gudy.azureus2.core3.download.DownloadManager;
/**
* @author gubatron
* @author aldenml
*
*/
public interface BTDownload {
public long getSize();
public long getSize(boolean update);
public String getDisplayName();
public boolean isResumable();
public boolean isPausable();
public boolean isCompleted();
public int getState();
public void remove();
public void pause();
public File getSaveLocation();
public void resume();
public int getProgress();
public String getStateString();
public long getBytesReceived();
public long getBytesSent();
public double getDownloadSpeed();
public double getUploadSpeed();
public long getETA();
public DownloadManager getDownloadManager();
public String getPeersString();
public String getSeedsString();
public boolean isDeleteTorrentWhenRemove();
public void setDeleteTorrentWhenRemove(boolean deleteTorrentWhenRemove);
public boolean isDeleteDataWhenRemove();
public void setDeleteDataWhenRemove(boolean deleteDataWhenRemove);
public String getHash();
public String getSeedToPeerRatio();
public String getShareRatio();
public boolean isPartialDownload();
public void updateDownloadManager(DownloadManager downloadManager);
public Date getDateCreated();
}
|
/*
* ProcesoCuadreCifrasSessionBean.java
*
* Created on 25/09/2007, 09:32:24 AM
*
* Babel Ver :1.0
*/
package com.davivienda.sara.procesos.reintegros.filtro.host.session;
import com.davivienda.sara.procesos.reintegros.servicio.ReintegrosProcesosServicio;
import com.davivienda.sara.procesos.reintegros.servicio.ReintegrosDiarioTEMPProcesosServicio;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import com.davivienda.sara.procesos.reintegros.filtro.host.servicio.ProcesadorHostServicio;
import com.davivienda.sara.entitys.Reintegros;
import com.davivienda.sara.entitys.Notasdebito;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.FileNotFoundException;
import javax.annotation.Resource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
/**
*
* @author jjvargas
*/
@Stateless
@Local(value = ProcesoHostSessionLocal.class)
@TransactionManagement(value = TransactionManagementType.BEAN)
public class ProcesoHostSessionBean implements ProcesoHostSessionLocal {
@Resource private UserTransaction utx;
@PersistenceContext
private EntityManager em;
private ProcesadorHostServicio servicio;
/**
* Método PostConstruct
*/
@PostConstruct
public void postConstructor() {
servicio = new ProcesadorHostServicio(em);
}
/**
* Realiza la generación de los registros de Dia sgte Real y Inico Día Real para la fecha pasada
* en el parámetro fecha
*
* @param fecha
* @returnx
* @throws com.davivienda.adminatm.base.excepcion.EntityServicioExcepcion
*/
// public Integer CargarArchivo(Calendar fecha) throws EntityServicioExcepcion,FileNotFoundException, IllegalArgumentException {
// return servicio.cargarArchivoHost( fecha);
// }
// public Integer CargarArchivo(Calendar fecha) throws EntityServicioExcepcion,FileNotFoundException, IllegalArgumentException {
// String[] indOcca ={"A","B","C","D","E","F"};
// Integer regHost=0;
//
// for(int i=0;i<6;i++)
// {
// regHost=regHost+CargarArchivoUnoAuno( fecha,indOcca[i]);
// }
//
// return regHost;
// }
public Integer CargarArchivo(Calendar fecha) throws EntityServicioExcepcion,FileNotFoundException, IllegalArgumentException {
Integer regHost=0;
int regArchivo=0;
int i =0;
try {
regArchivo = servicio.cuentaRegistros(fecha);
for(i=0;i==0||i<=regArchivo;i=i+20000)
{
regHost=regHost+CargarArchivoxFilas( fecha,i);
}
} catch (IOException ex) {
Logger.getLogger(ProcesoHostSessionBean.class.getName()).log(Level.SEVERE, null, ex);
}
return regHost;
}
public Integer CargarArchivoxFilas(Calendar fecha,int numRegistros) throws EntityServicioExcepcion,FileNotFoundException, IllegalArgumentException {
Integer registros = -1;
try {
utx.begin();
registros = servicio.cargarArchivoHost( fecha,numRegistros);
utx.commit();
} catch (FileNotFoundException ex) {
java.util.logging.Logger.getLogger("globalApp").info("No existe el archivo host ATM con fecha "+ fecha.toString() + " " + ex.getMessage());
} catch (EntityServicioExcepcion ex) {
java.util.logging.Logger.getLogger("globalApp").info("Error al grabar los datos archivo host ATM con fecha "+ fecha.toString() + " " + ex.getMessage());
} catch (IllegalArgumentException ex) {
java.util.logging.Logger.getLogger("globalApp").info("Error al grabar los datos archivo host ATM con fecha "+ fecha.toString() + " " + ex.getMessage());
}
catch (Exception ex) {
java.util.logging.Logger.getLogger("globalApp").info("No se grabaran los registros procesados de archivo host ATM con fecha "+ fecha.toString() + " " + ex.getMessage());
}finally{
try {
//Status.STATUS_COMMITTED tiene valor 6
if( utx.getStatus()!= 6){
java.util.logging.Logger.getLogger("globalApp").info("No se grabaran los registros procesados se realiza rollback de cargue archivo host ATM con fecha "+ fecha.toString() + " ");
utx.rollback();
}
} catch (IllegalStateException ex1) {
java.util.logging.Logger.getLogger("globalApp").info( ex1.getMessage());
} catch (SecurityException ex1) {
java.util.logging.Logger.getLogger("globalApp").info( ex1.getMessage());
} catch (SystemException ex1) {
java.util.logging.Logger.getLogger("globalApp").info(ex1.getMessage());
}
}
return registros;
}
}
|
package com.example.tallers13_eco;
import androidx.annotation.NonNull;
public class User {
public String id;
public String name, telephone, email, password;
public User() {
}
public User(String id, String name, String telephone, String email, String password) {
this.id = id;
this.name = name;
this.telephone = telephone;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package in.msmartpay.agent.rechargeBillPay;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import in.msmartpay.agent.R;
import in.msmartpay.agent.utility.BaseActivity;
import in.msmartpay.agent.utility.HttpURL;
import in.msmartpay.agent.utility.L;
import in.msmartpay.agent.utility.Mysingleton;
public class ElectricityPayActivity extends BaseActivity {
private LinearLayout linear_proceed_electricity;
private EditText consumer_no, amount, edit_email_electricity, contact_no,id_add1;
private Spinner id_electricity_spinner, spinner_additional_electricity;
private String operatorData, operatorData1;
private String spinnerselected;
private ProgressDialog pd;
private Context context;
private String electricity_url = HttpURL.BILL_PAY;
private SharedPreferences sharedPreferences;
private String agentID, txn_key = "";
private String response, AD1 = "", AD2 = "", AD3 = "", AD4 = "", CN = "", OP = "",operator,op;
private String viewBill = null;
private String operator_code_url = HttpURL.OPERATOR_CODE_URL;
private ArrayList<OperatorListModel> OperatorList = null;
private CustomOperatorClass operatorAdaptor;
private OperatorListModel listModel = null;
private String mob = "", amountString = "", connectionNo = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.electricity_bill_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Electricity");
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
context = ElectricityPayActivity.this;
sharedPreferences = getSharedPreferences("myPrefs", MODE_PRIVATE);
txn_key = sharedPreferences.getString("txn-key", null);
agentID = sharedPreferences.getString("agentonlyid", null);
consumer_no = findViewById(R.id.id_electricity_consumer_no);
amount = findViewById(R.id.id_electricity_amount);
edit_email_electricity = findViewById(R.id.edit_email_electricity);
contact_no = findViewById(R.id.edit_customer_no_electricity);
id_add1 = findViewById(R.id.id_add1);
id_electricity_spinner = findViewById(R.id.id_electricity_spinner);
linear_proceed_electricity = (LinearLayout) findViewById(R.id.linear_proceed_electricity);
amount.setVisibility(View.GONE);
contact_no.setVisibility(View.GONE);
linear_proceed_electricity.setVisibility(View.VISIBLE);
id_add1.setVisibility(View.GONE);
try {
operatorsCodeRequest();
} catch (Exception e) {
e.printStackTrace();
}
id_electricity_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>-1){
listModel = OperatorList.get(position);
id_add1.setVisibility(View.GONE);
amount.setText("");
contact_no.setText(""); //contact_no
consumer_no.setText(""); //consumer_no
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
id_add1.setText("");
contact_no.setVisibility(View.VISIBLE);
consumer_no.setHint("Enter Consumer Number");
amount.setVisibility(View.VISIBLE);
viewBill = OperatorList.get(position).getBillFetch();
op = OperatorList.get(position).getDisplayName();
operator = OperatorList.get(position).getOpCode();
spinnerselected = OperatorList.get(position).getDisplayName();
if (op.equals("UPPCL (RURAL) - UTTAR PRADESH") || op.equals("UPPCL (URBAN) - UTTAR PRADESH")) {
} else if (op.equals("Ajmer Vidyut Vitran Nigam - RAJASTHAN") || op.equals("BESL - BHARATPUR") || op.equals("BkESL - BIKANER") || op.equals("Jaipur Vidyut Vitran Nigam - RAJASTHAN")
|| op.equals("Jodhpur Vidyut Vitran Nigam - RAJASTHAN") || op.equals("Kota Electricity Distribution - RAJASTHAN") || op.equals("TPADL - AJMER")) {
consumer_no.setHint("K Number");
} else if (op.equals("APDCL - ASSAM") || op.equals("CESC - WEST BENGAL") || op.equals("MEPDCL - MEGHALAYA") || op.equals("TSECL - TRIPURA")) {
consumer_no.setHint("Consumer ID");
} else if (op.equals("APEPDCL - ANDHRA PRADESH") || op.equals("APSPDCL - ANDHRA PRADESH")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
consumer_no.setHint("Service Number");
} else if (op.equals("BESCOM - BENGALURU")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
consumer_no.setHint("Customer ID / Account ID");
} else if (op.equals("CSPDCL - CHHATTISGARH") || op.equals("JUSCO - JAMSHEDPUR")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
consumer_no.setHint("Business Partner Number");
} else if (op.equals("Daman and Diu Electricity") || op.equals("DHBVN - HARYANA") || op.equals("PSPCL - PUNJAB") || op.equals("UHBVN - HARYANA")) {
consumer_no.setHint("Account Number");
} else if (op.equals("DNHPDCL - DADRA & NAGAR HAVELI")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
consumer_no.setHint("Service Connection Number");
} else if (op.equals("NBPDCL - BIHAR") || op.equals("SBPDCL - BIHAR")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
consumer_no.setHint("CA Number");
} else if (op.equals("APDCL - ASSAM")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
consumer_no.setHint("K Number");
} else if (op.equals("UPCL - UTTARAKHAND")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
consumer_no.setHint("Service Connection Number");
} else if (op.equals("Torrent Power")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
consumer_no.setHint("Service Number");
id_add1.setVisibility(View.VISIBLE);
id_add1.setHint("City Name");
} else if (op.equals("MSEDC - MAHARASHTRA")) {
id_add1.setVisibility(View.VISIBLE);
id_add1.setHint("Billing Unit");
id_add1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
} else if (op.equals("Reliance Energy")) {
id_add1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
consumer_no.setHint("Account Number");
id_add1.setVisibility(View.VISIBLE);
id_add1.setHint("Billing Unit");
} else if (op.equals("Kerala State Electricity Board Ltd. (KSEB)")) {
consumer_no.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
consumer_no.setHint("Enter Consumer Number");
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
linear_proceed_electricity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isConnectionAvailable()) {
connectionNo = consumer_no.getText().toString();
amountString = amount.getText().toString();
mob = contact_no.getText().toString();
AD1 = id_add1.getText().toString();
if(id_electricity_spinner.getSelectedItem()==null) {
Toast.makeText(context, "Select Operator", Toast.LENGTH_SHORT).show();
}else if ("".equals(connectionNo)) {
Toast.makeText(context, "Enter Valid " + consumer_no.getHint().toString(), Toast.LENGTH_LONG).show();
} else if ("".equals(amountString) || Double.parseDouble(amountString) < 10) {
Toast.makeText(context, "Enter Valid Amount", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(context, BillPayActivity.class);
intent.putExtra("CN", connectionNo);
intent.putExtra("CN_hint", consumer_no.getHint().toString());
intent.putExtra("Amt", amountString);
intent.putExtra("Mob", mob);
intent.putExtra("Add1", AD1);
intent.putExtra(getString(R.string.pay_operator_model), getGson().toJson(listModel));
startActivity(intent);
}
} else {
Toast.makeText(context, "No Internet Connection !!!", Toast.LENGTH_SHORT).show();
}
}
});
}
//===========operatorCodeRequest==============
private void operatorsCodeRequest() {
pd = ProgressDialog.show(context, "", "Loading. Please wait...", true);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
try {
JSONObject jsonObjectReq = new JSONObject()
.put("agent_id", agentID)
.put("txn_key", txn_key)
.put("service", "ELECTRICITY");
L.m2("url-operators", operator_code_url);
L.m2("Request--operators", jsonObjectReq.toString());
JsonObjectRequest jsonrequest = new JsonObjectRequest(Request.Method.POST, operator_code_url, jsonObjectReq,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject data) {
pd.dismiss();
L.m2("Response--operators", data.toString());
try {
if (data.getString("response-code")!=null&&data.getString("response-code").equalsIgnoreCase("0")) {
OperatorList = new ArrayList<>();
JSONArray jsonArray = data.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object1 = jsonArray.getJSONObject(i);
OperatorListModel model = new OperatorListModel();
model.setBillFetch(object1.getString("BillFetch"));
model.setDisplayName(object1.getString("DisplayName"));
model.setOpCode(object1.getString("OpCode"));
model.setOperatorName(object1.getString("OperatorName"));
model.setService(object1.getString("Service"));
OperatorList.add(model);
}
Collections.sort(OperatorList, new Comparator<OperatorListModel>() {
@Override
public int compare(OperatorListModel model1, OperatorListModel model2) {
return model1.getOperatorName().compareTo(model2.getOperatorName());
}
});
operatorAdaptor = new CustomOperatorClass(context, OperatorList);
id_electricity_spinner.setAdapter(operatorAdaptor);
if (OperatorList.size()==0){
Toast.makeText(context, "No Operator Available!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, data.getString("response-message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
Toast.makeText(context, "Server Error : " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
getSocketTimeOut(jsonrequest);
Mysingleton.getInstance(context).addToRequsetque(jsonrequest);
} catch (Exception exp) {
pd.dismiss();
exp.printStackTrace();
}
}
//====================================
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
public boolean onSupportNavigateUp() {
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
return true;
}
}
|
package com.mingrisoft;
public class Test {
public static void main(String[] args) {
Employee employee = new Employee(); //创建Employee对象
System.out.println(employee.getInfo()); //输出Employee对象的getInfo()方法返回值
Manager manager = new Manager(); //创建Manager对象
System.out.println(manager.getInfo()); //输出Manager对象的getInfo()方法返回值
}
}
|
package io.dcbn.backend.core;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.fraunhofer.iosb.iad.maritime.datamodel.Vessel;
import io.dcbn.backend.core.activemq.Producer;
import io.dcbn.backend.datamodel.Outcome;
import io.dcbn.backend.inference.InferenceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Handles a new Vessel
*/
@Service
public class VesselHandler {
private final VesselCache vesselCache;
private final InferenceManager inferenceManager;
private final Producer producer;
@Autowired
public VesselHandler(VesselCache vesselCache, InferenceManager inferenceManager, Producer producer) {
this.inferenceManager = inferenceManager;
this.vesselCache = vesselCache;
this.producer = producer;
}
/**
* Inserts the given vessel into the cache. Calculates the inference for the given vessel and sends the Outcomes
* to the producer
*
* @param vessel New Vessel to be handled
* @throws JsonProcessingException
*/
public void handleVessel(Vessel vessel) throws JsonProcessingException {
vesselCache.insert(vessel);
List<Outcome> outcomes = inferenceManager.calculateInference(vessel.getUuid());
for (Outcome outcome : outcomes) {
producer.send(outcome);
}
}
}
|
/**
*/
package iso20022.impl;
import java.lang.String;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import iso20022.Code;
import iso20022.CodeSet;
import iso20022.Iso20022Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Code</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.CodeImpl#getCodeName <em>Code Name</em>}</li>
* <li>{@link iso20022.impl.CodeImpl#getOwner <em>Owner</em>}</li>
* </ul>
*
* @generated
*/
public class CodeImpl extends RepositoryConceptImpl implements Code {
/**
* The default value of the '{@link #getCodeName() <em>Code Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCodeName()
* @generated
* @ordered
*/
protected static final String CODE_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getCodeName() <em>Code Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCodeName()
* @generated
* @ordered
*/
protected String codeName = CODE_NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CodeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getCode();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getCodeName() {
return codeName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCodeName(String newCodeName) {
String oldCodeName = codeName;
codeName = newCodeName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.CODE__CODE_NAME, oldCodeName, codeName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CodeSet getOwner() {
if (eContainerFeatureID() != Iso20022Package.CODE__OWNER) return null;
return (CodeSet)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetOwner(CodeSet newOwner, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newOwner, Iso20022Package.CODE__OWNER, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOwner(CodeSet newOwner) {
if (newOwner != eInternalContainer() || (eContainerFeatureID() != Iso20022Package.CODE__OWNER && newOwner != null)) {
if (EcoreUtil.isAncestor(this, newOwner))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newOwner != null)
msgs = ((InternalEObject)newOwner).eInverseAdd(this, Iso20022Package.CODE_SET__CODE, CodeSet.class, msgs);
msgs = basicSetOwner(newOwner, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.CODE__OWNER, newOwner, newOwner));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.CODE__OWNER:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetOwner((CodeSet)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.CODE__OWNER:
return basicSetOwner(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Iso20022Package.CODE__OWNER:
return eInternalContainer().eInverseRemove(this, Iso20022Package.CODE_SET__CODE, CodeSet.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.CODE__CODE_NAME:
return getCodeName();
case Iso20022Package.CODE__OWNER:
return getOwner();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.CODE__CODE_NAME:
setCodeName((String)newValue);
return;
case Iso20022Package.CODE__OWNER:
setOwner((CodeSet)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.CODE__CODE_NAME:
setCodeName(CODE_NAME_EDEFAULT);
return;
case Iso20022Package.CODE__OWNER:
setOwner((CodeSet)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.CODE__CODE_NAME:
return CODE_NAME_EDEFAULT == null ? codeName != null : !CODE_NAME_EDEFAULT.equals(codeName);
case Iso20022Package.CODE__OWNER:
return getOwner() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (codeName: ");
result.append(codeName);
result.append(')');
return result.toString();
}
} //CodeImpl
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation.spr8761;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests cornering the regression reported in SPR-8761.
*
* @author Chris Beams
*/
class Spr8761Tests {
/**
* Prior to the fix for SPR-8761, this test threw because the nested MyComponent
* annotation was being falsely considered as a 'lite' Configuration class candidate.
*/
@Test
void repro() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan(getClass().getPackage().getName());
ctx.refresh();
assertThat(ctx.containsBean("withNestedAnnotation")).isTrue();
ctx.close();
}
}
@Component
class WithNestedAnnotation {
@Retention(RetentionPolicy.RUNTIME)
@Component
@interface MyComponent {
}
}
|
import java.awt.*;
public enum FeatureCategory {
BUS("Bus", Color.RED),
TRAIN("Train", Color.GREEN),
UNDERGROUND("Underground", Color.BLUE),
NONE("None", Color.BLACK);
private final String name;
private final Color color;
FeatureCategory(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return getName();
}
}
|
/**
* Copyright (C) 2006-2019 Talend Inc. - www.talend.com
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.talend.nexus.customizations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.jetty.InstrumentedQueuedThreadPool;
import com.yammer.metrics.reporting.ConsoleReporter;
@DisplayName("We enhance yammer (metrics 2.2) InstrumentedQueuedThreadPool to register its queue on JMX as well")
class JettyThreadPoolMonitoringAspectTest {
@Test
@DisplayName("Ensure jobs (queue) are registered on JMX")
void checkJobsAreRegisteredInMetricsRegistry() throws Exception {
final InstrumentedQueuedThreadPool pool = new InstrumentedQueuedThreadPool();
final MetricsRegistry registry = Metrics.defaultRegistry();
final MetricName metricName = new MetricName(QueuedThreadPool.class, "jobs", null);
assertEquals(0, doCaptureGauge(registry, metricName));
pool.setMaxThreads(1);
pool.start();
final CountDownLatch latch = new CountDownLatch(1);
try {
for (int i = 0; i < 2; i++) {
pool.execute(() -> {
try {
latch.await();
} catch (final InterruptedException e) {
Thread.currentThread()
.interrupt();
}
});
}
assertEquals(1, doCaptureGauge(registry, metricName));
} finally {
latch.countDown();
pool.stop();
}
}
private int doCaptureGauge(final MetricsRegistry registry, final MetricName metricName) {
final AtomicInteger called = new AtomicInteger(Integer.MIN_VALUE);
new ConsoleReporter(registry, new PrintStream(new OutputStream() {
@Override
public void write(final int b) {
// no-op
}
}), (name, metric) -> name.equals(metricName)) {
@Override
public void processGauge(final MetricName name, final Gauge<?> gauge, final PrintStream stream) {
assertEquals(Integer.MIN_VALUE, called.get()); // only called once
called.set(Number.class.cast(gauge.value()).intValue());
}
}.run();
return called.get();
}
}
|
/**
* Copyright (C), 1995-2018, XXX有限公司
* FileName: ErrorInfo
* Author: wens.
* Date: 2018/6/4 下午7:46
* Description: 错误通用传输类
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.phantom.dto;
/**
* 〈一句话功能简述〉<br>
* 〈错误通用传输类〉
*
* @author wens.
* @create 2018/6/4
* @since 1.0.0
*/
public class ErrorInfo<T> {
public static final Integer OK = 100;
public static final Integer ERROR = 101;
private Integer code;
private String message;
private String url;
private T data;
public static Integer getOK() {
return OK;
}
public static Integer getERROR() {
return ERROR;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
package bzh.pluvio.pluvioServer.repo;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import bzh.pluvio.pluvioServer.model.Relevepluie;
@Repository
public interface LastValueRepository extends CrudRepository<Relevepluie, Long> {
@Query(value="SELECT id, date, jour, mois, annee, valeur FROM relevepluie ORDER BY id DESC LIMIT 1", nativeQuery=true)
Relevepluie getLastValueRelevepluies();
}
|
package com.git.cloud.handler.automation;
/**
* Link路由的枚举定义
*
* 该枚举定义了Link路由字段编码
*/
public enum LinkRouteType {
DATACENTER_QUEUE_IDEN("DATACENTER_QUEUE_IDEN"), /** <数据中心路由标识 */
RESOURCE_CLASS("RESOURCE_CLASS"), /** < 资源类型 */
;
private final String value;
private LinkRouteType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static LinkRouteType fromString(String value) {
if (value != null) {
for (LinkRouteType v : LinkRouteType.values()) {
if (value.equalsIgnoreCase(v.value)) {
return v;
}
}
}
return null;
}
}
|
package behavioral.visitor;
/**
* @author Renat Kaitmazov
*/
public final class ShoppingCartVisitor implements Visitor {
/*--------------------------------------------------------*/
/* Instance variables
/*--------------------------------------------------------*/
private double totalPrice;
/*--------------------------------------------------------*/
/* API
/*--------------------------------------------------------*/
public final double totalPrice() {
return totalPrice;
}
/*--------------------------------------------------------*/
/* Visitor implementation
/*--------------------------------------------------------*/
@Override
public final void visit(Book book) {
totalPrice += book.getPrice();
}
@Override
public void visit(Phone phone) {
totalPrice += phone.getPrice();
}
}
|
package com.mediafire.sdk.api.responses;
/**
* Created by Chris on 5/18/2015.
*/
public class UploadAddWebUploadResponse extends ApiResponse {
private String upload_key;
public String getUploadKey() {
return upload_key;
}
}
|
package com.hhdb.csadmin.plugin.table_open;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import org.apache.commons.lang3.StringUtils;
import com.hh.frame.common.log.LM;
import com.hh.frame.dbobj.hhdb.HHdbColumn;
import com.hh.frame.swingui.swingcontrol.displayTable.TablePanelUtil;
import com.hhdb.csadmin.common.util.StartUtil;
import com.hhdb.csadmin.plugin.table_open.service.SqlOperationService;
import com.hhdb.csadmin.plugin.table_open.ui.ButtonPanelEditorRenderer;
import com.hhdb.csadmin.plugin.table_open.ui.HHOperateTablePanel;
import com.hhdb.csadmin.plugin.table_open.ui.HHPagePanel;
import com.hhdb.csadmin.plugin.table_open.ui.HHTableColumnCellRenderer;
/**
* 打开表操作面板
*/
public class TableOpenPanel extends JPanel {
private static final long serialVersionUID = 1L;
public String databaseName; // 数据库名
public String schemaName; // 模式名
public String table; // 表名
public SqlOperationService sqls;
public int j = 0; // 面板id
private TableOpen tabo;
private TablePanelUtil tablePanel;
private HHOperateTablePanel hhOpTbPanel;
private HHPagePanel hhPgPanel;
// 每页显示的数据条数
public final int inNum = 30;
// 模式+表名称
private String tableName;
// 查询表第N页数据SQL
private String nextPageData = "select *,true upd,ctid from %s limit "
+ inNum + " offset %d*" + inNum;
// 当前页码数
private int pageNum;
// 表数据修改前的集合
private List<TemporaryDate> oldValueLists = new ArrayList<>();
// 表数据修改后的集合
private List<TemporaryDate> newValueLists = new ArrayList<>();
// 选中表格数据的当前所在行数
private int row = 0;
// 选中表格数据的当前所在列数
private int column = 0;
public TableOpenPanel(String databaseName, String schemaName, String table,String tableName, TableOpen tableOpen) {
try {
this.databaseName = databaseName;
this.schemaName = schemaName;
this.table = table;
this.tabo = tableOpen;
this.tableName = tableName;
sqls = new SqlOperationService(tabo);
initPanel();
List<List<Object>> firstPageTable;
firstPageTable = pageTable(nextPageData, 0);
excutepage(firstPageTable);
showPageCount();
buttonAction();
} catch (Exception e) {
LM.error(LM.Model.CS.name(), e);
JOptionPane.showMessageDialog(null, "错误信息:" + e.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
}
// 初始化面板
public void initPanel() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createLineBorder(new Color(178, 178, 178),1));
tablePanel = new TablePanelUtil(new int[] { 0 });
tablePanel.drawAllowed(false);
tablePanel.setRowSorter(true);
tablePanel.nterlacedDiscoloration(true,null,null);
tablePanel.highlight(true,false,null);
tablePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
tablePanel.getBaseTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //表不拉伸
hhOpTbPanel = new HHOperateTablePanel();
//禁用部分按钮
hhOpTbPanel.getSaveData().setEnabled(false);
hhOpTbPanel.getDelRow().setEnabled(false);
hhPgPanel = new HHPagePanel();
add(tablePanel, new GridBagConstraints(0, 0, 2, 1, 1.0, 1.0,GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
add(hhOpTbPanel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,10, 0, 0), 0, 0));
add(hhPgPanel, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0,0, 0, 30), 0, 0));
}
// 表格填充数据
public void excutepage(List<List<Object>> pageTable) {
//表头数据
Vector<Object> colname = new Vector<Object>();
colname.add("");
for (Object field : pageTable.get(0)) {
colname.add(field);
}
tablePanel.addLineNumber(pageTable);
//判断哪些列需要加入流操作按钮
ButtonPanelEditorRenderer er = new ButtonPanelEditorRenderer(this);
Connection connection = null;
HHdbColumn hhdb = null;
for (Object name : colname) {
if(!"".equals(name)){
if(name.toString().equals("upd")){
break;
}
try {
connection = sqls.getConn();
hhdb = new HHdbColumn(connection, schemaName, table, name+"", true,StartUtil.prefix);
String type = hhdb.getColType();
if(null != type && type.equals("bytea")){
tablePanel.getBaseTable().getColumn(name).setCellRenderer(er);
tablePanel.getBaseTable().getColumn(name).setCellEditor(er);
}
} catch (Exception e) {
LM.error(LM.Model.CS.name(), e);
}
}
}
//设置行号列样式
TableColumn index = tablePanel.getBaseTable().getColumnModel().getColumn(0);
index.setMaxWidth(25);
index.setMinWidth(25);
index.setCellRenderer(new HHTableColumnCellRenderer());
//隐藏后面两列 upd ctid
TableColumn coln = tablePanel.getBaseTable().getColumnModel().getColumn(colname.size() - 1);
coln.setMinWidth(0);
coln.setMaxWidth(0);
coln.setWidth(0);
coln.setPreferredWidth(0);
TableColumn coln1 = tablePanel.getBaseTable().getColumnModel().getColumn(colname.size() - 2);
coln1.setMinWidth(0);
coln1.setMaxWidth(0);
coln1.setWidth(0);
coln1.setPreferredWidth(0);
//点击行时
tablePanel.getBaseTable().addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
judge();
}
});
//头部点击事件
tablePanel.getBaseTable().getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
//禁用部分按钮
hhOpTbPanel.getSaveData().setEnabled(false);
hhOpTbPanel.getDelRow().setEnabled(false);
}
});
}
/**
* 发送sql请求数据
*/
private List<List<Object>> pageTable(String pageData, int num) throws Exception {
List<List<Object>> pageTb = new ArrayList<>();
String pageDatas;
if (num == 0) {
pageDatas = String.format(pageData, tableName, 0);
} else {
pageDatas = String.format(pageData, tableName, num);
}
pageTb = sqls.getListList(pageDatas);
return pageTb;
}
private void showPageCount() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 先获取表总行数
String totalRowsSql = "select count(1) from " + tableName;
List<Object> rowStrList = sqls.getListList(
totalRowsSql).get(1);
int rowCount = Integer.parseInt(rowStrList.get(0) + "");
int intCount = rowCount / inNum;
int modCount = rowCount % inNum;
// 总页码数
int pageCount;
if (modCount != 0) {
pageCount = intCount + 1;
} else {
pageCount = intCount;
}
hhPgPanel.setPageCount(pageCount);
hhPgPanel.getTotalPageNum().setText(pageCount + "");
if (pageCount <= 1) {
hhPgPanel.getNextPage().setEnabled(false);
hhPgPanel.getLastPage().setEnabled(false);
}
} catch (Exception e) {
LM.error(LM.Model.CS.name(), e);
JOptionPane.showMessageDialog(null, "错误信息:" + e.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
}
}).start();
}
/**
* 刷新
*/
public void refresh() {
try {
String curPageNum = hhPgPanel.getCurPageNum().getText();
int cPNum = pageNum;
if (!"".equals(curPageNum)) {
cPNum = Integer.parseInt(curPageNum);
}
hhPgPanel.getCurPageNum().setText(cPNum + "");
List<List<Object>> nextPageTable = pageTable(nextPageData, cPNum - 1);
excutepage(nextPageTable);
oldValueLists.clear();
newValueLists.clear();
row = 0;
column = 0;
//禁用部分按钮
hhOpTbPanel.getSaveData().setEnabled(false);
hhOpTbPanel.getDelRow().setEnabled(false);
tablePanel.initializationColor();
} catch (Exception e) {
LM.error(LM.Model.CS.name(), e);
JOptionPane.showMessageDialog(null, "错误信息:" + e.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
}
/**
* 面板上的按钮点击事件
*/
private void buttonAction() {
// 点击第一页按钮回到第一页
hhPgPanel.getFirstPage().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
List<List<Object>> firstPageTable = new ArrayList<>();
try {
firstPageTable = pageTable(nextPageData, 0);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, "错误信息:" + e1.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
excutepage(firstPageTable);
hhPgPanel.getCurPageNum().setText("1");
hhPgPanel.getFirstPage().setEnabled(false);
hhPgPanel.getPrePage().setEnabled(false);
if (hhPgPanel.getPageCount() > 1) {
hhPgPanel.getNextPage().setEnabled(true);
hhPgPanel.getLastPage().setEnabled(true);
}
}
});
// 点击上一页按钮回到前一页
hhPgPanel.getPrePage().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String curPageNum = hhPgPanel.getCurPageNum().getText();
int cPNum = pageNum;
if (!"".equals(curPageNum)) {
cPNum = Integer.parseInt(curPageNum);
}
List<List<Object>> prePageTable = new ArrayList<>();
try {
prePageTable = pageTable(nextPageData,cPNum - 2);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, "错误信息:" + e1.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
excutepage(prePageTable);
cPNum--;
hhPgPanel.getCurPageNum().setText(cPNum + "");
if (cPNum <= 1) {
hhPgPanel.getFirstPage().setEnabled(false);
hhPgPanel.getPrePage().setEnabled(false);
}
if (hhPgPanel.getPageCount() > 1) {
hhPgPanel.getNextPage().setEnabled(true);
hhPgPanel.getLastPage().setEnabled(true);
}
}
});
// 保存当前页码
hhPgPanel.getCurPageNum().addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
String text = hhPgPanel.getCurPageNum().getText();
if (text != null && !"".equals(text) && !"0".equals("")) {
pageNum = Integer.parseInt(hhPgPanel.getCurPageNum().getText());
}
}
});
// 输入页码跳到当前输入页
hhPgPanel.getCurPageNum().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String curPageNum = hhPgPanel.getCurPageNum().getText();
if ("".equals(curPageNum)) {
return;
}
// 判断每个字符是不是数字
char[] ch = curPageNum.toCharArray();
for (char c : ch) {
if (!Character.isDigit(c)) {
JOptionPane.showMessageDialog(null, "请输入正确的页码");
hhPgPanel.getCurPageNum().setText(pageNum + "");
return;
}
}
// 判断输入的页数是不是大于总页数
int cPNum = Integer.parseInt(curPageNum);
if (cPNum > hhPgPanel.getPageCount() || cPNum <= 0) {
JOptionPane.showMessageDialog(null, "请输入正确的页码");
hhPgPanel.getCurPageNum().setText(pageNum + "");
return;
}
List<List<Object>> nextPageTable = new ArrayList<>();
try {
nextPageTable = pageTable(nextPageData, cPNum - 1);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, "错误信息:" + e1.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
excutepage(nextPageTable);
if (cPNum <= 1) {
hhPgPanel.getFirstPage().setEnabled(false);
hhPgPanel.getPrePage().setEnabled(false);
} else {
hhPgPanel.getFirstPage().setEnabled(true);
hhPgPanel.getPrePage().setEnabled(true);
}
if (cPNum >= hhPgPanel.getPageCount()) {
hhPgPanel.getNextPage().setEnabled(false);
hhPgPanel.getLastPage().setEnabled(false);
} else {
hhPgPanel.getNextPage().setEnabled(true);
hhPgPanel.getLastPage().setEnabled(true);
}
}
});
}
});
// 点击下一页按钮回到下一页
hhPgPanel.getNextPage().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String curPageNum = hhPgPanel.getCurPageNum().getText();
int cPNum = pageNum;
if (!"".equals(curPageNum)) {
cPNum = Integer.parseInt(curPageNum);
}
List<List<Object>> nextPageTable = new ArrayList<>();
try {
nextPageTable = pageTable(nextPageData,cPNum);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, "错误信息:" + e1.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
excutepage(nextPageTable);
cPNum++;
hhPgPanel.getCurPageNum().setText(cPNum + "");
if (cPNum > 1) {
hhPgPanel.getFirstPage().setEnabled(true);
hhPgPanel.getPrePage().setEnabled(true);
}
if (cPNum >= hhPgPanel.getPageCount()) {
hhPgPanel.getNextPage().setEnabled(false);
hhPgPanel.getLastPage().setEnabled(false);
}
}
});
// 点击最后一页按钮回到最后一页
hhPgPanel.getLastPage().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int tPNum = hhPgPanel.getPageCount();
if (tPNum <= 1) {
return;
}
List<List<Object>> lastPageTable = new ArrayList<>();
try {
lastPageTable = pageTable(nextPageData, tPNum - 1);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, "错误信息:" + e1.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
excutepage(lastPageTable);
hhPgPanel.getCurPageNum().setText(tPNum + "");
if (tPNum > 1) {
hhPgPanel.getFirstPage().setEnabled(true);
hhPgPanel.getPrePage().setEnabled(true);
}
hhPgPanel.getNextPage().setEnabled(false);
hhPgPanel.getLastPage().setEnabled(false);
}
});
}
});
// 点击添加按钮添加一个空行
hhOpTbPanel.getAddRow().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] object = new Object[tablePanel.getBaseTable().getColumnCount()];
tablePanel.getTableDataModel().addRow(object);
}
});
// 点击删除按钮删除所选行07 12
hhOpTbPanel.getDelRow().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int[] selectedRows = tablePanel.getBaseTable().getSelectedRows();
if(null != selectedRows && selectedRows.length != 0){ //判断是否选择了行
int option = JOptionPane.showConfirmDialog(tablePanel,"是否删除已选择行", "提示信息", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String delSql = "delete from " + tableName+ " where ctid='%s'";
int totalColumnCount = tablePanel.getBaseTable().getColumnCount();
for (int i = 0; i < selectedRows.length; ++i) {
String ctid = null == tablePanel.getBaseTable().getValueAt(selectedRows[i],totalColumnCount - 1) ? null : tablePanel.getBaseTable().getValueAt(selectedRows[i],totalColumnCount - 1).toString();
if(null != ctid && !ctid.equals("")){ //删除数据库的数据
String upd = null == tablePanel.getBaseTable().getValueAt(selectedRows[i],totalColumnCount - 2) ? null : tablePanel.getBaseTable().getValueAt(selectedRows[i],totalColumnCount - 2).toString();
if (StringUtils.isNoneBlank(upd)&& ("t".equalsIgnoreCase(upd) || "true".equalsIgnoreCase(upd))) {
String message = sqls.sendConn4Update(String.format(delSql, ctid));
if (StringUtils.isBlank(message)) {
return;
}
}
}else{ //删除临时数据
tablePanel.getTableDataModel().removeRow(selectedRows[i]);
//删除临时数据
Iterator<TemporaryDate> newtem = newValueLists.iterator();
while (newtem.hasNext()) {
TemporaryDate temporaryDate = newtem.next();
if(temporaryDate.getRow() == selectedRows[i]){
newtem.remove();
}
}
Iterator<TemporaryDate> oidtem = oldValueLists.iterator();
while (oidtem.hasNext()) {
TemporaryDate temporaryDate = oidtem.next();
if(temporaryDate.getRow() == selectedRows[i]){
oidtem.remove();
}
}
//从新排序
for (TemporaryDate temporaryDate : newValueLists) {
if( temporaryDate.getRow() > selectedRows[i] ){
temporaryDate.setRow(temporaryDate.getRow()-1);
}
}
for (TemporaryDate temporaryDate : oldValueLists) {
if( temporaryDate.getRow() > selectedRows[i] ){
temporaryDate.setRow(temporaryDate.getRow()-1);
}
}
row = 0;
column = 0;
tablePanel.initializationColor(); //重置隔行变色
judge();
return;
}
}
refresh();
}
});
}
}
}
});
// 点击刷新按钮刷新当前页面
hhOpTbPanel.getRefreshData().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refresh();
}
});
// 点击保存按钮保存修改
hhOpTbPanel.getSaveData().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
//当在编辑某单元格时,点击保存则直接终止编辑获取当前编辑格已输入的值进行保存
if (tablePanel.getBaseTable().isEditing()) {
tablePanel.getBaseTable().getCellEditor().stopCellEditing();
getEditedValues();
}
if(oldValueLists.size() == 0 ){
return;
}
int totalColumnCount = tablePanel.getBaseTable().getColumnCount();
String updateSql = "update " + tableName+ " set %s where ctid='%s'";
String insertSql = "insert into " + tableName+ " (%s) values (%s)";
List<TemporaryDate> newRowList = new ArrayList<>();
List<Integer> rowNumList = new ArrayList<>();
for (TemporaryDate temporaryDate : newValueLists) {
String column = tablePanel.getBaseTable().getColumnName(temporaryDate.getColumn());
Object ob = tablePanel.getBaseTable().getValueAt(temporaryDate.getRow(),totalColumnCount - 2);
String upd = null == ob ? null : ob.toString();
if (StringUtils.isNoneBlank(upd)&& ("t".equalsIgnoreCase(upd) || "true".equalsIgnoreCase(upd))) {
// 修改sql
String ctid = tablePanel.getTableDataModel().getValueAt(temporaryDate.getRow(),totalColumnCount - 1).toString();
String message = sqls.sendConn4Update(String.format(updateSql,column+ "="+ "'"+ StringUtils.replace(temporaryDate.getValue()+"","'","''") + "'", ctid));
if (StringUtils.isBlank(message)) {
return;
}
} else {
// 记录新增的行
newRowList.add(temporaryDate);
boolean flag = false;
for (int rowNum : rowNumList) {
if (rowNum == temporaryDate.getRow()) {
flag = true;
break;
}
}
if (!flag) {
rowNumList.add(temporaryDate.getRow());
}
}
}
//拼接添加sql
for (int rowNum : rowNumList) {
StringBuffer columnBuffer = new StringBuffer();
StringBuffer valueBuffer = new StringBuffer();
for (TemporaryDate temporaryDate : newRowList) {
if (rowNum == temporaryDate.getRow()) {
String column = tablePanel.getBaseTable().getColumnName(temporaryDate.getColumn());
columnBuffer.append(column);
String value = temporaryDate.getValue()+"";
if (value.contains("'")) {
value = value.replaceAll("'", "''");
}
valueBuffer.append("'" + value + "'");
columnBuffer.append(",");
valueBuffer.append(",");
}
}
String columnStr = columnBuffer.toString();
String valueStr = valueBuffer.toString();
columnStr = columnStr.substring(0,columnStr.length() - 1);
valueStr = valueStr.substring(0,valueStr.length() - 1);
String message = sqls.sendConn4Update(String.format(insertSql, columnStr, valueStr));
if (StringUtils.isBlank(message)) {
return;
}
}
oldValueLists.clear();
newValueLists.clear();
JOptionPane.showMessageDialog(null, "保存成功!", "提示",JOptionPane.INFORMATION_MESSAGE);
refresh();
} catch (Exception e2) {
LM.error(LM.Model.CS.name(), e2);
JOptionPane.showMessageDialog(null, "错误信息:" + e2.getMessage(),"错误", JOptionPane.ERROR_MESSAGE);
}
}
});
}
});
// 监听表格数据变更
tablePanel.getBaseTable().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("tableCellEditor".equalsIgnoreCase(evt.getPropertyName().trim())) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (tablePanel.getBaseTable().isEditing()) { //保存修改前的数据到数组
row = tablePanel.getBaseTable().convertRowIndexToModel(tablePanel.getBaseTable().getEditingRow());
column = tablePanel.getBaseTable().convertColumnIndexToModel(tablePanel.getBaseTable().getEditingColumn());
if (row != -1 && column != -1) {
Object oldValue = tablePanel.getBaseTable().getModel().getValueAt(row, column);
if (oldValue == null) {
oldValue = "";
}
boolean flag = false;
for (TemporaryDate temporaryDate : oldValueLists) {
if ( row == temporaryDate.getRow() && column == temporaryDate.getColumn() ) {
flag = true;
break;
}
}
TemporaryDate temporaryDate = new TemporaryDate();
if (!flag) {
temporaryDate.setRow(row);
temporaryDate.setColumn(column);
temporaryDate.setValue(oldValue);
oldValueLists.add(temporaryDate);
}
}
} else { //保存修改后的数据到数组
getEditedValues();
}
judge();
}
});
}
}
});
}
/**
* 获取单元格编辑后的值
*/
private void getEditedValues(){
Object newValue = tablePanel.getBaseTable().getModel().getValueAt(row, column);
if (newValue == null) {
newValue = "";
}
Iterator<TemporaryDate> oldValueIter = oldValueLists.iterator();
while (oldValueIter.hasNext()) {
TemporaryDate oldValues = oldValueIter.next();
if ( row == oldValues.getRow() && column == oldValues.getColumn() ) {
Iterator<TemporaryDate> list = newValueLists.iterator();
while (list.hasNext()) {
TemporaryDate temporaryDate = list.next();
if( row == temporaryDate.getRow() && column == temporaryDate.getColumn() ){
list.remove();
}
}
if (!newValue.toString().equals(oldValues.getValue().toString())) {
TemporaryDate tem = new TemporaryDate();
tem.setRow(row);
tem.setColumn(column);
tem.setValue(newValue);
newValueLists.add(tem);
} else {
oldValueIter.remove();
}
break;
}
}
}
/**
* 判断数据是否有变化,禁用按钮
* @return
*/
private void judge() {
for (TemporaryDate temporaryDate : newValueLists) {
for (TemporaryDate temporaryDate2 : oldValueLists) {
if ( temporaryDate.getRow() == temporaryDate2.getRow() && temporaryDate.getColumn() == temporaryDate2.getColumn() ) {
if(!temporaryDate.getValue().toString().equals(temporaryDate2.getValue().toString())){
hhOpTbPanel.getSaveData().setEnabled(true);
hhOpTbPanel.getDelRow().setEnabled(true);
return;
}
}
}
}
hhOpTbPanel.getSaveData().setEnabled(false);
hhOpTbPanel.getDelRow().setEnabled(true);
}
/**
* 记录表格数据变化的内部类
* @author hhxd
*/
public class TemporaryDate {
Integer row; //行
Integer column; //列
Object value; //值
public Integer getRow() {
return row;
}
public void setRow(Integer row) {
this.row = row;
}
public Integer getColumn() {
return column;
}
public void setColumn(Integer column) {
this.column = column;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
}
|
package com.gaoshin.onsalelocal.osl.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import common.db.entity.DbEntity;
@Entity
@Table
@XmlRootElement
public class UserInterest extends DbEntity {
@Column(nullable = true, length = 64)
private String userId;
@Column(nullable = true, length = 64)
private String offerId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getOfferId() {
return offerId;
}
public void setOfferId(String offerId) {
this.offerId = offerId;
}
}
|
package com.java.jwt.api.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "USER_TBL", uniqueConstraints = @UniqueConstraint(columnNames={"email"}))
public class User {
@Id
@SequenceGenerator(initialValue = 1, name = "user_seq", allocationSize = 1, sequenceName = "user_seq")
@GeneratedValue(generator = "user_seq")
private int id;
private String username;
private String password;
private String email;
@Enumerated(EnumType.STRING)
private Role role;
}
|
// File: SortedList.java
//
// Author: Rahul Simha
// Created: Sept 29, 1998
//
// Sorted linked list.
abstract class ComparableObject {
public abstract int compare (ComparableObject c);
}
class ListItem {
ComparableObject data = null;
ListItem next = null;
// Constructor.
public ListItem (ComparableObject obj)
{
data = obj; next = null;
}
// Accessor.
public ComparableObject getData ()
{
return data;
}
}
// Linked list class - also a dynamic class.
class LinkedList {
ListItem front = null;
ListItem rear = null;
int numItems = 0; // Current number of items.
// Could this class use a constructor?
// Instance method to add a data item.
public void addData (ComparableObject obj)
{
if (front == null) {
front = new ListItem (obj);
rear = front;
}
else {
// Find the right place.
ListItem tempPtr=front, prevPtr=front;
boolean found = false;
while ( (!found) && (tempPtr != null) ) {
if (tempPtr.data.compare(obj) > 0) {
found = true;
break;
}
prevPtr = tempPtr;
tempPtr = tempPtr.next;
}
// Now insert.
if (!found) { // Insert at rear.
rear.next = new ListItem (obj);
rear = rear.next;
}
else if (tempPtr == front) { // Insert in front.
ListItem Lptr = new ListItem (obj);
Lptr.next = front;
front = Lptr;
}
else { // Insert in the middle.
ListItem Lptr = new ListItem (obj);
prevPtr.next = Lptr;
Lptr.next = tempPtr;
}
}
numItems++;
}
public void printList ()
{
ListItem listPtr = front;
System.out.println ("List: (" + numItems + " items)");
int i = 1;
while (listPtr != null) {
System.out.println ("Item# " + i + ": "
+ listPtr.getData());
// Must implement toString()
i++;
listPtr = listPtr.next;
}
}
} // End of class "LinkedList"
// An object to use in the list:
class Person extends ComparableObject {
String name;
String ssn;
// Constructor.
public Person (String nameInit, String ssnInit)
{
name = nameInit; ssn = ssnInit;
}
// Override toString()
public String toString ()
{
return "Person: name=" + name + ", ssn=" + ssn;
}
// Must implement compare
public int compare (ComparableObject obj)
{
Person p = (Person) obj;
return name.compareTo (p.name);
}
} // End of class "Person"
// Test class.
public class SortedList {
public static void main (String[] argv)
{
// Create an instance of the list.
LinkedList L = new LinkedList ();
// Insert data.
L.addData (new Person ("Rogue", "1111-12-1212"));
L.addData (new Person ("Storm", "222-23-2323"));
L.addData (new Person ("Black Widow", "333-34-3434"));
L.addData (new Person ("Jean Grey", "888-89-8989"));
// Print contents.
L.printList();
}
} // End of class "SortedList"
|
package com.concurrent.features;
import cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"html:target/cucumber"})
public class RunTests {
}
|
package com.mining.power.list.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.administrator.mining.R;
import butterknife.BindView;
/**
* Created by yushuangping on 2018/8/23.
*/
public class DescHolder extends RecyclerView.ViewHolder {
public LinearLayout layout_a_id;
public TextView type_time_text;
public LinearLayout img_yhj;
public LinearLayout img_rx;
public TextView text_rx;
public TextView power_price;
public TextView danwei_text;
public TextView cpower_text;
public TextView surplus_text;
public TextView reference_yields;
public TextView day_yield_text;
public TextView release_time_text;
public DescHolder(View itemView) {
super(itemView);
initView();
}
private void initView() {
layout_a_id=(LinearLayout) itemView.findViewById(R.id.layout_a_id);//最外面那一层布局
type_time_text = (TextView) itemView.findViewById(R.id.type_time_text);//GRIN-29-180天
img_yhj = (LinearLayout) itemView.findViewById(R.id.img_yhj);//图片优惠劵
img_rx = (LinearLayout) itemView.findViewById(R.id.img_rx);//热销
text_rx = (TextView) itemView.findViewById(R.id.text_rx);//热销文字
power_price = (TextView) itemView.findViewById(R.id.power_price);//价格
reference_yields = (TextView) itemView.findViewById(R.id.reference_yields);//理论收益率
day_yield_text=(TextView) itemView.findViewById(R.id.day_yield_texts);//日理论产量
danwei_text = (TextView) itemView.findViewById(R.id.danwei_text);//单位
cpower_text = (TextView) itemView.findViewById(R.id.cpower_text);//1 graph/份
surplus_text = (TextView) itemView.findViewById(R.id.surplus_text);//20份
release_time_text = (TextView) itemView.findViewById(R.id.release_time_text);//2019-04-05
}
}
|
package cn.com.signheart.component.core.core.dao.impl;
import cn.com.signheart.common.platformbase.BaseDAOImpl;
import cn.com.signheart.component.core.core.dao.IPlatFormCfgDao;
import cn.com.signheart.component.core.core.model.TbPlatFormConfig;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
/**
* Created by ao.ouyang on 16-1-11.
*/
@Repository("platFormCfgDao")
public class PlatFormCfgDaoImpl extends BaseDAOImpl implements IPlatFormCfgDao {
@Override
public List<TbPlatFormConfig> getAllCfg() throws SQLException {
return super.getList("select * from tb_platform_config order by component_name",TbPlatFormConfig.class);
}
}
|
/*******************************************************************************
* Copyright (c) 2012, Eka Heksanov Lie
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.ehxnv.pvm.deployer.file;
import com.ehxnv.pvm.api.Process;
import com.ehxnv.pvm.api.ProcessMetadata;
import com.ehxnv.pvm.api.io.ProcessReader;
import com.ehxnv.pvm.api.repository.ProcessRepository;
import com.ehxnv.pvm.deployer.file.FileMonitorBasedProcessDeployer;
import org.easymock.EasyMock;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import static org.easymock.EasyMock.*;
/**
* Unit test for {@link FileMonitorBasedProcessDeployer}.
* @author Eka Lie
*/
public class FileMonitorBasedProcessDeployerTest {
/** Temporary folder rule. **/
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
/**
* Test of start method, of FileMonitorBasedProcessDeployer class.
*/
@Test(expected = IllegalStateException.class)
public void testStart() throws Exception {
FileMonitorBasedProcessDeployer fileMonitorBasedProcessDeployer = new FileMonitorBasedProcessDeployer(temporaryFolder.getRoot(),
1000, createMock(ProcessRepository.class), createMock(ProcessReader.class));
fileMonitorBasedProcessDeployer.start();
try {
fileMonitorBasedProcessDeployer.start();
} finally {
fileMonitorBasedProcessDeployer.stop();
}
}
/**
* Test of stop method, of FileMonitorBasedProcessDeployer class.
*/
@Test(expected = IllegalStateException.class)
public void testStop() throws Exception {
FileMonitorBasedProcessDeployer fileMonitorBasedProcessDeployer = new FileMonitorBasedProcessDeployer(temporaryFolder.getRoot(),
1000, createMock(ProcessRepository.class), createMock(ProcessReader.class));
fileMonitorBasedProcessDeployer.start();
fileMonitorBasedProcessDeployer.stop();
fileMonitorBasedProcessDeployer.stop();
}
/**
* Test the monitoring of new file i.e zip file inside monitored directory.
* It should read the file and deploy this into process repository.
*/
@Test
public void testMonitorNewFile() throws Exception {
ProcessMetadata processMetadata = new ProcessMetadata("test1", "1.0");
Process processMock = createMock(Process.class);
expect(processMock.getMetadata()).andReturn(processMetadata).anyTimes();
ProcessReader processReaderMock = createMock(ProcessReader.class);
expect(processReaderMock.readProcess(EasyMock.<File>anyObject())).andReturn(processMock).once();
ProcessRepository processRepositoryMock = createMock(ProcessRepository.class);
processRepositoryMock.addProcess(processMock);
expectLastCall().once();
replay(processMock, processReaderMock, processRepositoryMock);
FileMonitorBasedProcessDeployer fileMonitorBasedProcessDeployer = new FileMonitorBasedProcessDeployer(temporaryFolder.getRoot(),
1000, processRepositoryMock, processReaderMock);
fileMonitorBasedProcessDeployer.start();
File dumbProcessFile = new File(temporaryFolder.getRoot(), "test1.zip");
// test adding
dumbProcessFile.createNewFile();
fileMonitorBasedProcessDeployer.stop();
verify(processMock, processReaderMock, processRepositoryMock);
}
/**
* Test the monitoring of deletion of existing file i.e zip file inside monitored directory.
* It should read the file for the process metadata and undeploy this process from process repository.
*/
@Test
public void testMonitorRemovalOfFile() throws Exception {
ProcessMetadata processMetadata = new ProcessMetadata("test1", "1.0");
Process processMock = createMock(Process.class);
expect(processMock.getMetadata()).andReturn(processMetadata).anyTimes();
ProcessReader processReaderMock = createMock(ProcessReader.class);
expect(processReaderMock.readProcess(EasyMock.<File>anyObject())).andReturn(processMock).once();
ProcessRepository processRepositoryMock = createMock(ProcessRepository.class);
expect(processRepositoryMock.deleteProcess(processMetadata)).andReturn(true).once();
replay(processMock, processReaderMock, processRepositoryMock);
File dumbProcessFile = new File(temporaryFolder.getRoot(), "test1.zip");
dumbProcessFile.createNewFile();
FileMonitorBasedProcessDeployer fileMonitorBasedProcessDeployer = new FileMonitorBasedProcessDeployer(temporaryFolder.getRoot(),
1000, processRepositoryMock, processReaderMock);
fileMonitorBasedProcessDeployer.start();
// test removal
dumbProcessFile.delete();
fileMonitorBasedProcessDeployer.stop();
verify(processMock, processReaderMock, processRepositoryMock);
}
}
|
package com.roundarch.entity;
import com.annconia.api.entity.AbstractEntity;
public class UserEntity extends AbstractEntity {
}
|
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String userName = "max";
String password = "Tdutybq19911991";
String URL = "jdbc:mysql://localhost:3306/Lessons?serverTimezone=UTC&useSSL=false";
// Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(URL, userName, password);
}
}
|
package io.github.lburgazzoli.examples;
import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.builder.RouteBuilder;
@ApplicationScoped
public class ApplicationRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:conf")
.log("{{the.message}}");
}
}
|
public class Banana extends Weapon{
private int damage, speed;
private double xMovement, yMovement;
public Banana(String imagePath, int xPos, int yPos, int width, int height) {
super(imagePath, xPos, yPos, width, height);
xMovement = 0;
yMovement = 0;
}
}
|
package wawi.datenhaltung.bestellungverwaltungs.impl;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import wawi.datenhaltung.wawidbmodel.entities.Bestellung;
import wawi.datenhaltung.wawidbmodel.entities.Bestellungsposition;
import wawi.datenhaltung.wawidbmodel.entities.Kategorie;
import wawi.datenhaltung.wawidbmodel.entities.Kunde;
import wawi.datenhaltung.wawidbmodel.entities.Lagerort;
import wawi.datenhaltung.wawidbmodel.entities.Produkt;
import wawi.datenhaltung.wawidbmodel.impl.IDatabaseImpl;
/**
*
* @author Tugba, Christian
*/
public class IBestellungSachImplTest {
private EntityManager em;
private IBestellungSachImpl classUnderTest;
private java.sql.Date sqlDate;
public void setDate(String str) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sqlDate = java.sql.Date.valueOf(dateTime.toLocalDate());
}
public Date getDate() {
return this.sqlDate;
}
public IBestellungSachImplTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
/**
* ANGENOMMEN der EntityManager wird korrekt geholt, UND die Implementierung
* der ICRUDLager Schnittstelle wird als classUnderTest instanziiert, UND
* der EntityManager wird per setEntityManager Methode der classUnderTest
* gesetzt, UND die Transaktion von em wird gestartet, UND die Daten der
* betreffenden Entitäten wurden in der DB gelöscht.
*/
@Before
public void angenommen() {
IDatabaseImpl obj = new IDatabaseImpl();
em = obj.getEntityManager();
classUnderTest = new IBestellungSachImpl();
classUnderTest.setEntityManager(em);
em.getTransaction().begin();
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
em.createNativeQuery("DELETE FROM bestellung").executeUpdate();
}
/**
* AM ENDE wird die Transaktion zurück gesetzt.
*/
@After
public void amEnde() {
em.getTransaction().rollback();
}
/**
* Gültige Testbestellung mit dem Status abgerechnet
*
* @return
*/
public Bestellung testBestellungAbgerechnet() {
Bestellung bestellung = new Bestellung();
bestellung.setCreated(new Date(System.currentTimeMillis()));
bestellung.setBid(7);
bestellung.setGesamtbrutto(BigDecimal.valueOf(150));
bestellung.setGesamtnetto(BigDecimal.valueOf(180));
bestellung.setLieferadresse("Lieferadresse");
bestellung.setRechnungsadresse("Rechnungsadresse");
bestellung.setStatus("r");
bestellung.setKunde(new Kunde(1));
em.persist(bestellung);
em.flush();
return bestellung;
}
public Bestellung testBestellungUngueltigeId() {
Bestellung bestellung = new Bestellung();
bestellung.setCreated(new Date(System.currentTimeMillis()));
bestellung.setBid(17);
bestellung.setGesamtbrutto(BigDecimal.valueOf(150));
bestellung.setGesamtnetto(BigDecimal.valueOf(180));
bestellung.setLieferadresse("Lieferadresse");
bestellung.setRechnungsadresse("Rechnungsadresse");
bestellung.setStatus("r");
bestellung.setKunde(new Kunde(1));
return bestellung;
}
/**
* Gültige Testbestellung mit dem Status bezahlt
*
* @return
*/
public Bestellung testBestellungBezahlt() {
Bestellung bestellung = new Bestellung();
bestellung.setCreated(new Date(System.currentTimeMillis()));
bestellung.setBid(7);
bestellung.setGesamtbrutto(BigDecimal.valueOf(150));
bestellung.setGesamtnetto(BigDecimal.valueOf(180));
bestellung.setLieferadresse("Lieferadresse");
bestellung.setRechnungsadresse("Rechnungsadresse");
bestellung.setStatus("b");
bestellung.setKunde(new Kunde(1));
em.persist(bestellung);
em.flush();
return bestellung;
}
/**
* Gültige Testbestellung mit dem Status neu
*
* @return
*/
public Bestellung persistAndGetTestBestellungNeu() {
Bestellung bestellung = new Bestellung();
bestellung.setCreated(new Date(System.currentTimeMillis()));
bestellung.setBid(7);
bestellung.setGesamtbrutto(BigDecimal.valueOf(150));
bestellung.setGesamtnetto(BigDecimal.valueOf(180));
bestellung.setLieferadresse("Lieferadresse");
bestellung.setRechnungsadresse("Rechnungsadresse");
bestellung.setStatus("n");
bestellung.setKunde(new Kunde(1));
em.persist(bestellung);
em.flush();
return bestellung;
}
/**
* WENN x (x>0) Bestellungen in der DB existieren, UND y (y<x) abgerechnete
* Bestellungen in der DB existieren, UND die Methode
* getAlleAbgerechnetenBestellungen aufgerufen wird, DANN sollte sie eine
* Liste mit y Bestellungen zurückliefern
*/
@Test
public void getAlleAbgerechnetenBestellungen_00() {
em.createNativeQuery("INSERT INTO bestellung VALUES (1, 1, 'Lieferadresse', 'Rechnungsadresse', DATE '2018-12-17', 'b', 20, 10)").executeUpdate();
em.createNativeQuery("INSERT INTO bestellung VALUES (2,2, 'Lieferadresse', 'Rechnungsadresse', DATE '2018-12-17', 'r', 20, 10)").executeUpdate();
em.createNativeQuery("INSERT INTO bestellung VALUES (3,2, 'Lieferadresse', 'Rechnungsadresse', DATE '2018-12-17', 'r', 20, 10)").executeUpdate();
List<Bestellung> dbListe = em.createNamedQuery("Bestellung.findAll", Bestellung.class).getResultList();
assertTrue(dbListe.size() > 0);
List<Bestellung> list = classUnderTest.getAlleAbgerechnetenBestellungen();
assertTrue(list.size() < dbListe.size());
assertTrue(list.size() == 2);
}
/**
* WENN x (x>0) Bestellungen in der DB existieren, UND keine abgerechneten
* Bestellungen in der DB existieren, UND die Methode
* getAlleAbgerechnetenBestellungen aufgerufen wird, DANN sollte sie eine
* leere Liste zurückliefern.
*/
@Test
public void getAlleAbgerechnetenBestellungen_01() {
Bestellung bestellung = new Bestellung(1, "Lieferadresse", "Rechnungsadresse", new Date(System.currentTimeMillis()), "b", BigDecimal.TEN, BigDecimal.ONE);
bestellung.setKunde(new Kunde(1, "Name", "Vorname", "Adresse", new Date(System.currentTimeMillis())));
em.persist(bestellung);
List<Bestellung> dbListe = em.createNamedQuery("Bestellung.findAll", Bestellung.class).getResultList();
assertTrue(dbListe.size() > 0);
List<Bestellung> list = new ArrayList<>();
assertEquals(list, classUnderTest.getAlleAbgerechnetenBestellungen());
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungRechnungGesendet aufgerufen wird, UND die ID einer
* existierenden Bestellung übergeben wird, UND die Bestellung den Status
* neu hat, DANN sollte sie TRUE zurückliefern, UND die Bestellung in der DB
* den Status abgerechnet haben.
*/
@Test
public void setBestellungRechnungGesendet_00() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
boolean istWert = classUnderTest.setBestellungRechnungGesendet(bestellung.getBid());
assertTrue(istWert);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertEquals(status, "r");
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungRechnungGesendet aufgerufen wird, UND die ID einer nicht
* existierenden Bestellung übergeben wird, DANN sollte sie FALSE
* zurückliefern
*/
@Test
public void setBestellungRechnungGesendet_01() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
em.persist(bestellung);
boolean istWert = classUnderTest.setBestellungRechnungGesendet(12);
assertFalse(istWert);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungRechnungGesendet aufgerufen wird, UND die ID einer
* existierenden Bestellung übergeben wird, UND die Bestellung einen anderen
* Status als neu hat, DANN sollte sie FALSE zurückliefern, UND der Status
* der Bestellung in der DB nicht verändert sein.
*/
@Test
public void setBestellungRechnungGesendet_02() {
Bestellung bestellung = testBestellungBezahlt();
boolean istWert = classUnderTest.setBestellungRechnungGesendet(bestellung.getBid());
assertFalse(istWert);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertNotEquals("r", status);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungBezahlt aufgerufen wird, UND die ID einer existierenden
* Bestellung übergeben wird, UND die Bestellung den Status abgerechnet hat,
* DANN sollte sie TRUE zurückliefern, UND die Bestellung in der DB den
* Status bezahlt haben
*/
@Test
public void setBestellungBezahlt_00() {
Bestellung bestellung = testBestellungAbgerechnet();
boolean vergleiche = classUnderTest.setBestellungBezahlt(bestellung.getBid());
assertTrue(vergleiche);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertEquals("b", status);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungBezahlt aufgerufen wird, UND die ID einer nicht
* existierenden Bestellung übergeben wird, DANN sollte sie FALSE
* zurückliefern
*/
@Test
public void setBestellungBezahlt_01() {
Bestellung bestellung = testBestellungAbgerechnet();
boolean vergleiche = classUnderTest.setBestellungBezahlt(23);
assertFalse(vergleiche);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungBezahlt aufgerufen wird, UND die ID einer existierenden
* Bestellung übergeben wird, UND die Bestellung einen anderen Status als
* abgerechnet hat, DANN sollte sie FALSE zurückliefern, UND der Status der
* Bestellung in der DB nicht verändert sei
*/
@Test
public void setBestellungBezahlt_02() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
em.persist(bestellung);
boolean vergleiche = classUnderTest.setBestellungBezahlt(bestellung.getBid());
assertFalse(vergleiche);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertNotEquals("b", status);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungStorniert aufgerufen wird, UND die ID einer existierenden
* Bestellung übergeben wird, UND die Bestellung den Status abgerechnet hat,
* DANN sollte sie TRUE zurückliefern, UND die Bestellung in der DB den
* Status storniert haben
*/
@Test
public void setBestellungStorniert_00() {
Bestellung bestellung = testBestellungAbgerechnet();
em.persist(bestellung);
boolean vergleiche = classUnderTest.setBestellungStorniert(bestellung.getBid());
assertTrue(vergleiche);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertEquals("s", status);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungStorniert aufgerufen wird, UND die ID einer existierenden
* Bestellung übergeben wird, UND die Bestellung den Status neu hat, DANN
* sollte sie TRUE zurückliefern, UND die Bestellung in der DB den Status
* storniert haben.
*/
@Test
public void setBestellungStorniert_01() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
boolean vergleiche = classUnderTest.setBestellungStorniert(bestellung.getBid());
assertTrue(vergleiche);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertEquals("s", status);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungStorniert aufgerufen wird, UND die ID einer nicht
* existierenden Bestellung übergeben wird, DANN sollte sie FALSE
* zurückliefern.
*/
@Test
public void setBestellungStorniert_02() {
Bestellung bestellung = testBestellungAbgerechnet();
boolean vergleiche = classUnderTest.setBestellungBezahlt(23);
assertFalse(vergleiche);
}
/**
* WENN Bestellungen in der DB existieren, UND die Methode
* setBestellungStorniert aufgerufen wird, UND die ID einer existierenden
* Bestellung übergeben wird, UND die Bestellung nicht den Status
* abgerechnet oder nicht den Status neu hat, DANN sollte sie FALSE
* zurückliefern, UND der Status der Bestellung in der DB nicht verändert
* sei
*/
@Test
public void setBestellungStorniert_03() {
Bestellung bestellung = testBestellungBezahlt();
boolean vergleiche = classUnderTest.setBestellungStorniert(bestellung.getBid());
assertFalse(vergleiche);
String status = em.find(Bestellung.class, bestellung.getBid()).getStatus();
assertNotEquals("s", status);
}
/**
* WENN eine TestBestellung in der DB existiert, UND die Methode
* updateBestellung mit einer veränderten TestBestellung (aber gleicher ID)
* aufgerufen wird DANN sollte sie TRUE zurückliefern, UND die
* TestBestellung sollte in der DB verändert sein
*/
@Test
public void updateBestellung_00() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
em.flush();
bestellung.setRechnungsadresse("Zuhause");
boolean vergleiche = classUnderTest.updateBestellung(bestellung);
assertTrue(vergleiche);
assertSame("Zuhause", em.find(Bestellung.class, 7).getRechnungsadresse());
}
/**
* WENN eine TestBestellung nicht in der DB existiert, UND die Methode
* updateBestellung mit der TestBestellung aufgerufen wird, DANN sollte sie
* FALSE zurückliefern, UND die TestBestellung sollte nicht in der DB
* existieren
*/
@Test
public void updateBestellung_01() {
Bestellung bestellung = testBestellungUngueltigeId();
boolean vergleiche = classUnderTest.updateBestellung(bestellung);
assertFalse(vergleiche);
}
/**
* WENN eine TestBestellung in der DB existiert, UND die Methode
* deleteBestellung mit der ID der TestBestellung aufgerufen wird, DANN
* sollte sie TRUE zurückliefern, UND die TestBestellung sollte nicht mehr
* in der DB existieren
*/
@Test
public void deleteBestellung_00() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
em.flush();
assertNotNull(em.find(Bestellung.class, 7));
classUnderTest.deleteBestellung(bestellung.getBid());
assertNull(em.find(Bestellung.class, bestellung.getBid()));
}
/**
* WENN eine TestBestellung nicht in der DB existiert, UND die Methode
* deleteBestellung mit der ID der TestBestellung aufgerufen wird, DANN
* sollte sie FALSE zurückliefern
*/
@Test
public void deleteBestellung_01() {
assertFalse(classUnderTest.deleteBestellung(199));
assertNull(em.find(Bestellung.class, 199));
}
/**
* WENN eine TestBestellung bereits in der DB existiert, UND die Methode
* getBestellungById mit der Id der TestBestellung aufgerufen wird, DANN
* sollte sie die TestBestellung zurückliefern.
*/
@Test
public void getBestellungById_00() {
Bestellung bestellung = persistAndGetTestBestellungNeu();
Bestellung b = classUnderTest.getBestellungById(7);
assertEquals(bestellung, b);
}
/**
* WENN eine TestBestellung nicht in der DB existiert, UND die Methode
* getBestellungById mit der Id der TestBestellung aufgerufen wird, DANN
* sollte sie NULL zurückliefern.
*/
@Test
public void getBestellungById_01() {
Bestellung bestellung = new Bestellung(367);
em.persist(bestellung);
em.remove(bestellung);
Bestellung bid = classUnderTest.getBestellungById(bestellung.getBid());
assertNull(bid);
}
/*
* Nachfolgende Teste sind von Christian
*/
/**
* WENN x (x>0) Bestellungen in der DB existieren, UND y (y<x) neue
* Bestellungen in der DB existieren, UND die Methode
* getAlleNeuenBestellungen aufgerufen wird, DANN sollte sie eine Liste mit
* y Bestellungen zurückliefern
*/
@Test
public void getAlleNeuenBestellungen_00() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
em.createNativeQuery("DELETE FROM bestellung").executeUpdate();
List<Bestellung> list = new ArrayList<>();
em.createNativeQuery("INSERT INTO bestellung VALUES (1, 1, 'Lieferadresse', 'Rechnungsadresse', DATE '2018-12-17', 'b', 20, 10)").executeUpdate();
em.createNativeQuery("INSERT INTO bestellung VALUES (2, 2, 'Lieferadresse2', 'Rechnungsadresse2', DATE '2019-12-17', 'n', 20, 10)").executeUpdate();
list.add(em.find(Bestellung.class, 2));
assertEquals(list, classUnderTest.getAlleNeuenBestellungen());
}
/**
* WENN x (x>0) Bestellungen in der DB existieren, UND keine neuen
* Bestellungen in der DB existieren, UND die Methode
* getAlleNeuenBestellungen aufgerufen wird, DANN sollte sie eine leere
* Liste zurückliefern.
*/
@Test
public void getAlleNeuenBestellungen_01() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
em.createNativeQuery("DELETE FROM bestellung").executeUpdate();
List<Bestellung> list = new ArrayList<>();
em.createNativeQuery("INSERT INTO bestellung VALUES (1, 1, 'Lieferadresse', 'Rechnungsadresse', DATE '2018-12-17', 'b', 20, 10)").executeUpdate();
assertEquals(list, classUnderTest.getAlleNeuenBestellungen());
}
/* Achtung: AutoIncrement, faengt auch nicht bei null an, deshalb:
* DB leeren, ueberprufen, einfuegen und ueberpruefen ob DB nicht mehr leer ist
* Ausserdem: Um den Ablauf zu garanteren, muss vorher sicher gestellt sein, dass die Bestellungsposition
* nicht existiert. Um diese zu loeschen muss auch der Lagerverkehr geloescht werden (Constraints)
*/
/**
* WENN die Methode insertBestellposition mit einer TestBestellposition
* aufgerufen wird, UND die ID der TestBestellposition gleich null ist, DANN
* sollte sie TRUE zurückliefern, UND die TestBestellposition sollte in der
* DB existieren.
*/
@Test
public void insertBestellposition_00() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(null);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1, "Lieferadresse", "Rechnungsadresse", new Date(System.currentTimeMillis()), "b", BigDecimal.TEN, BigDecimal.ONE));
bp.getBestellung().setKunde(new Kunde(1, "Name", "Vorname", "Adresse", new Date(System.currentTimeMillis())));
bp.setProdukt(new Produkt(1, "Produkt", "Beschreibung", new Date(System.currentTimeMillis()), 1, BigDecimal.TEN, 10, true));
bp.getProdukt().setKategorie(new Kategorie(1, 2, "Name", "Beschreibung"));
bp.getProdukt().setLagerort(new Lagerort(1, "Bezeichnung", 1));
assertTrue(em.createNamedQuery("Bestellungsposition.findAll", Bestellungsposition.class).getResultList().isEmpty());
assertNull(bp.getBpid());
assertTrue(classUnderTest.insertBestellposition(bp));
assertNotNull(em.find(Bestellungsposition.class, bp.getBpid()));
}
/**
* WENN die Methode insertBestellposition mit einer TestBestellposition
* aufgerufen wird, UND die ID der TestlBestellposition ungleich null ist,
* DANN sollte sie FALSE zurückliefern, UND die DB wurde nicht verändert.
*/
@Test
public void insertBestellposition_01() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(1);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1));
bp.setProdukt(new Produkt(1));
boolean b = classUnderTest.insertBestellposition(bp);
assertFalse(b);
List<Bestellungsposition> list = em.createNamedQuery("Bestellungsposition.findByBpid", Bestellungsposition.class).setParameter("bpid", 1).getResultList();
assertTrue(list.isEmpty());
}
/**
* WENN eine TestBestellposition in der DB existiert, UND die Methode
* updateBestellposition mit einer veränderten TestBestellposition (aber
* gleicher ID) aufgerufen wird, DANN sollte sie TRUE zurückliefern, UND die
* TestBestellposition sollte in der DB verändert sein.
*/
@Test
public void updateBestellposition_00() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(1);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1));
bp.setProdukt(new Produkt(1));
em.persist(bp);
bp.setAnzahl(123);
assertTrue(classUnderTest.updateBestellposition(bp));
assertSame(123, em.find(Bestellungsposition.class, 1).getAnzahl());
}
/**
* WENN eine TestBestellposition nicht in der DB existiert, UND die Methode
* updateBestellposition mit der TestBestellposition aufgerufen wird, DANN
* sollte sie FALSE zurückliefern, UND die TestBestellposition sollte nicht
* in der DB existieren
*/
@Test
public void updateBestellposition_01() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(1);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1));
bp.setProdukt(new Produkt(1));
assertFalse(classUnderTest.updateBestellposition(bp));
assertNull(em.find(Bestellungsposition.class, 1));
}
/**
* WENN eine TestBestellposition in der DB existiert, UND die Methode
* deleteBestellposition mit der ID der TestBestellposition aufgerufen wird,
* DANN sollte sie TRUE zurückliefern, UND die TestBestellposition sollte
* nicht mehr in der DB existiere
*/
@Test
public void deleteBestellposition_00() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(1);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1));
bp.setProdukt(new Produkt(1));
em.persist(bp);
assertEquals(bp, em.find(Bestellungsposition.class, 1));
assertTrue(classUnderTest.deleteBestellposition(1));
assertNull(classUnderTest.getBestellpositionById(1));
}
/**
* WENN eine TestBestellposition nicht in der DB existiert, UND die Methode
* deleteBestellposition mit der ID der TestBestellposition aufgerufen wird,
* DANN sollte sie FALSE zurückliefern.
*/
@Test
public void deleteBestellposition_01() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
assertFalse(classUnderTest.deleteBestellposition(1));
}
/**
* WENN eine TestBestellposition bereits in der DB existiert, UND die
* Methode getBestellpositionById mit der Id der TestBestellposition
* aufgerufen wird DANN sollte sie die TestBestellposition zurückliefern
*/
@Test
public void getBestellpositionById_00() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
Bestellungsposition bp = new Bestellungsposition(197);
bp.setAnzahl(1);
bp.setBestellung(new Bestellung(1234));
bp.setProdukt(new Produkt(1235));
assertNull(classUnderTest.getBestellpositionById(197));
em.persist(bp);
assertEquals(bp, classUnderTest.getBestellpositionById(197));
}
/**
* WENN eine TestBestellposition nicht in der DB existiert, UND die Methode
* getBestellpositionById mit der Id der TestBestellposition aufge- rufen
* wird, DANN sollte sie NULL zurückliefern.
*/
@Test
public void getBestellpositionById_01() {
em.createNativeQuery("DELETE FROM lagerverkehr").executeUpdate();
em.createNativeQuery("DELETE FROM bestellungsposition").executeUpdate();
assertNull(classUnderTest.getBestellpositionById(198)); //Jede Id liefert null, weil die Tabelle leer ist
}
}
|
package com.hoanganhtuan95ptit.awesomekeyboard;
/**
* Created by HOANG ANH TUAN on 7/5/2017.
*/
public interface Keyboard {
void hideAllKeyboard();
void showKeyboard(KeyboardType type);
void updateSticker();
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.attr;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.types.basic.AttributeVisibility;
/**
* Helper class allowing to create string attributes easily.
* @author K. Benedyczak
*/
public class StringAttribute extends Attribute<String>
{
public StringAttribute(String name, String groupPath, AttributeVisibility visibility,
String... values)
{
super(name, new StringAttributeSyntax(), groupPath, visibility, asList(values));
}
public StringAttribute(String name, String groupPath, AttributeVisibility visibility,
List<String> values)
{
super(name, new StringAttributeSyntax(), groupPath, visibility, values);
}
public StringAttribute(String name, String groupPath, AttributeVisibility visibility,
String value)
{
this(name, groupPath, visibility, Collections.singletonList(value));
}
public StringAttribute()
{
}
private static List<String> asList(String[] vals)
{
List<String> ret = new ArrayList<String>(vals.length);
Collections.addAll(ret, vals);
return ret;
}
}
|
package com.esum.common.client;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.common.soappull.message.PullSoapElement;
import com.esum.router.status.PullQueryResponseBuilder;
import com.esum.router.status.SftpQueryResponseBuilder;
public class MessageReadRequester {
private static Logger logger = LoggerFactory.getLogger(MessageReadRequester.class);
public MessageReadRequester(String userName) {
}
public Map<String, byte[]> getMessages(String userName, int maxCount) throws Exception {
long stime = System.currentTimeMillis();
SftpQueryResponseBuilder builder = new SftpQueryResponseBuilder("[SFTP]["+userName+"] ");
Map<String, byte[]> responseMap = builder.getListSshFiles(userName, maxCount);
logger.info("[SFTP]["+userName+"] File reading completed. transfer elapsed : "+(System.currentTimeMillis()-stime)+" ms");
return responseMap;
}
public PullSoapElement getMessages(PullSoapElement requestElement) throws Exception {
long stime = System.currentTimeMillis();
PullQueryResponseBuilder builder = new PullQueryResponseBuilder("[SOAPPULL]["+requestElement.getLoginID()+"] ");
PullSoapElement responseElement = builder.query(requestElement, requestElement.getMaxPayloadCount());
logger.info("[SOAPPULL]["+requestElement.getLoginID()+"] File reading completed. transfer elapsed : "+(System.currentTimeMillis()-stime)+" ms");
return responseElement;
}
}
|
open module modmain { // allow reflective access, currently used in the example_jerry-mouse
requires modcommon;
}
|
package com.algo.webshop.common.domainimpl;
import java.util.List;
import com.algo.webshop.common.domain.GoodsList;
import com.algo.webshop.common.domain.Position;
public interface IOrderGood {
public void addGoodList(GoodsList goods, int numberOfOrder);
public List<Position> getGoodList(int orderId);
}
|
package com.auro.scholr.core.application.di.module;
import com.auro.scholr.core.application.AuroApp;
import com.auro.scholr.core.common.AppConstant;
import com.auro.scholr.core.network.URLConstant;
import com.auro.scholr.util.DeviceUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import dagger.Module;
import dagger.Provides;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class UtilsModule {
@Provides
@Singleton
HttpLoggingInterceptor provideInterceptor() {
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
}
@Provides
@Singleton
Gson provideGson() {
// set the field name policy as you want to send like with underscores, lowercase, with dases policy
GsonBuilder builder = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
return builder.setLenient().create();
}
@Provides
@Singleton
OkHttpClient getRequestHeader(HttpLoggingInterceptor httpLoggingInterceptor) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(httpLoggingInterceptor);
httpClient.addInterceptor(chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.header(AppConstant.CONTENT_TYPE, AppConstant.APPLICATION_JSON)
.header(AppConstant.DEVICE_ID, DeviceUtil.getDeviceId(AuroApp.getAppContext()))
.header(AppConstant.DEVICE_TYPE, AppConstant.PLATFORM_ANDROID)
.header(AppConstant.LANGUAGE, "EN")
.header("Authorization", Credentials.basic("bhanu", "123"))
//.header(AUTH_TOKEN, AppPref.INSTANCE.getModelInstance().getOtpRes().getAuthToken())
.build();
return chain.proceed(request);
})
.connectTimeout(3, TimeUnit.MINUTES)
.writeTimeout(3, TimeUnit.MINUTES)
.readTimeout(3, TimeUnit.MINUTES);
return httpClient.build();
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(URLConstant.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
//For Bypassing the SSL CERTIFICATE
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = builder.addInterceptor(interceptor).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package Teatrus.client;
import Teatrus.model.User;
import Teatrus.services.ITeatrusObserver;
import Teatrus.services.TeatrusException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.rmi.RemoteException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.ResourceBundle;
public class TeatrusProfilFXML extends UnicastRemoteObject implements Initializable, Serializable, ITeatrusObserver {
@FXML
public Label lblFullName;
public Label lblEmail;
public Label lblStatut;
public Button backButton;
public TextField updateFirstName;
public TextField updateLastName;
public TextField updateEmail;
public TextField updatePassword;
public Button btnDelete;
public TeatrusProfilFXML() throws RemoteException {
}
protected TeatrusProfilFXML(int port) throws RemoteException {
super(port);
}
protected TeatrusProfilFXML(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException {
super(port, csf, ssf);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
lblFullName.setText(StartApp.user.getNume()+" "+StartApp.user.getPrenume());
lblEmail.setText(StartApp.user.getEmail());
if (StartApp.user.getTipUtilizator()==1){
lblStatut.setText("Administrator");
}
else{
lblStatut.setText("Utilizator");
}
}
@FXML
public void back(ActionEvent event) throws TeatrusException, IOException {
if (StartApp.user.getTipUtilizator()==1){
SceneCreator.launchScene("/Teatrus/Teatrus-PanouCentralAdministrator.fxml","Teatrus - Panou central");
}
else{
SceneCreator.launchScene("/Teatrus/Teatrus-PanouCentralClient.fxml","Teatrus - Panou central");
}
}
/* @FXML
public void modifyName(KeyEvent keyEvent) {
lblFullName.setText(updateFirstName.getText()+" "+updateLastName.getText());
}
@FXML
public void modifySurname(KeyEvent keyEvent) {
lblFullName.setText(updateFirstName.getText()+" "+updateLastName.getText());
}
@FXML
public void modifyEmail(KeyEvent keyEvent) {
lblEmail.setText(updateEmail.getText());
}
*/
public void updateFields(User utilizator){
lblFullName.setText(utilizator.getNume()+" "+utilizator.getPrenume());
lblEmail.setText(utilizator.getEmail());
}
@FXML
public void saveData(ActionEvent event) throws TeatrusException,IOException {
try {
if (updateFirstName.getText().equals("")||updateFirstName.getText().equals("")||updateFirstName.getText().equals("")||updateFirstName.getText().equals("")){
throw new TeatrusException("Datele introduse nu sunt corespunzatoare !");
}
StartApp.user.setNume(updateFirstName.getText());
StartApp.user.setPrenume(updateLastName.getText());
StartApp.user.setEmail(updateEmail.getText());
StartApp.user.setParola(updatePassword.getText());
StartApp.serverOperations.updateUserProfile(StartApp.user,this);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Teatrus");
alert.setHeaderText("Modificarea contului s-a produs cu succes !");
alert.setContentText("Datele introduse au fost modificate in mod crespunzator in baza de date !");
alert.showAndWait();
updateFields(StartApp.user);
}
catch (Exception exception){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Teatrus");
alert.setHeaderText("Modificarea contului nu a avut loc !");
alert.setContentText("Datele introduse nu sunt corespunzatoare !");
alert.showAndWait();
System.out.println(exception.getMessage());
}
}
@Override
public void UserLoggedIn(User u) throws TeatrusException, RemoteException {
}
@Override
public void UserLoggedOut(User u) throws TeatrusException, RemoteException {
}
@Override
public void ActualizareUser(User u) throws TeatrusException, RemoteException {
lblFullName.setText(u.getNume()+" "+u.getPrenume());
lblEmail.setText(u.getEmail());
}
@FXML
public void delete(ActionEvent event) throws TeatrusException {
StartApp.serverOperations.logout(StartApp.user,null);
StartApp.serverOperations.deleteUser(StartApp.user);
System.exit(0);
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server.reactive;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.publisher.Operators;
import org.springframework.core.log.LogDelegateFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Publisher returned from {@link ServerHttpResponse#writeWith(Publisher)}.
*
* @author Arjen Poutsma
* @author Violeta Georgieva
* @author Rossen Stoyanchev
* @since 5.0
*/
class WriteResultPublisher implements Publisher<Void> {
/**
* Special logger for debugging Reactive Streams signals.
* @see LogDelegateFactory#getHiddenLog(Class)
* @see AbstractListenerReadPublisher#rsReadLogger
* @see AbstractListenerWriteProcessor#rsWriteLogger
* @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger
*/
private static final Log rsWriteResultLogger = LogDelegateFactory.getHiddenLog(WriteResultPublisher.class);
private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
private final Runnable cancelTask;
@Nullable
private volatile Subscriber<? super Void> subscriber;
private volatile boolean completedBeforeSubscribed;
@Nullable
private volatile Throwable errorBeforeSubscribed;
private final String logPrefix;
public WriteResultPublisher(String logPrefix, Runnable cancelTask) {
this.cancelTask = cancelTask;
this.logPrefix = logPrefix;
}
@Override
public final void subscribe(Subscriber<? super Void> subscriber) {
if (rsWriteResultLogger.isTraceEnabled()) {
rsWriteResultLogger.trace(this.logPrefix + "got subscriber " + subscriber);
}
this.state.get().subscribe(this, subscriber);
}
/**
* Invoke this to delegate a completion signal to the subscriber.
*/
public void publishComplete() {
State state = this.state.get();
if (rsWriteResultLogger.isTraceEnabled()) {
rsWriteResultLogger.trace(this.logPrefix + "completed [" + state + "]");
}
state.publishComplete(this);
}
/**
* Invoke this to delegate an error signal to the subscriber.
*/
public void publishError(Throwable t) {
State state = this.state.get();
if (rsWriteResultLogger.isTraceEnabled()) {
rsWriteResultLogger.trace(this.logPrefix + "failed: " + t + " [" + state + "]");
}
state.publishError(this, t);
}
private boolean changeState(State oldState, State newState) {
return this.state.compareAndSet(oldState, newState);
}
/**
* Subscription to receive and delegate request and cancel signals from the
* subscriber to this publisher.
*/
private static final class WriteResultSubscription implements Subscription {
private final WriteResultPublisher publisher;
public WriteResultSubscription(WriteResultPublisher publisher) {
this.publisher = publisher;
}
@Override
public final void request(long n) {
if (rsWriteResultLogger.isTraceEnabled()) {
rsWriteResultLogger.trace(this.publisher.logPrefix +
"request " + (n != Long.MAX_VALUE ? n : "Long.MAX_VALUE"));
}
getState().request(this.publisher, n);
}
@Override
public final void cancel() {
State state = getState();
if (rsWriteResultLogger.isTraceEnabled()) {
rsWriteResultLogger.trace(this.publisher.logPrefix + "cancel [" + state + "]");
}
state.cancel(this.publisher);
}
private State getState() {
return this.publisher.state.get();
}
}
/**
* Represents a state for the {@link Publisher} to be in.
* <p><pre>
* UNSUBSCRIBED
* |
* v
* SUBSCRIBING
* |
* v
* SUBSCRIBED
* |
* v
* COMPLETED
* </pre>
*/
private enum State {
UNSUBSCRIBED {
@Override
void subscribe(WriteResultPublisher publisher, Subscriber<? super Void> subscriber) {
Assert.notNull(subscriber, "Subscriber must not be null");
if (publisher.changeState(this, SUBSCRIBING)) {
Subscription subscription = new WriteResultSubscription(publisher);
publisher.subscriber = subscriber;
subscriber.onSubscribe(subscription);
publisher.changeState(SUBSCRIBING, SUBSCRIBED);
// Now safe to check "beforeSubscribed" flags, they won't change once in NO_DEMAND
if (publisher.completedBeforeSubscribed) {
publisher.state.get().publishComplete(publisher);
}
Throwable ex = publisher.errorBeforeSubscribed;
if (ex != null) {
publisher.state.get().publishError(publisher, ex);
}
}
else {
throw new IllegalStateException(toString());
}
}
@Override
void publishComplete(WriteResultPublisher publisher) {
publisher.completedBeforeSubscribed = true;
if(State.SUBSCRIBED == publisher.state.get()) {
publisher.state.get().publishComplete(publisher);
}
}
@Override
void publishError(WriteResultPublisher publisher, Throwable ex) {
publisher.errorBeforeSubscribed = ex;
if(State.SUBSCRIBED == publisher.state.get()) {
publisher.state.get().publishError(publisher, ex);
}
}
},
SUBSCRIBING {
@Override
void request(WriteResultPublisher publisher, long n) {
Operators.validate(n);
}
@Override
void publishComplete(WriteResultPublisher publisher) {
publisher.completedBeforeSubscribed = true;
if(State.SUBSCRIBED == publisher.state.get()) {
publisher.state.get().publishComplete(publisher);
}
}
@Override
void publishError(WriteResultPublisher publisher, Throwable ex) {
publisher.errorBeforeSubscribed = ex;
if(State.SUBSCRIBED == publisher.state.get()) {
publisher.state.get().publishError(publisher, ex);
}
}
},
SUBSCRIBED {
@Override
void request(WriteResultPublisher publisher, long n) {
Operators.validate(n);
}
},
COMPLETED {
@Override
void request(WriteResultPublisher publisher, long n) {
// ignore
}
@Override
void cancel(WriteResultPublisher publisher) {
// ignore
}
@Override
void publishComplete(WriteResultPublisher publisher) {
// ignore
}
@Override
void publishError(WriteResultPublisher publisher, Throwable t) {
// ignore
}
};
void subscribe(WriteResultPublisher publisher, Subscriber<? super Void> subscriber) {
throw new IllegalStateException(toString());
}
void request(WriteResultPublisher publisher, long n) {
throw new IllegalStateException(toString());
}
void cancel(WriteResultPublisher publisher) {
if (publisher.changeState(this, COMPLETED)) {
publisher.cancelTask.run();
}
else {
publisher.state.get().cancel(publisher);
}
}
void publishComplete(WriteResultPublisher publisher) {
if (publisher.changeState(this, COMPLETED)) {
Subscriber<? super Void> s = publisher.subscriber;
Assert.state(s != null, "No subscriber");
s.onComplete();
}
else {
publisher.state.get().publishComplete(publisher);
}
}
void publishError(WriteResultPublisher publisher, Throwable t) {
if (publisher.changeState(this, COMPLETED)) {
Subscriber<? super Void> s = publisher.subscriber;
Assert.state(s != null, "No subscriber");
s.onError(t);
}
else {
publisher.state.get().publishError(publisher, t);
}
}
}
}
|
package pl.basistam.shop;
import java.util.LinkedHashMap;
import java.util.Map;
public class Basket {
private Map<String, Integer> products = new LinkedHashMap<>();
public void add(String product, int quantity) {
if (products.containsKey(product)) {
Integer oldQuantity = products.get(product);
products.replace(product, oldQuantity + quantity);
} else {
products.put(product, quantity);
}
}
public void increment(String product) {
if (products.containsKey(product)) {
Integer oldQuantity = products.get(product);
products.replace(product, oldQuantity + 1);
}
}
public void decrement(String product) {
if (products.containsKey(product)) {
Integer oldQuantity = products.get(product);
if (oldQuantity == 1) {
products.remove(product);
}
products.replace(product, oldQuantity - 1);
}
}
public Map<String, Integer> getProducts() {
return products;
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pm,pn;
pm = in.nextInt();
pn = in.nextInt();
// System.out.println(isPrime(pm));
int flag = 1; // 换行flag
int pi = 1;
for(int i=2;i<=120000;i++)
{
if (isPrime(i))
{
if ((pi>=pm) && (pi<=pn))
{
if (flag==1)
{
System.out.printf("%d",i);
}
else if (flag<=9)
{
System.out.printf(" %d",i);
}else
{
System.out.printf(" %d\n",i);
flag = 0;
}
flag++;
}else if (pi>pn)
{
break;
}
pi++;
}
}
in.close();
}
private static boolean isPrime(int num)
{
// boolean result = true;
for (int i=2;i<num;i++)
{
if (num%i==0)
{
// result = false;
return false;
}
}
return true;
}
}
|
package com.smartlead.common.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tbl_lead_stage")
public class LeadStage {
@Id
@Column(name = "lead_stage_id")
private int stageId;
@Column(name = "lead_stage_name")
private String stageName;
public LeadStage() {
}
public int getStageId() {
return stageId;
}
public void setStageId(int stageId) {
this.stageId = stageId;
}
public String getStageName() {
return stageName;
}
public void setStageName(String stageName) {
this.stageName = stageName;
}
}
|
package com.example.mainuddin.icab12;
/**
* Created by mainuddin on 5/22/2017.
*/
public class passenger implements user {
private String name;
private String trips;
private String comment;
private String rating;
passenger(){
}
passenger(String name,String trips, String comment ,String rating){
this.name = name;
this.trips = trips;
this.comment = comment;
this.rating = rating;
}
public String getNames() {
return name;
}
public void setNames(String name) {
this.name = name;
}
public String getTrips() {
return trips;
}
public void setTrips(String trips) {
this.trips = trips;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
}
|
package gherkin.steps;
import cucumber.api.java.en.Given;
import presz.bddtdd.tests.java.model.Context;
public class GestionDesVirementsGivenStep {
private Context context;
public GestionDesVirementsGivenStep(Context ctx) {
this.context = ctx;
}
@Given("j'ai un compte cheque avec un solde de (.*)€")
public void GivenJAiUnCompteChequeAvecUnSoldeDe(int solde) {
context.getCompteCheque().setSolde(solde);
}
@Given("j'ai un compte épargne avec un solde de (.*)€")
public void GivenJAiUnCompteEpargneAvecUnSoldeDe(int solde) {
context.getCompteEpargne().setSolde(solde);
}
@Given("la limite de virement est (.*)€")
public void GivenLaLimiteDeVirementEst(int limite) {
context.getSrvVirement().setPlafond(limite);
}
}
|
package GoogleTests;
import libs.WebElements;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pages.GoogleMainPage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertArrayEquals;
public class GoogleSearchTests {
public WebDriver webDriver;
public GoogleMainPage googleMainPage;
public WebElements
@Test
public void searchTest(){
String searchText = "junit4";
String linkText = "";
String titlePageText = "";
System.out.println(webDriver.getCurrentUrl());
System.out.println(webDriver.getTitle());
System.out.println("-----------------------");
char[] expectedLinkText = {'J','u','n','i','t'};
char[] expectedTitlePageText = {'J','u','n','i','t'};
googleMainPage.searchInputFormFill(searchText);
char[] actualLink = googleMainPage.getTextFirstLink().toCharArray();
char[] actualTitle = googleMainPage.getFirstSearchResultTitle().toCharArray();
assertArrayEquals("smth L",expectedLinkText, actualLink);
assertArrayEquals("smth T",expectedTitlePageText, actualTitle);
System.out.println("expectedLinkText:");
System.out.println(expectedLinkText);
System.out.println("actual:");
}
@Before
public void beforeTest(){
File fileChromeDriver = new File("drivers/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", fileChromeDriver.getAbsolutePath());
webDriver = new ChromeDriver();
googleMainPage = new GoogleMainPage(webDriver);
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
webDriver.get("https://google.com");
}
@After
public void afterTest(){
webDriver.quit();
}
}
|
package com.example.gabrielm.appalunos.Controller.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.gabrielm.appalunos.Controller.Helper.FormHelper;
import com.example.gabrielm.appalunos.Model.DAO.ContatoDAO;
import com.example.gabrielm.appalunos.Model.Classes.Contato;
import com.example.gabrielm.appalunos.Model.Manager.CorreiosManager;
import com.example.gabrielm.appalunos.R;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import cz.msebera.android.httpclient.entity.mime.Header;
import static com.example.gabrielm.appalunos.R.id.form_name;
public class FormActivity extends AppCompatActivity {
private int CEP_LENGTH = 8;
private FormHelper formHelper;
ProgressBar progressBar;
private TextWatcher cepTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
getCep();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
this.setTextWatchers();
this.setupScreen();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_form_ok, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_formulario_ok:
Contato contato = formHelper.getContato();
ContatoDAO contatoDAO = new ContatoDAO(this);
if (shouldAddContact()){
setCoordinatesBasedOnAddress(contato);
if(contato.getId() != null){
contatoDAO.update(contato);
}
else
{
contatoDAO.add(contato);
}
contatoDAO.close();
Toast.makeText(FormActivity.this, "Contato "+contato.getNome()+" Salvo!",Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(FormActivity.this, "Você não pode deixar o campo nome em branco!",Toast.LENGTH_LONG).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private void setupScreen(){
formHelper = new FormHelper(this);
Intent intent = getIntent();
Contato contato = (Contato) intent.getSerializableExtra("contato");
if (contato != null){
formHelper.fillForm(contato);
}
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.INVISIBLE);
}
private boolean shouldAddContact() {
EditText contactName = (EditText) findViewById(form_name);
return !contactName.getText().toString().equals("");
}
private void setCoordinatesBasedOnAddress(Contato contato){
Geocoder geocoder = new Geocoder(FormActivity.this);
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocationName(contato.getEndereco(),1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses.size() > 0) {
contato.setLatitude(addresses.get(0).getLatitude());
contato.setLongitude(addresses.get(0).getLongitude());
}
}
private void setTextWatchers(){
EditText cepField = (EditText) findViewById(R.id.form_cep);
cepField.addTextChangedListener(cepTextWatcher);
}
private void getCep(){
EditText cepField = (EditText) findViewById(R.id.form_cep);
String cep = cepField.getText().toString();
if(cep.length() == CEP_LENGTH){
//String to place our result in
String result = "Failed";
//Instantiate new instance of our class
CorreiosManager getRequest = new CorreiosManager();
//Perform the doInBackground method, passing in our url
try {
progressBar.setVisibility(View.VISIBLE);
result = getRequest.execute(CorreiosManager.getFullUrl(cep)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (result != null){
this.fillAddressEditText(result);
}
else
{
Toast.makeText(FormActivity.this, "Servico Falhou", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private void fillAddressEditText(String result) {
String prettyAddress = CorreiosManager.getPrettyAddress(result);
EditText address = (EditText) findViewById(R.id.form_address);
address.setText(prettyAddress);
}
}
|
package edu.jak.dummymailers.sb.delegate.mail.impl;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import edu.jak.dummymailers.converter.MailConverter;
import edu.jak.dummymailers.model.eb.Mail;
import edu.jak.dummymailers.model.pojo.MailResponse;
import edu.jak.dummymailers.sb.dao.crud.MailFacadeLocal;
import edu.jak.dummymailers.sb.delegate.mail.MailGetterDelegateLocal;
@Stateless
public class MailGetterDelegate implements MailGetterDelegateLocal {
@EJB
MailFacadeLocal mailFacade;
public MailResponse getMailsByLimits(int start, int end) {
Mail mail = mailFacade.getMail(12986);
return MailConverter.convert(mail);
}
public MailResponse getMailById(int id) {
Mail mail = mailFacade.getMail(id);
return MailConverter.convert(mail);
}
}
|
package com.company;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Human human = new Human("Marat", 11);
Human human1 = new Human("Marat", 32);
Human human2 = new Human("Marat", 19);
Human human3 = new Human("Marat", 17);
Human human4 = new Human("Marat", 78);
Human human5 = new Human("Marat", 90);
Human human6 = new Human("Marat", 91);
System.out.println(human.equals(human1));
Human humans[] = { human, human1, human2, human3 , human4 ,human5, human6,};
int countAges[] = new int[120];
for (int i = 0; i < humans.length; i++) {
countAges[humans[i].getAge()] ++;
}
for (int i = 0; i < countAges.length; i++) {
System.out.println(countAges[i]);
}
HumansUtils.countAges(humans);
}
}
|
package com.github.cukedoctor.util;
import org.apache.maven.shared.utils.io.DirectoryScanner;
import org.apache.maven.shared.utils.io.FileUtils;
import org.apache.maven.shared.utils.io.IOUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Created by pestano on 02/06/15.
*/
public class FileUtil {
public static Logger log = Logger.getLogger(FileUtil.class.getName());
public static final Pattern ADOC_FILE_EXTENSION = Pattern.compile("([^\\s]+(\\.(?i)(ad|adoc|asciidoc|asc))$)");
/**
* @param path full path to the json feature result
* @return absolute path to to json result file
*/
public static String findJsonFile(String path) {
if (path == null) {
path = "";
}
File f = new File(path);
if (f.exists()) {
return f.getAbsolutePath();
}
//relative path
if (path.startsWith("/")) {//remove slash to use relative paths
path = path.substring(1);
}
return Paths.get(path.trim()).toAbsolutePath().toString();
}
/**
* @param startDir initial directory to scan for features
* @return all found json files path that represent cucumber features
*/
public static List<String> findJsonFiles(String startDir) {
if (startDir == null) {
startDir = "";
}
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.json"});
File f = new File(startDir);
if (f.exists()) {
startDir = f.getAbsolutePath();
scanner.setBasedir(startDir);
} else {//relative path
if (startDir.startsWith("/")) {//remove slash to use relative paths
startDir = startDir.substring(1);
}
scanner.setBasedir(new File(Paths.get(startDir.trim()).toAbsolutePath().toString()));
}
scanner.scan();
List<String> absolutePaths = new ArrayList<>(scanner.getIncludedFiles().length);
for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
absolutePaths.add(new File(scanner.getBasedir(), scanner.getIncludedFiles()[i]).getAbsolutePath());
}
//scanner.getIncludedFiles()
return absolutePaths;
}
/**
* Saves a file into filesystem. Note that name can be saved as absolute (if it has a leading slash) or relative to current path.
* EX: /target/name.adoc will save the file into
* @param name file name
* @param data file content
* @return
*/
public static File saveFile(String name, String data) {
if (name == null) {
name = "";
}
String fullyQualifiedName = name;
/**
* if filename is not absolute use current path as base dir
*/
if(!new File(fullyQualifiedName).isAbsolute()){
fullyQualifiedName = Paths.get("").toAbsolutePath().toString() + "/"+name;
}
try {
//create subdirs (if there any)
if(fullyQualifiedName.contains("/")){
File f = new File(fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf("/")));
f.mkdirs();
}
File file = new File(fullyQualifiedName);
file.createNewFile();
FileUtils.fileWrite(file, "UTF-8", data);
log.info("Wrote: " + file.getAbsolutePath());
return file;
} catch (IOException e) {
log.log(Level.SEVERE, "Could not create file " + name, e);
return null;
}
}
public static File loadFile(String path) {
if (path == null) {
path = "/";
}
File f = new File(path);
if (f.exists()) {
return f.getAbsoluteFile();
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return new File(Paths.get("").toAbsolutePath().toString() + path.trim());
}
public static boolean removeFile(String path) {
File fileToRemove = loadFile(path);
return fileToRemove.delete();
}
public static File copyFile(String source, String dest) {
if (source != null && dest != null) {
/*if (dest.startsWith("/")) { //remove slash to use relative paths. Dest file is saved using folder where Cukedoctor is executed as relative path
dest = dest.substring(1);
}*/
try {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(source);
//OutputStream out = new FileOutputStream(new File(Paths.get(dest).toAbsolutePath().toString()));
//IOUtil.copy(in, out);
return saveFile(dest, IOUtil.toString(in));
} catch (IOException e) {
log.log(Level.SEVERE, "Could not copy source file: " + source + " to dest file: " + dest, e);
}
}
return null;
}
}
|
package com.example.anujj.attendence.Event;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import com.example.anujj.attendence.R;
import java.util.Calendar;
public class AddEventActivity extends AppCompatActivity {
TextView AddEventTypeHeading, StartTimeEditTextEvent, EndTimeEditTextEvent, Add_Reminder_in_Event_TextView;
EditText add_Subject_Event_EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_event);
init();
Intent i = getIntent();
String eventName = i.getStringExtra("eventName");
Log.d("123", eventName);
AddEventTypeHeading.setText(eventName);
listeners();
}
private void listeners() {
reminderListener();
//date picker
StartTimeEditTextEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addDate();
}
});
//TIME PICKER
EndTimeEditTextEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addTime();
}
});
}
private void addDate() {
final int day,month,year;
Calendar cal=Calendar.getInstance();
day= cal.get(Calendar.DAY_OF_MONTH);
month= cal.get(Calendar.MONTH);
year=cal.get(Calendar.YEAR);
DatePickerDialog datePickerDialog=new DatePickerDialog(AddEventActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
StartTimeEditTextEvent.setText(dayOfMonth+"/"+month+"/"+year);
}
},year,month,day);
datePickerDialog.show();
}
private void addTime(){
final int hour,minute;
Calendar cal=Calendar.getInstance();
hour= cal.get(Calendar.HOUR);
minute= cal.get(Calendar.MINUTE);
EndTimeEditTextEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog timePickerDialog=new TimePickerDialog(AddEventActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
EndTimeEditTextEvent.setText(hourOfDay+":"+minute);
}
},hour,minute,false);
timePickerDialog.show();
}
});
}
private void reminderListener() {
Add_Reminder_in_Event_TextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("event", "onClick: Add_Reminder_in_Event_TextView ");
}
});
}
private void init() {
AddEventTypeHeading = (TextView) findViewById(R.id.AddEventTypeHeading);
Add_Reminder_in_Event_TextView = (TextView) findViewById(R.id.Add_Reminder_in_Event_TextView);
add_Subject_Event_EditText = (EditText) findViewById(R.id.add_Subject_Event_EditText);
StartTimeEditTextEvent = (TextView) findViewById(R.id.StartTimeEditTextEvent);
EndTimeEditTextEvent = (TextView) findViewById(R.id.EndTimeEditTextEvent);
}
}
|
package com.icanit.app_v2.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.TextView;
import com.icanit.app_v2.R;
import com.icanit.app_v2.common.IConstants;
import com.icanit.app_v2.entity.AppOrder;
public class PayResultFragment extends Fragment implements OnClickListener {
private View self;
private int resId = R.layout.fragment4pay_pay_result;
private Button backToOrigin;
private TextView resultDescription;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();bindListeners();describeResult();
}
private void describeResult() {
String str = "订单支付成功\n将从您账户扣除 ¥"+
String.format("%.2f", ((AppOrder)getActivity().getIntent().getSerializableExtra(IConstants.ORDER_INFO)).sum);
SpannableString ss = new SpannableString(str);
ss.setSpan(new ForegroundColorSpan(Color.rgb(0x33, 0xaa, 0x33)), 0, str.indexOf('¥'),
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new AbsoluteSizeSpan(20, true), 0, str.indexOf('¥'),
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ForegroundColorSpan(Color.rgb(0xdd, 0x33, 0x33)), str.indexOf('¥'), str.length(),
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new AbsoluteSizeSpan(22,true), str.indexOf('¥'), str.length(),
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
resultDescription.setText(ss);
}
private void init() {
self=LayoutInflater.from(getActivity()).inflate(resId, null,false);
backToOrigin=(Button)self.findViewById(R.id.button1);
resultDescription=(TextView)self.findViewById(R.id.textView1);
}
private void bindListeners() {
backToOrigin.setOnClickListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewParent vp=self.getParent();
if(vp!=null) ((ViewGroup)vp).removeAllViews();
return self;
}
@Override
public void onClick(View v) {
if(v==backToOrigin){
//TODO
getActivity().finish();
}
}
}
|
package com.example.demo2.strategy;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.example.demo2.strategy.MessageService;
@Component("messageService")
public class MessageServiceContext {
private final Map<Integer, MessageService> handlerMap = new HashMap<>();
public MessageService getMessageService(Integer type) {
return handlerMap.get(type);
}
public void putMessageService(Integer code, MessageService messageService) {
handlerMap.put(code, messageService);
}
}
|
package com.genuinelygreen.management.controller;
import com.genuinelygreen.management.domain.Employee;
import com.genuinelygreen.management.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping(value = {"", "/"})
public List<Employee> listEmployees() {
return this.employeeService.getEmployees();
}
@CrossOrigin
@PostMapping("/save")
public ResponseEntity<String> saveEmployee(@RequestBody Employee employee) {
employeeService.save(employee);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
package org.apache.hadoop.hdfs.server.namenode.persistance.context.entity;
import java.util.*;
import org.apache.hadoop.hdfs.server.namenode.CounterType;
import org.apache.hadoop.hdfs.server.namenode.FinderType;
import org.apache.hadoop.hdfs.server.namenode.Lease;
import org.apache.hadoop.hdfs.server.namenode.persistance.PersistanceException;
import org.apache.hadoop.hdfs.server.namenode.persistance.context.TransactionContextException;
import org.apache.hadoop.hdfs.server.namenode.persistance.data_access.entity.LeaseDataAccess;
import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageException;
/**
*
* @author Hooman <hooman@sics.se>
*/
public class LeaseContext extends EntityContext<Lease> {
/**
* Lease
*/
private Map<String, Lease> leases = new HashMap<String, Lease>();
private Map<Integer, Lease> idToLease = new HashMap<Integer, Lease>();
private Map<Lease, Lease> newLeases = new HashMap<Lease, Lease>();
private Map<Lease, Lease> modifiedLeases = new HashMap<Lease, Lease>();
private Map<Lease, Lease> removedLeases = new HashMap<Lease, Lease>();
private boolean allLeasesRead = false;
private int byHoldernullCount = 0;
private int byIdNullCount = 0;
private LeaseDataAccess dataAccess;
public LeaseContext(LeaseDataAccess dataAccess) {
this.dataAccess = dataAccess;
}
@Override
public void add(Lease lease) throws PersistanceException {
if (removedLeases.containsKey(lease)) {
throw new TransactionContextException("Removed lease passed to be persisted");
}
if (leases.containsKey(lease.getHolder()) && leases.get(lease.getHolder()) == null) {
byHoldernullCount--;
}
if (idToLease.containsKey(lease.getHolderID()) && idToLease.get(lease.getHolderID()) == null) {
byIdNullCount--;
}
newLeases.put(lease, lease);
leases.put(lease.getHolder(), lease);
idToLease.put(lease.getHolderID(), lease);
log("added-lease", CacheHitState.NA, new String[]{"holder", lease.getHolder(),
"hid", String.valueOf(lease.getHolderID())});
}
@Override
public void clear() {
storageCallPrevented = false;
idToLease.clear();
newLeases.clear();
modifiedLeases.clear();
removedLeases.clear();
leases.clear();
allLeasesRead = false;
byHoldernullCount = 0;
byIdNullCount = 0;
}
@Override
public int count(CounterType<Lease> counter, Object... params) throws PersistanceException {
Lease.Counter lCounter = (Lease.Counter) counter;
switch (lCounter) {
case All:
if (allLeasesRead) {
log("count-all-leases", CacheHitState.HIT);
return leases.size() - byHoldernullCount;
} else {
log("count-all-leases", CacheHitState.LOSS);
return dataAccess.countAll();
}
}
throw new RuntimeException(UNSUPPORTED_COUNTER);
}
@Override
public Lease find(FinderType<Lease> finder, Object... params) throws PersistanceException {
Lease.Finder lFinder = (Lease.Finder) finder;
Lease result = null;
switch (lFinder) {
case ByPKey:
String holder = (String) params[0];
if (leases.containsKey(holder)) {
log("find-lease-by-pk", CacheHitState.HIT, new String[]{"holder", holder});
result = leases.get(holder);
} else {
log("find-lease-by-pk", CacheHitState.LOSS, new String[]{"holder", holder});
aboutToAccessStorage();
result = dataAccess.findByPKey(holder);
if (result == null) {
byHoldernullCount++;
} else {
idToLease.put(result.getHolderID(), result);
}
leases.put(holder, result);
}
return result;
case ByHolderId:
int holderId = (Integer) params[0];
if (idToLease.containsKey(holderId)) {
log("find-lease-by-holderid", CacheHitState.HIT, new String[]{"hid", Integer.toString(holderId)});
result = idToLease.get(holderId);
} else {
log("find-lease-by-holderid", CacheHitState.LOSS, new String[]{"hid", Integer.toString(holderId)});
aboutToAccessStorage();
result = dataAccess.findByHolderId(holderId);
if (result == null) {
byIdNullCount++;
} else {
leases.put(result.getHolder(), result);
}
idToLease.put(holderId, result);
}
return result;
}
throw new RuntimeException(UNSUPPORTED_FINDER);
}
@Override
public Collection<Lease> findList(FinderType<Lease> finder, Object... params) throws PersistanceException {
Lease.Finder lFinder = (Lease.Finder) finder;
Collection<Lease> result = null;
switch (lFinder) {
case ByTimeLimit:
long timeLimit = (Long) params[0];
log("find-leases-by-timelimit", CacheHitState.NA, new String[]{"timelimit", Long.toString(timeLimit)});
aboutToAccessStorage();
result = syncLeaseInstances(dataAccess.findByTimeLimit(timeLimit));
return result;
case All:
if (allLeasesRead) {
log("find-all-leases", CacheHitState.HIT);
result = new TreeSet<Lease>();
for (Lease l : leases.values()) {
if (l != null) {
result.add(l);
}
}
} else {
log("find-all-leases", CacheHitState.LOSS);
aboutToAccessStorage();
result = syncLeaseInstances(dataAccess.findAll());
allLeasesRead = true;
}
return result;
}
throw new RuntimeException(UNSUPPORTED_FINDER);
}
@Override
public void prepare() throws StorageException {
dataAccess.prepare(removedLeases.values(), newLeases.values(), modifiedLeases.values());
}
@Override
public void remove(Lease lease) throws PersistanceException {
if (leases.remove(lease.getHolder()) == null) {
throw new TransactionContextException("Unattached lease passed to be removed");
}
idToLease.remove(lease.getHolderID());
newLeases.remove(lease);
modifiedLeases.remove(lease);
removedLeases.put(lease, lease);
log("removed-lease", CacheHitState.NA, new String[]{"holder", lease.getHolder()});
}
@Override
public void removeAll() throws PersistanceException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void update(Lease lease) throws PersistanceException {
if (removedLeases.containsKey(lease)) {
throw new TransactionContextException("Removed lease passed to be persisted");
}
modifiedLeases.put(lease, lease);
leases.put(lease.getHolder(), lease);
idToLease.put(lease.getHolderID(), lease);
log("updated-lease", CacheHitState.NA, new String[]{"holder", lease.getHolder()});
}
private SortedSet<Lease> syncLeaseInstances(Collection<Lease> list) {
SortedSet<Lease> finalSet = new TreeSet<Lease>();
for (Lease lease : list) {
if (!removedLeases.containsKey(lease)) {
if (leases.containsKey(lease.getHolder())) {
if (leases.get(lease.getHolder()) == null) {
byHoldernullCount--;
leases.put(lease.getHolder(), lease);
}
finalSet.add(leases.get(lease.getHolder()));
} else {
finalSet.add(lease);
leases.put(lease.getHolder(), lease);
}
if (idToLease.containsKey(lease.getHolderID())) {
if (idToLease.get(lease.getHolderID()) == null) {
byIdNullCount--;
idToLease.put(lease.getHolderID(), lease);
}
} else {
idToLease.put(lease.getHolderID(), lease);
}
}
}
return finalSet;
}
}
|
/**
*
*/
package com.kaishengit.Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import com.kaishengit.exception.DateException;
/**
* @ClassName: ConnectionManager
* @Description: 创建连接
* @author: 刘忠伟
* @date: 2016年11月22日 下午10:51:08
* @version 1.0
*
*/
public class ConnectionManager {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql:///book";
private static final String username = "root";
private static final String password = "root";
/**
*
* @Description:创建连接
* @author: 刘忠伟
* @return
* @return:Connection
* @time:2016年11月22日 下午10:52:50
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new DateException("conn错误",e);
} catch (SQLException e) {
e.printStackTrace();
throw new DateException("conn关闭错误",e);
}
}
}
|
package com.tinygame.cmdhandler;
import com.tinygame.msg.GameMsgProtocol;
import com.tinygame.rank.RankItem;
import com.tinygame.rank.RankService;
import io.netty.channel.ChannelHandlerContext;
import java.util.Collections;
public class GetRankCmdHadler implements ICmdHandler<GameMsgProtocol.GetRankCmd> {
@Override
public void handler(ChannelHandlerContext ctx, GameMsgProtocol.GetRankCmd cmd) {
if (null == ctx || null == cmd){
return;
}
RankService.getInstance().getRank((rankItemList)->{
if (null == rankItemList){
rankItemList = Collections.emptyList();
}
GameMsgProtocol.GetRankResult.Builder getRankBuild = GameMsgProtocol.GetRankResult.newBuilder();
for (RankItem rankItem : rankItemList){
GameMsgProtocol.GetRankResult.RankItem.Builder rankItemBuild = GameMsgProtocol.GetRankResult.RankItem.newBuilder();
rankItemBuild.setRankId(rankItem.getRankId());
rankItemBuild.setUserId(rankItem.getUserId());
rankItemBuild.setUserName(rankItem.getUserName());
rankItemBuild.setHeroAvatar(rankItem.getHeroAvatar());
rankItemBuild.setWin(rankItem.getWin());
getRankBuild.addRankItem(rankItemBuild);
}
GameMsgProtocol.GetRankResult build = getRankBuild.build();
ctx.writeAndFlush(build);
return null;
});
}
}
|
package Domain;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by Emma on 8/11/2018.
*/
public class Admin
{
//Admin
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long AdminID;
private String adminName;
private String adminSurname;
private String password;
private String role;
private Admin(){}
public long getAdminID() {
return AdminID;
}
public String getadminName() {
return adminName;
}
public String getadminSurname() {
return adminSurname;
}
public String getPassword() {
return password;
}
public String getRole() {
return role;
}
public Admin(Builder builder)
{
this.AdminID = builder.AdminID;
this.adminName = builder.adminName;
this.adminSurname = builder.adminSurname;
this.password=builder.password;
this.role=builder.role;
}
public static class Builder {
private long AdminID;
private String adminName, adminSurname, password, role;
public Builder AdminID(long value) {
this.AdminID = value;
return this;
}
public Builder adminName(String value) {
this.adminName = value;
return this;
}
public Builder adminSurname(String value) {
this.adminSurname = value;
return this;
}
public Builder password(String value) {
this.password = value;
return this;
}
public Builder role(String value) {
this.role = value;
return this;
}
public Admin build() {
return new Admin(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Admin ad = (Admin) o;
return AdminID == ad.AdminID;
}
@Override
public int hashCode() {
return (int) (AdminID ^ (AdminID >>> 32));
}
}
}
|
package com.org.base;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
@Data
public class CurrentMenu {
@ApiModelProperty(value = "Id")
private String id;
@ApiModelProperty(value = "菜单名")
private String name;
@ApiModelProperty(value = "父Id")
private String pId;
@ApiModelProperty(value = "链接")
private String url;
@ApiModelProperty(value = "排序")
private Integer orderNum;
@ApiModelProperty(value = "图标")
private String icon;
@ApiModelProperty(value = "创建人")
private String createBy;
@ApiModelProperty(value = "创建时间")
private Date createDate;
@ApiModelProperty(value = "更新人")
private String updateBy;
@ApiModelProperty(value = "更新时间")
private Date updateDate;
@ApiModelProperty(value = "权限标识")
private String permission;
@ApiModelProperty(value = "菜单类型")
private Byte menuType;
@ApiModelProperty(value = "菜单排序id 填充菜单展示id")
private int num;
public CurrentMenu(String id, String name, String pId, String url, Integer orderNum, String icon, String permission, Byte menuType, int num) {
this.id = id;
this.name = name;
this.pId = pId;
this.url = url;
this.orderNum = orderNum;
this.icon = icon;
this.permission = permission;
this.menuType = menuType;
this.num = num;
}
}
|
package labrom.litlbro;
import java.io.FileOutputStream;
import labrom.litlbro.browser.BrowserClient;
import labrom.litlbro.browser.BrowserSettings;
import labrom.litlbro.browser.ChromeClient;
import labrom.litlbro.browser.ChromeClient.PagePublisher;
import labrom.litlbro.browser.NavFlags;
import labrom.litlbro.browser.PageLoadController;
import labrom.litlbro.data.DBHistoryManager;
import labrom.litlbro.data.DBSitePreferencesManager;
import labrom.litlbro.data.Database;
import labrom.litlbro.data.HistoryManager;
import labrom.litlbro.icon.IconCache;
import labrom.litlbro.state.Event;
import labrom.litlbro.state.State;
import labrom.litlbro.state.StateBase;
import labrom.litlbro.util.ShakeManager;
import labrom.litlbro.util.ShakeManager.ShakeListener;
import labrom.litlbro.util.UrlUtil;
import labrom.litlbro.widget.ControlBar;
import labrom.litlbro.widget.ShakeDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
/**
*
* @author Romain Laboisse labrom@gmail.com
*
*/
public class ActivityBrowser extends Activity implements BrowserClient.Listener, PageLoadController, OnClickListener, OnCheckedChangeListener, BrowserClient.IntentHandler, ShakeListener, ShakeDialog.Listener {
private static final int SHAKE_MIN_ACCEL = 3;
private final class ShareScreenshotTask extends AsyncTask<String, Void, Uri> {
private Picture screenshot;
@Override
protected void onPreExecute() {
screenshot = browser.capturePicture();
}
@Override
protected Uri doInBackground(String... params) {
Bitmap receptacle = Bitmap.createBitmap(Math.min(1000, screenshot.getWidth()), Math.min(800, screenshot.getHeight()), Config.ARGB_8888);
Canvas c = new Canvas(receptacle);
screenshot.draw(c);
String filename = params[0]+ ".png";
try {
FileOutputStream out = openFileOutput(filename, MODE_WORLD_READABLE);
receptacle.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
String fileStreamPath = getFileStreamPath(filename).getAbsolutePath();
String uri = Images.Media.insertImage(getContentResolver(), fileStreamPath, params[0], null);
return Uri.parse(uri);
} catch(Exception e) {
return null;
}
}
protected void onPostExecute(Uri imageUri) {
dismissDialog(DIALOG_PROGRESS_SHARE_SCREENSHOT);
if(imageUri == null)
return;
Intent i = new Intent(Intent.ACTION_SEND);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(Intent.EXTRA_TEXT, "Here is a picture of the page at " + browser.getUrl());
i.putExtra(Intent.EXTRA_STREAM, imageUri);
i.setType("image/png");
startActivity(Intent.createChooser(i, getString(R.string.shareScreenshotDialogTitle)));
}
}
private final class PagePublisherWrapper implements PagePublisher {
private PagePublisher wrapped;
private IconCache iconCache;
private String currentUrl;
public PagePublisherWrapper(PagePublisher wrapped, IconCache iconCache) {
this.wrapped = wrapped;
this.iconCache = iconCache;
}
public void setCurrentUrl(String url) {
this.currentUrl = url;
}
@Override
public void setProgress(int progress) {
wrapped.setProgress(progress);
}
@Override
public void setTitle(String title) {
wrapped.setTitle(title);
}
@Override
public void setIcon(Bitmap icon) {
wrapped.setIcon(icon);
if(this.currentUrl != null) {
String host = UrlUtil.getHost(currentUrl);
this.iconCache.cache(icon, host);
}
}
}
private static final int DIALOG_PROGRESS_SHARE_SCREENSHOT = 1;
WebView browser;
ControlBar controlBar;
View optionsPane;
CompoundButton starToggle;
CompoundButton jsToggle;
BrowserClient viewClient;
ProgressBar progress;
private Animation pushOptions;
private Animation pullOptions;
Database db;
DBSitePreferencesManager sitePrefs;
HistoryManager history;
IconCache iconCache;
private State state;
private SharedPreferences prefs;
private ShakeManager shaker;
private ShakeDialog shakeDialog;
private AlertDialog currentlyShowingShakeDialog;
private PagePublisherWrapper pagePublisher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chrome);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
shaker = new ShakeManager(this, this);
shakeDialog = new ShakeDialog(this, prefs, this);
this.browser = (WebView)findViewById(R.id.web);
this.optionsPane = findViewById(R.id.optionsPane);
this.starToggle = (CompoundButton)this.optionsPane.findViewById(R.id.star);
this.starToggle.setOnCheckedChangeListener(this);
this.jsToggle = (CompoundButton)this.optionsPane.findViewById(R.id.optionsJsToggle);
this.jsToggle.setOnCheckedChangeListener(this);
findViewById(R.id.share).setOnClickListener(this);
findViewById(R.id.shareScreenshot).setOnClickListener(this);
findViewById(R.id.prefs).setOnClickListener(this);
this.controlBar = (ControlBar)findViewById(R.id.controlBar);
this.controlBar.setPageLoadController(this);
// Control pad animations
pullOptions = AnimationUtils.loadAnimation(this, R.anim.pull_options_pane);
pushOptions = AnimationUtils.loadAnimation(this, R.anim.push_options_pane);
pushOptions.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
optionsPane.setVisibility(View.INVISIBLE);
}
});
configureBrowser();
WebIconDatabase.getInstance().open(getCacheDir().getAbsolutePath());
this.iconCache = new IconCache(getCacheDir());
this.pagePublisher = new PagePublisherWrapper(this.controlBar, this.iconCache);
this.browser.setWebChromeClient(new ChromeClient(pagePublisher));
this.state = StateBase.NAVIGATE_INTENT;
}
@Override
protected void onStart() {
super.onStart();
// Initialize DB-based services
this.db = Database.create(getApplicationContext());
this.sitePrefs = new DBSitePreferencesManager(this.db);
this.history = new DBHistoryManager(this.db);
this.viewClient = new BrowserClient(this.controlBar, this.sitePrefs, this.history, this);
this.viewClient.setListener(this);
this.browser.setWebViewClient(viewClient);
if(state == StateBase.NAVIGATE_INTENT) {
navigate(getIntent());
}
else if(state == StateBase.PAGE_OPTIONS) {
changeState(Event.BACK);
setUI();
}
shaker.register();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
navigate(intent);
}
@Override
protected void onStop() {
super.onStop();
this.shaker.unregister();
this.browser.stopLoading();
this.db.close();
this.db = null;
}
@Override
protected void onDestroy() {
super.onDestroy();
// Workaround for crasher with zoom controls, see http://stackoverflow.com/questions/5267639/how-to-safely-turn-webview-zooming-on-and-off-as-needed
this.browser.postDelayed(new Runnable() {
@Override
public void run() {
browser.destroy();
}
}, ViewConfiguration.getZoomControlsTimeout());
}
private void configureBrowser() {
WebSettings settings = this.browser.getSettings();
settings.setJavaScriptEnabled(false); // Javascript disabled by default
BrowserSettings.configure(settings);
}
private void setUI() {
boolean useAnimations = ActivityPrefs.useWindowAnimations(prefs, getResources());
if(state == StateBase.PAGE_LOADING) {
browser.setVisibility(View.VISIBLE);
controlBar.show(useAnimations);
hideOptionsPane();
} else if(state == StateBase.PAGE_LOADED) {
browser.setVisibility(View.VISIBLE);
if(controlBar.isShown())
this.controlBar.hide(useAnimations);
hideOptionsPane();
} else if(state == StateBase.PAGE_OPTIONS) {
if(controlBar.isShown())
this.controlBar.hide(useAnimations);
starToggle.setChecked(history.isStarred(this.browser.getUrl()));
jsToggle.setChecked(this.browser.getSettings().getJavaScriptEnabled());
showOptionsPane();
}
}
private void showOptionsPane() {
if(!optionsPane.isShown()) {
if(ActivityPrefs.useWindowAnimations(prefs, getResources())) {
optionsPane.startAnimation(pullOptions);
}
optionsPane.setVisibility(View.VISIBLE);
}
}
private void hideOptionsPane() {
if(optionsPane.isShown() && ActivityPrefs.useWindowAnimations(prefs, getResources())) {
optionsPane.startAnimation(pushOptions);
} else {
optionsPane.setVisibility(View.INVISIBLE);
}
}
void navigate(String url, boolean forceJs, boolean forceNoJs, boolean noHistory) {
NavFlags flags = new NavFlags();
flags.forceJs = forceJs;
flags.forceNoJs = forceNoJs;
flags.noHistory = noHistory;
flags.explicitNav = true;
this.browser.setTag(R.id.tag_nav_flags, flags);
// if(!forceJs && !forceNoJs) {
// this.sitePrefs.askWhetherJavascriptEnabled(url, new Delegate() {
// @Override
// public void notifyJavascriptEnabled(boolean enabled) {
// browser.getSettings().setJavaScriptEnabled(enabled);
// }
// });
// }
this.browser.loadUrl(url);
}
void navigate(Intent intent) {
if (intent != null) {
state = StateBase.NAVIGATE_INTENT;
browser.clearHistory();
String url = intent.getDataString();
if(url != null) {
boolean forceJs = isSearchNavigateIntent(intent);
boolean noHistory = forceJs;
if(forceJs) {
browser.getSettings().setJavaScriptEnabled(true);
}
changeState(Event.IMPLICIT_NEXT);
setUI();
navigate(url, forceJs, false, noHistory);
return;
}
}
}
private boolean isSearchNavigateIntent(Intent intent) {
String appid = intent.getStringExtra("com.android.browser.application_id");
Uri u = intent.getData();
boolean search = "com.android.quicksearchbox".equals(appid) || "com.google.android.googlequicksearchbox".equals(appid) || (u != null && "duckduckgo.com".equals(u.getHost()));
return search;
}
@Override
public void restart(boolean enableJavascript) {
changeState(Event.TAP_JS_TOGGLE);
setUI();
String url = this.browser.getUrl();
this.browser.stopLoading();
this.browser.getSettings().setJavaScriptEnabled(enableJavascript);
navigate(url, enableJavascript, !enableJavascript, true); // Should already be in history right?
}
@Override
public boolean isRestarting() {
return state != null && state.getLastEvent() == Event.TAP_JS_TOGGLE;
}
@Override
public void onPageFinished() {
changeState(Event.PAGE_FINISHED_LOADING);
setUI();
}
@Override
public void onPageStarted(String url) {
this.pagePublisher.setCurrentUrl(url);
/*
* We had a page loaded, now a (supposedly new) page is loading,
* so someone must have clicked on a link or something...
*/
if(state == StateBase.PAGE_LOADED) {
changeState(Event.TAP_LINK);
setUI();
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_MENU) {
// Display/hide options bar on Menu hardware button
changeState(Event.TAP_HW_MENU);
setUI();
return true; // Means we intercept Menu hardware key when control bar is shown too
}
if(keyCode == KeyEvent.KEYCODE_BACK) {
changeState(Event.BACK);
if(state == null) {
if(this.browser.canGoBack()) {
state = StateBase.PAGE_LOADING;
NavFlags flags = new NavFlags();
flags.isBack = true;
this.browser.setTag(R.id.tag_nav_flags, flags);
this.browser.goBack();
setUI();
return true;
} else /*if(gotViewIntent())*/ {
return super.onKeyUp(keyCode, event);
}
} else {
setUI();
return true;
}
}
if(keyCode == KeyEvent.KEYCODE_SEARCH) {
onGoHome();
return true;
}
return super.onKeyUp(keyCode, event);
}
// @Override
// public void onBackPressed() {
//
// changeState(Event.BACK);
//
// if(state == null) {
// if(this.browser.canGoBack()) {
// state = StateBase.PAGE_LOADING;
// this.browser.goBack();
// setUI();
// } else /*if(gotViewIntent())*/ {
// super.onBackPressed();
// }
// } else {
// setUI();
// }
// }
private void changeState(Event e) {
if(state != null)
state = state.change(e);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.share:
share();
return;
case R.id.shareScreenshot:
shareScreenshot();
return;
case R.id.prefs:
ActivityPrefs.startBy(this);
return;
}
}
@Override
public void onCheckedChanged(CompoundButton v, boolean checked) {
switch(v.getId()) {
case R.id.star:
toggleStarred(checked);
return;
case R.id.optionsJsToggle:
restart(checked);
this.controlBar.setJavascriptEnabled(checked);
}
}
private void share() {
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, this.browser.getUrl());
i.setType("text/plain");
startActivity(Intent.createChooser(i, getString(R.string.shareDialogTitle)));
}
private void toggleStarred(boolean star) {
if(star)
this.history.starUrl(this.browser.getUrl());
else
this.history.unstarUrl(this.browser.getUrl());
}
private void shareScreenshot() {
showDialog(DIALOG_PROGRESS_SHARE_SCREENSHOT);
new ShareScreenshotTask().execute(UrlUtil.getDomain(browser.getUrl()));
}
@Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_PROGRESS_SHARE_SCREENSHOT) {
ProgressDialog d = new ProgressDialog(this);
d.setIndeterminate(true);
d.setMessage(getString(R.string.progressShareScreenshot));
return d;
}
return super.onCreateDialog(id);
}
@Override
public void handleIntent(Intent i) {
Log.d(L.TAG, "Sending intent " + i);
startActivity(i);
}
@Override
public void onShake(float acceleration) {
if(acceleration > SHAKE_MIN_ACCEL + prefs.getInt("shakeLevel", getResources().getInteger(R.integer.prefShakeLevelDefault))) {
if(currentlyShowingShakeDialog != null) {
if(currentlyShowingShakeDialog.isShowing())
return;
}
currentlyShowingShakeDialog = shakeDialog.create();
if(currentlyShowingShakeDialog != null)
currentlyShowingShakeDialog.show();
else
onGoHome(); // No confirmation needed
}
}
@Override
public void onGoHome() {
startActivity(new Intent(this, ActivityHome.class));
finish();
}
}
|
package com.knu.medifree;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//Firebase Auth를 위한 API
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class PRegActivity extends AppCompatActivity {
// 인스턴스 생성
private FirebaseAuth mAuth;
//Button
Button btn_reg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_reg);
// Auth 인스턴스 생성
mAuth = FirebaseAuth.getInstance();
// 객체 할당
btn_reg = (Button) findViewById(R.id.p_reg_btn_reg);
// 클릭 리스너 할당
btn_reg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 회원 가입 버튼을 눌렀을 때
createAccount_Patient();
// 현재 상황 : PHomeActivity로 이동
}
});
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
private void createAccount_Patient() {
String email = ((TextView) findViewById(R.id.email_P)).getText().toString();
String password = ((TextView) findViewById(R.id.password_P)).getText().toString();
String passwordCheck = ((TextView) findViewById(R.id.passwordCheck_P)).getText().toString();
if (email.length() > 0 && password.length() > 0 && passwordCheck.length() > 0){
if (password.equals(passwordCheck)) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// 회원가입 성공
FirebaseUser user = mAuth.getCurrentUser();
startToast("회원가입이 완료되었습니다.");
//현재 유저의 uid가져오기.
String uid = user.getUid();
insert_user_Information(uid);
} else {
// 회원가입 실패=> 비밀번호 길이 및 아이디 중복 여부 등
if (task.getException() != null){
startToast(task.getException().toString());
}
}
}
});
} else {
// 비밀번호 확인실패.
startToast("비밀번호가 일치하지 않습니다.");
}
} else{
startToast("이메일 또는 비밀번호를 입력해주세요.");
}
}
//알림을 출력하는 method
private void startToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); }
//생성된 uid 및 나머지 정보들 firestore에 넣는 작업.
private void insert_user_Information(String uid) {
String name = ((EditText)findViewById(R.id.name_P)).getText().toString();
String phone = ((EditText)findViewById((R.id.phone_P))).getText().toString();
String address = ((EditText)findViewById(R.id.address_P)).getText().toString();
FirebaseFirestore db = FirebaseFirestore.getInstance();
Map<String, Object> user = new HashMap<>();
user.put("userType","Patient");
user.put("name",name);
user.put("phoneNum",phone);
user.put("Address",address);
//실제 firestore에 추가하는 작업, add=> 자동으로 문서id(문서이름)를 만들어줌
// Add a new document with a generated ID
db.collection("Profile").document(uid)
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void avoid) {
//홈화면으로 이동.
Intent intent = new Intent(getApplicationContext(), PHomeActivity.class);
startActivity(intent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
startToast("정보저장에 실패하였습니다.");
}
});
}
}
|
package tony.hortalizas;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] titulosHortalizas = {"Brócoli","Alcachofa","Calabacín","Guisante","Haba","Maíz","Champiñon"};
final String[] subtitulosHortalizas = {
"El brócoli es una hortaliza de la familia de las coles. " +
"Su consumo aumenta constantemente, ya que es un alimento sano y " +
"que admite múltiples preparaciones.",
"La alcachofa es una inflorescencia inmadura de color verde o morado." +
" Se consume de muy diversas formas y su sabor es muy apreciado.",
"Se trata de una de las plantas comestibles más antiguas y probablemente de las primeras" +
" cultivadas. Se presenta en una vaina de color verde (claro u oscuro, según variedad), más o menos comprimida," +
" en muchos casos cilíndrica y puntiaguda en sus dos extremos.",
"La planta de los calabacines tiene un aspecto frondoso y se consumen sus frutos cuando están tiernos." +
" Sus flores masculinas se consumen fritas cuando se hallan todavía en capullo.",
"El haba es una hortaliza comestible, sus semillas" +
" y sus vainas pueden cocinarse de muy distintas formas," +
" desde hervidas o como puré hasta como sopa de verano. " +
"Incluso sus hojas superiores pueden ser utilizadas a modo de espinacas.",
"El maíz dulce se comercializa bien en forma de ‘mazorca’ o bien como granos sueltos," +
" frescos en conserva o congelados.",
"El champiñón es un hongo formado por un sombrero de forma semiesférica" +
" o plana y pie cilíndrico, normalmente blanco." +
"El champiñón se consume tanto fresco como en conserva," +
" crudo o cocinado, formando parte de ensaladas, frito o asado y como guarnición en muchos platos" +
" e incluso se elaboran salsas."};
final int[] imagenesHortalizas = {R.drawable.brocoli,R.drawable.alcachofa,R.drawable.calabacin,R.drawable.guisante,R.drawable.haba,R.drawable.maiz,R.drawable.champ};
HortalizasAdapter adapter = new HortalizasAdapter(this, titulosHortalizas, subtitulosHortalizas, imagenesHortalizas);
ListView listView = (ListView) findViewById(R.id.hortalizasList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,VisualizacionDetallesHortalizas.class);
Bundle bundle = new Bundle();
bundle.putInt("IMAGENES",imagenesHortalizas[position]);
bundle.putString("TITULOS",titulosHortalizas[position]);
bundle.putString("DESCRIPCIONES",subtitulosHortalizas[position]);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
|
package com.beike.common.entity.trx;
/**
* @Title: SendType.java
* @Package com.beike.common.entity.trx
* @Description: 凭证发送类型
* @date 3 11, 2012 4:58:40 PM
* @author wh.cheng
* @version v1.0
*/
public enum SendType {
SMS, EMAIL, BOTH;
}
|
package controllers.chorbi;
import java.util.Collection;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.ChorbiService;
import services.CreditCardService;
import services.SearchTemplateService;
import controllers.AbstractController;
import domain.Chorbi;
import domain.CreditCard;
import domain.Genre;
import domain.RelationshipType;
import domain.SearchTemplate;
@Controller
@RequestMapping("/searchTemplate/chorbi")
public class SearchTemplateChorbiController extends AbstractController {
// Services ---------------------------------------------------------------
@Autowired
private SearchTemplateService searchTemplateService;
@Autowired
private ChorbiService chorbiService;
@Autowired
private CreditCardService creditCardService;
// Constructors -----------------------------------------------------------
public SearchTemplateChorbiController() {
super();
}
// Display ----------------------------------------------------------------
@RequestMapping(value = "/display", method = RequestMethod.GET)
public ModelAndView display() {
ModelAndView result;
Chorbi chorbi;
SearchTemplate searchTemplate;
chorbi = this.chorbiService.findByPrincipal();
searchTemplate = this.searchTemplateService.findByChorbiId(chorbi);
result = new ModelAndView("searchTemplate/display");
result.addObject("searchTemplate", searchTemplate);
return result;
}
// Creation ---------------------------------------------------------------
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView result;
SearchTemplate searchTemplate;
Chorbi chorbi;
chorbi = this.chorbiService.findByPrincipal();
searchTemplate = this.searchTemplateService.create(chorbi);
result = this.createEditModelAndView(searchTemplate);
return result;
}
@RequestMapping(value = "/findBySearchTemplate", method = RequestMethod.GET)
public ModelAndView findBySearchTemplate(@RequestParam final int searchTemplateId) {
ModelAndView result;
SearchTemplate searchTemplate;
Collection<Chorbi> chorbies;
CreditCard creditCard;
searchTemplate = this.searchTemplateService.findOne(searchTemplateId);
Assert.notNull(searchTemplate);
creditCard = this.creditCardService.findByActor(this.chorbiService.findByPrincipal().getId());
if (this.creditCardService.checkValidation(creditCard) == false || creditCard == null) {
System.out.println("Invalid Credit Card");
result = new ModelAndView("master.page");
result.addObject("message", "searchTemplate.commit.errorCC");
} else {
chorbies = this.searchTemplateService.findChorbiesBySearchTemplate(searchTemplate);
result = new ModelAndView("chorbi/list");
result.addObject("chorbies", chorbies);
result.addObject("principalId", 0);
result.addObject("requestURI", "searchTemplate/chorbi/findBySearchTemplate.do?searchTemplateId=" + searchTemplateId);
}
return result;
}
// Edition ----------------------------------------------------------------
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam final int searchTemplateId) {
ModelAndView result;
SearchTemplate searchTemplate;
searchTemplate = this.searchTemplateService.findOne(searchTemplateId);
Assert.notNull(searchTemplate);
result = this.createEditModelAndView(searchTemplate);
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(@Valid final SearchTemplate searchTemplate, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors()) {
System.out.println(binding.toString());
result = this.createEditModelAndView(searchTemplate);
} else
try {
this.searchTemplateService.save(searchTemplate);
result = new ModelAndView("redirect:display.do");
} catch (final Throwable oops) {
System.out.println(oops.toString());
result = this.createEditModelAndView(searchTemplate, "searchTemplate.commit.error");
}
return result;
}
// Deleting ---------------------------------------------------------------
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(@Valid final SearchTemplate searchTemplate, final BindingResult binding) {
ModelAndView result;
searchTemplate.setRelationshipType(null);
searchTemplate.setApproximateAge(null);
searchTemplate.setSingleKeyword(null);
searchTemplate.setGenre(null);
searchTemplate.setCountry(null);
searchTemplate.setState(null);
searchTemplate.setProvince(null);
searchTemplate.setCity(null);
this.searchTemplateService.save(searchTemplate);
result = new ModelAndView("redirect:display.do");
return result;
}
// Ancillary methods ------------------------------------------------------
protected ModelAndView createEditModelAndView(final SearchTemplate searchTemplate) {
ModelAndView result;
result = this.createEditModelAndView(searchTemplate, null);
return result;
}
protected ModelAndView createEditModelAndView(final SearchTemplate searchTemplate, final String message) {
ModelAndView result;
final Genre[] genres;
final RelationshipType[] relationshipTypes;
genres = Genre.values();
relationshipTypes = RelationshipType.values();
result = new ModelAndView("searchTemplate/edit");
result.addObject("searchTemplate", searchTemplate);
result.addObject("genres", genres);
result.addObject("relationshipTypes", relationshipTypes);
result.addObject("message", message);
return result;
}
}
|
package com.dtstack.logstash.inputs;
public interface IKafkaChg {
/**
* 某个topic对应的分区发生变化,或者消耗的客户端数量发生变化
* @param topicName
* @param consumers
* @param partitions
*/
public void onInfoChgTrigger(String topicName, int consumers, int partitions);
/**
* kafka集群挂掉
*/
public void onClusterShutDown();
}
|
package Servlets;
import Utils.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AllEmissionsServlet
*/
@WebServlet("/AllEmissionsServlet")
public class AllEmissionsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
if(username != null) {
ArrayList<FoodEmission> foodEmissionsList = selectFoodEmissions(username);
ArrayList<TransportEmission> transportEmissionsList = selectTransportEmissions(username);
if(foodEmissionsList != null && transportEmissionsList != null ) {
RequestDispatcher rd = request.getRequestDispatcher("/allEmissions.jsp");
request.setAttribute("FoodEmissions", foodEmissionsList);
request.setAttribute("TransportEmissions", transportEmissionsList);
request.setAttribute("username", username);
rd.forward(request, response);
} else {
out.print("Oops.. Something went wrong!");
request.setAttribute("username", username);
RequestDispatcher rd = request.getRequestDispatcher("main.jsp");
rd.include(request, response);
}
}
}
/* NOTE: REMEMBER TO HANDLE EMPTY TABLES ACCORDINGLY*/
public ArrayList<FoodEmission> selectFoodEmissions(String username) {
ArrayList<FoodEmission> list = null;
ConnectionDetails connDetails = new ConnectionDetails();
Connection conn = connDetails.getConnection();
String sql = "SELECT * FROM FoodEmissions WHERE username=? AND MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, username);
ResultSet rs = preparedStatement.executeQuery();
list = new ArrayList<FoodEmission>();
while (rs.next())
{
String foodType = rs.getString("foodType");
float foodQuantity = rs.getFloat("foodQuantity");
float carbonQuantity = rs.getFloat("carbonQuantity");
Date date = rs.getDate("date");
FoodEmission foodEmission = new FoodEmission();
foodEmission.setUsername(username);
foodEmission.setFoodType(foodType);
foodEmission.setFoodQuantity(foodQuantity);
foodEmission.setCarbonQuantity(carbonQuantity);
foodEmission.setDate(date);
list.add(foodEmission);
}
} catch(SQLException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
return list;
}
public ArrayList<TransportEmission> selectTransportEmissions(String username) {
ArrayList<TransportEmission> list = null;
ConnectionDetails connDetails = new ConnectionDetails();
Connection conn = connDetails.getConnection();
String sql = "SELECT * FROM TransportEmissions WHERE username=? AND MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, username);
ResultSet rs = preparedStatement.executeQuery();
list = new ArrayList<TransportEmission>();
while (rs.next())
{
String transportType = rs.getString("transportType");
float distance = rs.getFloat("distance");
float carbonQuantity = rs.getFloat("carbonQuantity");
Date date = rs.getDate("date");
TransportEmission transportEmission = new TransportEmission();
transportEmission.setUsername(username);
transportEmission.setTransportType(transportType);
transportEmission.setDistance(distance);
transportEmission.setCarbonQuantity(carbonQuantity);
transportEmission.setDate(date);
list.add(transportEmission);
}
} catch(SQLException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
return list;
}
}
|
package com.esum.cluster.module;
import java.io.Serializable;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.cluster.table.ClusterInfoRecord;
import com.esum.framework.common.util.SysUtil;
import com.esum.framework.core.component.ComponentConstants;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.core.event.log.LoggingEvent;
import com.esum.framework.core.event.message.MessageEvent;
import com.esum.framework.core.logger.LoggerConfig;
import com.esum.framework.core.management.ManagementException;
import com.esum.framework.core.management.admin.XTrusAdmin;
import com.esum.framework.core.management.admin.XtrusAdminFactory;
import com.esum.framework.core.management.manager.XTrusManager;
import com.esum.framework.core.queue.JmsMessageHandler;
import com.esum.framework.core.queue.QueueHandlerFactory;
import com.esum.framework.core.queue.QueueMonitorFactory;
import com.esum.framework.core.queue.mq.JmsMessageTypes;
import com.esum.framework.core.queue.mq.JmsQueueMessageHandler;
import com.esum.framework.core.queue.mq.QueueMonitor;
import com.esum.framework.net.queue.HornetQServer;
/**
* Checking the xtrus engine is alive.
*/
public class EngineClusterHandler extends Thread {
private Logger logger = LoggerFactory.getLogger(EngineClusterHandler.class);
private String traceId;
private String nodeId;
private XTrusAdmin admin;
private int interval;
private ClusterInfoRecord infoRecord;
public EngineClusterHandler(ThreadGroup group, String nodeId, ClusterInfoRecord infoRecord) {
super(group, nodeId+"-xtrus-cluster-handler");
this.traceId = "["+nodeId+"][XTRUS] ";
this.nodeId = nodeId;
this.infoRecord = infoRecord;
this.interval = infoRecord.getCheckInterval();
}
public void run() {
logger.debug(traceId+"EngineChecker Starting. checking interval : "+interval);
logger.debug(traceId+"Target node Id : "+infoRecord.getTargetNodeId());
logger.debug(traceId+"Channel Data move : "+infoRecord.isMoveChannelData());
try {
this.admin = XtrusAdminFactory.getInstance().getXtrusAdmin(nodeId);
} catch (ManagementException e) {
logger.error(traceId+"Could not connection to '"+nodeId+"'.", e);
return;
}
logger.debug(traceId+"EngineChecker Starting completed.");
while(!Thread.interrupted()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
break;
}
boolean serverRunning = false;
try {
serverRunning = this.admin.getComponentStatus(LoggerConfig.LOGGER_NAME).equals(
ComponentConstants.STATUS_RUNNING);
} catch (ManagementException e) {
logger.warn(traceId+"xTrus Engine shutdowned. Starting error handling...");
serverRunning = false;
}
logger.debug(traceId+"xTrus Engine status : "+(serverRunning?"STARTED":"STOPPED"));
if(!serverRunning) {
if(recovery()) {
logger.info(traceId+"Xtrus channel data moving completed. stopping the cluster engine.");
break;
}
}
}
logger.warn(traceId+"Xtrus Engine Checking Module Stopped.");
}
private boolean recovery() {
logger.info(traceId+"xTrus Engine Recovery start");
// retry connect to xTrus Server.
logger.info(traceId+"Retrying connection to xTrus Server.");
boolean serverRunning = false;
try {
serverRunning = this.admin.getComponentStatus(LoggerConfig.LOGGER_NAME).equals(
ComponentConstants.STATUS_RUNNING);
} catch (Exception ex) {
serverRunning = false;
}
if(serverRunning)
return false;
if(infoRecord.isMoveChannelData()) {
logger.info(traceId+"Moving channel data to '"+infoRecord.getTargetNodeId()+"' channels.");
XTrusManager xtrusManager = null;
HornetQServer hqServer = null;
try {
Configurator.init(QueueHandlerFactory.CONFIG_QUEUE_HANDLER_ID,
Configurator.getInstance().getString("queue.properties"));
xtrusManager = XTrusManager.getInstance();
xtrusManager.setIpAddress(Configurator.getInstance().getString("manager.ip"));
xtrusManager.setPort(Configurator.getInstance().getInt("manager.port"));
xtrusManager.startup();
xtrusManager.initializeMBeanList();
hqServer = HornetQServer.getInstance();
hqServer.start();
} catch (Exception e) {
logger.error(traceId+"HornetQ Server start failed.", e);
return true;
}
try {
relocateChannelMessages();
} catch (Exception e) {
logger.error(traceId+"Could not reloate channel message.", e);
} finally {
try {
if(xtrusManager!=null)
xtrusManager.shutdown();
} catch (ManagementException ex) {
}
try {
if(hqServer!=null && hqServer.isStarted())
hqServer.stop();
} catch (Exception e) {
}
hqServer=null;
xtrusManager = null;
}
}
return true;
}
private void relocateChannelMessages() throws Exception {
QueueMonitor monitor = QueueMonitorFactory.getInstance(JmsMessageTypes.MQ_TYPE_HORNETQ);
String[] queueNames = monitor.getQueueNames();
if(queueNames==null || queueNames.length==0) {
logger.error(traceId+"Could not found ChannelNames.");
return;
}
try {
for(String channel : queueNames) {
long messageCnt = 0;
try {
messageCnt = monitor.getQueueMessageCount(channel);
} catch (Exception e) {
continue;
}
if(messageCnt==0)
continue;
logger.info(traceId+channel+" has '"+messageCnt+"' messages. Relocating target node : "+infoRecord.getTargetNodeId());
JmsQueueMessageHandler channelHandler = null;
JmsQueueMessageHandler targetHandler = null;
try {
channelHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance(channel);
targetHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance(
"TARGET_"+channel+"_ID",
SysUtil.replacePropertyToValue(infoRecord.getTargetQueueConfigPath()), channel);
for(int i=0;i<messageCnt;i++) {
sendToTarget(targetHandler, channelHandler.receive());
}
} catch(Exception e){
logger.error(traceId+"Channel data moving error.", e);
} finally {
if(channelHandler!=null)
channelHandler.close();
if(targetHandler!=null)
targetHandler.close();
}
}
} finally {
if(monitor!=null)
monitor.close();
}
}
private void sendToTarget(JmsMessageHandler targetHandler, Message message) {
if(message==null)
return;
ObjectMessage om = (ObjectMessage)message;
Serializable m = null;
String messageCtrlId = "";
try {
m = om.getObject();
if(m instanceof MessageEvent) {
messageCtrlId = ((MessageEvent)m).getMessageControlId();
} else if(m instanceof LoggingEvent) {
messageCtrlId = ((LoggingEvent)m).getMessageCtrlId();
}
logger.debug(traceId+"["+messageCtrlId+"] Relocating message. Sending...");
targetHandler.send(m);
logger.info(traceId+"["+messageCtrlId+"] Message Sending completed.");
} catch (JMSException e) {
logger.error(traceId+"["+messageCtrlId+"] Could not read the message.", e);
} finally {
try {
message.acknowledge();
} catch (JMSException e) {
}
message = null;
}
}
public void close() {
logger.info(traceId+"Interrupt requeted.");
interrupt();
}
}
|
package scut218.pisces.utils.impl;
import android.util.Log;
import java.util.List;
import scut218.pisces.Constants;
import scut218.pisces.beans.Friend;
import scut218.pisces.beans.Moment;
import scut218.pisces.beans.User;
import scut218.pisces.factory.UtilFactory;
import scut218.pisces.network.ClientProtoAnalyze;
import scut218.pisces.network.RequestPacker;
import scut218.pisces.proto.MsgProtocol;
import scut218.pisces.utils.NetworkUtil;
import scut218.pisces.utils.UserUtil;
/**
* Created by Lenovo on 2018/5/9.
*/
public class UserUtilImpl implements UserUtil {
public static String id;
@Override
public List<Friend> requestFriends() {
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
long rid=networkUtil.send(packer.rquesetFriendPack(id));
MsgProtocol.msgProtocol msg=networkUtil.receive(rid);
if(msg==null)
{
Log.e("requestFriend","receive error");
return null;
}
ClientProtoAnalyze analyze=new ClientProtoAnalyze();
int type=analyze.getType(msg);
if(type==analyze.ERROR){
/*请求失败*/
Log.e("requestFriend","requestFriend failure");
return null;
}
else return analyze.toFriends(msg);
}catch (Exception e){
e.printStackTrace();
Log.e("requestFriend","send error");
return null;
}
}
@Override
public String getMyId() {
return id;
}
@Override
public List<User> requestProf(String id) {
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
long rid=networkUtil.send(packer.rquesetUserPack(id,this.id));
MsgProtocol.msgProtocol msg=networkUtil.receive(rid);
if(msg==null)
{
Log.e("requestProf","receive error");
return null;
}
ClientProtoAnalyze analyze=new ClientProtoAnalyze();
int type=analyze.getType(msg);
if(type==analyze.ERROR){
/*请求失败*/
Log.e("requestProf","requestProf failure");
return null;
}
else {
List<User> users=analyze.toUsers(msg);
User.userMap.put(users.get(0).getId(),users.get(0));
return users;
}
}catch (Exception e){
e.printStackTrace();
Log.e("requestProf","send error");
return null;
}
}
public int register(User user)
{
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
networkUtil.send(packer.RegisterPack(user));
}catch (Exception e){
e.printStackTrace();
Log.e("register","send error");
return Constants.FAILURE;
}
return Constants.SUCCESS;
}
public int login(String id,String pw)
{
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
long rid=networkUtil.send(packer.LoginPack(id,pw));
MsgProtocol.msgProtocol msg=networkUtil.receive(rid);
Log.e("login","sent");
if(msg==null)
{
Log.e("login","receive error");
return Constants.FAILURE;
}
ClientProtoAnalyze analyze=new ClientProtoAnalyze();
int type=analyze.getType(msg);
if(type==analyze.ERROR){
/*密码错误*/
Log.e("login","authentification failure");
return Constants.WRONGPW;
}
}catch (Exception e){
e.printStackTrace();
Log.e("login","send error");
return Constants.FAILURE;
}
this.id=id;
return Constants.SUCCESS;
}
public int updateProf(User user)
{
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
long rid=networkUtil.send(packer.UpdateprofilePack(user));
MsgProtocol.msgProtocol msg=networkUtil.receive(rid);
if(msg==null)
{
Log.e("updateProf","receive error");
return Constants.FAILURE;
}
ClientProtoAnalyze analyze=new ClientProtoAnalyze();
int type=analyze.getType(msg);
if(type==analyze.ERROR){
Log.e("updateProf","updateProf failure");
return Constants.WRONGPW;
}
}catch (Exception e){
e.printStackTrace();
Log.e("updateProf","send error");
return Constants.FAILURE;
}
return Constants.SUCCESS;
}
public int addFriend(Friend friend){
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
networkUtil.send(packer.AddFriendPack(friend));
}catch (Exception e){
e.printStackTrace();
Log.e("addFriend","send error");
return Constants.FAILURE;
}
return Constants.SUCCESS;
}
public int deleteFriend(String friendId){
RequestPacker packer=new RequestPacker();
NetworkUtil networkUtil= UtilFactory.getNetworkUtil();
try{
networkUtil.send(packer.DeletePack(friendId,packer.DELETEFRIEND,id));
}catch (Exception e){
e.printStackTrace();
Log.e("deleteFriend","send error");
return Constants.FAILURE;
}
return Constants.SUCCESS;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.credential;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.exceptions.IllegalCredentialException;
import pl.edu.icm.unity.exceptions.InternalException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Used to express a new password for {@link PasswordVerificator}. Implements serialization to/from JSON.
* <pre>
* {
* "existingPassword" : "existingPassword"
* "password": "password",
* "question": "NUMBER",
* "answer": "answer"
* }
* </pre>
* @author K. Benedyczak
*/
public class PasswordToken
{
private String password;
private String existingPassword = null;
private int question = -1;
private String answer = null;
private PasswordToken()
{
}
public PasswordToken(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getExistingPassword()
{
return existingPassword;
}
public void setExistingPassword(String existingPassword)
{
this.existingPassword = existingPassword;
}
public int getQuestion()
{
return question;
}
public void setQuestion(int question)
{
this.question = question;
}
public String getAnswer()
{
return answer;
}
public void setAnswer(String answer)
{
this.answer = answer;
}
public JsonNode toJsonNode()
{
ObjectNode root = Constants.MAPPER.createObjectNode();
if (existingPassword != null)
root.put("existingPassword", existingPassword);
root.put("password", password);
if (answer != null)
{
root.put("answer", answer);
root.put("question", question);
}
return root;
}
public String toJson()
{
try
{
JsonNode root = toJsonNode();
return Constants.MAPPER.writeValueAsString(root);
} catch (JsonProcessingException e)
{
throw new InternalException("Can't serialize password credential to JSON", e);
}
}
public static PasswordToken loadFromJson(String json) throws IllegalCredentialException
{
try
{
PasswordToken ret = new PasswordToken();
ObjectNode inputNode = (ObjectNode) Constants.MAPPER.readTree(json);
ret.password = inputNode.get("password").asText();
if (inputNode.has("existingPassword"))
ret.existingPassword = inputNode.get("existingPassword").asText();
if (inputNode.has("answer"))
ret.answer = inputNode.get("answer").asText();
if (inputNode.has("question"))
ret.question = inputNode.get("question").asInt();
return ret;
} catch (Exception e)
{
throw new IllegalCredentialException("The supplied credential definition has invlid syntax", e);
}
}
}
|
package com.pattern.program.mycode;
public class Pattern10{
public static void main(String[] args) {
int input=5;
for(int row=1;row<=5;row++){
for(int data=1;data<=5; data++){
if(row==3||data==3) {
System.out.print(input);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
|
package com.sinodynamic.hkgta.service.fms;
import java.util.List;
import com.sinodynamic.hkgta.dto.fms.FacilityUtilizationRateListDto;
import com.sinodynamic.hkgta.entity.fms.FacilityUtilizationRateTime;
import com.sinodynamic.hkgta.service.IServiceBase;
public interface FacilityUtilizationRateTimeService extends IServiceBase<FacilityUtilizationRateTime> {
public void saveFacilityUtilizationRateTime(FacilityUtilizationRateListDto facilityUtilizationRateDateListDto,String userId);
List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeList(String facilityType,String weekDay, String subType);
List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeList(String facilityType);
List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeListBySubType(String facilityType,String facilitySubtypeId);
}
|
package rally;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Teams {
private HashMap<String, Team> teams;
@Value("${teams}")
private String teamsValue;
@Autowired
public void loadTeams() {
teams = new HashMap<>();
for(String name : teamsValue.split(",")) {
teams.put(name, new Team(name));
}
}
public void addTeam(String name, Team team) {
teams.put(name, team);
}
public Team getTeam(String name) {
return teams.get(name);
}
public HashMap<String, Team> getTeams() {
return teams;
}
}
|
package com.culturaloffers.maps.repositories;
import com.culturaloffers.maps.model.OfferNews;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OfferNewsRepository extends JpaRepository<OfferNews, Integer> {
OfferNews findByTitle(String title);
List<OfferNews> findByCulturalOfferId(int id);
Page<OfferNews> findByCulturalOfferId(int id, Pageable pageable);
}
|
package example.awarnessapi;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.awareness.Awareness;
import com.google.android.gms.awareness.snapshot.DetectedActivityResult;
import com.google.android.gms.awareness.snapshot.HeadphoneStateResult;
import com.google.android.gms.awareness.snapshot.LocationResult;
import com.google.android.gms.awareness.snapshot.PlacesResult;
import com.google.android.gms.awareness.snapshot.WeatherResult;
import com.google.android.gms.awareness.state.HeadphoneState;
import com.google.android.gms.awareness.state.Weather;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* This activity will demonstrate how to use snapshot apis.
*
* @see 'https://developers.google.com/awareness/android-api/snapshot-get-data'
*/
public class SnapshotApiActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks {
private static final int GET_LOCATION_PERMISSION_REQUEST_CODE = 12345;
private static final int GET_PLACE_PERMISSION_REQUEST_CODE = 123456;
private static final int GET_WEATHER_PERMISSION_REQUEST_CODE = 1234567;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snapshot);
buildApiClient();
}
/**
* Build the google api client to use awareness apis.
*/
private void buildApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(SnapshotApiActivity.this)
.addApi(Awareness.API)
.addConnectionCallbacks(this)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable final Bundle bundle) {
//Google API client connected.
//ready to use awareness api
callSnapShotGroupApis();
}
/**
* This method will call all the snap shot group apis.
*/
private void callSnapShotGroupApis() {
//get info about user's current activity
getCurrentActivity();
//get the current state of the headphones.
getHeadphoneStatus();
//get current location. This will need location permission, so first check that.
if (ContextCompat.checkSelfPermission(SnapshotApiActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
SnapshotApiActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
GET_LOCATION_PERMISSION_REQUEST_CODE);
} else {
getLocation();
}
//get current place. This will need location permission, so first check that.
if (ContextCompat.checkSelfPermission(SnapshotApiActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
SnapshotApiActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
GET_PLACE_PERMISSION_REQUEST_CODE);
} else {
getPlace();
}
//get current weather conditions. This will need location permission, so first check that.
if (ContextCompat.checkSelfPermission(SnapshotApiActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
SnapshotApiActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
GET_WEATHER_PERMISSION_REQUEST_CODE);
} else {
getWeather();
}
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case GET_LOCATION_PERMISSION_REQUEST_CODE://location permission granted
//noinspection MissingPermission
getLocation();
break;
case GET_PLACE_PERMISSION_REQUEST_CODE://location permission granted
//noinspection MissingPermission
getPlace();
break;
case GET_WEATHER_PERMISSION_REQUEST_CODE://location permission granted
//noinspection MissingPermission
getWeather();
break;
}
}
}
/**
* Get the current weather condition at current location.
*/
@RequiresPermission("android.permission.ACCESS_FINE_LOCATION")
private void getWeather() {
//noinspection MissingPermission
Awareness.SnapshotApi.getWeather(mGoogleApiClient)
.setResultCallback(new ResultCallback<WeatherResult>() {
@Override
public void onResult(@NonNull WeatherResult weatherResult) {
if (!weatherResult.getStatus().isSuccess()) {
Toast.makeText(SnapshotApiActivity.this, "Could not get weather.", Toast.LENGTH_LONG).show();
return;
}
//parse and display current weather status
Weather weather = weatherResult.getWeather();
String weatherReport = "Temperature: " + weather.getTemperature(Weather.CELSIUS)
+ "\nHumidity: " + weather.getHumidity();
((TextView) findViewById(R.id.weather_status)).setText(weatherReport);
}
});
}
/**
* Get the nearby places using Snapshot apis. We are going to display only first 5 places to the user in the list.
*/
@RequiresPermission("android.permission.ACCESS_FINE_LOCATION")
private void getPlace() {
//noinspection MissingPermission
Awareness.SnapshotApi.getPlaces(mGoogleApiClient)
.setResultCallback(new ResultCallback<PlacesResult>() {
@Override
public void onResult(@NonNull final PlacesResult placesResult) {
if (!placesResult.getStatus().isSuccess()) {
Toast.makeText(SnapshotApiActivity.this, "Could not get places.", Toast.LENGTH_LONG).show();
return;
}
//get the list of all like hood places
List<PlaceLikelihood> placeLikelihoodList = placesResult.getPlaceLikelihoods();
// Show the top 5 possible location results.
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.current_place_container);
linearLayout.removeAllViews();
if (placeLikelihoodList != null) {
for (int i = 0; i < 5 && i < placeLikelihoodList.size(); i++) {
PlaceLikelihood p = placeLikelihoodList.get(i);
//add place row
View v = LayoutInflater.from(SnapshotApiActivity.this).inflate(R.layout.row_nearby_place, linearLayout, false);
((TextView) v.findViewById(R.id.place_name)).setText(p.getPlace().getName());
((TextView) v.findViewById(R.id.place_address)).setText(p.getPlace().getAddress());
linearLayout.addView(v);
}
} else {
Toast.makeText(SnapshotApiActivity.this, "Could not get nearby places.", Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Get user's current location. We are also displaying Google Static map.
*/
@RequiresPermission("android.permission.ACCESS_FINE_LOCATION")
private void getLocation() {
//noinspection MissingPermission
Awareness.SnapshotApi.getLocation(mGoogleApiClient)
.setResultCallback(new ResultCallback<LocationResult>() {
@Override
public void onResult(@NonNull LocationResult locationResult) {
if (!locationResult.getStatus().isSuccess()) {
Toast.makeText(SnapshotApiActivity.this, "Could not get location.", Toast.LENGTH_LONG).show();
return;
}
//get location
Location location = locationResult.getLocation();
((TextView) findViewById(R.id.current_latlng)).setText(location.getLatitude() + ", " + location.getLongitude());
//display the time
TextView timeTv = (TextView) findViewById(R.id.latlng_time);
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a dd-MM-yyyy", Locale.getDefault());
timeTv.setText("as on: " + sdf.format(new Date(location.getTime())));
//Load the current map image from Google map
String url = "https://maps.googleapis.com/maps/api/staticmap?center="
+ location.getLatitude() + "," + location.getLongitude()
+ "&zoom=20&size=400x250&key=" + getString(R.string.api_key);
Picasso.with(SnapshotApiActivity.this).load(url).into((ImageView) findViewById(R.id.current_map));
}
});
}
/**
* Check weather the headphones are plugged in or not? This is under snapshot api category.
*/
private void getHeadphoneStatus() {
Awareness.SnapshotApi.getHeadphoneState(mGoogleApiClient)
.setResultCallback(new ResultCallback<HeadphoneStateResult>() {
@Override
public void onResult(@NonNull HeadphoneStateResult headphoneStateResult) {
if (!headphoneStateResult.getStatus().isSuccess()) {
Toast.makeText(SnapshotApiActivity.this, "Could not get headphone state.", Toast.LENGTH_LONG).show();
return;
}
HeadphoneState headphoneState = headphoneStateResult.getHeadphoneState();
//display the status
TextView headphoneStatusTv = (TextView) findViewById(R.id.headphone_status);
headphoneStatusTv.setText(headphoneState.getState() == HeadphoneState.PLUGGED_IN ? "Plugged in." : "Unplugged.");
}
});
}
/**
* Get current activity of the user. This is under snapshot api category.
* Current activity and confidence level will be displayed on the screen.
*/
private void getCurrentActivity() {
Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
.setResultCallback(new ResultCallback<DetectedActivityResult>() {
@Override
public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
if (!detectedActivityResult.getStatus().isSuccess()) {
Toast.makeText(SnapshotApiActivity.this, "Could not get the current activity.", Toast.LENGTH_LONG).show();
return;
}
ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult();
DetectedActivity probableActivity = ar.getMostProbableActivity();
//set the activity name
TextView activityName = (TextView) findViewById(R.id.probable_activity_name);
switch (probableActivity.getType()) {
case DetectedActivity.IN_VEHICLE:
activityName.setText("In vehicle");
break;
case DetectedActivity.ON_BICYCLE:
activityName.setText("On bicycle");
break;
case DetectedActivity.ON_FOOT:
activityName.setText("On foot");
break;
case DetectedActivity.RUNNING:
activityName.setText("Running");
break;
case DetectedActivity.STILL:
activityName.setText("Still");
break;
case DetectedActivity.TILTING:
activityName.setText("Tilting");
break;
case DetectedActivity.UNKNOWN:
activityName.setText("Unknown");
break;
case DetectedActivity.WALKING:
activityName.setText("Walking");
break;
}
//set the confidante level
ProgressBar confidenceLevel = (ProgressBar) findViewById(R.id.probable_activity_confidence);
confidenceLevel.setProgress(probableActivity.getConfidence());
//display the time
TextView timeTv = (TextView) findViewById(R.id.probable_activity_time);
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a dd-MM-yyyy", Locale.getDefault());
timeTv.setText("as on: " + sdf.format(new Date(ar.getTime())));
}
});
}
@Override
public void onConnectionSuspended(final int i) {
new AlertDialog.Builder(this)
.setMessage("Cannot connect to google api services.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialogInterface, final int i) {
finish();
}
}).show();
}
}
|
package kr.waytech.attendancecheck_beacon.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import kr.waytech.attendancecheck_beacon.R;
import kr.waytech.attendancecheck_beacon.other.Utils;
import kr.waytech.attendancecheck_beacon.server.SelectUserDB;
import kr.waytech.attendancecheck_beacon.server.UserData;
/**
* 모바일프로그래밍 프로젝트
* beacon을 이용한 출석체크 앱
* 로그인 액티비티
*/
public class LoginActivity extends AppCompatActivity {
private EditText etId;
private EditText etPassword;
private Button btnLogin;
private ImageView ivSign;
private SharedPreferences pref;
private SharedPreferences.Editor edit;
private ProgressDialog progressDialog;
private InputMethodManager imm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
findById();
init();
// 자동로그인
if (pref.getBoolean(Utils.PREF_AUTOLOGIN, false)) {
String type = pref.getString(Utils.PREF_TYPE, null);
Intent intent = null;
if (type.equals(Utils.USER_STD))
intent = new Intent(LoginActivity.this, StdActivity.class);
else if (type.equals(Utils.USER_EDU))
intent = new Intent(LoginActivity.this, EduActivity.class);
else
return;
startActivity(intent);
finish();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Utils.closePopup(this);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
private void findById() {
etId = (EditText) findViewById(R.id.etId);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
ivSign = (ImageView) findViewById(R.id.ivSign);
}
private void init() {
pref = getSharedPreferences(getPackageName(), 0);
edit = pref.edit();
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
ivSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!Utils.isOnline(LoginActivity.this)) {
Toast.makeText(LoginActivity.this, "인터넷 상태를 확인해주세요", Toast.LENGTH_SHORT).show();
return;
}
if (etId.getText().length() == 0 || etPassword.getText().length() == 0) {
Toast.makeText(LoginActivity.this, "빈칸을 입력해주세요", Toast.LENGTH_SHORT).show();
return;
}
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.show();
new SelectUserDB(mHandler).execute(etId.getText().toString(), etPassword.getText().toString());
}
});
}
public void linearClick(View v) {
imm.hideSoftInputFromWindow(etId.getWindowToken(), 0);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(progressDialog.isShowing())
progressDialog.dismiss();
switch (msg.what) {
case SelectUserDB.HANDLE_SELECT_OK:
UserData data = (UserData) msg.obj;
edit.putString(Utils.PREF_ID, data.getId());
edit.putString(Utils.PREF_TYPE, data.getType());
edit.putBoolean(Utils.PREF_AUTOLOGIN, true);
edit.putString(Utils.PREF_NAME, data.getName());
edit.commit();
Intent intent = null;
if (data.getType().equals(Utils.USER_STD))
intent = new Intent(LoginActivity.this, StdActivity.class);
else if (data.getType().equals(Utils.USER_EDU))
intent = new Intent(LoginActivity.this, EduActivity.class);
else
return;
Toast.makeText(LoginActivity.this, data.getName() + "님 환영합니다.", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
break;
case SelectUserDB.HANDLE_SELECT_FAIL:
Toast.makeText(LoginActivity.this, "아이디와 비밀번호를 확인해주세요", Toast.LENGTH_SHORT).show();
break;
}
}
};
}
|
package no.nav.vedtak.felles.integrasjon.felles.ws;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import no.nav.vedtak.log.mdc.MDCOperations;
class MDCOperationsTest {
public static final String DUMMY_FNR = "00000000000";
@Test
void test_generateCallId() {
String callId1 = MDCOperations.generateCallId();
assertThat(callId1).isNotNull();
String callId2 = MDCOperations.generateCallId();
assertThat(callId2).isNotNull().isNotEqualTo(callId1);
}
@Test
void test_mdc() {
MDCOperations.putToMDC("myKey", "myValue");
assertThat(MDCOperations.getFromMDC("myKey")).isEqualTo("myValue");
MDCOperations.remove("myKey");
assertThat(MDCOperations.getFromMDC("myKey")).isNull();
}
@Test
void mask_fnr() {
MDCOperations.putUserId(DUMMY_FNR);
var userId = MDCOperations.getUserId();
assertThat(userId).isEqualTo("000000*****");
MDCOperations.putUserId("ikkefnr");
var userId2 = MDCOperations.getUserId();
assertThat(userId2).isEqualTo("ikkefnr");
}
}
|
package templatemethod2;
/**
*
*
* GraduateAdvising extinde clasa Advising.
* Un obiect creat folosind clasa GraduateAdvising poate fi folosit
* oriunde un obiect Advising este folosit.
*
*/
public class GraduateAdvising extends Advising {
/**
*
* Pentru acest pas al proecsului clasa GraduateAdvising
* defineste propria implementare pentru metoda findAdvisor
* din moment ce fiecare clasa copil al clasei Advising
* trebuie sa faca ceva diferit in aceasta etapa a algoritmului.
*/
public void findAdvisor() {
System.out.println("Gasire consilier pentru student promovat...");
}
@Override
public String toString() {
return "Avizare proces pentru student promovat" ;
}
}
|
/**
*/
package org.eclipse.pss.dsl.metamodel.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.pss.dsl.metamodel.Action_invocation;
import org.eclipse.pss.dsl.metamodel.Component_Invocation;
import org.eclipse.pss.dsl.metamodel.MetamodelPackage;
import org.eclipse.pss.dsl.metamodel.RootComponent;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Root Component</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.eclipse.pss.dsl.metamodel.impl.RootComponentImpl#getComponent_invocation <em>Component invocation</em>}</li>
* <li>{@link org.eclipse.pss.dsl.metamodel.impl.RootComponentImpl#getAction_invocation <em>Action invocation</em>}</li>
* </ul>
*
* @generated
*/
public class RootComponentImpl extends Abstract_ComponentImpl implements RootComponent {
/**
* The cached value of the '{@link #getComponent_invocation() <em>Component invocation</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getComponent_invocation()
* @generated
* @ordered
*/
protected EList<Component_Invocation> component_invocation;
/**
* The cached value of the '{@link #getAction_invocation() <em>Action invocation</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAction_invocation()
* @generated
* @ordered
*/
protected Action_invocation action_invocation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RootComponentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MetamodelPackage.Literals.ROOT_COMPONENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EList<Component_Invocation> getComponent_invocation() {
if (component_invocation == null) {
component_invocation = new EObjectContainmentEList<Component_Invocation>(Component_Invocation.class, this,
MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION);
}
return component_invocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION:
return ((InternalEList<?>) getComponent_invocation()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Action_invocation getAction_invocation() {
if (action_invocation != null && action_invocation.eIsProxy()) {
InternalEObject oldAction_invocation = (InternalEObject) action_invocation;
action_invocation = (Action_invocation) eResolveProxy(oldAction_invocation);
if (action_invocation != oldAction_invocation) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION, oldAction_invocation,
action_invocation));
}
}
return action_invocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Action_invocation basicGetAction_invocation() {
return action_invocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setAction_invocation(Action_invocation newAction_invocation) {
Action_invocation oldAction_invocation = action_invocation;
action_invocation = newAction_invocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION,
oldAction_invocation, action_invocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION:
return getComponent_invocation();
case MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION:
if (resolve)
return getAction_invocation();
return basicGetAction_invocation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION:
getComponent_invocation().clear();
getComponent_invocation().addAll((Collection<? extends Component_Invocation>) newValue);
return;
case MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION:
setAction_invocation((Action_invocation) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION:
getComponent_invocation().clear();
return;
case MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION:
setAction_invocation((Action_invocation) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MetamodelPackage.ROOT_COMPONENT__COMPONENT_INVOCATION:
return component_invocation != null && !component_invocation.isEmpty();
case MetamodelPackage.ROOT_COMPONENT__ACTION_INVOCATION:
return action_invocation != null;
}
return super.eIsSet(featureID);
}
} //RootComponentImpl
|
package com.cb.cbfunny.fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.VolleyError;
import com.cb.cbfunny.R;
import com.cb.cbfunny.ResideMenu.ResideMenu;
import com.cb.cbfunny.activity.MainActivity;
import com.cb.cbfunny.qbxx.adapter.QbxxFragmentAdapter;
import com.cb.cbfunny.ui.PagerSlidingTabStrip;
import org.json.JSONObject;
public class QbxxFragment extends BaseFragment {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String TAG = "QbxxFragment";
private View parentView;
private ResideMenu resideMenu;
private PagerSlidingTabStrip pagerTab;
private ViewPager mViewPager;
private QbxxFragmentAdapter adapter;
private static String[] TabData = new String[3];
public static QbxxFragment getInstance(){
return new QbxxFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
private void initData() {
TabData[0] = getString(R.string.qbxx_tab_mz);
TabData[1] = getString(R.string.qbxx_tab_db);
TabData[2] = getString(R.string.qbxx_tab_xe);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
parentView = inflater.inflate(R.layout.fmlayout_qbxx, container, false);
setUpViews(parentView);
return parentView;
}
private void setUpViews(View v) {
MainActivity parentActivity = (MainActivity) getActivity();
resideMenu = parentActivity.getResideMenu();
pagerTab = (PagerSlidingTabStrip) v.findViewById(R.id.tab_strip);
mViewPager = (ViewPager) v.findViewById(R.id.qbxx_view_pager);
adapter = new QbxxFragmentAdapter(getActivity().getSupportFragmentManager(),TabData);
mViewPager.setAdapter(adapter);
mViewPager.setOffscreenPageLimit(2);
pagerTab.setViewPager(mViewPager);
// add gesture operation's ignored views
resideMenu.addIgnoredView(parentView);
}
@Override
public String getFragmentTag() {
return TAG;
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(JSONObject response) {
}
@Override
public void onResponse(String response) {
}
}
|
package ru.job4j.crud.models;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author Sir-Hedgehog (mailto:quaresma_08@mail.ru)
* @version 1.0
* @since 18.02.2020
*/
public class MemoryStore implements Store {
private CopyOnWriteArrayList<User> users;
private static MemoryStore memoryInstance = new MemoryStore();
public MemoryStore() {
this.users = new CopyOnWriteArrayList<>();
}
/**
* Метод дает право создать единственный экземпляр класса для взаимосвязи с логическим (валидационным) блоком проекта
* @return - экземпляр класса MemoryStore
*/
public static MemoryStore getInstance() {
return memoryInstance;
}
/**
* Метод добавляет пользователя
* @param user - пользователь
* @return - успешность операции
*/
@Override
public boolean add(User user) {
return this.users.add(user);
}
/**
* Метод обновляет данные существующего пользователя
* @param id - идентификатор существующего пользователя
* @param recent - новые данные о пользователе
* @return - успешность операции
*/
@Override
public boolean update(int id, User recent) {
boolean result = false;
for (User old : users) {
if (id == old.getId()) {
old.setName(recent.getName());
old.setLogin(recent.getLogin());
old.setEmail(recent.getEmail());
result = true;
break;
}
}
return result;
}
/**
* Метод удаляет существующего пользователя
* @param id - идентификатор существующего пользователя
* @return - успешность операции
*/
@Override
public boolean delete(int id) {
boolean result = false;
for (User user : users) {
if (id == user.getId()) {
this.users.remove(user);
result = true;
break;
}
}
return result;
}
/**
* Метод получает список существующих пользователей
* @return - список существующих пользователей
*/
@Override
public CopyOnWriteArrayList<User> findAll() {
return this.users;
}
/**
* Метод получает данные существующего пользователя по id
* @param id - идентификатор существующего пользователя
* @return - данные существующего пользователя
*/
@Override
public User findById(int id) {
User result = null;
for (User user : users) {
if (id == user.getId()) {
result = user;
}
}
return result;
}
}
|
package br.com.amaro.demo.repositories;
import br.com.amaro.demo.entities.SimilarProduct;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Repository for the database transactions of similar product entities
*
* @see SimilarProduct
*
* @author Marine Muniz
* @version 1.0.0
*/
@Repository
public interface SimilarProductRepository extends CrudRepository<SimilarProduct, Integer> {
/**
* Method responsible for searching similar products in token using the UID product.
*
* @see Pageable
* @see SimilarProduct
*
* @param pageable the limit resources object
* @param productUid the unique product identifier
* @return the database entity of product
*/
@Query(value = "SELECT sp FROM SimilarProduct sp WHERE sp.token LIKE %:productUid% ORDER BY sp.similarity DESC")
List<SimilarProduct> findByToken(final String productUid, final Pageable pageable);
/**
* Responsible method in returning the similarity between two products
*
* @param newProductUid uid of the new producer
* @param productUid uid of the product already registered in the database
* @param pageable quantity of products to be returned
* @return list of similar products
*/
@Query(value = "SELECT sp FROM SimilarProduct sp WHERE sp.token LIKE %:newProductUid% AND sp.token LIKE %:productUid% ORDER BY sp.similarity DESC")
List<SimilarProduct> findByTokens(final String newProductUid, final String productUid, final Pageable pageable);
}
|
package com.egswebapp.egsweb.repasotory;
import com.egswebapp.egsweb.model.UserToken;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
@Deprecated
public interface UserTokenRepository extends JpaRepository<UserToken, String> {
/**
*
* Get user token by user id
*
// */
@Query("SELECT u FROM UserToken as u WHERE u.user.id=?1")
Optional<UserToken> getUserToken(String userId);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.