text
stringlengths
10
2.72M
package com.recrutationproject.recrutationproject; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class RecrutationprojectApplicationTests { @Test void contextLoads() { } }
// Kathryn Brusewitz // Bellevue College CS211 // Instructor - Bill Iverson // Chapter 13 - Runtime Complexity with Collections.sort() import java.util.*; public class Testing { public static void main(String[] args) { int randomRange = 5000000; // Random number range int min = 1000; // Starting number of elements int max = 4096000; // Final maximum number of elements // n is number of elements for (int n = min; n <= max; n *= 2) { // Double n for every loop // Create a list of n random elements List<Integer> list = new ArrayList<Integer>(); Random random = new Random(); // Random number stream for (int i = 0; i < n; i++) { int randomElement = random.nextInt(randomRange); list.add(randomElement); } // Obtain time it takes to sort list double timeStart = System.currentTimeMillis(); Collections.sort(list); double timeEnd = System.currentTimeMillis(); // Print number of elements and time results double time = timeEnd - timeStart; System.out.println(n + ", " + time); } } }
package com.cos.springlegacy.dto; import lombok.Data; @Data public class RequestJsonDto { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
package com.example.hotelmange; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.ParseException; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class ConfirmOrder extends Activity implements OnItemSelectedListener { JSONArray jArray; String result = null; InputStream is = null; StringBuilder sb=null; private Button add, selectOk, selectCancel, loginCancel, loginOk, selectRemove; private Button minus; private String a, selecteditemname, selecteditemprice, selecteditemId, selecteditemPricePerUnit; private Integer b = 1, inc, value, value2, value3, c, dec; private EditText Quantity; private EditText Itemname, ItemPrice , Remarks; protected ListAdapter arrayadapter; protected ListView OrderedItemList; protected Cursor cursor; protected Cursor cursor1; private TextView EditTotal; private Spinner spinner2; private String selectedTable; private String ServerName; private String SourceName; public static String tid; Context context = this; private ListView listView; /** Called when the activity is first created. */ @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.confirm_order); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); addItemsOnSpinner2(); // addListenerOnButton(); // addListenerOnSpinnerItemSelection(); // Toast.makeText(getApplicationContext(), selectedTable, // Toast.LENGTH_LONG).show(); selectedTable = spinner2.getSelectedItem().toString(); spinner2.setOnItemSelectedListener(this); final SQLiteDatabase db = (new DataBaseHelper(this)) .getWritableDatabase(); Cursor cursor3 = db .rawQuery( "SELECT _id,ServerName,SourceName FROM Setting ", new String[] { }); if (cursor3.getCount() == 1) { cursor3.moveToFirst(); ServerName = (cursor3.getString(cursor3 .getColumnIndex("ServerName"))); SourceName=(cursor3.getString(cursor3 .getColumnIndex("SourceName"))); } /* Button btn_mainmenu = (Button) findViewById(R.id.btn_order_mainmenu); btn_mainmenu.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { final Dialog dialog = new Dialog(ConfirmOrder.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.menu_login); loginCancel = (Button) dialog .findViewById(R.id.btn_login_cancel); loginOk = (Button) dialog.findViewById(R.id.btn_login_ok); loginCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { dialog.cancel(); } }); loginOk.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { final EditText passwd = (EditText) dialog .findViewById(R.id.txt_pwd); final String loginPasswd = passwd.getText().toString(); if (loginPasswd.equals("admin")) { Intent myIntent = new Intent( getApplicationContext(), MainActivity.class); startActivity(myIntent); } else { showNoticeDialogBox("Message", "Incorrect Password"); } } }); dialog.show(); } }); */ Button btn_Submit = (Button) findViewById(R.id.btn_submit); btn_Submit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { syncfromdbtid(); // ConnectivityManager connMgr = (ConnectivityManager) this // .getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager connMgr =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo wifi = connMgr .getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = connMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if( (wifi.isAvailable()) || (mobile.isAvailable())) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); // set title alertDialogBuilder.setTitle("Alert"); // set dialog message alertDialogBuilder .setMessage("Do you want to Confirm the Order?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { selectedTable = spinner2 .getSelectedItem().toString(); // db.execSQL("INSERT INTO Ordereditem SELECT * FROM customer WHERE CustTable = "+selectedTable // ); // db.execSQL("DELETE FROM customer WHERE CustTable = "+selectedTable // ); // Intent myIntent = new // Intent(getApplicationContext(),Welcome.class); // startActivity(myIntent); // db.execSQL("INSERT INTO Ordereditem SELECT _id,CustTable FROM customer WHERE "); db.execSQL("INSERT INTO Ordereditem SELECT * FROM customer WHERE CustTable ='"+selectedTable+"'"); db.execSQL("DELETE FROM customer WHERE CustTable ='"+selectedTable+"'"); UpdateList(); startSync(); // db.execSQL("DELETE FROM Ordereditem"); db.execSQL("DELETE FROM MenuItem"); syncfromdbmenu(); Toast.makeText(getApplicationContext(), "Data has been synched successfully", Toast.LENGTH_SHORT).show(); db.execSQL("DELETE FROM Ordereditem"); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } else { Toast.makeText(getApplicationContext(), "No Internet Connection Available", Toast.LENGTH_LONG).show(); } } }); Button btn_cancel = (Button) findViewById(R.id.btn_cancel); btn_cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); // set title alertDialogBuilder.setTitle("Alert"); // set dialog message alertDialogBuilder .setMessage("Do you want to Cancel the Order ?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // db.execSQL("INSERT INTO Ordereditem SELECT * FROM customer"); db.execSQL("DELETE FROM customer WHERE CustTable ='"+selectedTable+"'"); UpdateList(); Toast.makeText(getApplicationContext(), " Order Cancelled", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); Button btn_Later = (Button) findViewById(R.id.btn_later); btn_Later.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); // set title alertDialogBuilder.setTitle("Alert"); // set dialog message alertDialogBuilder .setMessage("Do you want to Confirm the Order Later?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // db.execSQL("INSERT INTO Ordereditem SELECT * FROM customer"); // db.execSQL("DELETE FROM customer"); Toast.makeText(getApplicationContext(), "Later Can take Order", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); /* * * * Button btnpizza=(Button)findViewById(R.id.btn_layout_pizza); * * btnpizza.setOnClickListener(new View.OnClickListener() { * * public void onClick(View view) { * * * List<HashMap<String,String>> aList1 = new * ArrayList<HashMap<String,String>>(); * * for(int i=0;i<5;i++){ HashMap<String, String> hm = new * HashMap<String,String>(); hm.put("txt", "" + countries[i]); * hm.put("cur","" + currency[i]); hm.put("price", ""+price[i]); * hm.put("flag", Integer.toString(flags[i]) ); aList1.add(hm); } * * // Keys used in Hashmap String[] from = { "flag","txt","cur","price" * }; * * // Ids of views in listview_layout int[] to = { * R.id.item_photo,R.id.item_name,R.id.item_desc,R.id.item_price}; * * // Instantiating an adapter to store each items // * R.layout.listview_layout defines the layout of each item * SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList1, * R.layout.item_details_view, from, to); * * // Getting a reference to listview of main.xml layout file ListView * listView = ( ListView ) findViewById(R.id.listView_item); * * // Setting the adapter to the listView listView.setAdapter(adapter); * * } }); */ final Cursor cursor1 = db .rawQuery( "SELECT _id,ItemID,CustTable,ItemName,Quantity,PricePerUnit,TotalPrice,Status,Remarks,Billed FROM customer WHERE CustTable = ?", new String[] { "" + selectedTable }); /* * while(cursor.moveToNext()) { * db_results.add(String.valueOf(cursor.getDouble * (cursor.getColumnIndex("ItemID")))); } */ OrderedItemList = (ListView) findViewById(R.id.listView_ordereditem); arrayadapter = new SimpleCursorAdapter(this, R.layout.gift_text_image, cursor1, new String[] { "ItemName", "Quantity", "TotalPrice", "Remarks", "ItemID", "PricePerUnit" }, new int[] { R.id.txtview_productname, R.id.txtview_Quantity, R.id.txtview_Price, R.id.txtview_ItemRemarks, R.id.txtview_ItemId, R.id.txtview_ItemPricePerunit }); OrderedItemList.setAdapter(arrayadapter); OrderedItemList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { /* * Intent myIntent = new Intent(view.getContext(), * SelectedProduct.class); * myIntent.putExtra("selectedproduct_price", * selectedProductPrice); * myIntent.putExtra("selectedproduct_name", selectedProductName * ); myIntent.putExtra("selectedproduct_link", selectedLink ); * startActivity(myIntent); */ selecteditemId = ((TextView) view .findViewById(R.id.txtview_ItemId)).getText() .toString(); selecteditemPricePerUnit = ((TextView) view .findViewById(R.id.txtview_ItemPricePerunit)).getText() .toString(); final Dialog dialog = new Dialog(ConfirmOrder.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.alert_update_page); Cursor cursor3 = db .rawQuery( "SELECT _id,ItemID,CustTable,ItemName,Quantity,PricePerUnit,TotalPrice,Status,Remarks,Billed FROM customer WHERE ItemID=?", new String[] { "" + selecteditemId }); if (cursor3.getCount() == 1) { cursor3.moveToFirst(); EditTotal = (TextView) findViewById(R.id.txt_Total); Itemname = (EditText) dialog .findViewById(R.id.txt_itemname); Itemname.setClickable(false); Itemname.setFocusable(false); Itemname.setText(cursor3.getString(cursor3 .getColumnIndex("ItemName"))); ItemPrice = (EditText) dialog.findViewById(R.id.txt_price); ItemPrice.setClickable(false); ItemPrice.setFocusable(false); ItemPrice.setText(cursor3.getString(cursor3 .getColumnIndex("TotalPrice"))); Quantity = (EditText) dialog .findViewById(R.id.txt_quantity); Quantity.setClickable(false); Quantity.setFocusable(false); Quantity.setText(cursor3.getString(cursor3 .getColumnIndex("Quantity"))); Remarks = (EditText) dialog .findViewById(R.id.txt_remarks); Remarks.setText(cursor3.getString(cursor3 .getColumnIndex("Remarks"))); } cursor3.requery(); selectOk = (Button) dialog.findViewById(R.id.btn_select_ok); selectCancel = (Button) dialog .findViewById(R.id.btn_select_cancel); selectRemove = (Button) dialog .findViewById(R.id.btn_select_remove); Quantity = (EditText) dialog.findViewById(R.id.txt_quantity); a = Quantity.getText().toString(); if (a.equals("")) { c = 0; Quantity.setText(c.toString()); } add = (Button) dialog.findViewById(R.id.btn_add); add.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { a = Quantity.getText().toString(); value = Integer.parseInt(a); Quantity.setText(value.toString()); inc = value + b; Quantity.setText(inc.toString()); // SelectedUnitPrice=EditUnitPrice.getText().toString(); value2 = Integer.parseInt(selecteditemPricePerUnit); value3 = inc * value2; String resvalue = value3.toString(); ItemPrice.setText(resvalue); } }); minus = (Button) dialog.findViewById(R.id.btn_minus); minus.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { a = Quantity.getText().toString(); value = Integer.parseInt(a); if (value >= 1) { dec = value - b; Quantity.setText(dec.toString()); value2 = Integer.parseInt(selecteditemPricePerUnit); value3 = dec * value2; String resvalue = value3.toString(); ItemPrice.setText(resvalue); } else { AlertDialog.Builder altDialog = new AlertDialog.Builder( ConfirmOrder.this); altDialog.setMessage("Quantity Cannot Be Negative"); // here // add // your // message altDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { // TODO Auto-generated method stub // Toast.makeText(getApplicationContext(),"",Toast.LENGTH_LONG).show(); } }); altDialog.show(); } } }); selectRemove.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { db.execSQL("DELETE FROM customer where ItemID = " + selecteditemId + " "); UpdateList(); dialog.dismiss(); } }); selectCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { dialog.cancel(); } }); selectOk.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // final SQLiteDatabase db = (new // DataBaseHelper(this)).getWritableDatabase(); String updateitemquantity = Quantity.getText() .toString(); int updateditemQuantity = Integer .parseInt(updateitemquantity); String Updateprice = ItemPrice.getText().toString(); int updateditemprice = Integer.parseInt(Updateprice); String UpdateRemarks = Remarks.getText().toString(); db.execSQL("UPDATE customer SET Quantity =" + updateditemQuantity + ",TotalPrice =" + updateditemprice + " WHERE ItemID = " + selecteditemId + " "); UpdateList(); dialog.dismiss(); } }); dialog.show(); } }); selectedTable = spinner2.getSelectedItem().toString(); // ItemonClick(); final Cursor cursor2 = db .rawQuery( "SELECT _id,CustTable,sum(TotalPrice),Status,Billed FROM customer WHERE CustTable = ?", new String[] { "" + selectedTable }); if (cursor2.getCount() == 1) { cursor2.moveToFirst(); EditTotal = (TextView) findViewById(R.id.txt_Total); EditTotal.setClickable(false); EditTotal.setFocusable(false); EditTotal.setText(cursor2.getString(cursor2 .getColumnIndex("sum(TotalPrice)"))); } cursor2.requery(); } public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) { selectedTable = spinner2.getSelectedItem().toString(); final SQLiteDatabase db = (new DataBaseHelper(this)) .getWritableDatabase(); Cursor cursor1 = db .rawQuery( "SELECT _id,ItemID,CustTable,ItemName,Quantity,PricePerUnit,TotalPrice,Status,Billed FROM customer WHERE CustTable = ?", new String[] { "" + selectedTable }); /* * while(cursor.moveToNext()) { * db_results.add(String.valueOf(cursor.getDouble * (cursor.getColumnIndex("ItemID")))); } */ cursor1.requery(); OrderedItemList = (ListView) findViewById(R.id.listView_ordereditem); arrayadapter = new SimpleCursorAdapter(this, R.layout.gift_text_image, cursor1, new String[] { "ItemName", "Quantity", "TotalPrice", "ItemID", "PricePerUnit" }, new int[] { R.id.txtview_productname, R.id.txtview_Quantity, R.id.txtview_Price, R.id.txtview_ItemId, R.id.txtview_ItemPricePerunit }); OrderedItemList.setAdapter(arrayadapter); Cursor cursor2 = db .rawQuery( "SELECT _id,CustTable,sum(TotalPrice),Status,Billed FROM customer WHERE CustTable = ?", new String[] { "" + selectedTable }); if (cursor2.getCount() == 1) { cursor2.moveToFirst(); EditTotal = (TextView) findViewById(R.id.txt_Total); EditTotal.setClickable(false); EditTotal.setFocusable(false); EditTotal.setText(cursor2.getString(cursor2 .getColumnIndex("sum(TotalPrice)"))); } cursor2.requery(); } public void onNothingSelected(AdapterView<?> arg0) { } public void onBackHome(View vv) { Intent backToHomePage = new Intent(ConfirmOrder.this, MainMenu.class); backToHomePage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(backToHomePage); } public void UpdateList() { selectedTable = spinner2.getSelectedItem().toString(); final SQLiteDatabase db = (new DataBaseHelper(this)) .getWritableDatabase(); Cursor cursor1 = db .rawQuery( "SELECT _id,ItemID,CustTable,ItemName,Quantity,PricePerUnit,TotalPrice,Status,Billed FROM customer WHERE CustTable = ?", new String[] {""+selectedTable}); cursor1.requery(); OrderedItemList = (ListView) findViewById(R.id.listView_ordereditem); arrayadapter = new SimpleCursorAdapter(this, R.layout.gift_text_image, cursor1, new String[] { "ItemName", "Quantity", "TotalPrice", "ItemID", "PricePerUnit" }, new int[] { R.id.txtview_productname, R.id.txtview_Quantity, R.id.txtview_Price, R.id.txtview_ItemId, R.id.txtview_ItemPricePerunit }); OrderedItemList.setAdapter(arrayadapter); final Cursor cursor2 = db .rawQuery( "SELECT _id,CustTable,sum(TotalPrice),Status,Billed FROM customer WHERE CustTable = ?", new String[] { "" + selectedTable }); if (cursor2.getCount() == 1) { cursor2.moveToFirst(); EditTotal = (TextView) findViewById(R.id.txt_Total); EditTotal.setClickable(false); EditTotal.setFocusable(false); EditTotal.setText(cursor2.getString(cursor2 .getColumnIndex("sum(TotalPrice)"))); } } public void addItemsOnSpinner2() { spinner2 = (Spinner) findViewById(R.id.spinner_order); List<String> list = new ArrayList<String>(); list.add("Table_1"); list.add("Table_2"); list.add("Table_3"); list.add("Table_4"); list.add("Table_5"); list.add("Table_6"); list.add("Table_7"); list.add("Table_8"); list.add("Table_9"); list.add("Table_10"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(dataAdapter); } public void addListenerOnSpinnerItemSelection() { spinner2 = (Spinner) findViewById(R.id.spinner_order); // spinner2.setOnItemSelectedListener(new // CustomOnItemSelectedListener()); } public void syncfromdbtid() { ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(ServerName+"/"+SourceName+"/tid_get.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data int c_id; String c_tid; // Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show(); try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); // c_id=json_data.getInt("Vi_ID"); tid=json_data.getString("tid"); // Toast.makeText(getBaseContext(), tid ,Toast.LENGTH_LONG).show(); } } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Id Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } } public void syncfromdbmenu() { ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(ServerName+"/"+SourceName+"/get.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data int c_id; String c_Menu; String c_Submenu; String c_Price; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); c_id=json_data.getInt("Vi_ID"); c_Menu=json_data.getString("Vi_MainMenu"); c_Submenu=json_data.getString("Vi_SubMenu"); c_Price=json_data.getString("Vi_Price"); System.out.println(+c_id+c_Menu+c_Submenu+c_Price); final SQLiteDatabase db = (new DataBaseHelper(this)).getWritableDatabase(); ContentValues addItem = new ContentValues(); addItem.put("_id", c_id); addItem.put("Menu", c_Menu); addItem.put("SubMenu", c_Submenu); addItem.put("Price", c_Price); db.insert("MenuItem", "Menu", addItem); } } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Record Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } } void sync(String row, String CustTable, String ItemName, String ItemID, String Quantity , String PricePerUnit , String TotalPrice , String Status,String Remarks,String Covers, String Billed) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(ServerName+"/"+SourceName+"/poster.php"); // HttpPost httppost = new HttpPost("http://10.0.2.2/oracleconn/index.php"); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(9); nameValuePairs.add(new BasicNameValuePair("id", row)); nameValuePairs.add(new BasicNameValuePair("CustTable", CustTable)); nameValuePairs.add(new BasicNameValuePair("ItemName", ItemName)); nameValuePairs.add(new BasicNameValuePair("ItemID", ItemID)); nameValuePairs.add(new BasicNameValuePair("Quantity", Quantity)); nameValuePairs.add(new BasicNameValuePair("PricePerUnit", PricePerUnit)); nameValuePairs.add(new BasicNameValuePair("TotalPrice", TotalPrice)); nameValuePairs.add(new BasicNameValuePair("Status", Status)); nameValuePairs.add(new BasicNameValuePair("Remarks", Remarks)); nameValuePairs.add(new BasicNameValuePair("Covers", Covers)); nameValuePairs.add(new BasicNameValuePair("Billed", Billed)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); Log.v("resp", response.toString()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } /* * this method chooses the latest entry from the online database then * selects then selects the later entries that this and posts them to the * remote db */ public void startSync() { // read from Db int no_rows = 0; HttpClient httpclienty = new DefaultHttpClient(); HttpPost httpposty = new HttpPost( ServerName+"/"+SourceName+"/rows.php"); try { HttpResponse responsey = httpclienty.execute(httpposty); String result = EntityUtils.toString(responsey.getEntity()); JSONObject jo = new JSONObject(result); if(jo.toString().equals("{\"rows\":null}")){ Log.v("obj", "is null"); } else { JSONArray ja = jo.getJSONArray("rows"); Log.v("lenght", ja.toString()); JSONObject cobj = ja.getJSONObject(0); Log.v("c", cobj.toString()); no_rows = cobj.getInt("row"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } String[] columns = new String[] {"_id","CustTable","ItemName","ItemID","Quantity","PricePerUnit","TotalPrice", "Status", "Billed" }; //final Cursor c = ourDb.query("Ordereditem",columns, "_id" + "" // + no_rows, null, null, null, null); final SQLiteDatabase db = (new DataBaseHelper(this)).getWritableDatabase(); final Cursor c = db.rawQuery("SELECT * FROM Ordereditem", null); final int iRow = c.getColumnIndex("_id"); final int iCustTable = c.getColumnIndex("CustTable"); final int iItemName = c.getColumnIndex("ItemName"); final int iItemID = c.getColumnIndex("ItemID"); final int iQuantity = c.getColumnIndex("Quantity"); final int iPricePerUnit = c.getColumnIndex("PricePerUnit"); final int iTotalPrice = c.getColumnIndex("TotalPrice"); final int iStatus = c.getColumnIndex("Status"); final int iRemarks = c.getColumnIndex("Remarks"); final int iCovers = c.getColumnIndex("Covers"); final int iBilled = c.getColumnIndex("Billed"); class sender extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { sync(c.getString(iRow), c.getString(iCustTable), c.getString(iItemName), c.getString(iItemID), c.getString(iQuantity),c.getString(iPricePerUnit),c.getString(iTotalPrice), c.getString(iStatus),c.getString(iRemarks),c.getString(iCovers),c.getString(iBilled)); } return null; } @Override protected void onPostExecute(Void result) { // TODO Auto-generated method stub // close(); } } sender s = new sender(); s.execute(); } private void showNoticeDialogBox(final String title, final String message) { Builder setupAlert; setupAlert = new AlertDialog.Builder(this).setTitle(title) .setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Intent myIntent = new // Intent(getApplicationContext(),AddCustomer.this); // startActivity(myIntent); } }); setupAlert.show(); } private void showNoticeDialogBoxadd(final String title, final String message) { Builder setupAlert; setupAlert = new AlertDialog.Builder(this).setTitle(title) .setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent myIntent = new Intent(getApplicationContext(), Welcome.class); startActivity(myIntent); } }); setupAlert.show(); } }
package com.alura.service; import com.alura.dto.CursoDto; import com.alura.exception.CursoNotFoundException; import com.alura.modelo.Curso; import com.alura.repository.CursoRepository; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CursoService { @Autowired private CursoRepository cursoRepository; public CursoDto criar(final CursoDto cursoDto) { Curso curso = new Curso(); curso.setNome(cursoDto.getNome()); curso.setCategoria(cursoDto.getCategoria()); cursoRepository.save(curso); return cursoDto; } public List<Curso> listar() { List<Curso> cursos = cursoRepository.findAll(); return cursos; } public Curso buscar(final Long id) { Optional<Curso> curso = cursoRepository.findById(id); if (!curso.isPresent()) { throw new CursoNotFoundException("Curso não encontrado"); } return curso.get(); } public void atualizar(final CursoDto cursoDto, final Long id) { cursoRepository.findById(id) .map(curso -> { BeanUtils.copyProperties(cursoDto, curso, "id"); cursoRepository.save(curso); return curso; }).orElseThrow(() -> new CursoNotFoundException("Curso não encontrado para id solicitado")); } public void deletar(final Long id){ Optional<Curso> cursos = cursoRepository.findById(id); if(!cursos.isPresent()){ throw new CursoNotFoundException("Curso não encontrado para id solicitado"); } cursoRepository.delete(cursos.get()); } }
package com.example.db1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Spinner; import com.example.db1.adapters.AdapterGridView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Spinner spfiltros; GridView gridView; ListView listView; Toolbar toolbar; ImageButton imgButtonAdd; FrameLayout frameGrid, frameList; // adaptadores ArrayAdapter<String> adapterSpinner; String arraySpinner[] = {"En Lista", "En Celdas"}; ArrayList<String> nombres, telefonos, urls; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spfiltros = (Spinner)findViewById(R.id.spinner_filtro_vista); gridView = (GridView)findViewById(R.id.grid); listView = (ListView)findViewById(R.id.list); imgButtonAdd = (ImageButton)findViewById(R.id.img_button); frameGrid =(FrameLayout)findViewById(R.id.frame_grid); frameList =(FrameLayout)findViewById(R.id.frame_list); toolbar = (Toolbar)findViewById(R.id.toolbarmain); setSupportActionBar(toolbar); // asignar adaptadores adapterSpinner = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arraySpinner); spfiltros.setAdapter(adapterSpinner); init(); gridView.setAdapter(new AdapterGridView(this, nombres, telefonos, urls)); spfiltros.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(position==0) { frameGrid.setVisibility(View.GONE); frameGrid.setEnabled(false); frameList.setVisibility(View.VISIBLE); frameList.setEnabled(true); } else if(position==1){ frameGrid.setVisibility(View.VISIBLE); frameGrid.setEnabled(true); frameList.setVisibility(View.GONE); frameList.setEnabled(false); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void init() { frameGrid.setVisibility(View.GONE); frameGrid.setEnabled(false); frameList.setVisibility(View.VISIBLE); frameList.setEnabled(true); crearContactos(); } public void cargarLista(){ } public void cargarGrid(){ } public void crearContactos(){ nombres = new ArrayList<String>(); telefonos = new ArrayList<String>(); urls = new ArrayList<String>(); nombres.add("Alberto"); nombres.add("Edith"); nombres.add("Sergio"); nombres.add("Angel"); telefonos.add("5512345678"); telefonos.add("5578968697"); telefonos.add("5598765432"); telefonos.add("5582719346"); urls.add("/img1"); urls.add("/img2"); urls.add("/img3"); urls.add("/img4"); } }
package org.team16.team16week5; import org.team16.team16week5.Bill; import static org.junit.Assert.*; import org.junit.Test; public class DetailedCostTest{ public static final String GOLD = "Gold"; public static final String SILVER = "Silver"; private Bill bill; private void setBillInfo(String type, int minute, int line) { this.bill = new Bill(type, minute, line); } private double getAdditionalLineCost() { return bill.getDetailedCostObject().getAdditionalLineCost(); } private double getOverExcessMinutesCost() { return bill.getDetailedCostObject().getOverExcessMinutesCost(); } private double getTotalCost() { return bill.getDetailedCostObject().getTotalCost(); } @Test public void testGoldBillCase1() { setBillInfo(GOLD, 878, 4); assertEquals(2*14.50 + 5.00, getAdditionalLineCost(), 0.01); assertEquals(0 , getOverExcessMinutesCost(), 0.01); assertEquals(83.95, getTotalCost(),0.01); } @Test public void testGoldBillCase2() { setBillInfo(GOLD, 1123, 1); assertEquals(0, getAdditionalLineCost(), 0.01); assertEquals(123*0.45 , getOverExcessMinutesCost(), 0.01); assertEquals(105.3, getTotalCost(),0.01); } @Test public void testGoldBillCase3() { setBillInfo(GOLD, 1123, 4); assertEquals((2*14.50) + 5.00, getAdditionalLineCost(), 0.01); assertEquals(123*0.45 , getOverExcessMinutesCost(), 0.01); assertEquals(139.3, getTotalCost(), 0.01); } @Test public void testGoldBillCase4() { setBillInfo(GOLD, 1123, 3); assertEquals(2*14.50, getAdditionalLineCost(), 0.01); assertEquals(123*0.45, getOverExcessMinutesCost(), 0.01); assertEquals(134.3, getTotalCost(), 0.01); } @Test public void testSilverBillCase1() { setBillInfo(SILVER, 523, 2); assertEquals(21.50, getAdditionalLineCost(), 0.01); assertEquals(23*0.54 , getOverExcessMinutesCost(), 0.01); assertEquals(63.87, getTotalCost(),0.01); } @Test public void testSilverBillCase2() { setBillInfo(SILVER, 44, 5); assertEquals((2*21.50) + (2*5.00), getAdditionalLineCost(), 0.01); assertEquals(0 , getOverExcessMinutesCost(), 0.01); assertEquals(82.95, getTotalCost(),0.01); } @Test public void testSilverBillCase3() { setBillInfo(SILVER, 521, 5); assertEquals((2*21.50) + (2*5.00), getAdditionalLineCost(), 0.01); assertEquals(21*0.54, getOverExcessMinutesCost(), 0.01); assertEquals(94.29, getTotalCost(),0.01); } }
/** * */ package com.zh.java.basic.rmi; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; /** * @author ZH * 远程方法调用测试 客户端代码。 */ public class HelloRmiClient { public static void main(String[] args) { IHelloRmi h; try { h = (IHelloRmi)Naming.lookup("rmi://localhost:1234/helloRmi"); System.out.println(h.helloRmiTest("test")); } catch (MalformedURLException e) { System.out.println("url格式异常"); e.printStackTrace(); } catch (RemoteException e) { System.out.println("创建对象异常"); e.printStackTrace(); } catch (NotBoundException e) { System.out.println("对象未绑定"); e.printStackTrace(); } } }
package com.ibisek.outlanded.components; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.widget.EditText; /** * EditText with extended functionality. * * @author ibisek * @version 2013-10-02 */ public class EditText2 extends EditText { private String initialText; public EditText2(Context context) { super(context); init(null); } public EditText2(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public EditText2(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } /** * @param attrs * @param attrName * @return attribute value */ private String getAttributeValue(AttributeSet attrs, String attrName) { // (1) try to get it as resource: int resourceId = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", attrName, 0); if (resourceId != 0) { String attrValue = getResources().getString(resourceId); return attrValue; } // (2) or just return a 'raw' value: if (attrs != null) { for (int i = 0; i < attrs.getAttributeCount(); i++) { String name = attrs.getAttributeName(i); if (name!= null && name.toLowerCase().equals(attrName)) { String attrValue = attrs.getAttributeValue(i); return attrValue; } } } return null; } private void init(AttributeSet attrs) { initialText = getAttributeValue(attrs, "text"); setSelectAllOnFocus(true); this.addTextChangedListener(new MyTextWatcher()); } /** * Sets the text if the text is not null. If so, the original value will * remain. * * @param text */ public void setText2(CharSequence text) { if (text != null) super.setText(text); } /** * @return true if the text is equal to initial */ public boolean isEmpty() { return getText().toString().equals(initialText) || getText().toString().isEmpty(); } private class MyTextWatcher implements TextWatcher { @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { setText(initialText); selectAll(); } EditText2.this.setError(null); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // nix } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // nix } } }
package com.meehoo.biz.core.basic.service.security; import com.meehoo.biz.common.util.BaseUtil; import com.meehoo.biz.common.util.StreamUtil; import com.meehoo.biz.common.util.StringUtil; import com.meehoo.biz.core.basic.dao.bos.IMenuDao; import com.meehoo.biz.core.basic.dao.security.IAuthRoleMenuDao; import com.meehoo.biz.core.basic.domain.bos.Menu; import com.meehoo.biz.core.basic.domain.security.*; import com.meehoo.biz.core.basic.ro.security.AuthRoleMenuRO; import com.meehoo.biz.core.basic.ro.security.SetDefinesRO; import com.meehoo.biz.core.basic.service.BaseService; import com.meehoo.biz.core.basic.util.VOUtil; import com.meehoo.biz.core.basic.vo.bos.MenuVO; import com.meehoo.biz.core.basic.vo.security.AuthMenuTreeVO; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; /** * Created by CZ on 2017/10/25. */ @Service @Transactional public class AuthMenuServiceImpl extends BaseService implements IAuthMenuService { private final IAuthRoleMenuDao authRoleMenuDao; private final IUserService userService; private final IMenuDao menuDao; @Autowired public AuthMenuServiceImpl(IAuthRoleMenuDao authRoleMenuDao, IUserService userService, IMenuDao menuDao) { this.authRoleMenuDao = authRoleMenuDao; this.userService = userService; this.menuDao = menuDao; } @Override public AuthMenuTreeVO getMenuListByRoleId(String roleId) throws Exception { Role role = queryById(Role.class,roleId); AuthMenuTreeVO authMenuTreeVO = new AuthMenuTreeVO(); //查出用户对应类型的所有的菜单 List<Menu> menuList = menuDao.queryByMenuType(role.getRoleType()); List<Menu> topMenus = new ArrayList<>(); for (Menu menu : menuList) { if (menu.getStatus() == Menu.STATUS_ENABLE) { if (menu.getGrade() == Menu.GRADE_ROOT) { topMenus.add(menu); } else { menu.getParentMenu().addChildMenu(menu); } } } topMenus.sort(Comparator.comparingInt(Menu::getSeq)); authMenuTreeVO.setChildren(VOUtil.convertDomainListToTempList(topMenus, MenuVO.class)); //查出已授权的菜单 List<AuthRoleMenu> authRoleMenuList = this.authRoleMenuDao.queryByRoleId(roleId); List<String> checkedIdList = new ArrayList<>(authRoleMenuList.size()); if (BaseUtil.collectionNotNull(authRoleMenuList)) { for (AuthRoleMenu authRoleMenu : authRoleMenuList) { Menu menu = authRoleMenu.getMenu(); if (menu != null) { checkedIdList.add(menu.getId()); } } } authMenuTreeVO.setChecked(checkedIdList); return authMenuTreeVO; } @Override public void setDefine(SetDefinesRO ro) { // 删除旧有的 DetachedCriteria dc = DetachedCriteria.forClass(Role2MenuDefine.class); dc.add(Restrictions.eq("role.id",ro.getRoleId())); List list = list(dc); batchDelete(list); // if (BaseUtil.listNotNull(ro.getMenuDefineIds())){ Role role = queryById(Role.class, ro.getRoleId()); List<MenuDefine> menuDefines = queryByIds(MenuDefine.class, ro.getMenuDefineIds()); List<Role2MenuDefine> collect = menuDefines.stream().map(e -> { Role2MenuDefine role2MenuDefine = new Role2MenuDefine(); role2MenuDefine.setRole(role); role2MenuDefine.setMenuDefine(e); return role2MenuDefine; }).collect(Collectors.toList()); batchSave(collect); } } @Override public void saveOrUpdateAuthMenu(AuthRoleMenuRO authRoleMenuRO) throws Exception { authRoleMenuDao.deleteByRoleId(authRoleMenuRO.getRoleId()); if (BaseUtil.collectionNotNull(authRoleMenuRO.getMenuIdList())) { Role role = new Role(); role.setId(authRoleMenuRO.getRoleId()); List<Menu> menuList = menuDao.findAllById(authRoleMenuRO.getMenuIdList()); List<AuthRoleMenu> authRoleMenuList = new ArrayList<>(menuList.size()); for (Menu menu : menuList) { AuthRoleMenu authRoleMenu = new AuthRoleMenu(); authRoleMenu.setRole(role); authRoleMenu.setMenu(menu); authRoleMenuList.add(authRoleMenu); } authRoleMenuDao.saveAll(authRoleMenuList); } } @Override public AuthMenuTreeVO getMenuListByOrgUserId(String orgId, String userId) throws Exception { AuthMenuTreeVO authMenuTreeVO = new AuthMenuTreeVO(); //1、查询出当前组织机构当前登录用户下的角色列表 // List<Role> roleListOfUser = userService.getRolesByUserAndOrg(userId, orgId); // List<String> roleIdList = StreamUtil.extractFieldToList(roleListOfUser, Role::getId); User user = queryById(User.class, userId); List<String> roleIdList = new ArrayList<>(); roleIdList.add(user.getRoleId()); if (BaseUtil.collectionNotNull(roleIdList)) { //2、根据角色列表获取有权菜单 List<AuthRoleMenu> authRoleMenuList = this.authRoleMenuDao.queryByRoleIdIn(roleIdList); //菜单去重,即多个角色相同菜单的情况 Set<Menu> authMenuSet = StreamUtil.extractFieldToSet(authRoleMenuList, AuthRoleMenu::getMenu); Set<Menu> topMenuSetOfUser = new HashSet<>(); //向上寻找正常启用了的根菜单 for (Menu authMenu : authMenuSet) { Menu searchMenu = authMenu; //非根且启用了的菜单才能向上搜索 while (searchMenu.getGrade() != Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { Menu parentMenu = searchMenu.getParentMenu(); parentMenu.addChildMenu(searchMenu); searchMenu = parentMenu; } if (searchMenu.getGrade() == Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { topMenuSetOfUser.add(searchMenu); } } List<Menu> topMenuListOfUser = new ArrayList<>(topMenuSetOfUser); topMenuListOfUser.sort(Comparator.comparingInt(Menu::getSeq)); //过滤被禁用的菜单 authMenuTreeVO.setChildren(VOUtil.convertDomainListToTempListWithFilter(topMenuListOfUser, MenuVO.class, menu -> menu.getStatus() == Menu.STATUS_ENABLE)); } else { authMenuTreeVO.setChildren(new ArrayList<>(0)); } return authMenuTreeVO; } @Override public AuthMenuTreeVO getMenuListByProjectId(String projectId, String userId) throws Exception { // 根据projectId,userId查到ProjectUser // ProjectUser projectUser = projectUserDao.getByProAndUser(projectId, userId); // // 拿到roleIdList // List<ProUserRole> proUserRoles = proUserRoleDao.getByProjectUser(projectUser.getId()); // List<String> roleIdList = new ArrayList<>(); // for (ProUserRole pus:proUserRoles){ // roleIdList.add(pus.getRole().getId()); // } // // AuthMenuTreeVO authMenuTreeVO = new AuthMenuTreeVO(); // if (BaseUtil.collectionNotNull(roleIdList)) { // //2、根据角色列表获取有权菜单 // List<AuthRoleMenu> authRoleMenuList = this.authRoleMenuDao.queryByRoleIdIn(roleIdList); // //菜单去重,即多个角色相同菜单的情况 // Set<Menu> authMenuSet = StreamUtil.extractFieldToSet(authRoleMenuList, AuthRoleMenu::getMenu); // Set<Menu> topMenuSetOfUser = new HashSet<>(); // //向上寻找正常启用了的根菜单 // for (Menu authMenu : authMenuSet) { // Menu searchMenu = authMenu; // //非根且启用了的菜单才能向上搜索 // while (searchMenu.getGrade() != Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { // Menu parentMenu = searchMenu.getParentMenu(); // parentMenu.addChildMenu(searchMenu); // searchMenu = parentMenu; // } // if (searchMenu.getGrade() == Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { // topMenuSetOfUser.add(searchMenu); // } // // } // List<Menu> topMenuListOfUser = BaseUtil.convertSetToList(topMenuSetOfUser, Menu::getSeq); // topMenuListOfUser.sort(Comparator.comparingInt(Menu::getSeq)); // //过滤被禁用的菜单 // authMenuTreeVO.setChildren(VOUtil.convertDomainListToTempListWithFilter(topMenuListOfUser, MenuVO.class, menu -> menu.getStatus() == Menu.STATUS_ENABLE)); // } else { // authMenuTreeVO.setChildren(new ArrayList<>(0)); // } // return authMenuTreeVO; return null; } @Override public AuthMenuTreeVO getMenuListByAdminId(String adminId) throws Exception{ Admin admin = queryById(Admin.class,adminId); AuthMenuTreeVO authMenuTreeVO = new AuthMenuTreeVO(); if (StringUtil.stringNotNull(admin.getRoleId())) { //2、根据角色列表获取有权菜单 List<AuthRoleMenu> authRoleMenuList = this.authRoleMenuDao.queryByRoleId(admin.getRoleId()); //菜单去重,即多个角色相同菜单的情况 Set<Menu> authMenuSet = StreamUtil.extractFieldToSet(authRoleMenuList, AuthRoleMenu::getMenu); Set<Menu> topMenuSetOfUser = new HashSet<>(); //向上寻找正常启用了的根菜单 for (Menu authMenu : authMenuSet) { Menu searchMenu = authMenu; //非根且启用了的菜单才能向上搜索 while (searchMenu.getGrade() != Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { Menu parentMenu = searchMenu.getParentMenu(); parentMenu.addChildMenu(searchMenu); searchMenu = parentMenu; } if (searchMenu.getGrade() == Menu.GRADE_ROOT && searchMenu.getStatus() == Menu.STATUS_ENABLE) { topMenuSetOfUser.add(searchMenu); } } List<Menu> topMenuListOfUser = new ArrayList<>(topMenuSetOfUser); topMenuListOfUser.sort(Comparator.comparingInt(Menu::getSeq)); //过滤被禁用的菜单 authMenuTreeVO.setChildren(VOUtil.convertDomainListToTempListWithFilter(topMenuListOfUser, MenuVO.class, menu -> menu.getStatus() == Menu.STATUS_ENABLE)); } else { authMenuTreeVO.setChildren(new ArrayList<>(0)); } return authMenuTreeVO; } }
package org.flowable.cloud.runtime.core.behavior.classdelegate; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.flowable.cloud.runtime.core.behavior.classdelegate.annotation.CloudClassDelegateScan; import org.flowable.cloud.runtime.core.utils.NameUtil; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * <Description> <br> * * @author chen.xing01<br> * @version 1.0<br> */ public class CloudClassDelegateBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { private static Set<BeanDefinitionHolder> beanDefinitionHolders = new HashSet<>(); @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(CloudClassDelegateScan.class.getName())); CloudClassDelegateBeanDefinitionScanner scanner = new CloudClassDelegateBeanDefinitionScanner(registry); Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass"); if (!Annotation.class.equals(annotationClass)) { scanner.setAnnotationClass(annotationClass); } Class<?> markerInterface = annoAttrs.getClass("markerInterface"); if (!Class.class.equals(markerInterface)) { scanner.setMarkerInterface(markerInterface); } List<String> basePackages = new ArrayList<String>(); for (String pkg : annoAttrs.getStringArray("value")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (String pkg : annoAttrs.getStringArray("basePackages")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) { basePackages.add(ClassUtils.getPackageName(clazz)); } scanner.registerFilters(); scanner.setBeanNameGenerator((definition, definitionRegistry) -> NameUtil.getJavaDelegateBeanName(definition.getBeanClassName())); beanDefinitionHolders.addAll(scanner.doScan(StringUtils.toStringArray(basePackages))); } public static Set<BeanDefinitionHolder> getBeanDefinitionHolders() { return beanDefinitionHolders; } public static void clearBeanDefinitionHolders() { beanDefinitionHolders.clear(); } }
package com.esum.framework.core.management.manager; import java.util.Set; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.core.component.ComponentInfo; import com.esum.framework.core.component.ComponentManager; import com.esum.framework.core.component.ComponentManagerFactory; import com.esum.framework.core.management.ManagementConstants; import com.esum.framework.core.management.ManagementException; import com.esum.framework.jmx.JmxMBeanRegistryHandler; import com.esum.framework.jmx.JmxServer; import com.esum.framework.utils.Assert; /** * JMX기반의 XTRUS를 관리하는 Manager. */ public class XTrusManager { private Logger log = LoggerFactory.getLogger(XTrusManager.class); private String ipAddress = "localhost"; private int port = 8026; private JmxServer jmxServer; private static XTrusManager manager = null; public synchronized static XTrusManager getInstance() { if (manager == null) { manager = new XTrusManager(); } return manager; } private XTrusManager() { } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public synchronized void startup() throws ManagementException { Assert.notNull(ipAddress, "'ipAddress' must not be null."); Assert.notNull(port, "'port' must not be null."); if(this.jmxServer==null) { this.jmxServer = new JmxServer(ipAddress, port); this.jmxServer.startup(); } } public JmxServer getJmxServer() { return jmxServer; } public void registMBean(JmxMBeanRegistryHandler registryHandler) throws ManagementException { jmxServer.registMBean(registryHandler); } public void registMbean(String jmxName, String implClass) throws ManagementException { jmxServer.registMBean(jmxName, implClass); } public void initializeMBeanList() throws ManagementException { jmxServer.registMBean(new JmxMBeanRegistryHandler() { @Override public void handleMBean(MBeanServerConnection serverConnection) throws Exception { ObjectName objectName = new ObjectName(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_COMPONENT_CONTROL, objectName); log.info("Register the Component Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_QUEUE_CONTROL,objectName); log.info("Register the Queue Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_MESSAGE_CONTROL, objectName); log.info("Register the Message Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_SECURITY_CONTROL, objectName); log.info("Register the Security Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_SYSTEM_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_SYSTEM_CONTROL, objectName); log.info("Register the System Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_LOG_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_LOG_CONTROL, objectName); log.info("Register the Log Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_LICENSE_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_LICENSE_CONTROL, objectName); log.info("Register the License Control MBean to xTrusManager."); } objectName = new ObjectName(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); if(!serverConnection.isRegistered(objectName)) { serverConnection.createMBean(ManagementConstants.MAIN_CLASS_DEPLOY_CONTROL, objectName); log.info("Register the HotDeploy MBean to xTrusManager."); } } }); try{ boolean hasEBMS = ComponentManagerFactory.currentComponentManager().hasComponent("EBMS"); if(hasEBMS) { ComponentInfo ebmsInfo = ComponentManagerFactory.currentComponentManager().getComponentInfo("EBMS"); if(ebmsInfo!=null) initializeMBeanCheck("EBMS"); } } catch (Exception e){ log.error("Can not regist 'EBMS' Control", e); } try { boolean hasAS2 = ComponentManagerFactory.currentComponentManager().hasComponent("AS2"); if(hasAS2) { ComponentInfo as2Info = ComponentManagerFactory.currentComponentManager().getComponentInfo("AS2"); if(as2Info!=null) initializeMBeanCheck("AS2"); } } catch (Exception e){ log.error("Can not regist 'AS2' Control", e); } } public void initializeMBeanCheck(String compid) throws ManagementException { ComponentInfo componentInfo = null; try { ComponentManager componentManager = ComponentManagerFactory.currentComponentManager(); componentInfo = componentManager.getComponentInfo(compid); } catch(Exception e){ log.error(compid+" is not found!", e); } if(componentInfo != null && componentInfo.isAutoStarted()){ if(compid.equals("EBMS")){ initializeEbMSMBeanList(); } else if(compid.equals("AS2")){ initializeAS2MBeanList(); } else { log.error(compid+" is not found!"); } } } public void initializeEbMSMBeanList() throws ManagementException { jmxServer.registMBean(new JmxMBeanRegistryHandler() { @Override public void handleMBean(MBeanServerConnection serverConnection) throws Exception { ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_EBMS_CONTROL); if(serverConnection.isRegistered(objectName)) { return; } serverConnection.createMBean(ManagementConstants.MAIN_CLASS_EBMS_CONTROL, objectName); log.info("Register the EbMS Control MBean to xTrusManager."); objectName = new ObjectName(ManagementConstants.OBJECT_NAME_EBMS_MESSAGE_CONTROL); if(serverConnection.isRegistered(objectName)) { return; } serverConnection.createMBean(ManagementConstants.MAIN_CLASS_EBMS_MESSAGE_CONTROL, objectName); log.info("Register the EbMS Message Control MBean to xTrusManager."); } }); } public void initializeAS2MBeanList() throws ManagementException { jmxServer.registMBean(new JmxMBeanRegistryHandler() { @Override public void handleMBean(MBeanServerConnection serverConnection) throws Exception { ObjectName objectName = new ObjectName(ManagementConstants.OBJECT_NAME_AS2_CONTROL); if(serverConnection.isRegistered(objectName)) { return; } serverConnection.createMBean(ManagementConstants.MAIN_CLASS_AS2_CONTROL, objectName); log.info("Register the AS2 Control MBean to xTrusManager."); objectName = new ObjectName(ManagementConstants.OBJECT_NAME_AS2_MESSAGE_CONTROL); if(serverConnection.isRegistered(objectName)) { return; } serverConnection.createMBean(ManagementConstants.MAIN_CLASS_AS2_MESSAGE_CONTROL, objectName); log.info("Register the AS2 Message Control MBean to xTrusManager."); } }); } public void unregister(final String objectNameFilter) throws ManagementException { if(jmxServer==null || !jmxServer.isStarted()) return; jmxServer.registMBean(new JmxMBeanRegistryHandler() { @Override public void handleMBean(MBeanServerConnection serverConnection) throws Exception { ObjectName name = ObjectName.getInstance(objectNameFilter); Set<ObjectName> objectNames = serverConnection.queryNames(name, null); for(ObjectName n : objectNames) { System.out.println("name : "+n.toString()); serverConnection.unregisterMBean(n); } } }); } public void shutdown() throws ManagementException { if(jmxServer==null || !jmxServer.isStarted()) return; jmxServer.shutdown(); jmxServer = null; } }
package net.server; import core.server.Lobby; import core.server.LoggedInUser; import core.server.Room; import core.server.WelcomeSession; /** * This class represents a generic server-side object, like * {@linkplain WelcomeSession}, {@linkplain Lobby}, and * {@linkplain Room}. * * @author Harry * */ public interface ServerEntity { /** * When a user enters * * @param user */ public void onUserJoined(LoggedInUser user); /** * When a user disconnects due to either user action or internet disconnection * * @param user */ public void onUserDisconnected(LoggedInUser user); /** * When a user reconnects from disconnection * * @param user */ public void onUserReconnected(LoggedInUser user); /** * When a user is removed from server due to failure to reconnect after a certain disconnection timeout * @param user */ public void onUserRemoved(LoggedInUser user); }
package mvc.controller; import mvc.objects.ResultApi; import mvc.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by martea on 2018/8/23. */ @Controller @RequestMapping("test") public class TestController { @Autowired TestService testService; @InitBinder public void initBinder(WebDataBinder binder) throws Exception { DateFormat df = new SimpleDateFormat("yyyy---MM---dd HH:mm:ss"); CustomDateEditor dateEditor = new CustomDateEditor(df, true); binder.registerCustomEditor(Date.class, dateEditor); } @RequestMapping(value = "test1") @ResponseBody public String test1(@RequestParam("param") String param){ System.out.println(param); return "hello "+param; } @RequestMapping(value = "test2") @ResponseBody public ResultApi<String> test2(@RequestParam("param") String param){ return ResultApi.successItem(param); } @RequestMapping(value = "test3", produces = "application/json;charset=utf-8",consumes ="application/json;charset=utf-8") public void response2(HttpServletResponse response) throws IOException { //表示响应的内容区数据的媒体类型为json格式,且编码为utf-8(客户端应该以utf-8解码) // response.setContentType("application/text;charset=utf-8"); //写出响应体内容 String jsonData = "{\"username\":\"zhang\", \"password\":\"123\"}"; response.getWriter().write(jsonData); } @RequestMapping(value = "test4") @ResponseBody public ResultApi<String> test4(){ return ResultApi.successItem(testService.testString1("")); } @RequestMapping(value = "test5") @ResponseBody public ResultApi<String> test5(){ return ResultApi.successItem(testService.testString1("")); } @RequestMapping(value = "test6") @ResponseBody public String test6(){ return testService.testString3(""); } @RequestMapping(value = "test7") @ResponseBody public String test7(){ return testService.testString4(""); } /** * 测试{@link InitBinder} * @param date * @return */ @RequestMapping(value="test8",method= RequestMethod.GET) @ResponseBody public Map<String,Object> test8(Date date){ Map<String,Object> map=new HashMap<String,Object>(); map.put("name","lg"); map.put("age",23); map.put("date",new Date()); map.put("old",date); return map; } /** * 测试{@link HttpEntity}(好像是加了@ResponseBody的效果一样) * 猜想 {@link org.springframework.web.bind.annotation.RequestBody}也可以用 * {@link org.springframework.http.HttpEntity}来代替效果。//TODO 以上猜想未经证实 * @return */ @RequestMapping(value="/test9",method=RequestMethod.GET) public HttpEntity<String> test9(){ HttpEntity<String> stringHttpEntity = new HttpEntity<>("你好啊~"); return stringHttpEntity; } /** * 和上面的test9结合起来测试 * @return */ @RequestMapping(value="/test10",method=RequestMethod.GET) public String test10(){ return "你好啊~"; } @RequestMapping(value = "test11") @ResponseBody public String test11(){ Integer i = 1/0; return i.toString(); } }
package de.varylab.discreteconformal.plugin.hyperelliptic; public class EditChangeEvent { public Object source; public EditChangeEvent(Object source) { this.source= source; } }
import java.io.*; import java.util.*; class baek__7785 { static class Custom implements Comparator<String> { public int compare(String u, String v) { return -u.compareTo(v); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); HashMap<String, String> map = new HashMap<>(); String[] temp; for (int i = 0; i < n; i++) { temp = br.readLine().split(" "); String name = temp[0]; String result = temp[1]; if (map.containsKey(name)) { map.remove(name); map.put(name, result); } else { map.put(name, result); } } PriorityQueue<String> q = new PriorityQueue<>(1, new Custom()); Set<String> set = map.keySet(); for (String key : set) { if (map.get(key).equals("enter")) { q.add(key); } } while (!q.isEmpty()) { System.out.println(q.poll()); } } }
package frc.built_groups; import java.util.function.Consumer; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.ParallelRaceGroup; public class BuiltRace extends ParallelRaceGroup { public BuiltRace(Consumer<GroupBuilder> lambda) { var builder = new GroupBuilder(); lambda.accept(builder); addCommands(builder.commands.toArray(new Command[0])); } }
package com.aliam3.polyvilleactive.model.transport; import com.aliam3.polyvilleactive.model.deserializer.SectionDeserializer; import com.aliam3.polyvilleactive.model.location.Place; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.time.LocalDateTime; /** * Classe representant une etape d'un trajet * @author vivian * @author clement */ @JsonDeserialize(using = SectionDeserializer.class) public class Section { private Place from; private Place to; private long duration; private LocalDateTime arrivalDateTime; private LocalDateTime departureDateTime; private Transport transport; private double co2emission; private boolean reached; public Section() { reached = false; } @Override public String toString() { return "Section{" + "from=" + from + ", to=" + to + ", duration=" + duration + ", arrivalDateTime=" + arrivalDateTime + ", departureDateTime=" + departureDateTime + ", co2emission=" + co2emission + '}'; } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public Place getFrom() { return from; } public void setFrom(Place from) { this.from = from; } public Place getTo() { return to; } public void setTo(Place to) { this.to = to; } public LocalDateTime getArrivalDateTime() { return arrivalDateTime; } public void setArrivalDateTime(LocalDateTime arrivalDateTime) { this.arrivalDateTime = arrivalDateTime; } public LocalDateTime getDepartureDateTime() { return departureDateTime; } public void setDepartureDateTime(LocalDateTime departureDateTime) { this.departureDateTime = departureDateTime; } public double getCo2emission() { return co2emission; } public void setCo2emission(double co2emission) { this.co2emission = co2emission; } public boolean isReached() { return reached; } public void setReached(boolean reached) { this.reached = reached; } }
/** * Created by mohammad on 5/21/17. */ public class GraduationService { GraduationStrategy graduationStrategy; public boolean validateGraduation(StudentInfo studentInfo, History history){ if (studentInfo.hasMinor()){ graduationStrategy = new WithMinorStrategy(); } else { graduationStrategy = new NormalStrategy(); } return graduationStrategy.satisfy(studentInfo, history); } public boolean graduate(Student student){ return false; } }
package technicalblog.model; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") // It is optional to use the @Column annotation unless you want to override the default column naming, // which defaults to the attribute name. Here, we do not want to override the column name; therefore, // it is not necessary to use the @Column annotation private Integer id; @Column(name="username") private String username; @Column(name="password") private String password; // To define one to one mapping with user profile. Here User is parent and User_Profile is a child entity. //CascadeType represents that if change happens to parent entity then related entity should also be changed. @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) // A user can have a unique profile, and there can be only one user mapped to one user profile. // Therefore, there exists One to One mapping between the users table and the user_profile table. // The profile_id column in the users table is a foreign key and references the id column (primary key) // in the user_profile table. Note that in One to One mapping, we generally create a separate column as // a foreign key in any table referencing the primary key of the other table to specify the relationship between them. @JoinColumn(name="profile_id") private UserProfile profile; @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) //If you remove the user the respective post also will be removed // For one to many Fetch type is lazy private List<Post> posts = new ArrayList<>(); /*If a User object propagates through the REMOVE operation, the Post object referencing that particular User object must also propagate through the same operation. For example, if a record in the ‘users’ table is deleted, all the records in the posts table referencing that particular user record must also be deleted. Therefore, cascade = CascadeType.REMOVE is used to implement this functionality. But, if a User object propagates through PERSIST, REFRESH, MERGE, or DETACH, the Post object must not propagate through all these operations. For example, if a user is registered or user details are updated in the application, all the posts related to that user must not undergo any change. Therefore, cascade = CascadeType.ALL is not used.*/ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UserProfile getProfile() { return profile; } public void setProfile(UserProfile profile) { this.profile = profile; } public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } }
package kxg.searchaf.url.juicycouture; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import kxg.searchaf.mail.SystemMail; import kxg.searchaf.url.juicycouture.JuicycoutureMailList; import kxg.searchaf.url.juicycouture.JuicycoutureMailListMongoDao; public class JuicycoutureMailList implements Comparable<Object> { private static List<JuicycoutureMailList> maillist; public static String mail_subject = "Juicycouture 监视系统提醒"; public static String mailto_women = "watch_juicycouture@163.com"; public String mailaddress; public Date valideTime; public String userType; public boolean warningWomen; public float womencheckingSaleDiscount; public JuicycoutureMailList() { } public JuicycoutureMailList(String mailaddress, Date valideTime) { this.mailaddress = mailaddress; this.valideTime = valideTime; } public static void sync() { try { JuicycoutureMailListMongoDao dao = new JuicycoutureMailListMongoDao(); maillist = dao.findAll(); Collections.sort(maillist); } catch (Exception e) { SystemMail.sendSystemMail("error when get mongdb,err:" + e.getMessage()); } } public static List<JuicycoutureMailList> getinstance() { if (maillist == null || maillist.size() == 0) { // maillist = getinstanceFromText(); sync(); } return maillist; } public static boolean HasLicense(String validateEmail) { if (validateEmail == null || "".equals(validateEmail)) return false; Date currentDate = new Date(); List<JuicycoutureMailList> juicycouturemailist = JuicycoutureMailList .getinstance(); for (int i = 0; i < juicycouturemailist.size(); i++) { JuicycoutureMailList amail = juicycouturemailist.get(i); if (validateEmail.equalsIgnoreCase(amail.mailaddress)) { if (amail.valideTime.after(currentDate)) { return true; } } } return false; } public int getSendingMailRetryTimes() { if ("buyer".equalsIgnoreCase(this.userType)) return 1; // retry 3 times return 1; // not try } @Override public int compareTo(Object o) { JuicycoutureMailList comp = (JuicycoutureMailList) o; int flag = 0; flag = this.userType.compareTo(comp.userType); if (flag != 0) return flag; flag = comp.valideTime.compareTo(this.valideTime); if (flag != 0) return flag; return 0; } }
package com.karachevtsevuu.mayaghosts; import org.andengine.entity.scene.CameraScene; import android.view.KeyEvent; public class Room extends CameraScene { private boolean childsAttached = false; public Room() { super(MainActivity.mainCamera); } public void Show() { setVisible(true); setIgnoreUpdate(false); onShow(); } public void Hide() { setVisible(false); setIgnoreUpdate(true); onHide(); } public void onShow() { } public void onHide() { } public void onKeyMenu(int keyCode, KeyEvent event) { } public boolean isChildsAttached() { return childsAttached; } public void setChildsAttached(boolean childsAttached) { this.childsAttached = childsAttached; } }
package com.example.umarramadhana.atp.network; import android.content.Context; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.ListView; import com.example.umarramadhana.atp.R; import com.example.umarramadhana.atp.pojo.Account; import com.example.umarramadhana.atp.pojo.AccountAPI; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class AccountClient { // private final String BASE_URL = "http://192.168.0.15"; private final String BASE_URL = "http://192.168.43.46"; private Retrofit retrofit; private AccountAPI accountAPI; private Account myAccount; private boolean isValidLogin; public AccountClient() { getAPIClient(); } public AccountAPI getAPIClient() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); accountAPI = retrofit.create(AccountAPI.class); return accountAPI; } public void addAccount(Account account) { Call<Account> call = accountAPI.addAccount(account.getName(), account.getEmail(), account.getNoktp(), account.getAddress(), account.getNohp(), account.getUsername(), account.getPassword()); call.enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { } @Override public void onFailure(Call<Account> call, Throwable t) { t.printStackTrace(); } }); } public void addSaldo(String nohp, Integer jumlah, String lokasi) { Call<Account> call = accountAPI.addSaldo(nohp, jumlah, lokasi); call.enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { } @Override public void onFailure(Call<Account> call, Throwable t) { t.printStackTrace(); } }); } public void topup(String nohp, Integer jumlah, String lokasi) { Call<Account> call = accountAPI.topup(nohp, jumlah, lokasi); call.enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { } @Override public void onFailure(Call<Account> call, Throwable t) { t.printStackTrace(); } }); } public void getDataTransaksi(final Context context, final ListView listView, final String nohp, final AutoCompleteTextView suggetion_box1) { Call<List<Account>> call = accountAPI.getTransaksi(); call.enqueue(new Callback<List<Account>>() { @Override public void onResponse(Call<List<Account>> call, Response<List<Account>> response) { ArrayAdapter<String> adapter; ArrayList<String> listv = new ArrayList<>(); for (int i = 0; i < response.body().size(); i++) { if (response.body().get(i).getNohp().equals(nohp)) { listv.add(response.body().get(i).getDate()); } } adapter = new ArrayAdapter<>(context, R.layout.support_simple_spinner_dropdown_item, listv); listView.setAdapter(adapter); suggetion_box1.setAdapter(adapter); } @Override public void onFailure(Call<List<Account>> call, Throwable t) { } }); } public void login(String username, String password){ Call<Account> call = accountAPI.login(username, password); call.enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { isValidLogin = true; myAccount = response.body(); } @Override public void onFailure(Call<Account> call, Throwable t) { isValidLogin = false; } }); } public Account getMyAccount() { return myAccount; } public boolean isValidLogin() { return isValidLogin; } public AccountAPI getAccountAPI() { return accountAPI; } }
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.reviewit; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.google.common.base.Strings; import com.google.reviewit.app.QueryConfig; import com.google.reviewit.app.ServerConfig; import com.google.reviewit.util.WidgetUtil; public class QuerySettingsFragment extends BaseFragment { private static final String LABEL_REGEXP = "^[a-zA-Z][a-zA-Z0-9]*$"; @Override protected @LayoutRes int getLayout() { return R.layout.content_query_settings; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); init(); displayQueryConfig(getApp().getConfigManager().getQueryConfig()); } private void init() { v(R.id.edit_server).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { display(ServerListFragment.class); } }); v(R.id.saveQuerySettings).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isQueryInputComplete()) { widgetUtil.showError(R.string.incompleteInput); return; } // TODO check that query is valid if (!isLabelValid()) { widgetUtil.showError(getString(R.string.invalidLabel, LABEL_REGEXP)); return; } saveQuerySettings(); } }); } private void displayQueryConfig(QueryConfig config) { initServerDropDown(); v(R.id.incompleteSettings).setVisibility( config.isComplete() ? View.GONE : View.VISIBLE); Spinner serverInput = (Spinner) v(R.id.serverIdInput); ServerConfig serverConfig = getApp().getConfigManager().getServerConfig (config.serverId); serverInput.setSelection( ((ArrayAdapter<ServerConfig>) serverInput.getAdapter()) .getPosition(serverConfig)); WidgetUtil.setText(v(R.id.queryInput), config.query); WidgetUtil.setText(v(R.id.labelInput), config.label); } private void initServerDropDown() { Spinner serverInput = (Spinner) v(R.id.serverIdInput); ArrayAdapter<ServerConfig> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, getApp().getConfigManager().getServers()); serverInput.setAdapter(adapter); } private boolean isQueryInputComplete() { return !Strings.isNullOrEmpty(getServerId()) && !Strings.isNullOrEmpty(textOf(R.id.queryInput)) && !Strings.isNullOrEmpty(textOf(R.id.labelInput)); } private boolean isLabelValid() { return textOf(R.id.labelInput).matches(LABEL_REGEXP); } private void saveQuerySettings() { getApp().getConfigManager().setQueryConfig( new QueryConfig.Builder() .setServerId(getServerId()) .setQuery(textOf(R.id.queryInput)) .setLabel(textOf(R.id.labelInput)) .build()); widgetUtil.toast(R.string.query_saved); switch (getApp().getPrefs().startScreen) { case REVIEW_SCREEN: display(ReviewChangesFragment.class); break; case SORT_SCREEN: default: display(SortChangesFragment.class); } } private String getServerId() { Spinner serverInput = (Spinner) v(R.id.serverIdInput); return ((ServerConfig) serverInput.getSelectedItem()).id; } }
/* * Copyright (C) 2011 MineStar.de * * This file is part of MineStarLibrary. * * MineStarLibrary 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, version 3 of the License. * * MineStarLibrary 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 MineStarLibrary. If not, see <http://www.gnu.org/licenses/>. */ package de.minestar.syncchest.library; /** * Represents a command with a varible number of Arguments. The only difference to Command is, that the argumentcount given by the constructor is the argumentcount the command must have atleast! * * @author Meldanor, GeMoschen * */ public abstract class AbstractExtendedCommand extends AbstractCommand { /** * Creating an ExtendedCommand which can have at least arguments than given in the paramater * * @param syntax * The label of the command. Example : /who * @param arguments * The arguments covered with Tags < >. Additional arguments can be covered by [ ] * @param node * The permission needed to call this command. Leave it empty to allow this command to everybody */ public AbstractExtendedCommand(String syntax, String arguments, String node) { super(syntax, arguments, node); } /** * Creating an ExtendedCommand which can have at least arguments than given in the paramater * * @param pluginName * Name of the plugin, without brackets [ ] * @param syntax * The label of the command. Example : /who * @param arguments * The arguments covered with Tags < >. Additional arguments can be covered by [ ] * @param node * The permission needed to call this command. Leave it empty to allow this command to everybody */ public AbstractExtendedCommand(String pluginName, String syntax, String arguments, String node) { super(pluginName, syntax, arguments, node); } /** * Allows at least the count of arguments given in constructor * * @param args * The arguments */ @Override protected boolean hasCorrectSyntax(String[] args) { return args.length >= super.getArgumentCount(); } }
package com.example.usuario.recyclerview; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.BreakIterator; public class InfoFragment extends Fragment { private TextView nombre; private TextView infocorta; private TextView info; private ImageView imagen; private ImageButton favs; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_info, container, false); nombre = (TextView)v.findViewById(R.id.idNombreDetalles2); infocorta = (TextView)v.findViewById(R.id.idInfoDetallesmini2); info = (TextView)v.findViewById(R.id.idInfoDetalles2); imagen = (ImageView) v.findViewById(R.id.idImageDetalles2); favs = (ImageButton) v.findViewById(R.id.favbtn2); // Bundle bundle = getArguments(); String nama = null; String infa=null; String infal = null; int fota; Bundle bundle = getArguments(); if (bundle != null) { nama = bundle.getString("name"); nombre.setText(nama); infa = bundle.getString("infoshort"); infocorta.setText(infa); infal = bundle.getString("infolong"); info.setText(infal); fota=bundle.getInt("photo"); imagen.setImageResource(fota); } //Toast.makeText(getActivity(),data,Toast.LENGTH_SHORT).show(); //nombre.setText(getArguments().getString("name")); // Hardware hw = (Hardware)b.getSerializable("id1"); // nombre.setText(hw.getNombre()); // nombre.setText(name); return v; } String direccion, mensaje, asunto; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Bundle b = getArguments(); Hardware hw = (Hardware)b.getSerializable("id1"); */ // nombre.setText(hw.getNombre()); /* infocorta.setText(hw.getInfo()); info.setText(hw.getInfolarga()); imagen.setImageResource(hw.getFotoid()); direccion = hw.getURL(); if(hw.isFavorito()==true) { favs.setImageResource(R.mipmap.ic_launcher_favllen); } else { favs.setImageResource(R.mipmap.ic_launcher_favacio); } */ } }
package com.zc.pivas.statistics.repository; import com.zc.base.orm.mybatis.annotation.MyBatisRepository; import com.zc.base.sc.modules.batch.entity.Batch; import com.zc.pivas.statistics.bean.allocationWork.AllocationSQLBean; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * 配置工作量Dao * * @author jagger * @version 1.0 */ @MyBatisRepository("allocationWorkDAO") public interface AllocationWorkDAO { /** * 获取所有的空批 * * @return * @throws Exception */ List<Batch> getBatchList() throws Exception; /** * 获取拆药数量 * * @param param * @return * @throws Exception */ List<AllocationSQLBean> getWorkList(@Param("param") Map<String, Object> param) throws Exception; }
package com.lq.dao; import java.util.List; import javax.annotation.Resource; import com.lq.entity.Isbn; import com.lq.other.PartRentable; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; @Repository public class IsbnDaoImpl implements IsbnDao{ @Resource(name="sessionFactory") private SessionFactory sessionFactory; @Override public void addIsbn(Isbn isbninfo) { sessionFactory.getCurrentSession().save(isbninfo); } @Override public Isbn getOneIsbninfor(String isbn) { String hql = "FROM Isbn u Where u.isbn=? "; // 根据需要显示的信息不同 将*替换成不同属性,还是封装成一个类CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setString(0, isbn); return (Isbn) query.uniqueResult(); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getSearchInfo(String keyword) { // TODO Auto-generated method stub String hql= "select new PartRentable(u.id,u.picture,u.way,u.rent_price,u.sale_price,t.title) from Rentable u,Isbn t where u.information = t.isbn and u.information in( select isbn " + "from Isbn where title like '%"+keyword+"%' or subtitle like '%"+keyword+"%' or author like '%"+keyword+"%' or publisher like '%"+keyword+"%' or keyword like '%"+keyword+"%' )"; Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getSearchInCore(String keyword) { // TODO Auto-generated method stub String hql= "select new PartRentable(u.id,t.picture,u.way,u.rent_price,u.sale_price,t.title) from Rentable u,Isbn t where u.information = t.isbn and u.information in( " + "select isbn from Isbn where title like :key or subtitle like :key or author like :key or publisher like :key or keyword like :key)" + "order by length(t.title),t.author,t.pubdate,u.way"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("key", "%"+keyword+"%"); return query.list(); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getSearchInfoByTwokey(String keyword,String keyword2){ // TODO Auto-generated method stub String hql= "select new PartRentable(u.id,t.picture,u.way,u.rent_price,u.sale_price,t.title) from Rentable u,Isbn t where u.information = t.isbn and u.information in( " + "select isbn from Isbn where (title like :key and author like :key2) or (author like :key and publisher like :key2) or (keyword like :key and like :key2) " + "order by t.title,t.author,t.pubdate,u.way"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("key", "%"+keyword+"%"); query.setParameter("key2", "%"+keyword2+"%"); return query.list(); } /* * 以下是未完成的扩展检索方法 * */ @SuppressWarnings("unchecked") @Override public List<String> getSearchIsbn(String keyword) { // TODO Auto-generated method stub String hql = "select isbn from Isbn where title like :key or subtitle like :key or author like :key or publisher like :key or keyword like :key " + "order by length(title) "; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("key", "%"+keyword+"%"); return query.list(); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getSearchOrderByKeys(List<String> isbns) { // TODO Auto-generated method stub String hql= "select new PartRentable(u.id,u.picture,u.way,u.rent_price,u.sale_price,t.title) from Rentable u,Isbn t where u.information = t.isbn and u.information = (:keys)"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameterList("keys", isbns); return query.list(); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getSearchOrderByKey(String isbnstr) { // TODO Auto-generated method stub String hql= "select new PartRentable(u.id,u.picture,u.way,u.rent_price,u.sale_price,t.title) from Rentable u,Isbn t where u.information = (:keys)"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("keys", isbnstr); return query.list(); } }
/** * Copyright (c) 2013 SLL <http://sll.se/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.sll.rtjp.puadapter.extractor; import se.sll.rtjp.puadapter.extractor.fields.SnodFieldsInterface; /** * Helperclass that performs substring exctractions from SNOD responses * using positions from a {@link SnodFieldsInterface}. */ public class ResidentExtractor { /** The point at which the proper data starts in a SNOD response string. */ private static final int SNOD_DATA_START_POSITION = 9; /** The SNOD response string to extract from. */ private String snodResponse; public ResidentExtractor(String snodResponse) { this.snodResponse = snodResponse.substring(SNOD_DATA_START_POSITION); } /** * Fetches the value for a specific {@link SnodFieldsInterface} from * the stored snodResponse. * @param field The {@link SnodFieldsInterface} to extract. * @return The extracted value for the desired field. */ public String getField(SnodFieldsInterface field) { return snodResponse.substring(field.startIndex(), field.endIndex()).trim(); } }
package Dao; import java.sql.SQLException; import java.util.List; import entity.UserTicket; public interface UserTicketDao { /** * 添加 * @param UserTicket * @return * @throws Exception */ boolean add(int userticketuserid,int userticketticketid,String userticketname,String userticketidentity_number,String userticketstation_arrival,String userticketstation_depart,String userticketdepart_date,String userticketdepart_time,int userticketticket_number,String userticketseattype,String usertickettickettype,String userticketfares,String userticketticket_office) throws Exception; /** * 修改 * @param UserTicket * @return * @throws SQLException */ boolean update(UserTicket UserTicket) throws SQLException; /** * 删除 * @param UserTicketid * @return * @throws SQLException */ void delete(int userticketid) throws SQLException; /** * 通过UserTicketid查找记录 * @param UserTicketid * @return * @throws SQLException */ List<UserTicket> QueryByuserticketuserid(int userticketuserid) throws SQLException; /** * 通过UserTicketid查找记录 * @param UserTicketid * @return * @throws SQLException */ List<UserTicket> QueryByuserticketticketid(int userticketticketid) throws SQLException; /** * 查找全部记录 * @return * @throws SQLException */ List<UserTicket> queryAll() throws SQLException; /** * 重复验证 * @param ticketid * @param userid * @return * @throws SQLException * @throws Exception */ boolean buyTicket(int ticketid,int userid) throws SQLException, Exception; /** * adduserticket * @param ticketid * @param userid * @return * @throws SQLException * @throws Exception */ boolean buyTicketb(int ticketid,int userid) throws SQLException, Exception; /** * 根据userticketid,userticketticketid 删除一条信息 * @param userticketid * @param userticketticketid * @return * @throws SQLException * @throws Exception */ boolean fundTicket(int userticketid,int userticketticketid) throws SQLException, Exception; /** * 重复性验证 * @param userid * @param ticketid * @return * @throws SQLException */ boolean SelectUidTid(int userid,int ticketid) throws SQLException; boolean Left(int ticketid) throws SQLException; }
package pl.pjatk.gameplay.controller; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import pl.pjatk.gameplay.model.Player; import pl.pjatk.gameplay.service.PlayerService; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc public class PlayerControllerTestIT { @Autowired private MockMvc mockMvc; @Autowired private PlayerService playerService; @Test void findAll() throws Exception { mockMvc.perform(get("/player")).andDo(print()).andExpect(status().isOk()); } // utowrzyc test aby sprawdzic czy zwraca podana wartosc / stworzyc metode w player controler z "/player/test" // @Test // void shouldMatchContent() throws Exception { // mockMvc.perform(get("/player/test")) // .andDo(print()) // .andExpect(status().isOk()) // .andExpect(content().string(containsString("Hello"))); // } @Test void shouldNotFound() throws Exception { mockMvc.perform(get("/player/1")) .andDo(print()) .andExpect(status().isNotFound()); } @Test void shouldFoundPlayer() throws Exception { playerService.save(new Player("nickname", 100, 10, 10)); mockMvc.perform(get("/player/1")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(equalTo( "{\"id\":1,\"nickname\":\"nickname\",\"health\":100,\"attack\":10,\"mana\":10}"))); } }
package com.suntf.pkm.util; import org.apache.http.HttpEntity; /** * The call back interface for * * @author bright_zheng * */ public interface AsyncResponseListener { /** Handle successful response */ public void onResponseReceived(HttpEntity response); /** Handle exception */ public void onResponseReceived(Throwable response); }
package com.sai.one.dto; public interface Entity { }
package controllers; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import models.Cart; import models.Product; public class CartController { public static void addProduct(Cart cart, Product product, Integer qnt) { Map<Product, Integer> set = cart.getProducts(); if (set.containsKey(product)) { qnt += cart.getProducts().get(product); } cart.getProducts().put(product, qnt); CartController.countCartSize(cart); CartController.countTotalCost(cart); } public static void setProductQnt(Cart cart, Product product, Integer qnt) { Map<Product, Integer> set = cart.getProducts(); if (set.containsKey(product)) { cart.getProducts().put(product, qnt); } cart.getProducts().put(product, qnt); CartController.countCartSize(cart); CartController.countTotalCost(cart); } public static void removeProduct(Cart cart, Product product, Integer qnt) { Set<Product> set = cart.getProducts().keySet(); if (set.contains(product)) { if (qnt >= cart.getProducts().get(product)) { qnt = cart.getProducts().get(product) - qnt; cart.getProducts().put(product, qnt); } else { removeProductFully(cart, product); } CartController.countCartSize(cart); CartController.countTotalCost(cart); } } public static void countTotalCost(Cart cart) { Set<Product> set = cart.getProducts().keySet(); int total = 0; for (Product product : set) { total += product.getPrice() * cart.getProducts().get(product); } cart.setTotalCost(total); } public static void removeProductFully(Cart cart, Product product) { cart.getProducts().remove(product); CartController.countCartSize(cart); CartController.countTotalCost(cart); } public static void cleanCart(Cart cart) { cart.setProducts(new HashMap<Product, Integer>()); cart.setTotalCost(0); } public static void countCartSize(Cart cart) { Set<Product> set = cart.getProducts().keySet(); int size = 0; for (Product product : set) { size += cart.getProducts().get(product); } cart.setSize(size); } }
package com.aidmo.aidmod.blocks; public class AidBlocks { }
package com.technicaltest.prices.project.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.technicaltest.prices.project.business.PricesManager; import com.technicaltest.prices.project.controller.dto.RequestDTO; import com.technicaltest.prices.project.model.Prices; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/v1/prices") public class PricesController { @Autowired private PricesManager pricesManager; @ApiOperation(value = "Checks the price of a certain product in a certain date") @PostMapping(path = "/checkPrice") public ResponseEntity<Prices> checkPrice(@RequestBody RequestDTO requestedPrice) { Prices response = pricesManager.getPrice(requestedPrice); return ResponseEntity.ok(response); } }
package com.stockstats.exception; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Stats Request is Bad") public class BadStatsRequestException extends Exception { private static final long serialVersionUID = -3622347161140753809L; private String error = "Missing Parameters: "; public BadStatsRequestException(List<FieldError> list) { for (FieldError objectError : list) { error += objectError.getField() + ", "; } error = error.trim(); if (error.charAt(error.length() - 1) == ',') { error = error.substring(0, error.length() - 1); } } @Override public String getMessage() { return error; } }
package emp.entidades; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.CascadeType; @Entity @Table(name="tb_tipo_solicitud") public class TipoSolicitud extends com.axcessfinancial.domain.BaseEntity implements Serializable{ private String nombre; private String descripcion; private int diasTramite; private int diasObservacion; private int estado; @Column(name="estado") public int getEstado() { return estado; } public void setEstado(int estado) { this.estado = estado; } @Column(name="descripcion", length=200) public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @Column(name="nombre", length=200) public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name="diasTramite", length=200) public int getDiasTramite() { return diasTramite; } public void setDiasTramite(int diasTramite) { this.diasTramite = diasTramite; } @Column(name="diasObservacion", length=200) public int getDiasObservacion() { return diasObservacion; } public void setDiasObservacion(int diasObservacion) { this.diasObservacion = diasObservacion; } }
package file; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.Select; public class SeMethods implements WdMethod{ RemoteWebDriver driver; int i = 1; public void startApp(String browser, String url) { if (browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); driver = new ChromeDriver(); } else { System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe"); driver = new FirefoxDriver(); } driver.manage().window().maximize(); driver.get(url); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); System.out.println("The Browser is Launched"); } public WebElement locateElement(String locator, String locValue) { switch (locator) { case "id": return driver.findElementById(locValue); case "name": return driver.findElementByName(locValue); case "class": return driver.findElementByClassName(locValue); case "link": return driver.findElementByLinkText(locValue); case "tag": return driver.findElementByTagName(locValue); case "xpath": return driver.findElementByXPath(locValue); default: break; } return null; } public WebElement locateElement(String locValue) { return locateElement("id", locValue); } public void type(WebElement ele, String data) { ele.clear(); ele.sendKeys(data); System.out.println("The Value is Entered"); takeSnap(); } public void click(WebElement ele) { ele.click(); System.out.println("The Element Is Clicked"); takeSnap(); } public void clickWithNoSnap(WebElement ele) { ele.click(); System.out.println("The Element Is Clicked without snap"); } public String getText(WebElement ele) { ele.getText(); takeSnap(); return null; } public void selectDropDownUsingText(WebElement ele, String value) { Select sel=new Select(ele); sel.selectByVisibleText(value); System.out.println("The Element is Selected using Visible Text"); takeSnap(); } public void selectDropDownUsingIndex(WebElement ele, int index) { Select Sell=new Select(ele); Sell.selectByIndex(index); System.out.println("The Element is Selected using Visible Index"); takeSnap(); } public boolean verifyTitle(String expectedTitle) { String actualTitle=driver.getTitle(); if (actualTitle.contentEquals(expectedTitle)) System.out.println("Title is Verified "); else System.out.println("Title is Not Verified"); takeSnap(); return true; } public void verifyExactText(WebElement ele, String expectedText) { String text = ele.getText(); if (text.equals(expectedText)) System.out.println(" Exact Text "+text+"is been Verified "); else System.out.println("Exact Text "+text+"is Not verfied"); takeSnap(); } public void verifyPartialText(WebElement ele, String expectedText) { String text = ele.getText(); if (text.contains(expectedText)) System.out.println(" Partial Text Verified "); else System.out.println("Partial Text is not Verified"); takeSnap(); } public void verifyExactAttribute(WebElement ele, String attribute, String value) { String attribute1 = ele.getAttribute(attribute); if (attribute1.equals(value)) System.out.println("The Attribute " +attribute1+" is Verified"); else System.out.println("The Attribute " +attribute1+" is not Verified"); takeSnap(); } public void verifyPartialAttribute(WebElement ele, String attribute, String value) { String attribute1 = ele.getAttribute(attribute); if (attribute1.contains(value)) System.out.println("The Partial Attribute is Verified"); else System.out.println("The Partial Attribute is not Verified"); takeSnap(); } public void verifySelected(WebElement ele) { if (ele.isSelected()) System.out.println("The Checkbox Value is Selected"); else System.out.println("The Checkbox Value is Not Selected"); takeSnap(); } public void verifyDisplayed(WebElement ele) { if (ele.isDisplayed()) System.out.println("The Element is Displayed"); else System.out.println("The Element is NOt Dispalyed"); takeSnap(); } public void switchToWindow(int index) { Set<String> allWindows = driver.getWindowHandles(); List<String> all=new ArrayList<String>(); all.addAll(allWindows); driver.switchTo().window(all.get(index)); System.out.println("The Window is Switched of Index " +index); takeSnap(); } public void switchToFrame(WebElement ele) { driver.switchTo().frame(ele); System.out.println("The Frame is Switched Using Webelement " +ele); takeSnap(); } public void acceptAlert() { driver.switchTo().alert().accept(); System.out.println("The Alert is Accepted"); takeSnap(); } public void dismissAlert() { driver.switchTo().alert().dismiss(); System.out.println("The Alert is Dismissed"); takeSnap(); } public String getAlertText() { driver.switchTo().alert().getText(); System.out.println("The Text Alert is Displayed"); takeSnap(); return null; } public void takeSnap() { File src = driver.getScreenshotAs(OutputType.FILE); File desc = new File("./snaps/img"+i+".png"); try { FileUtils.copyFile(src, desc); } catch (IOException e) { e.printStackTrace(); } i++; } public void closeBrowser() { driver.close(); System.out.println("The Browser is Closed"); takeSnap(); } public void closeAllBrowsers() { driver.quit(); System.out.println("All Browsers are Closed"); } }
package controller; import model.ModelUsuarios; import DAO.DAOUsuarios; import java.util.ArrayList; /** * * @author Vinicius Lisboa */ public class ControllerUsuarios { private DAOUsuarios daoUsuarios = new DAOUsuarios(); /** * grava Usuarios * @param pModelUsuarios * return int */ public int salvarUsuariosController(ModelUsuarios pModelUsuarios){ return this.daoUsuarios.salvarUsuariosDAO(pModelUsuarios); } /** * recupera Usuarios * @param pUsuarioId * return ModelUsuarios */ public ModelUsuarios getUsuariosController(int pUsuarioId){ return this.daoUsuarios.getUsuariosDAO(pUsuarioId); } /** * recupera uma lista deUsuarios * @param pUsuarioId * return ArrayList */ public ArrayList<ModelUsuarios> getListaUsuariosController(){ return this.daoUsuarios.getListaUsuariosDAO(); } /** * atualiza Usuarios * @param pModelUsuarios * return boolean */ public boolean atualizarUsuariosController(ModelUsuarios pModelUsuarios){ return this.daoUsuarios.atualizarUsuariosDAO(pModelUsuarios); } /** * exclui Usuarios * @param pUsuarioId * return boolean */ public boolean excluirUsuariosController(int pUsuarioId){ return this.daoUsuarios.excluirUsuariosDAO(pUsuarioId); } /** * Validar login e senha * @param pModelUsuarios * @return */ public boolean getValidarUsuarioController(ModelUsuarios pModelUsuarios) { return this.daoUsuarios.getValidarUsuarioDAO(pModelUsuarios); } public void getUsuarioIdController(int usuarioId) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package serve.serveup.views; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import serve.serveup.R; import serve.serveup.views.login.LoginFragment; import serve.serveup.views.login.RegistrationFragment; public class MainActivity extends AppCompatActivity implements LoginFragment.OnFragmentInteractionListener, RegistrationFragment.OnFragmentInteractionListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_login); LoginFragment myLoginFrag = new LoginFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, myLoginFrag).commit(); } @Override public void onFragmentInteraction(Uri uri) { // fragment interaction } @Override public void onBackPressed() { int isH = findViewById(R.id.login_container).getVisibility(); if(isH == View.INVISIBLE) findViewById(R.id.login_container).setVisibility(View.VISIBLE); super.onBackPressed(); } }
package starwars.app.starwarsse.adapters; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import starwars.app.starwarsse.R; import starwars.app.starwarsse.model.Result; /** * Created by cba on 2017-09-12. */ public class ShipsAdapter extends RecyclerView.Adapter<ShipsAdapter.ShipsViewHolder> { private List<Result> results; private int rowLayout; public class ShipsViewHolder extends RecyclerView.ViewHolder { LinearLayout shipsLayout; TextView shipName, model, manufacturer, creditCost, length, maxAtmSpeed, crew, passengers, cargoCap, consumables, hyperDRating, mGLT, starShipClass; public ShipsViewHolder(View shipsView) { super(shipsView); shipsLayout = (LinearLayout) shipsView.findViewById(R.id.shipsLayout); shipName = (TextView) shipsView.findViewById(R.id.shipName); model = (TextView) shipsView.findViewById(R.id.model); manufacturer = (TextView) shipsView.findViewById(R.id.manufacturer); creditCost = (TextView) shipsView.findViewById(R.id.creditCost); length = (TextView) shipsView.findViewById(R.id.shipLength); maxAtmSpeed = (TextView) shipsView.findViewById(R.id.maxSpeed); crew = (TextView) shipsView.findViewById(R.id.crew); passengers = (TextView) shipsView.findViewById(R.id.passengers); cargoCap = (TextView) shipsView.findViewById(R.id.cargoCapacity); consumables = (TextView) shipsView.findViewById(R.id.consumables); hyperDRating = (TextView) shipsView.findViewById(R.id.hdRating); mGLT = (TextView) shipsView.findViewById(R.id.mGLT); starShipClass = (TextView) shipsView.findViewById(R.id.shipClass); } } public ShipsAdapter(List<Result> results, int rowLayout) { this.results = results; this.rowLayout = rowLayout; } @Override public ShipsAdapter.ShipsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false); return new ShipsViewHolder(view); } @Override public void onBindViewHolder(ShipsAdapter.ShipsViewHolder holder, int position) { holder.shipName.setText(results.get(position).getName()); holder.model.setText("Model: " + results.get(position).getModel()); holder.manufacturer.setText("Manufacturer: " + results.get(position).getManufacturer()); holder.creditCost.setText("Cost in Credits: " + results.get(position).getCostInCredits()); holder.length.setText("Length: " + results.get(position).getLength()); holder.maxAtmSpeed.setText("Max Atmosphering Speed: " + results.get(position).getMaxAtmospheringSpeed()); holder.crew.setText("Crew: " + results.get(position).getCrew()); holder.passengers.setText("Passengers: " + results.get(position).getPassengers()); holder.cargoCap.setText("Cargo Capacity: " + results.get(position).getCargoCapacity()); holder.consumables.setText("Consumables: " + results.get(position).getConsumables()); holder.hyperDRating.setText("Hyperdrive Rating: " + results.get(position).getHyperdriveRating()); holder.mGLT.setText("MGLT: " + results.get(position).getMGLT()); holder.starShipClass.setText("Starship Class: " + results.get(position).getStarshipClass()); } @Override public int getItemCount() { return results.size(); } }
package com.application.dockers.SQLite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import androidx.annotation.Nullable; public class DockersActivitySQLiteHelper extends SQLiteOpenHelper { public static final String NOM_TABLE = "activites"; public static final String COLONNE_ID = "_id"; public static final String COLONNE_ACTIVITE = "activite"; public static final String COLONNE_ACTION = "actions"; public static final String COLONNE_DATE = "dates"; public static final String DATABASE_NAME = "DockersActivity.db"; private static final int VERSION = 1; public DockersActivitySQLiteHelper(@Nullable Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { System.out.println("ICI"); db.execSQL("CREATE TABLE " + NOM_TABLE + " (" + COLONNE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLONNE_ACTIVITE + " text not null, " + COLONNE_DATE + " text not null, " + COLONNE_ACTION + " text not null)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(DockersActivitySQLiteHelper.class.getName(), "Mise à jour de la version " + oldVersion + " à " + newVersion + " - les anciennes données seront perdues"); db.execSQL("drop table if exists " + NOM_TABLE); onCreate(db); } }
package com.testFileUpload.filter; import com.testFileUpload.util.JWTToken; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class JwtFilter extends BasicHttpAuthenticationFilter { @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException { if (((HttpServletRequest) request).getHeader("Token") != null) { //如果存在,则进入 executeLogin 方法执行登入,检查 token 是否正确 try { executeLogin(request, response); return true; } catch (Exception e) { //token 错误 System.out.println(e.getMessage()); } } return true; //如果请求头不存在 Token,则可能是执行登陆操作或者是游客状态访问,无需检查 token,直接返回 true } @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader("Token"); JWTToken jwtToken = new JWTToken(token); // 提交给realm进行登入,如果错误他会抛出异常并被捕获 getSubject(request, response).login(jwtToken); // 如果没有抛出异常则代表登入成功,返回true return true; } }
package com.zxq.spring.controller; import com.zxq.spring.entity.CommentResult; import com.zxq.spring.entity.Payment; import com.zxq.spring.service.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import java.util.concurrent.TimeUnit; @RestController @Slf4j public class PaymentController { @Autowired private PaymentService paymentService; @Value("${server.port}") private String serverPort; @PostMapping("/payment/create") public CommentResult<Payment> create(@RequestBody Payment payment){ int number = paymentService.create(payment); log.info("=======查询结果为:"+number); if (number>0){ return new CommentResult(200,"新增成功,serverPort:"+serverPort,number); }else{ return new CommentResult(444,"新增失败",number); } } @GetMapping("/payment/select/{id}") public CommentResult<Payment> select(@PathVariable("id") Long id){ Payment payment = paymentService.selectById(id); if (payment!=null){ return new CommentResult(200,"查询成功,serverPort:"+serverPort,payment); }else{ return new CommentResult(444,"没有该id为"+id+"的数据",null); } } //设置该方法超时时间为3秒 @GetMapping("/payment/timeOut") public String paymentTimeOut() { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return serverPort; } }
package com.capp.test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.capp.config.SpringRootConfig; import com.capp.dao.UserDAO; import com.capp.domain.User; import com.capp.service.UserService; public class TestUserServiceRegister { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRootConfig.class); UserService userService= ctx.getBean(UserService.class); User u = new User(); u.setName("Arnav"); u.setPhone("5555555555"); u.setAddress("Court"); u.setPassword("a123"); u.setRole(UserService.ROLE_ADMIN); u.setLoginName("ArnavGoswami"); u.setEmail("A@gmail.com"); u.setLoginStatus(UserService.LOGIN_STATUS_ACTIVE); userService.register(u); System.out.println("User registered successfully"); } }
package com.way.mobile.permission; import java.lang.annotation.*; /** * 功能描述:服务鉴权方式 :注解可以加在方法 * * @ClassName AuthPermission * @Author:xinpei.xu * @Date:2017/07/20 20:49 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface AuthPermission { /** * 是否需要验证 :yes:需要 no:不需要 * @return */ AuthorityType authType() default AuthorityType.YES; }
package ru.qa.rtsoft; import org.testng.Assert; import org.testng.annotations.Test; /** * Created by korvin on 17.02.2017. */ public class SquareTests { @Test public void testArea(){ Square s = new Square(7); Assert.assertEquals(s.area(), 49.0); } }
package com.esum.framework.common.thread; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ThreadFactory. * Thread생성을 daemon으로 생성하도록 하며, thread마다 고유의 이름을 부여한다.(xtrus로 시작함) */ public class CommonThreadFactory implements ThreadFactory { private static Logger log = LoggerFactory.getLogger(CommonThreadFactory.class); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public CommonThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); this.group = ((s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup()); String effectiveName = name.replace(' ', '-'); this.namePrefix = "xtrus-" + effectiveName + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0); if (!(t.isDaemon())) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } if (log.isTraceEnabled()) { log.trace("newThread({})[{}] runnable={}", group, t.getName(), r); } return t; } }
package com.delaroystudios.alarmreminder.Adapter; public interface IClickListenerAvatarChildAdapter { void ClickAvatarChild(int iD); }
package core; public enum Type { XPATH, CSS }
package com.lsjr.zizisteward.activity.product.ui; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import com.alipay.sdk.app.PayTask; import com.google.gson.Gson; import com.lsjr.base.MvpActivity; import com.lsjr.zizisteward.Config; import com.lsjr.zizisteward.R; import com.lsjr.zizisteward.activity.product.presenter.PayWayPresenter; import com.lsjr.zizisteward.activity.product.view.IPayWayListView; import com.lsjr.zizisteward.bean.AliPayBean; import com.lsjr.zizisteward.bean.WeiPayBean; import com.lsjr.zizisteward.http.AppUrl; import com.tencent.mm.opensdk.modelpay.PayReq; import com.ymz.baselibrary.utils.L_; import com.ymz.baselibrary.utils.SystemBarHelper; import com.ymz.baselibrary.utils.T_; import com.ymz.baselibrary.utils.UIUtils; import com.ymz.baselibrary.widget.NavigationBarView; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import static com.lsjr.zizisteward.MyApplication.wxApi; /** * Created by admin on 2017/5/24. */ public class PayWayActivity extends MvpActivity<PayWayPresenter> implements IPayWayListView { @BindView(R.id.webview) WebView webview; @BindView(R.id.id_nativgation_view) NavigationBarView idNativgationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @SuppressLint({"JavascriptInterface", "AddJavascriptInterface", "SetJavaScriptEnabled"}) @Override protected void initView() { super.initView(); Bundle bundle = getIntent().getExtras(); String orderUrl = bundle.getString(Config.ORDERUTL); WebSettings webSettings = webview.getSettings(); webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setJavaScriptEnabled(true); webview.addJavascriptInterface(new PayWayH5Contrl(), Config.H5CONTRL); if (orderUrl != null) { webview.loadUrl(AppUrl.Http + orderUrl); } } @Override public void onNetWeiPayWayResult(String result) { L_.e("微信支付" + result); PayReq payReq = new PayReq(); WeiPayBean wx_bean = new Gson().fromJson(result, WeiPayBean.class); List<WeiPayBean.AlipayValueBean> wx_code = wx_bean.getAlipayValue(); payReq.appId = wx_code.get(0).getAppid();/*应用id*/ payReq.partnerId = wx_code.get(0).getPartnerid();/*商户号*/ payReq.packageValue = "Sign=WXPay";/*扩展字段*/ payReq.prepayId = wx_code.get(0).getPrepayid();/*预支付订单号*/ payReq.nonceStr = wx_code.get(0).getNoncestr();/*随机字符串*/ payReq.timeStamp = wx_code.get(0).getTimestamp();/*时间戳*/ payReq.sign = wx_code.get(0).getSign();/*签名*/ if (payReq.checkArgs()) { wxApi.sendReq(payReq); } else { T_.showToastReal("请检查参数"); } } private static final int SDK_PAY_FLAG = 1; @Override public void onNetZFBPayWayResult(String result) { L_.e("支付宝支付返回" + result); AliPayBean aliPayBean = new Gson().fromJson(result, AliPayBean.class); final String orderInfo = aliPayBean.getAlipayValue(); Runnable payRunnable = new Runnable() { @Override public void run() { PayTask alipay = new PayTask(PayWayActivity.this); Map<String, String> result = alipay.payV2(orderInfo, true); Message msg = new Message(); msg.what = SDK_PAY_FLAG; msg.obj = result; alipayHandler.sendMessage(msg); } }; Thread payThread = new Thread(payRunnable); payThread.start(); } @Override protected void initTitle() { super.initTitle(); SystemBarHelper.tintStatusBar(this, UIUtils.getColor(R.color.colorBlack)); idNativgationView.setTitleText("选择付款"); } @Override protected int getLayoutId() { return R.layout.activity_payway; } @Override protected void afterCreate(Bundle bundle) { } @SuppressLint("HandlerLeak") private Handler alipayHandler = new Handler() { @SuppressWarnings("unused") public void handleMessage(Message msg) { switch (msg.what) { case SDK_PAY_FLAG: { @SuppressWarnings("unchecked") AliPayBean.PayResult payResult = new AliPayBean.PayResult((Map<String, String>) msg.obj); /** * 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。 */ String resultInfo = payResult.getResult();// 同步返回需要验证的信息 String resultStatus = payResult.getResultStatus(); // 判断resultStatus 为9000则代表支付成功 if (TextUtils.equals(resultStatus, "9000")) { // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。 T_.showToastReal("支付成功"); finish(); } else { // 该笔订单真实的支付结果,需要依赖服务端的异步通知。 T_.showToastReal("支付失败"); } break; } } } }; public class PayWayH5Contrl { public PayWayH5Contrl() { super(); } /** * 微信支付交互 * 和H5方法名 参数类型必须一致 * * @param */ @JavascriptInterface public void WXpayment(String body, String out_trade_no, String total_amount) { getWeiChatPayParamForNet(body, out_trade_no, total_amount); } /** * 支付宝支付 * * @param body * @param subject * @param out_trade_no * @param total_amount */ @JavascriptInterface public void ZFBpayment(String body, String subject, String out_trade_no, String total_amount) { getZFBPayParamForNet(body, subject, out_trade_no, total_amount); } } public void getZFBPayParamForNet(String body, String subject, String out_trade_no, String total_amount) { HashMap<String, String> map = new HashMap<String, String>(); map.put("OPT", "93"); map.put("tradeNo", out_trade_no); map.put("amount", total_amount); map.put("description", body); map.put("title", subject); createPresenter().getZFBPayParam(map); } public void getWeiChatPayParamForNet(String body, String out_trade_no, String total_amount) { HashMap<String, String> map = new HashMap<>(); map.put("OPT", "337"); map.put("tradeNo", out_trade_no); map.put("amount", total_amount); map.put("body", body); map.put("user_ip", createPresenter().getIPAddress(this)); createPresenter().getWeiPayParam(map); } @Override protected PayWayPresenter createPresenter() { return new PayWayPresenter(this); } @Override protected void onDestroy() { if (webview != null) { ViewParent parent = webview.getParent(); if (parent != null) { ((ViewGroup) parent).removeView(webview); } webview.stopLoading(); // 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错 webview.getSettings().setJavaScriptEnabled(false); webview.clearHistory(); webview.clearView(); webview.removeAllViews(); try { webview.destroy(); } catch (Throwable ex) { } } super.onDestroy(); } @Override public int getFragmentContentId() { return 0; } }
package com.example.android.sunshine.app.gcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.example.android.sunshine.app.MainActivity; import com.example.android.sunshine.app.R; import com.google.android.gms.gcm.GcmListenerService; import org.json.JSONException; import org.json.JSONObject; /** * Created by sorengoard on 10/10/16. */ public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; private static final String EXTRA_DATA = "data"; private static final String EXTRA_WEATHER = "weather"; private static final String EXTRA_LOCATION = "location"; public static final int NOTIFICATION_ID = 1; @Override public void onMessageReceived(String from, Bundle data) { //unparcelling the bundle if (!data.isEmpty()) { String senderId = getString(R.string.gcm_defaultSenderId); if(senderId.length() == 0) { Toast.makeText(this, "senderID string needsd to be set", Toast.LENGTH_LONG).show(); } //check message is coming from your server if((senderId).equals(from)) { //process message and then post a notification of the received message try { JSONObject jsonObject = new JSONObject(data.getString(EXTRA_DATA)); String weather = jsonObject.getString(EXTRA_WEATHER); String location = jsonObject.getString(EXTRA_LOCATION); String alert = String.format(getString(R.string.gcm_weather_alert), weather, location); sendNotification(alert); } catch(JSONException e){ //json parszing failed, so we let this message go - gcm ain't a critical feature } } Log.i(TAG, "received: " + data.toString()); } } //puts the message into a notification and posts it private void sendNotification(String message) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); //need to create a bmp from resource id Bitmap largeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.art_storm); NotificationCompat.Builder bobTheBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.art_clear) .setLargeIcon(largeIcon) .setContentTitle("HOLD UP! Weather Alert!") .setStyle(new NotificationCompat.BigTextStyle().bigText(message)) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_HIGH); bobTheBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, bobTheBuilder.build()); } }
package ejercicio17; import java.util.ArrayList; import java.util.Scanner; /** * * @author Javier */ public class Ejercicio17 { public static boolean esPrimo(int numero) { boolean primo = true; for (int i = 2; i < numero/2+1 & primo; i++) { if (numero %i == 0) primo = false; } return primo; } public static void main(String[] args) { Scanner entrada = new Scanner(System.in); ArrayList <Integer> numeros = new ArrayList <>(); boolean seguir = true; System.out.println("Introduce un numero para su comprobación" + "\nIntroduce 0 para terminar: "); do { int intro = entrada.nextInt(); if (intro == 0) seguir = false; else numeros.add(intro); } while (seguir); for (int i = 0; i < numeros.size(); i++) { if (esPrimo(numeros.get(i))) System.out.println(numeros.get(i)+ " es primo"); else System.out.println(numeros.get(i)+ " no es primo"); } } }
package diabetes.aclass.presenter; import android.util.Log; import java.io.IOException; import diabetes.aclass.diabetes.HomePageActivity; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static android.support.constraint.Constraints.TAG; public class PostManagement { public void saveData(String url, String postdata, final Callback callback){ OkHttpClient client = new OkHttpClient(); MediaType MEDIA_TYPE = MediaType.parse("application/json"); RequestBody body = RequestBody.create(MEDIA_TYPE, postdata); Request request = new Request.Builder() .url(url) .post(body) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.w("failure Response", "failure Response"); if (callback == null) return; callback.onFailure(call,e); } @Override public void onResponse(Call call, Response response) throws IOException { String mMessage = response.body().string(); Log.e(TAG, mMessage); try { if (callback == null) return; callback.onResponse(call, response); } catch (IOException e) { e.printStackTrace(); } } }); } }
package com.beike.wap.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.beike.wap.dao.MCatalogDao; import com.beike.wap.entity.MAbstractCatlog; import com.beike.wap.entity.MCouponCatlog; import com.beike.wap.entity.MerchantCatlog; import com.beike.wap.service.MCatalogService; @Service("mCatalogService") public class MCatalogServiceImpl implements MCatalogService { @Autowired private MCatalogDao mCatalogDao; // @Resource(name = "wapRegionDao") // private MRegionDao regionDao; @Override public MAbstractCatlog findById(Long id) { // TODO Auto-generated method stub return null; } @Override public MCouponCatlog getCouponCatlogById(long couponId) { MCouponCatlog catalog = mCatalogDao.findCouponCatalogById(couponId); // MRegion region = null; // try { // region = regionDao.findRegionById(catalog.getRegionextid()); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // if(region != null) // { // catalog.setRegionName(region.getRegionName()); // } return catalog; } @Override public int getCouponCatalogSum(MCouponCatlog couponCatlog) throws Exception { return mCatalogDao.getCouponCatalogSum(couponCatlog); } @Override public List<Long> getAllCouponId(int startPage, MCouponCatlog couponCatlog) throws Exception { return mCatalogDao.queryCouponId(startPage, couponCatlog); } @Override public int getBrandCatlogSum(MerchantCatlog brandCatlog) throws Exception { return mCatalogDao.getBrandCatalogSum(brandCatlog); } @Override public List<Long> getAllMerchantId(int startPage, MerchantCatlog brandCatlog) throws Exception { return mCatalogDao.queryBrandId(startPage, brandCatlog); } }
package dao; import java.util.List; import hibernate.HibernateUtil; import model.AddressLookup; import model.Directorate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; public class DirectorateDAO implements DirectorateInterface{ private Session session; private Transaction transaction; public void openSession() { session = HibernateUtil.getSessionFactory().openSession(); } public void openSessionWithBeginTransaction() { session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); } public void commit() { transaction.commit(); } public void rollback() { transaction.rollback(); } // public static void main(String args[]){ // DirectorateDAO dao = new DirectorateDAO(); // Directorate dir = new Directorate("123abc"); // // dao.insertDir(dir); // System.out.println("Insert successfull"); // // } public void closeSession () { session.close(); } @Override public void deleteDir(Directorate directorate) { try { openSessionWithBeginTransaction(); session.delete(directorate); commit(); } catch (HibernateException e) { System.out.println("Failed when to delete Directorate!"); e.printStackTrace(); rollback(); } finally { closeSession(); } } @Override public void insertDir(Directorate directorate) { try { openSessionWithBeginTransaction(); session.saveOrUpdate(directorate); commit(); } catch (HibernateException e) { System.out.println("Failed when to insert Directorate!"); e.printStackTrace(); rollback(); } finally { closeSession(); } } @Override public List<Directorate> getAllDir() { try { openSessionWithBeginTransaction(); @SuppressWarnings("unchecked") List<Directorate> directorate = session.createCriteria(Directorate.class).list(); for (Directorate dir : directorate) { System.out.println(dir.getDirectorateName()); System.out.println(dir.getAddrLine1()); System.out.println(dir.getLeadContact()); System.out.println(dir.getPostcode()); System.out.println(dir.isActive()); } commit(); return directorate; } catch (HibernateException e) { System.out.println("Failed when to get list directorate!"); e.printStackTrace(); rollback(); } finally { closeSession(); } return null; } //upadte directorate public void updateDir(Directorate directorate){ try { openSessionWithBeginTransaction(); //Find directorate Directorate oldDir = (Directorate) session.get(Directorate.class, directorate.getDirectorateName()); //set short description oldDir.setShortDescr(directorate.getShortDescr()); //set lead contact oldDir.setLeadContact(directorate.getLeadContact()); //set copy address from organisation oldDir.setCpAddr(directorate.isCpAddr()); //set address line 1 oldDir.setAddrLine1(directorate.getAddrLine1()); //set postcode oldDir.setPostcode(directorate.getPostcode()); //set town oldDir.setTown(directorate.getTown()); //set county oldDir.setCounty(directorate.getCounty()); //set nation oldDir.setNation(directorate.getNation()); //set type of business oldDir.setTypeBusiness(directorate.getTypeBusiness()); //set SICCode oldDir.setSICcode(directorate.getSICcode()); //set full decription oldDir.setFullDescr(directorate.getFullDescr()); //set phone number oldDir.setPhoneNumber(directorate.getPhoneNumber()); //set fax oldDir.setFax(directorate.getFax()); //set email oldDir.setEmail(directorate.getEmail()); //set web address oldDir.setWebAddress(directorate.getWebAddress()); //set charity number oldDir.setCharNumber(directorate.getCharNumber()); //set company number oldDir.setCompNumber(directorate.getCompNumber()); commit(); } catch (HibernateException e) { System.out.println("Failed when to update Directorate!"); e.printStackTrace(); rollback(); } finally { closeSession(); } } @Override public Directorate FindDir(String directorateName) { try { openSession(); Directorate dir = (Directorate)session.get(Directorate.class, directorateName); return dir; } catch (HibernateException e) { System.out.println("Failed when to Find Directorate!"); e.printStackTrace(); } finally { closeSession(); } return null; } }
package com.shichuang.mobileworkingticket.entify; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Administrator on 2018/3/23. */ public class WorkingTicketDetails { private List<WorkFlowModels> workFlowModels; private List<MemberRosModel> memberRos; private TicketRowModel ticketRow; private List<CauseAnalysisModel> causeAnalysisModels; public List<WorkFlowModels> getWorkFlowModels() { return workFlowModels; } public void setWorkFlowModels(List<WorkFlowModels> workFlowModels) { this.workFlowModels = workFlowModels; } public List<MemberRosModel> getMemberRos() { return memberRos; } public void setMemberRos(List<MemberRosModel> memberRos) { this.memberRos = memberRos; } public TicketRowModel getTicketRow() { return ticketRow; } public void setTicketRow(TicketRowModel ticketRow) { this.ticketRow = ticketRow; } public List<CauseAnalysisModel> getCauseAnalysisModels() { return causeAnalysisModels; } public void setCauseAnalysisModels(List<CauseAnalysisModel> causeAnalysisModels) { this.causeAnalysisModels = causeAnalysisModels; } public static class WorkFlowModels { private int id; @SerializedName("ticket_id") private int ticketId; @SerializedName("flow_content") private String flowContent; @SerializedName("add_time") private String addTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTicketId() { return ticketId; } public void setTicketId(int ticketId) { this.ticketId = ticketId; } public String getFlowContent() { return flowContent; } public void setFlowContent(String flowContent) { this.flowContent = flowContent; } public String getAddTime() { return addTime; } public void setAddTime(String addTime) { this.addTime = addTime; } } public static class MemberRosModel { private int id; @SerializedName("nick_name") private String nickName; @SerializedName("head_portrait") private String headPortrait; @SerializedName("phone_num") private String phoneNum; @SerializedName("position_name") private String positionName; @SerializedName("dept_name") private String deptName; @SerializedName("user_type_of_work") private int userTypeOfWork; // 计划员=1,调度员=2,发料员=3,工序组长=4,检验员=5,工序组员=6,发运员=7 @SerializedName("process_name") private String processName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getHeadPortrait() { return headPortrait; } public void setHeadPortrait(String headPortrait) { this.headPortrait = headPortrait; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public int getUserTypeOfWork() { return userTypeOfWork; } public void setUserTypeOfWork(int userTypeOfWork) { this.userTypeOfWork = userTypeOfWork; } public String getProcessName() { return processName; } public void setProcessName(String processName) { this.processName = processName; } } public static class TicketRowModel { private int id; @SerializedName("work_ticket_num") private String workTicketNum; @SerializedName("work_order_no") private String workOrderNo; @SerializedName("product_drawing_no") private String productDrawingNo; private String component; @SerializedName("parts_drawing_no") private String partsDrawingNo; @SerializedName("brand_no") private String brandNo; private String specifications; @SerializedName("overall_dimensions") private String overallDimensions; @SerializedName("parts_name") private String partsName; @SerializedName("each_number") private int eachNumber; @SerializedName("plan_number") private int planNumber; @SerializedName("complete_count") private int completeCount; private int priority; // 优先级 1=紧急 2=普通 @SerializedName("work_ticket_state") private String workTicketState; @SerializedName("reference_drawings") private String referenceDrawings; @SerializedName("add_time") private String addTime; @SerializedName("workshop_name") private String workshopName; @SerializedName("operation_display") private int operationDisplay; // 操作显示 2=发料 3=分配 4=生产作业未开始 5=生产作业进行中 6=质量检查 @SerializedName("process_state") private String processState; @SerializedName("process_name") private String processName; @SerializedName("now_process_id") private int nowProcessId; @SerializedName("release_user_name") private String releaseUsername; @SerializedName("working_hours") private String workingHours; // 当前工序总工时 @SerializedName("preparation_hours") private String preparationHours; // 当前工序准备工时 @SerializedName("single_hours") private String singleHours; // 当前工序单件工时 private String lastProcess; // 最后一道工序 @SerializedName("leader_remarks") private String leaderRemarks; // 当期工序组长备注信息 @SerializedName("group_remarks") private String groupRemarks; // 当前工序组员备注信息 @SerializedName("work_ticket_remark") private String workTicketRemark; // 施工备注信息 private String remark; private String remark1; private String remark2; @SerializedName("craft_name") private String craftName; // 程序 @SerializedName("steel_seal") private String steelSeal; // 钢印 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getWorkTicketNum() { return workTicketNum; } public void setWorkTicketNum(String workTicketNum) { this.workTicketNum = workTicketNum; } public String getWorkOrderNo() { return workOrderNo; } public void setWorkOrderNo(String workOrderNo) { this.workOrderNo = workOrderNo; } public String getProductDrawingNo() { return productDrawingNo; } public void setProductDrawingNo(String productDrawingNo) { this.productDrawingNo = productDrawingNo; } public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } public String getPartsDrawingNo() { return partsDrawingNo; } public void setPartsDrawingNo(String partsDrawingNo) { this.partsDrawingNo = partsDrawingNo; } public String getBrandNo() { return brandNo; } public void setBrandNo(String brandNo) { this.brandNo = brandNo; } public String getSpecifications() { return specifications; } public void setSpecifications(String specifications) { this.specifications = specifications; } public String getOverallDimensions() { return overallDimensions; } public void setOverallDimensions(String overallDimensions) { this.overallDimensions = overallDimensions; } public String getPartsName() { return partsName; } public void setPartsName(String partsName) { this.partsName = partsName; } public int getEachNumber() { return eachNumber; } public void setEachNumber(int eachNumber) { this.eachNumber = eachNumber; } public int getPlanNumber() { return planNumber; } public void setPlanNumber(int planNumber) { this.planNumber = planNumber; } public int getCompleteCount() { return completeCount; } public void setCompleteCount(int completeCount) { this.completeCount = completeCount; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getWorkTicketState() { return workTicketState; } public void setWorkTicketState(String workTicketState) { this.workTicketState = workTicketState; } public String getReferenceDrawings() { return referenceDrawings; } public void setReferenceDrawings(String referenceDrawings) { this.referenceDrawings = referenceDrawings; } public String getAddTime() { return addTime; } public void setAddTime(String addTime) { this.addTime = addTime; } public String getWorkshopName() { return workshopName; } public void setWorkshopName(String workshopName) { this.workshopName = workshopName; } public int getOperationDisplay() { return operationDisplay; } public void setOperationDisplay(int operationDisplay) { this.operationDisplay = operationDisplay; } public String getProcessState() { return processState; } public void setProcessState(String processState) { this.processState = processState; } public String getProcessName() { return processName; } public void setProcessName(String processName) { this.processName = processName; } public int getNowProcessId() { return nowProcessId; } public void setNowProcessId(int nowProcessId) { this.nowProcessId = nowProcessId; } public String getReleaseUsername() { return releaseUsername; } public void setReleaseUsername(String releaseUsername) { this.releaseUsername = releaseUsername; } public String getWorkingHours() { return workingHours; } public void setWorkingHours(String workingHours) { this.workingHours = workingHours; } public String getPreparationHours() { return preparationHours; } public void setPreparationHours(String preparationHours) { this.preparationHours = preparationHours; } public String getSingleHours() { return singleHours; } public void setSingleHours(String singleHours) { this.singleHours = singleHours; } public String getLastProcess() { return lastProcess; } public void setLastProcess(String lastProcess) { this.lastProcess = lastProcess; } public String getLeaderRemarks() { return leaderRemarks; } public void setLeaderRemarks(String leaderRemarks) { this.leaderRemarks = leaderRemarks; } public String getGroupRemarks() { return groupRemarks; } public void setGroupRemarks(String groupRemarks) { this.groupRemarks = groupRemarks; } public String getWorkTicketRemark() { return workTicketRemark; } public void setWorkTicketRemark(String workTicketRemark) { this.workTicketRemark = workTicketRemark; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public String getCraftName() { return craftName; } public void setCraftName(String craftName) { this.craftName = craftName; } public String getSteelSeal() { return steelSeal; } public void setSteelSeal(String steelSeal) { this.steelSeal = steelSeal; } } public static class CauseAnalysisModel { private int id; @SerializedName("process_info_id") private int processInfoId; @SerializedName("cause_content") private String causeContent; @SerializedName("is_enable") private int isEnable; private int sort; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getProcessInfoId() { return processInfoId; } public void setProcessInfoId(int processInfoId) { this.processInfoId = processInfoId; } public String getCauseContent() { return causeContent; } public void setCauseContent(String causeContent) { this.causeContent = causeContent; } public int getIsEnable() { return isEnable; } public void setIsEnable(int isEnable) { this.isEnable = isEnable; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } } }
package test.xitikit.examples.java.mysql.logwatch.cli; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.Mockito; import org.xitikit.examples.java.mysql.logwatch.cli.LogWatchCli; import org.xitikit.examples.java.mysql.logwatch.data.*; import org.xitikit.examples.java.mysql.logwatch.files.AccessLogService; import org.xitikit.examples.java.mysql.logwatch.files.AccessLogServiceImpl; import java.time.LocalDateTime; import java.util.List; import static java.util.Arrays.*; import static org.mockito.Mockito.*; /** * Copyright ${year} * * @author J. Keith Hoopes */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LogWatchCliTest{ @Test void emptyCommand(){ LogEntrySearchService logEntrySearchService = Mockito.mock(LogEntrySearchServiceImpl.class); AccessLogService accessLogService = Mockito.mock(AccessLogServiceImpl.class); BlockedIpv4Repository blockedIpv4Repository = Mockito.mock(BlockedIpv4Repository.class); LogWatchCli logWatchCli = new LogWatchCli(logEntrySearchService, accessLogService, blockedIpv4Repository); String[] args = args(); Ipv4SearchQuery query = ipv4SearchQuery(); List<LogEntrySearchResult> toBeReturned = asList(ipv4SearchResult()); doReturn(toBeReturned) .when(logEntrySearchService) .findAddressesThatExceedThreshold(query); logWatchCli.run(args); verify(logEntrySearchService, times(1)) .findAddressesThatExceedThreshold(any()); verify(accessLogService, times(1)) .parseAndSaveAccessLogEntries(any(String.class)); } private static Ipv4SearchQuery ipv4SearchQuery(){ Ipv4SearchQuery query = new Ipv4SearchQuery(); query.setStartDate( LocalDateTime.from(LogWatchCli.formatter.parse("2017-01-01.13:00:00")) ); query.setEndDate(query.getStartDate().plusHours(1)); query.setThreshold(100); return query; } private static LogEntrySearchResult ipv4SearchResult(){ return new LogEntrySearchResult(){ private String ipv4 = "10.150.10.1"; private Integer total = 110; @Override public String getIpv4(){ return ipv4; } @Override public Integer getTotal(){ return total; } }; } private static String[] args(){ return new String[]{ "--accessLog=src/test/resources/access.log", "--startDate=2017-01-01.13:00:00", "--duration=hourly", "--threshold=100"}; } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.explorer.client.layout; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.core.client.resources.ThemeStyles; import com.sencha.gxt.core.client.resources.ThemeStyles.Styles; import com.sencha.gxt.explorer.client.model.Example.Detail; @Detail(name = "VerticalLayout (UiBinder)", icon = "rowlayout", category = "Layouts", files = "VerticalLayoutUiBinderExample.ui.xml") public class VerticalLayoutUiBinderExample implements IsWidget, EntryPoint { @UiField(provided = true) Styles themeStyles = ThemeStyles.getStyle(); interface MyUiBinder extends UiBinder<Widget, VerticalLayoutUiBinderExample> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); public Widget asWidget() { return uiBinder.createAndBindUi(this); } public void onModuleLoad() { RootPanel.get().add(asWidget()); } }
package learnspring.controller; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; 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.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller public class CkeditorController { // Lưu file upload vào thư mục này trên server private static String UPLOAD_FOLDER = "D:/new/upload/"; // Đường dẫn URL đến thư mục chứa các file upload private static String UPLOAD_PATH = "http://localhost:8080/spring-mvc-ckeditor/static/"; /** * Upload bởi hộp thoại. * Khi thêm tùy chọn filebrowserUploadUrl thì các hộp thoại của Link, Image, * HTML5 Video, HTML5 Audio sẽ thêm mục upload. * * @param upload * File upload * @param funcNum * Hàm của CKEditor * @return Trả về trang, trong trang này cần thực hiện hàm JavaScript */ @RequestMapping(value = "/upload-by-dialog", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String uploadByDialog(@RequestParam MultipartFile upload, @RequestParam(value = "CKEditorFuncNum") String funcNum) throws Exception { String newFileName = saveFile(upload); String url = UPLOAD_PATH + newFileName; return "<script>window.parent.CKEDITOR.tools.callFunction(" + funcNum + ", '" + url + "');</script>"; } /** * Upload bởi drag and drop. * * @param upload * File được upload * @return Đối tượng JSON */ @RequestMapping(value = "/upload-drag-and-drop", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String uploadDragAndDrop(@RequestParam MultipartFile upload) throws Exception { String newFileName = saveFile(upload); String url = UPLOAD_PATH + newFileName; String oldFileName = upload.getOriginalFilename(); return String.format("{" + " \"uploaded\": 1, " + " \"fileName\": \"%s\", " + " \"url\": \"%s\" " + "}", oldFileName, url); } /** * Lưu file trên server. * * @param file * File được upload * @return Tên file khi lưu trên server */ private String saveFile(MultipartFile file) throws IOException { DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd hhmmss "); String newFileName = dateFormat.format(new Date()) + file.getOriginalFilename(); file.transferTo(new File(UPLOAD_FOLDER + newFileName)); return newFileName; } }
package cz.metacentrum.perun.spRegistration.web.models; import cz.metacentrum.perun.spRegistration.common.enums.AuditMessageType; import java.sql.Timestamp; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @EqualsAndHashCode(exclude = {"madeAt"}) public class AuditLog { @NonNull private Long requestId; @NonNull private Long actorId; @NonNull private String actorName; @NonNull private AuditMessageType type; @NonNull private Timestamp madeAt; }
/** * Copyright (C) 2008 Atlassian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.atlassian.theplugin.idea.crucible; import com.atlassian.connector.cfg.ProjectCfgManager; import com.atlassian.connector.intellij.crucible.IntelliJCrucibleServerFacade; import com.atlassian.connector.intellij.crucible.ReviewAdapter; import com.atlassian.theplugin.commons.UiTaskAdapter; import com.atlassian.theplugin.commons.UiTaskExecutor; import com.atlassian.theplugin.commons.crucible.api.model.Review; import com.atlassian.theplugin.commons.exception.ServerPasswordNotProvidedException; import com.atlassian.theplugin.commons.remoteapi.RemoteApiException; import com.atlassian.theplugin.commons.remoteapi.ServerData; import com.atlassian.theplugin.idea.IdeaVersionFacade; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.DataKey; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.DataSink; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.CachingCommittedChangesProvider; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.RepositoryLocation; import com.intellij.openapi.vcs.VcsDataKeys; import com.intellij.openapi.vcs.changes.ChangeList; import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser; import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.Collections; import java.util.List; public class CrucibleCreatePostCommitReviewForm extends AbstractCrucibleCreatePostCommitReviewForm implements DataProvider { public static final String COMMITTED_CHANGES_BROWSER = "theplugin.crucible.committedchangesbrowser"; public static final DataKey<CrucibleCreatePostCommitReviewForm> COMMITTED_CHANGES_BROWSER_KEY = DataKey .create(COMMITTED_CHANGES_BROWSER); private final CommittedChangesTreeBrowser commitedChangesBrowser; private final UiTaskExecutor taskExecutor; private int revisionsNumber = 30; public CrucibleCreatePostCommitReviewForm(final Project project, final IntelliJCrucibleServerFacade crucibleServerFacade, @NotNull final ProjectCfgManager projectCfgManager, @NotNull final UiTaskExecutor taskExecutor) { super(project, crucibleServerFacade, "", projectCfgManager); this.taskExecutor = taskExecutor; commitedChangesBrowser = new CommittedChangesTreeBrowser(project, Collections.<CommittedChangeList>emptyList()); ActionManager manager = ActionManager.getInstance(); ActionGroup group = (ActionGroup) manager.getAction("ThePlugin.CommittedChangesToolbar"); ActionToolbar toolbar = manager.createActionToolbar("PostCommitReview", group, true); //commitedChangesBrowser.addToolBar(toolbar.getComponent()); setCustomComponent(commitedChangesBrowser); this.taskExecutor.execute(new ChangesRefreshTask("Fetching recent commits", getContentPane())); setTitle("Create Review"); pack(); } public void updateChanges() { CrucibleRevisionsNumber dialog = new CrucibleRevisionsNumber(revisionsNumber); dialog.show(); if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { revisionsNumber = dialog.getValue(); this.taskExecutor.execute(new ChangesRefreshTask("Fetching recent commits", getContentPane())); } } @Override protected boolean isPatchForm() { return false; } @Override protected ReviewAdapter createReview(final ServerData server, final Review reviewBeingConstructed) throws RemoteApiException, ServerPasswordNotProvidedException { final MyDataSink dataSink = new MyDataSink(); //noinspection deprecation commitedChangesBrowser.calcData(VcsDataKeys.CHANGE_LISTS, dataSink); final ChangeList[] changes = dataSink.getChanges(); return createReviewImpl(server, reviewBeingConstructed, changes); } public Object getData(@NonNls final String dataId) { if (dataId.equals(COMMITTED_CHANGES_BROWSER)) { return this; } return null; } private class MyDataSink implements DataSink { public ChangeList[] getChanges() { return changes; } private ChangeList[] changes; public <T> void put(final DataKey<T> key, final T data) { changes = (ChangeList[]) data; } } private class ChangesRefreshTask extends UiTaskAdapter { List<CommittedChangeList> list; public ChangesRefreshTask(final String actionMame, final Component component) { super(actionMame, component); } public void run() throws Exception { //IdeaVersionFacade.getInstance().setEmptyText(commitedChangesBrowser, "Fetching recent commits..."); IdeaVersionFacade.getInstance() .setCommitedChangesList(commitedChangesBrowser, Collections.<CommittedChangeList>emptyList(), false); final VirtualFile baseDir = project.getBaseDir(); if (baseDir == null) { throw new RuntimeException("Cannot determine base directory of the project"); } ProjectLevelVcsManager mgr = ProjectLevelVcsManager.getInstance(project); AbstractVcs abstractVcs = mgr.getVcsFor(baseDir); if (abstractVcs != null) { @SuppressWarnings("unchecked") final CachingCommittedChangesProvider<CommittedChangeList, ChangeBrowserSettings> committedChangesProvider = abstractVcs.getCachingCommittedChangesProvider(); if (committedChangesProvider == null) { throw new RuntimeException("Cannot determine VCS support for the project"); } ChangeBrowserSettings changeBrowserSettings = new ChangeBrowserSettings(); RepositoryLocation repositoryLocation = committedChangesProvider .getLocationFor(VcsUtil.getFilePath(baseDir.getPath())); try { list = committedChangesProvider.getCommittedChanges(changeBrowserSettings, repositoryLocation, revisionsNumber); } catch (ClassCastException e) { // PL-2074 - not supporting perforce e.printStackTrace(); Messages.showErrorDialog(project, "Cannot fetch VCS commits (is it provider supported?)", "Error"); } } } @Override public void onSuccess() { //IdeaVersionFacade.getInstance().setEmptyText(commitedChangesBrowser, "No recent commits"); if (list == null) { list = Collections.emptyList(); } IdeaVersionFacade.getInstance().setCommitedChangesList(commitedChangesBrowser, list, false); } } }
/** * @Author: Mahmoud Abdelrahman * Main Class */ package com.easylearn.easylearn; import com.easylearn.easylearn.entity.Parent; import com.easylearn.easylearn.entity.Student; import com.easylearn.easylearn.entity.Teacher; import com.easylearn.easylearn.jwt.JwtUserDetails; import com.easylearn.easylearn.model.enums.UserType; import com.easylearn.easylearn.repository.ParentRepository; import com.easylearn.easylearn.repository.StudentRepository; import com.easylearn.easylearn.repository.TeacherRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.annotation.PostConstruct; import java.util.HashSet; import java.util.Set; @SpringBootApplication public class EasylearnApplication { public static Set<JwtUserDetails> inMemoryUserList; BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); @Autowired ParentRepository parentRepository; @Autowired StudentRepository studentRepository; @Autowired TeacherRepository teacherRepository; @Autowired EasylearnApplication easylearnApplication; public static void main(String[] args) { SpringApplication.run(EasylearnApplication.class, args); } /** * In this method, all users in the database will be created as JwtUserDetails Users */ @PostConstruct public void fillUsersList() { inMemoryUserList = new HashSet<>(); Set<Parent> parents = parentRepository.findAll(Sort.by("lastName")); Set<Student> students = studentRepository.findAll(Sort.by("lastName")); Set<Teacher> teachers = teacherRepository.findAll(Sort.by("lastName")); if (!parents.isEmpty()) { for (Parent parent : parents) { inMemoryUserList.add(new JwtUserDetails(parent.getId(), parent.getUsername(), encoder.encode(parent.getPassword()), "ROLE_USER_2", UserType.PARENT)); } } if (!students.isEmpty()) { for (Student student : students) { inMemoryUserList.add(new JwtUserDetails(student.getId(), student.getUsername(), encoder.encode(student.getPassword()), "ROLE_USER_2", UserType.STUDENT)); } } if (!teachers.isEmpty()) { for (Teacher teacher : teachers) { inMemoryUserList.add(new JwtUserDetails(teacher.getId(), teacher.getUsername(), encoder.encode(teacher.getPassword()), "ROLE_USER_2", UserType.TEACHER)); } } inMemoryUserList.add(new JwtUserDetails(999999L, "admin@easylearn.mis.com", encoder.encode("123456"), "ROLE_USER_1", UserType.ADMIN)); } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final String LINE_SPR = System.getProperty("line.separator"); final int BIG_MOD = 1000000007; char[][] grid; boolean[][] safe; int nr, nc; void run() throws Exception { int nt = ni(); for(int t = 0; t < nt; t++) { String[] nums = ns().split(" "); nr = Integer.parseInt(nums[0]); nc = Integer.parseInt(nums[1]); grid = new char[nr][nc]; safe = new boolean[nr][nc]; for(int r = 0; r < nr; r++) { String cs = ns(); for(int c = 0; c < nc; c++) { grid[r][c] = cs.charAt(c); } } int res = solve(); if(res == -1) { gcjPrint("IMPOSSIBLE", t + 1); } else { gcjPrint(Integer.toString(res), t + 1); } } } int solve() { int count = 0; for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { if(safe[r][c]) continue; if(grid[r][c] != '.' && loop(r,c)) safe[r][c] = true; } } for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { if(grid[r][c] == '.' || safe[r][c]) continue; boolean found = false; for(int c2 = 0; c2 < nc; c2++) { if(safe[r][c2]) { count++; safe[r][c] = true; found = true; break; } } if(found) continue; for(int r2 = 0; r2 < nr; r2++) { if(safe[r2][c]) { count++; safe[r][c] = true; found = true; break; } } if(found) continue; int calc = calc(r, c); if(calc == -1) return -1; else count += calc; } } return max; } int calc(int r, int c) { int max1 = 0, max2 = 0; boolean imp = true; for(int c2 = 0; c2 < nc; c2++) if(c2 != c && grid[r][c2] != '.') { if(c2 > c && (grid[r][c] == '>' || grid[r][c2] == '<' ) || c2 < c && (grid[r][c] == '<' || grid[r][c2] == '>')) { max1 = Math.max(1, max1); } else { max1 = Math.max(2, max1); } imp = false; } for(int r2 = 0; r2 < nr; r2++) { if(r2 != r && grid[r2][c] != '.') { if(r2 > r && (grid[r][c] == 'v' || grid[r2][c] == '^') || r2 < r && (grid[r][c] == '^' || grid[r2][c] == 'v')) { max2 = Math.max(1, max2); }else { max2 = Math.max(2, max2); } imp = false; } } if(imp) return -1; else if(max1 == 0) return max2; else if(max2 == 0) return max1; else return Math.min(max1, max2); } boolean loop(int r, int c) { int tmpr = r, tmpc = c; int dr = 0, dc = 0; boolean[][] visited; visited = new boolean[nr][nc]; while(true) { dr = 0; dc = 0; switch(grid[tmpr][tmpc]) { case '>': dc = 1; break; case '<': dc = -1; break; case '^': dr = -1; break; case 'v': dr = 1; break; } // go as far as poss while(tmpr >= 0 && tmpr < nr && tmpc >= 0 && tmpc < nc) { // find arrow tmpr += dr; tmpc += dc; if(tmpr < 0 || tmpr >= nr || tmpc < 0 || tmpc >= nc) return false; if(grid[tmpr][tmpc] != '.') break; } if(visited[tmpr][tmpc]) return true; visited[tmpr][tmpc] = true; } } void dump() { System.out.println("###"); for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { System.out.print(grid[r][c] + " "); } System.out.println(); } System.out.println("###"); } /* * Templates */ void dumpObjArr(Object[] arr, int n) { for(int i = 0; i < n; i++) { System.out.print(arr[i]); if(i < n - 1) System.out.print(" "); } System.out.println(""); } void dumpObjArr2(Object[][] arr, int m, int n) { for(int j = 0; j < m; j++) dumpObjArr(arr[j], n); } int ni() throws Exception { return Integer.parseInt(br.readLine().trim()); } long nl() throws Exception { return Long.parseLong(br.readLine().trim()); } String ns() throws Exception { return br.readLine(); } boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } int getPrime(int n) { List<Integer> primes = new ArrayList<Integer>(); primes.add(2); int count = 1; int x = 1; while(primes.size() < n) { x+=2; int m = (int)Math.sqrt(x); for(int p : primes) { if(p > m) { primes.add(x); break; } if(x % p == 0) break; } } return primes.get(primes.size() - 1); } long lcm(long a, long b) { return a * b / gcd(a, b); } long gcd(long a, long b) { if(a < b) { long tmp = a; a = b; b = tmp; } // a >= b long mod = a % b; if(mod == 0) return b; else return gcd(b, mod); } void gcjPrint(String str, int t) { System.out.println("Case #" + t + ": " + str); } public static void main(String[] args) throws Exception { new Main().run(); } }
package com.github.tobby48.java.example; /** * <pre> * com.github.tobby48.java.example * Fibonacci.java * * 설명 : 재귀함수를 이용한 피보나치 수열, 10번까지 결과 출력 * </pre> * * @since : 2017. 6. 28. * @author : tobby48 * @version : v1.0 */ public class Fibonacci { public static int recursive(int value){ // 반복문 및 조건문이 한줄일 경우 아래와 같이 붙여서 표기할 수 있다. if(value == 1 || value == 2) return 1; return recursive(value-2) + recursive(value-1); } public static void main(String[] args) { // 합산 for(int index=1; index<10; index++) System.out.printf("%d번째: %d\n", index, recursive(index)); } }
package com.homework.pattern.abstractfactory; /** * @author lq * @version 1.0 * @desc * @date 2019/3/19 0:09 **/ public class LenovoFactory implements IFactory { @Override public IMouse createMouse() { return new LenovoMouse(); } @Override public IKeyboard createKeyboard() { return new LenovoKeyboard(); } }
package test.java.liceosorolla; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import mein.java.liceosorolla.Usuario; public class UsuarioTest { private Usuario usuario; @Before public void Before() { usuario = new Usuario("Nacho","Martin", "2020-03-6", 9); } @Test public void comprobarNombre() { assertEquals("Nacho", usuario.getNombre()); } @Test public void comprobarApellidos() { assertEquals("Martin", usuario.getApellidos()); } @Test public void comprobarNombreCompleto() { assertEquals("Nacho Martin ",usuario.getNombre()+" "+usuario.getApellidos()); } @Test public void comprobarMayus() { assertEquals("NACHO MARTIN",usuario.mayus()); } @Test public void comprobarMinus() { assertEquals("nacho martin",usuario.minus()); } }
package com.foxweave.connector.mixpanel; import com.foxweave.test.FoxWeaveTestCase; import com.foxweave.test.web.jetty.RequestResponse; import com.foxweave.test.web.jetty.SimpleServer; import com.mixpanel.mixpanelapi.MixpanelAPI; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a> */ public class MixPanelOutputConnectorTest extends FoxWeaveTestCase { private SimpleServer mockMixpanelServer; @Before public void setUp() throws Exception { mockMixpanelServer = new SimpleServer(); } @After public void tearDown() throws Exception { mockMixpanelServer.stop(); } @Test public void test_set_profile() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(null, mockMixpanelServer.getServerURL() + "/engage"); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/engage") .setExpectedRequestParam("data", "W3siJHRpbWUiOjEyNDU2MTM4ODUwMDAsIiRkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCIkc2V0Ijp7Ik5hbWUiOiJNYXJrIERvd25lcyIsIkVtYWlsIjoibWRAeC5jb20ifSwiJGlwIjoiMTI3LjAuMC4xIn1d") .setResponsePayload("1") ); mixPanelOutputConnector.setUserProfile(new JSONObject(SAMPLE_SET_PROFILE)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } @Test public void test_event() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(mockMixpanelServer.getServerURL() + "/track", null); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/track?ip=0") .setExpectedRequestParam("data", "W3siZXZlbnQiOiJnYW1lIiwicHJvcGVydGllcyI6eyJ0aW1lIjoxMjQ1NjEzODg1LCJkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCJ0b2tlbiI6ImUzYmM0MTAwMzMwYzM1NzIyNzQwZmI4YzZmNWFiZGRjIiwiYWN0aW9uIjoicGxheSIsIm1wX2xpYiI6ImpkayIsImlwIjoiMTIzLjEyMy4xMjMuMTIzIn19XQ==") .setResponsePayload("1") ); mixPanelOutputConnector.logActivity(new JSONObject(SAMPLE_EVENT)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } @Test public void test_delete_profile() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(null, mockMixpanelServer.getServerURL() + "/engage"); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/engage") .setExpectedRequestParam("data", "W3siJHRpbWUiOjEyNDU2MTM4ODUwMDAsIiRkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCIkZGVsZXRlIjoiIn1d") .setResponsePayload("1") ); mixPanelOutputConnector.deleteUserProfile(new JSONObject(SAMPLE_DELETE_PROFILE)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } public static final String SAMPLE_SET_PROFILE = "{ \n" + " \"distinct_id\": \"50479b24671bf\", \n" + " \"ip\": \"127.0.0.1\", \n" + " \"time\": 1245613885000, \n" + " \"properties\": {\n" + " \"Name\": \"Mark Downes\", \n" + " \"Email\": \"md@x.com\" \n" + " }\n" + "}\n"; public static final String SAMPLE_EVENT = "{ \n" + " \"event\": \"game\", \n" + " \"properties\": {\n" + " \"distinct_id\": \"50479b24671bf\", \n" + " \"ip\": \"123.123.123.123\", \n" + " \"token\": \"e3bc4100330c35722740fb8c6f5abddc\", \n" + " \"time\": 1245613885000, \n" + " \"action\": \"play\" \n" + " }\n" + "}\n"; public static final String SAMPLE_DELETE_PROFILE = "{ \n" + " \"distinct_id\": \"50479b24671bf\", \n" + " \"time\": 1245613885000\n" + "}\n"; }
package com.egswebapp.egsweb.enums; import org.springframework.http.HttpStatus; public enum PostErrorCode implements ErrorCode { POST_NOT_EXIST(HttpStatus.NOT_FOUND, "Post not exist"), POST_CONTENT_NOT_EXIST(HttpStatus.NOT_FOUND, "Post content not found"), CATEGORY_NOT_EXIST(HttpStatus.NOT_FOUND, "Category not exist") ; private HttpStatus httpStatus; private String message; PostErrorCode(HttpStatus httpStatus, String message) { this.httpStatus = httpStatus; this.message = message; } @Override public String getMessage() { return message; } @Override public HttpStatus getStatus() { return httpStatus; } }
package com.qianqian.cms.util; /** * 在ThreadLocal里保存当前线程的数据源 * @Project : maxtp.framelib * @Program Name: com.framelib.db.DataSourceSwitch.java * @ClassName : DataSourceSwitch * @Author : zhangyan * @CreateDate : 2014-4-22 下午3:52:40 */ public class DataSourceSwitch { private static final ThreadLocal<String> contextHolder=new ThreadLocal<String>(); public static void setDataSourceType(String dataSourceType){ contextHolder.set(dataSourceType); } public static String getDataSourceType(){ return (String) contextHolder.get(); } public static void clearDataSourceType(){ contextHolder.remove(); } }
package com.memberComment.model; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class MemberCommServiceB { private MemberCommentDAOInterfaceB dao; public MemberCommServiceB() { dao = new MemberCommentDAOB(); } public MemberCommentVO addMemberComm(MemberCommentVO memberCommVO) { dao.insert(memberCommVO); return memberCommVO; } public MemberCommentVO updateMemberComm(MemberCommentVO memberCommVO) { dao.update(memberCommVO); return memberCommVO; } public void deleteMemberComm(String memberCommId) { dao.delete(memberCommId); } public MemberCommentVO selectOneMemberComm(String memberCommId) { return dao.selectOne(memberCommId); } public List<MemberCommentVO> selectAllMemberComm() { return dao.selectAll(); } public List<MemberCommentVO> selectAllMemberCommByMember(String memberId) { List<MemberCommentVO> all = dao.selectAll(); List<MemberCommentVO> allById = new ArrayList<MemberCommentVO>(); allById = all.stream() .filter(mc -> memberId.equals(mc.getMemberAId())) .collect(Collectors.toList()); return allById; } }
package by.htp.cratemynewpc.controller.command.impl; import by.htp.cratemynewpc.controller.command.Command; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SignOut implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession(true).setAttribute("user", null); RequestDispatcher dispatcher = request.getRequestDispatcher(JSPPagePath.MAIN_PAGE); dispatcher.forward(request, response); } }
package com.spring.professional.exam.tutorial.module03.question04.callback.custom; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.expression.AddExpressionEvaluator; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.expression.ExpressionEvaluator; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.expression.MinusExpressionEvaluator; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.printer.DecoratedValuePrinter; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.printer.StandardValuePrinter; import com.spring.professional.exam.tutorial.module03.question04.callback.custom.printer.ValuePrinter; public class Example1 { public static void main(String[] args) { } private void run() { //ExpressionEvaluator expressionEvaluator = new AddExpressionEvaluator(); /* * ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { * * @Override public int evaluate(int a, int b) { return a*b; } }; */ // ExpressionEvaluator expressionEvaluator = new MinusExpressionEvaluator(); //ExpressionEvaluator expressionEvaluator = (a,b) ->a+b; //ExpressionEvaluator expressionEvaluator = (a,b) -> a-b; ExpressionEvaluator expressionEvaluator = this::powEvaluator; //ExpressionEvaluator expressionEvaluator = Integer::sum; ValuePrinter valuePrinter = new StandardValuePrinter(); //ValuePrinter valuePrinter = new DecoratedValuePrinter(); } private int powEvaluator(int a, int b) { return (int)Math.pow(a, b); } }
package com.mtl.hulk; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; public class HulkShutdownHook { private static final Logger logger = LoggerFactory.getLogger(HulkShutdownHook.class); private static final HulkShutdownHook hulkShutdownHook = new HulkShutdownHook(); public static HulkShutdownHook getHulkShutdownHook() { return hulkShutdownHook; } /** * Has it already been destroyed or not? */ private final AtomicBoolean destroyed; private HulkShutdownHook() { this.destroyed = new AtomicBoolean(false); } public void destroyAll() { if (!destroyed.compareAndSet(false, true)) { return; } HulkResourceManager.destroy(); } }
/* Nama : Nurindah Sari Stambuk : 13020180004 Tanggal : 21 April 2020 Waktu : 19.35 WITA */ class ModifierNoAccess{ double kecepatan; void setKecepatan(double kecepatan){ this.kecepatan = kecepatan; } double getKecepatan(){ return kecepatan; } }
package farmerline.com.dev.farmerserviceapp.dashboard.home; import android.support.annotation.Nullable; import farmerline.com.dev.farmerserviceapp.dashboard.home.analytics.AnalyticsFragment; import farmerline.com.dev.farmerserviceapp.dashboard.home.baseFragment.BaseFragment; import farmerline.com.dev.farmerserviceapp.dashboard.home.baseFragment.FragmentNavigation; public class HomePresenter implements HomeMVP.Presenter,FragmentNavigation.Presenter { @Nullable HomeMVP.View view; HomeMVP.Model model; public HomePresenter(HomeMVP.Model model) { this.model = model; } @Override public void setView(HomeMVP.View view) { this.view=view; } @Override public void getDefaultFragment() { if (view !=null) view.setFragement(AnalyticsFragment.newInstance()); } @Override public void addFragment(BaseFragment fragment) { if (view != null) view.setFragement(fragment); } @Override public void removeFragment() { if (view !=null) view.removeFragment(); } }
package com.twu.biblioteca.Books; import com.twu.biblioteca.Books.Book; import com.twu.biblioteca.Books.BookPrinter; import com.twu.biblioteca.Books.SampleBooks; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BookPrinterTest { private static final ByteArrayOutputStream BYTE_ARRAY_OUTPUT_STREAM = new ByteArrayOutputStream(); @Before public void setOutputStream() { System.setOut(new PrintStream(BYTE_ARRAY_OUTPUT_STREAM)); } @Test public void shouldPrintBooks() { Book HarryPotter = new Book("Harry Potter", "JK Rolling", "1998"); Book HarryPotter2 = new Book("Harry Potter and the chamber of secrets", "JK Rolling", "2002"); Book HarryPotter3 = new Book("Harry Potter and the prisoner of ascaban", "JK Rolling", "2005"); BookPrinter bookPrinter = new BookPrinter(); SampleBooks sampleBooks = new SampleBooks(); List<Book> books = sampleBooks.Sample(); bookPrinter.printBooks((ArrayList<Book>) books); assertThat(BYTE_ARRAY_OUTPUT_STREAM.toString(), is(HarryPotter.toString()+System.lineSeparator()+HarryPotter2.toString()+System.lineSeparator()+HarryPotter3.toString()+System.lineSeparator())); } }
package com.multivision.ehrms.business; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Update: Added JPA(JSR 317) support for Hibernate to get rid of HBM files. * @version 2.0 * @author Zubair Shaikh */ @Entity @Table(name="Employee_Project_Mapping") public class EmployeeProjectMapping { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @ManyToOne @JoinColumn(name="emp_id", referencedColumnName="id") private Employee employee = new Employee(); @ManyToOne @JoinColumn(name="project_id", referencedColumnName="id") private Project project = new Project(); @Column(name="start_date") private String startDate; @Column(name="end_date") private String endDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } }
package com.alibaba.druid.bvt.pool.vendor; import java.sql.SQLException; import com.alibaba.druid.PoolTestCase; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.pool.vendor.InformixExceptionSorter; public class InformixExceptionSorterTest extends PoolTestCase { public void test_informix() throws Exception { InformixExceptionSorter sorter = new InformixExceptionSorter(); Assert.assertEquals(false, sorter.isExceptionFatal(new SQLException())); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -710))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79716))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79730))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79734))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79735))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79736))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79756))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79757))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79758))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79759))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79760))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79788))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79811))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79812))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79836))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79837))); Assert.assertEquals(true, sorter.isExceptionFatal(new SQLException("", "", -79879))); Assert.assertEquals(false, sorter.isExceptionFatal(new SQLException("", "", 100))); } }
package com.seven.contract.manage.controller.contract.data.request; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; /** * Created by apple on 2018/12/24. */ public class InitiateSigningRequest implements Serializable { /** * 合同id */ private String id; /** * 合同名 */ private String contractName; /** * 结束时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd") private java.util.Date endTime; /** * 有效期 */ @DateTimeFormat(pattern = "yyyy-MM-dd") private java.util.Date validTime; /** * 标签id */ private String labelId; /** * 备注 */ private String remark; /** * 是否绝密合同 Y:是 N:否 */ private String secretContract = "N"; /** * 合同地址 */ private String contractUrl; /** * 联系人MID,多人用逗号分割 */ private String contactMids; /** * 短信验证码 */ private String verifyCode; /** * 私钥密码 */ private String privateKeyPwd; /** * PDF合同地址 */ private String contractSourceUrl; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContractName() { return contractName; } public void setContractName(String contractName) { this.contractName = contractName; } @JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+8") public Date getEndTime() { return endTime; } @JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+8") public void setEndTime(Date endTime) { this.endTime = endTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getSecretContract() { return secretContract; } public void setSecretContract(String secretContract) { this.secretContract = secretContract; } public String getContractUrl() { return contractUrl; } public void setContractUrl(String contractUrl) { this.contractUrl = contractUrl; } public String getContactMids() { return contactMids; } public void setContactMids(String contactMids) { this.contactMids = contactMids; } public String getVerifyCode() { return verifyCode; } public void setVerifyCode(String verifyCode) { this.verifyCode = verifyCode; } public Date getValidTime() { return validTime; } public void setValidTime(Date validTime) { this.validTime = validTime; } public String getLabelId() { return labelId; } public void setLabelId(String labelId) { this.labelId = labelId; } public String getPrivateKeyPwd() { return privateKeyPwd; } public void setPrivateKeyPwd(String privateKeyPwd) { this.privateKeyPwd = privateKeyPwd; } public String getContractSourceUrl() { return contractSourceUrl; } public void setContractSourceUrl(String contractSourceUrl) { this.contractSourceUrl = contractSourceUrl; } }
package com.example.hotel.config.security; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; @Configuration @EnableAuthorizationServer @Order(Ordered.HIGHEST_PRECEDENCE) @RequiredArgsConstructor class OAuthConfig extends AuthorizationServerConfigurerAdapter { private final AuthenticationManager authenticationManager; private final UserDetailsService userDetailsService; @Value("${app.client.id}") private String clientId; @Value("${app.client.secret}") private String clientSecret; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { super.configure(security); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient(clientId) .secret(clientSecret) .authorizedGrantTypes("password", "refresh_token", "access_token") .scopes("openid"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.userDetailsService(userDetailsService) .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET) .authenticationManager(authenticationManager); } }
package strings.cifraDeCesar; import java.text.CharacterIterator; import java.text.StringCharacterIterator; public class Mensagem implements CifraDeCesar { String msg; int cod; public Mensagem(final String msg, final int cod){ this.msg = msg.toUpperCase(); //lidar com caracteres uppercase para usar tabela ASCII this.cod = cod; } @Override public String encriptada() { CharacterIterator charIt = new StringCharacterIterator(msg); StringBuilder emsg = new StringBuilder(); int ascLetra; //vai armazenar o codigo ASCII do char // CharacterIterator.DONE eh fim de arquivo(string) while (charIt.current() != CharacterIterator.DONE){ //verifica se o char eh um espaco em branco if (Character.isWhitespace(charIt.current())){ emsg.append(" "); charIt.next(); } ascLetra = charIt.current() + cod; //voltar ao inicio dos chars, eles vão de 65 até 90(A ao Z) //quando uma encriptacao ultrapassa 90 ele volta ao inicio //exemplo: ZUZA encriptado com chave 3, Z(3) = 93, voltando ao inicio //64+3=67 => C (comeca com 64 para incluir 65) if(ascLetra > 90){ ascLetra -= 90; ascLetra += 64; } emsg.append(Character.toString(ascLetra)); charIt.next(); } return emsg.toString(); } @Override public String decriptada() { CharacterIterator charIt = new StringCharacterIterator(msg); StringBuilder dmsg = new StringBuilder(); int ascLetra; //vai armazenar o codigo ASCII do char // CharacterIterator.DONE eh fim de arquivo(string) while (charIt.current() != CharacterIterator.DONE){ //verifica se o char eh um espaco em branco if (Character.isWhitespace(charIt.current())){ dmsg.append(" "); charIt.next(); } ascLetra = charIt.current() - cod; //Vale o mesmo conceito da encriptacao, se menor que 65 sai do intervalo // dos nossos Chars da tabela ASCII if(ascLetra < 65){ ascLetra = 64 - ascLetra; ascLetra = 90- ascLetra; } dmsg.append(Character.toString(ascLetra)); charIt.next(); } return dmsg.toString(); } }
import com.fasterxml.jackson.core.JsonProcessingException; import domain.CalculateKwhRequest; import domain.CalculatePrijsRequest; import logic.ServiceController; import org.junit.Test; import static org.junit.Assert.*; public class UnitTests { private ServiceController s = new ServiceController(); private CalculatePrijsRequest cpr = new CalculatePrijsRequest(0, 0, false); private CalculateKwhRequest ckr = new CalculateKwhRequest(0, false); // EXTERNE LOGICA @Test public void testErrors() throws JsonProcessingException { // PARSE ERROR assertEquals("{\"errorcode\":9001,\"errordesc\":\"ParseError, be sure your parameters are using the right datatypes as mentioned in the documentation.\"}", s.getCalculatePrijsResponse("geengetal", "geengetal", "true")); // NULL POINTER assertEquals("{\"errorcode\":9000,\"errordesc\":\"Welcome to the calculate kwh price REST API, be sure to read the documentation about which parameters you can use.\"}", s.getCalculatePrijsResponse(null,null, null)); } @Test public void testCalculatePrijsExtern() throws JsonProcessingException { assertNotEquals("{\"prijs\":16866.58}", s.getCalculatePrijsResponse("124", "73457", "false")); assertEquals("{\"prijs\":16866.59}", s.getCalculatePrijsResponse("124", "73457", "false")); assertNotEquals("{\"prijs\":16866.60}", s.getCalculatePrijsResponse("124", "73457", "false")); } @Test public void testCalculateKwhExtern() throws JsonProcessingException { assertNotEquals("{\"kwh\":5060.434782608695}", s.getCalculateKwhResponse("581.95", "true")); assertEquals("{\"kwh\":5060.434782608696}", s.getCalculateKwhResponse("581.95", "true")); assertNotEquals("{\"kwh\":5060.434782608697}", s.getCalculateKwhResponse("581.95", "true")); } // INTERNE LOGICA @Test public void testCalculatePrijsIntern() throws JsonProcessingException { cpr.setBeginstand(124); cpr.setEindstand(73457); cpr.setZonnepanelen(false); // INCLUSIEF RANDWAARDES assertNotEquals(16866.58, cpr.calculatePrijs().getPrijs(), 0); assertEquals(16866.59, cpr.calculatePrijs().getPrijs(), 0); assertNotEquals(16866.60, cpr.calculatePrijs().getPrijs(), 0); } @Test public void testCalculateKwhIntern() throws JsonProcessingException { ckr.setPrijs(581.95); ckr.setZonnepanelen(true); assertNotEquals(5060.434782608695, ckr.calculateKwh().getKwh(), 0); assertEquals(5060.434782608696, ckr.calculateKwh().getKwh(), 0); assertNotEquals(5060.434782608697, ckr.calculateKwh().getKwh(), 0); } }
package pl.olart.pmsuite.model; import java.io.Serializable; /** * User: grp * Date: 16.06.16 * Time: 02:39 */ public class TypKosztuBean implements Serializable, Comparable { private String nazwa; private String ktoPrzypisany; public TypKosztuBean(String nazwa) { this.nazwa = nazwa; } public String getNazwa() { return nazwa; } public void setNazwa(String nazwa) { this.nazwa = nazwa; } public String getKtoPrzypisany() { return ktoPrzypisany; } public void setKtoPrzypisany(String ktoPrzypisany) { this.ktoPrzypisany = ktoPrzypisany; } @Override public int compareTo(Object o) { return this.getNazwa().compareTo(((TypKosztuBean) o).getNazwa()); } }
package com.github.ytjojo.supernestedlayout; import android.animation.ValueAnimator; import android.content.Context; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v4.view.ViewCompat; import android.support.v4.widget.ScrollerCompat; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewParent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.LinearInterpolator; //import com.orhanobut.logger.Logger; /** * Created by Administrator on 2016/9/26 0026. */ public class TouchEventWatcher { private static final String TAG = "TouchEventWatcher"; SuperNestedLayout mParent; OnScrollListener mOnScrollListener; private ScrollerCompat mScroller; /** * Position of the last motion event. */ private int mLastMotionY; private int mLastMotionX; private float mOneDrectionDeltaY; /** * True if the user is currently dragging this ScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private boolean mIsBeingDragged = false; private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; private int mActivePointerId = INVALID_POINTER; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; private boolean mLastScrollDrectionIsUp; private float mOrginalValue; private float mTotalUnconsumed; private final int[] mParentScrollConsumed = new int[2]; private final int[] mParentOffsetInWindow = new int[2]; private int mNestedYOffset; public TouchEventWatcher(SuperNestedLayout parent) { this.mParent = parent; init(mParent.getContext()); } private void init(Context context) { mScroller = ScrollerCompat.create(context, null); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity() * 2; mMaximumVelocity = (int) (configuration.getScaledMaximumFlingVelocity() * 0.3f); setupAnimators(); } ValueAnimator mValueAnimator; ValueAnimator.AnimatorUpdateListener mUpdateListener; private boolean isNeedCheckHorizontal = false; private void setupAnimators() { mUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); if ((value != 0f && value != 1f) && value == mOrginalValue) { return; } if (mScroller.computeScrollOffset()) { int oldY = getScrollY(); int y = mScroller.getCurrY(); if (oldY != y) { mParent.scrollTo(0, y); } } else { stopScroll(); } mOrginalValue = value; } }; mValueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f); mValueAnimator.setRepeatCount(Animation.INFINITE); mValueAnimator.setRepeatMode(ValueAnimator.RESTART); mValueAnimator.setDuration(1000); //fuck you! the default interpolator is AccelerateDecelerateInterpolator mValueAnimator.setInterpolator(new LinearInterpolator()); } public void startAnim() { mValueAnimator.removeAllUpdateListeners(); mValueAnimator.addUpdateListener(mUpdateListener); mValueAnimator.setRepeatCount(ValueAnimator.INFINITE); mValueAnimator.setDuration(1000); mValueAnimator.start(); } public void stopScroll() { mValueAnimator.removeUpdateListener(mUpdateListener); mValueAnimator.removeAllUpdateListeners(); mValueAnimator.setRepeatCount(0); mValueAnimator.setDuration(0); mValueAnimator.end(); mScroller.abortAnimation(); } public void onDispatchTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (activePointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); return; } final int y = (int) MotionEventCompat.getY(ev, activePointerIndex); int deltaY = mLastMotionY - y; if (deltaY * mOneDrectionDeltaY > 0) { mOneDrectionDeltaY = deltaY + mOneDrectionDeltaY; } else { mOneDrectionDeltaY = deltaY; } doScroll(deltaY); mLastMotionY = y; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); return; } switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have TOP valid id, the touch down wasn't on content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); if (pointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } final int y = (int) MotionEventCompat.getY(ev, pointerIndex); final int x = (int) MotionEventCompat.getX(ev, pointerIndex); final int yDiff = Math.abs(y - mLastMotionY); if (yDiff > mTouchSlop && (Math.abs(x - mLastMotionX) <= y)) { mIsBeingDragged = true; mOneDrectionDeltaY = y - mLastMotionY; mLastMotionY = y; mLastMotionX = x; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); } break; } case MotionEvent.ACTION_DOWN: { final int y = (int) ev.getY(); // if(mValueAnimator.isRunning()){ // stopScroll(); // } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionY = y; mLastMotionX = (int) ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); mOneDrectionDeltaY = 0; /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. We need to call computeScrollOffset() first so that * isFinished() is correct. */ // mScroller.computeScrollOffset(); // mIsBeingDragged = !mScroller.isFinished(); break; } case MotionEventCompat.ACTION_POINTER_DOWN: final int index = MotionEventCompat.getActionIndex(ev); mLastMotionY = (int) MotionEventCompat.getY(ev, index); mLastMotionX = (int) MotionEventCompat.getX(ev, index); mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { smoothScrollToFinal(); } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker, mActivePointerId); smoothScrollToFinal(); } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } } Boolean isBlockingInteractionBelow; public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mParent.isEnabled()) { // Fail fast if we're not in TOP state where TOP swipe is possible return false; } if(mParent.isSkipInterceptTouch()){ return false; } final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { return true; } switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have TOP valid id, the touch down wasn't on content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); if (pointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } final int y = (int) MotionEventCompat.getY(ev, pointerIndex); final int x = (int) MotionEventCompat.getX(ev, pointerIndex); final int yDiff = Math.abs(y - mLastMotionY); if (yDiff > mTouchSlop) { if (isBlockingInteractionBelow == null) { if (mParent.isBlockingInteractionBelow(mLastMotionX, mLastMotionY)) { isBlockingInteractionBelow = Boolean.TRUE; } else { isBlockingInteractionBelow = Boolean.FALSE; } } } if(isBlockingInteractionBelow !=null && isBlockingInteractionBelow&& mParent.isNestedScrollInProgress()){ return false; } if (yDiff > mTouchSlop && (mParent.getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) { Log.e(getClass().getName(), "onInterceptTouchEvent"); mIsBeingDragged = true; mLastMotionY = y; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); mNestedYOffset = 0; final ViewParent parent = mParent.getParent(); int xDiff = Math.abs(x - mLastMotionX); if (parent != null && yDiff>xDiff) { parent.requestDisallowInterceptTouchEvent(true); } mParent.onStartDrag(mLastMotionX,mLastMotionY); } break; } case MotionEvent.ACTION_DOWN: final int y = (int) ev.getY(); isBlockingInteractionBelow = null; /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionY = y; mLastMotionX = (int) ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. We need to call computeScrollOffset() first so that * isFinished() is correct. */ mScroller.computeScrollOffset(); // mIsBeingDragged = !mScroller.isFinished(); mIsBeingDragged = false; Log.e("onInterceptTouchEvent", "onInterceptTouchEvent" + mParent.isNestedScrollInProgress()); mParent.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; recycleVelocityTracker(); //TODO anim if(!mParent.isNestedScrollInProgress()){ mParent.stopNestedScroll(); } break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (isBlockingInteractionBelow != null && isBlockingInteractionBelow) { return true; } return mIsBeingDragged; } boolean isOnStartDrageCalled = false; public boolean onTouchEvent(MotionEvent ev) { if (!mParent.isEnabled()) { // Fail fast if we're not in TOP state where TOP swipe is possible return false; } initVelocityTrackerIfNotExists(); MotionEvent vtev = MotionEvent.obtain(ev); final int actionMasked = MotionEventCompat.getActionMasked(ev); if (actionMasked == MotionEvent.ACTION_DOWN) { mNestedYOffset = 0; } vtev.offsetLocation(0, mNestedYOffset); switch (actionMasked) { case MotionEvent.ACTION_DOWN: { if (mParent.getChildCount() == 0) { return false; } if ((mIsBeingDragged = !mScroller.isFinished())) { final ViewParent parent = mParent.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } /* * If being flinged and user touches, stopScroll the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); stopScroll(); } // Remember where the motion event started mLastMotionY = (int) ev.getY(); mLastMotionX = (int) ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mParent.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); mParent.onStartDrag(mLastMotionX, mLastMotionY); break; } case MotionEvent.ACTION_MOVE: final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (activePointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); break; } final int y = (int) MotionEventCompat.getY(ev, activePointerIndex); int deltaY = mLastMotionY - y; if (mParent.dispatchNestedPreScroll(0, deltaY, mParentScrollConsumed, mParentOffsetInWindow)) { deltaY -= mParentScrollConsumed[1]; vtev.offsetLocation(0, mParentOffsetInWindow[1]); mNestedYOffset += mParentOffsetInWindow[1]; } if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) { int x = (int) MotionEventCompat.getX(ev, activePointerIndex); int deltaX = mLastMotionX - x; if (!isNeedCheckHorizontal || (isNeedCheckHorizontal && Math.abs(deltaX) < Math.abs(deltaY))) { final ViewParent parent = mParent.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } mIsBeingDragged = true; if (deltaY > 0) { deltaY -= mTouchSlop; } else { deltaY += mTouchSlop; } mParent.dragedScrollBy(0, deltaY); // Logger.e("offsetDydeltaY"+deltaY); } } if (mIsBeingDragged) { Log.e(getClass().getName(), mIsBeingDragged + "isNestedScrollInProgress" + mParent.isNestedScrollInProgress()); // Scroll to follow the motion event mLastMotionY = y - mParentOffsetInWindow[1]; // Logger.e("offsetDydeltaY"+deltaY); final int scrolledDeltaY = mParent.dragedScrollBy(0, deltaY); final int unconsumedY = deltaY - scrolledDeltaY; if (mParent.dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mParentOffsetInWindow)) { mLastMotionY -= mParentOffsetInWindow[1]; vtev.offsetLocation(0, mParentOffsetInWindow[1]); mNestedYOffset += mParentOffsetInWindow[1]; } } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker, mActivePointerId); Log.e(TouchEventWatcher.class.getName(), initialVelocity + "initialVelocity"); if ((Math.abs(initialVelocity) > mMinimumVelocity)) { mParent.dispatchDragedFling(-initialVelocity); } mParent.onStopDrag(); } else { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker, mActivePointerId); Log.e(getClass().getName(), initialVelocity + "mIsBeingDragged" + mIsBeingDragged); if ((Math.abs(initialVelocity) > mMinimumVelocity)) { if (!mParent.dispatchNestedPreFling(0, -initialVelocity)) { mParent.dispatchNestedFling(0, -initialVelocity, false); } }else{ if(mParent.isClickable()){ mParent.performClick(); } } } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_CANCEL: // if (mIsBeingDragged && mParent.getChildCount() > 0) { // if (mScroller.springBack(0, getScrollY(), 0, 0, mParent.getMinScrollY(), // mParent.getMaxScrollY())) { // ViewCompat.postInvalidateOnAnimation(mParent); // } // } if (mIsBeingDragged) { mParent.onStopDrag(); } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); mLastMotionY = (int) MotionEventCompat.getY(ev, index); mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionY = (int) MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } if (mVelocityTracker != null) { mVelocityTracker.addMovement(vtev); } vtev.recycle(); return true; } /** * Smooth scroll by TOP Y delta * * @param delta the number of pixels to scroll by on the Y axis */ private void doScrollY(int delta, boolean mSmoothScrollingEnabled) { if (delta != 0) { if (mSmoothScrollingEnabled) { smoothScrollBy(0, delta); } else { mParent.scrollBy(0, delta); } } } static int constrain(int value, int min, int max) { if (min == max) { return min; } if (min > max) { min = min ^ max; max = min ^ max; min = min ^ max; } if (value < min) { return min; } if (value > max) { return max; } return value; } private long mLastScroll; static final int ANIMATED_SCROLL_GAP = 250; int mMinScrollY; int mMaxScrollY; /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ public final void smoothScrollBy(int dx, int dy) { if (mParent.getChildCount() == 0) { // Nothing to do. return; } long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; if (duration > ANIMATED_SCROLL_GAP) { final int maxScrollY = mMaxScrollY; final int minScrollY = mMinScrollY; final int scrollY = getScrollY(); dy = constrain(scrollY + dy, maxScrollY, minScrollY) - scrollY; mScroller.startScroll(0, scrollY, 0, dy); startAnim(); } else { if (!mScroller.isFinished()) { stopScroll(); } mParent.scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } public boolean flingWithNestedDispatch(int velocityY) { final int scrollY = getScrollY(); boolean canFling = false; if (velocityY != 0 && scrollY < mMaxScrollY && scrollY > mMinScrollY) { canFling = true; } if (!mParent.dispatchNestedPreFling(0, velocityY)) { mParent.dispatchNestedFling(0, velocityY, canFling); if (canFling) { fling(velocityY); return true; } else { return false; } } else { return true; } } /** * Fling the scroll view * * @param velocityY The initial velocity in the Y direction. Positive * numbers mean that the finger/cursor is moving down the screen, * which means we want to scroll towards the top. */ public void fling(int velocityY) { fling(velocityY, mMinScrollY, mMaxScrollY); } /** * velocityY >0 向上滚动 * * @param velocityY * @param minY * @param maxY */ public void fling(int velocityY, final int minY, final int maxY) { Log.e("watcher", minY + "minY" + velocityY + "velocityY" + maxY); stopScroll(); if (velocityY < 0) { // if(minY == getScrollY()){ // return; // } // if(getScrollY()-minY <= mTouchSlop){ // ViewCompat.postOnAnimationDelayed(mParent, new Runnable() { // @Override // public void run() { // mParent.scrollTo(0,minY); // } // },16); // return; // } } if (velocityY > 0) { // if(maxY == getScrollY()){ // return; // } // if(maxY - getScrollY() <= mTouchSlop){ // ViewCompat.postOnAnimationDelayed(mParent, new Runnable() { // @Override // public void run() { // mParent.scrollTo(0,maxY); // } // },16); // return; // } } if (Math.abs(velocityY) < mMinimumVelocity) { velocityY = velocityY > 0 ? mMinimumVelocity : -mMinimumVelocity; } if (Math.abs(velocityY) > mMaximumVelocity) { velocityY = velocityY > 0 ? mMaximumVelocity : -mMaximumVelocity; } if (mParent.getChildCount() > 0) { if (velocityY > 0) { mScroller.fling(0, getScrollY(), 0, velocityY, 0, 0, Math.min(minY, maxY), Math.max(minY, maxY)); } else { mScroller.fling(0, getScrollY(), 0, velocityY, 0, 0, Math.min(minY, maxY), Math.max(minY, maxY)); } startAnim(); } } private int getScrollY() { return mParent.getScrollY(); } /** * 大于0向上滚动顶部,小于0向下滚动底部 * * @param derection */ private void smoothScroll(int derection) { if (derection > 0) { smoothScrollBy(0, mMinScrollY - getScrollY()); } else if (derection < 0) { smoothScrollBy(0, mMaxScrollY - getScrollY()); } } private void smoothScrollToFinal() { // if ((mOneDrectionDeltaY == 0 && (mTarget.getTranslationY() == 0 ||mTarget.getTranslationY() ==getScrollRange())) || !isFollowMove) { // return; // } if (mOneDrectionDeltaY > 0) { startScrollDown(); } else { startScrollUp(); } mOneDrectionDeltaY = 0; } private void doScroll(int deltaY) { boolean isFollowMove = false; if (isFollowMove) { final int curScrollY = getScrollY(); int finalScrollY = curScrollY + deltaY; // mTarget.setTranslationY(finalScrollY); } else { if (Math.abs(mOneDrectionDeltaY) > 3 * mTouchSlop) { if (mOneDrectionDeltaY > 0) { mOneDrectionDeltaY = 0; startScrollDown(); } else { mOneDrectionDeltaY = 0; startScrollUp(); } } } } private void startScrollUp() { startAnim(); } private void startScrollDown() { startAnim(); } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) >> MotionEventCompat.ACTION_POINTER_INDEX_SHIFT; final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose TOP new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionY = (int) MotionEventCompat.getY(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; mOneDrectionDeltaY = 0; recycleVelocityTracker(); mParent.stopNestedScroll(); } void recycleVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void initVelocityTrackerIfNotExists() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } } private void initOrResetVelocityTracker() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } } public static final int ANIMATE_OFFSET_DIPS_PER_SECOND = 300; ValueAnimator mAnimator; private void animateOffsetTo(final View parent, final int currentOffset, final int offset) { if (currentOffset == offset) { if (mAnimator != null && mAnimator.isRunning()) { mAnimator.cancel(); } return; } if (mAnimator == null) { mAnimator = new ValueAnimator(); mAnimator.setInterpolator(new DecelerateInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { int value = (int) animator.getAnimatedValue(); } }); } else { mAnimator.cancel(); } // Set the duration based on the amount of dips we're travelling in final float distanceDp = Math.abs(currentOffset - offset) / mParent.getResources().getDisplayMetrics().density; mAnimator.setDuration(Math.round(distanceDp * 1000 / ANIMATE_OFFSET_DIPS_PER_SECOND)); mAnimator.setIntValues(currentOffset, offset); mAnimator.start(); } public interface OnScrollListener { void onTriger(boolean isScrollUp); void onScroll(float dy); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util.xml; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.XMLEvent; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Implementation of {@code XMLEventReader} based on a {@link List} * of {@link XMLEvent} elements. * * @author Arjen Poutsma * @author Juergen Hoeller * @since 5.0 */ class ListBasedXMLEventReader extends AbstractXMLEventReader { private final List<XMLEvent> events; @Nullable private XMLEvent currentEvent; private int cursor = 0; public ListBasedXMLEventReader(List<XMLEvent> events) { Assert.notNull(events, "XMLEvent List must not be null"); this.events = new ArrayList<>(events); } @Override public boolean hasNext() { return (this.cursor < this.events.size()); } @Override public XMLEvent nextEvent() { if (hasNext()) { this.currentEvent = this.events.get(this.cursor); this.cursor++; return this.currentEvent; } else { throw new NoSuchElementException(); } } @Override @Nullable public XMLEvent peek() { if (hasNext()) { return this.events.get(this.cursor); } else { return null; } } @Override public String getElementText() throws XMLStreamException { checkIfClosed(); if (this.currentEvent == null || !this.currentEvent.isStartElement()) { throw new XMLStreamException("Not at START_ELEMENT: " + this.currentEvent); } StringBuilder builder = new StringBuilder(); while (true) { XMLEvent event = nextEvent(); if (event.isEndElement()) { break; } else if (!event.isCharacters()) { throw new XMLStreamException("Unexpected non-text event: " + event); } Characters characters = event.asCharacters(); if (!characters.isIgnorableWhiteSpace()) { builder.append(event.asCharacters().getData()); } } return builder.toString(); } @Override @Nullable public XMLEvent nextTag() throws XMLStreamException { checkIfClosed(); while (true) { XMLEvent event = nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_ELEMENT: case XMLStreamConstants.END_ELEMENT: return event; case XMLStreamConstants.END_DOCUMENT: return null; case XMLStreamConstants.SPACE: case XMLStreamConstants.COMMENT: case XMLStreamConstants.PROCESSING_INSTRUCTION: continue; case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: if (!event.asCharacters().isWhiteSpace()) { throw new XMLStreamException( "Non-ignorable whitespace CDATA or CHARACTERS event: " + event); } break; default: throw new XMLStreamException("Expected START_ELEMENT or END_ELEMENT: " + event); } } } @Override public void close() { super.close(); this.events.clear(); } }
package com.hubPlayer.ui.tool; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import com.hubPlayer.expansion.game_2048.My2048; import com.hubPlayer.expansion.game_snake.MySnake; import view.ChessFrame; /** * 拓展功能面板,为播放器增加一些游戏程序 * * @date 2016-6-6 * */ public class AppPanel extends JPanel { private JButton game2048; private JButton gameSnake; private JButton gameGobang; private JFrame parent; public AppPanel(JFrame parent) { this.parent = parent; setLayout(new GridLayout(3, 3)); setSize(300, 500); addButtons(); setButtonsAction(); } private void addButtons() { game2048 = new IconButton("2048", "icon/item.png"); add(game2048); gameSnake = new IconButton("贪吃蛇", "icon/item.png"); add(gameSnake); gameGobang = new IconButton("网络五子棋", "icon/item.png"); add(gameGobang); add(new IconButton(null, "icon/item.png")); add(new IconButton(null, "icon/item.png")); add(new IconButton(null, "icon/item.png")); add(new IconButton(null, "icon/item.png")); add(new IconButton(null, "icon/item.png")); add(new IconButton(null, "icon/item.png")); } private void setButtonsAction() { game2048.addActionListener(event -> { new My2048(parent); }); gameSnake.addActionListener(event -> { new MySnake(parent); }); gameGobang.addActionListener(event -> { new ChessFrame(parent); }); } }
package com.HTTPServer; import java.util.List; public class Utility { public static String toString(List<Talk> talks){ StringBuilder sb = new StringBuilder(); for(Talk t: talks){ sb.append(t.title); sb.append(","); sb.append(t.description); sb.append(","); sb.append(t.topic); sb.append("\n"); } return sb.toString(); } public static String toString(Talk t){ return "Title = " + t.title + ", Topic = " + t.topic + ", Description = " + t.description; } }
package bwi.prog2B.SS2017.wi16b044_kapferer.ExerciseSheet03; import bwi.prog.utils.TextIO; public class Track { private int duration; private Artist performer = new Artist(); private String title; private Artist writer = new Artist();; private int year; // CONSTRUCTORS public Track() { this.title = null; this.duration = 0; this.performer = new Artist(); this.writer = new Artist(); } public Track(String title) { this(); this.title = title; } public Track(Track t) { this.duration = t.duration; this.performer = new Artist(t.performer); this.title = t.title; this.writer = new Artist(t.writer); this.year = t.year; } // METHODS public int getDuration() { return duration; } public Artist getPerformer() { return performer; } public String getString() { String writer, performer, title; if (this.title == null) { title = "unknown"; } else { title = this.title; } if (this.writer == null || this.writer.getName() == null) { writer = "unknown"; } else { writer = this.writer.getName(); } if (this.performer == null || this.performer.getName() == null) { performer = "unknown"; } else { performer = this.performer.getName(); } return String.format("%10.10s by %10.10s performed by %10.10s (%02d:%02d)", title, writer, performer, getDuration() / 60, getDuration() % 60); } public String getTitle() { if (title == null) { return "unknown title"; } else { return this.title; } } public Artist getWriter() { return writer; } public int getYear() { return year; } public void setDuration(int duration) { if (duration <= 0) { return; } else { this.duration=duration; } } public void setPerformer(Artist performer) { if (performer == null) { return; } else { this.performer=performer; } } public void setTitle(String title) { if (title == null) { this.title="unknown title"; } else { this.title=title; } } public void setWriter(Artist writer) { if (writer != null) { this.writer = writer; } } public void setYear(int year) { if (year < 1900 || year > 2999) { return; } else { this.year=year; } } public boolean writerIsKnown() { if (writer != null && writer.getName() != null) { return true; } else { return false; } } }
package qdu.java.recruit.service; import org.apache.ibatis.annotations.Param; public interface HrappService { Boolean inserthrapp(int positionId, int hrId,int userId); int delecthrapp(int positionId,int userId); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package graphic; import hibernate.HibernateUtil; import hibernate.Profils; import java.util.Iterator; import java.util.Map; import org.hibernate.Session; import org.snmp4j.smi.OctetString; import snmp_server.Profil; import snmp_server.ProfilFactory; /** * * @author Tomek */ public class ProfilFrame extends javax.swing.JFrame { MainFrame mother; public ProfilFrame(MainFrame mother) { this.mother = mother; initComponents(); SnmpVersion.addItem("snmpv1"); SnmpVersion.addItem("snmpv2c"); SnmpVersion.addItem("snmpv3"); setAuthProtocol(); setPrivProtocol(); } private void setAuthProtocol() { Iterator i = mother.getAuthProtocols().entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); authBox.addItem(entry.getKey().toString()); } } private void setPrivProtocol() { Iterator i = mother.getPrivProtocols().entrySet().iterator(); privBox.addItem(""); while(i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); privBox.addItem(entry.getKey().toString()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); SnmpVersion = new javax.swing.JComboBox(); SecuName = new javax.swing.JTextField(); AuthPass = new javax.swing.JTextField(); PrivPass = new javax.swing.JTextField(); SaveButton = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); ProfilName = new javax.swing.JTextField(); authBox = new javax.swing.JComboBox(); privBox = new javax.swing.JComboBox(); jLabel1.setText("SNMP version:"); jLabel2.setText("Security Name:"); jLabel3.setText("Authentication Protocol:"); jLabel4.setText("Authentication Password:"); jLabel5.setText("Privacy Protocol:"); jLabel6.setText("Privacy Passowrd:"); SaveButton.setText("Save"); SaveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveButtonActionPerformed(evt); } }); jLabel7.setText("Profil Name:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(SaveButton) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6)) .addGap(38, 38, 38)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(SecuName, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE) .addComponent(AuthPass) .addComponent(PrivPass) .addComponent(ProfilName) .addComponent(authBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(privBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(65, 65, 65) .addComponent(SnmpVersion, 0, 135, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(SnmpVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ProfilName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(SecuName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(authBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(AuthPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(privBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(PrivPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addComponent(SaveButton) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveButtonActionPerformed mother.getProfils().add(mother.getProfils().size(),new Profil( ProfilFactory.addName(new OctetString(ProfilName.getText())), ProfilFactory.addVersion(SnmpVersion.getSelectedItem().toString()), ProfilFactory.addSecurityName(new OctetString(SecuName.getText())), ProfilFactory.addAuthProtocol(new OctetString(authBox.getSelectedItem().toString()),mother.getAuthProtocols()), ProfilFactory.addAuthPassword(new OctetString(AuthPass.getText())), ProfilFactory.addPrivProtocol(new OctetString(privBox.getSelectedItem().toString()),mother.getPrivProtocols()), ProfilFactory.addPrivPassword(new OctetString(PrivPass.getText())))); mother.setProfilsTab(); saveProfil(); }//GEN-LAST:event_SaveButtonActionPerformed private void saveProfil() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Profils profils = new Profils(); profils.setName(ProfilName.getText()); profils.setVersion(SnmpVersion.getSelectedItem().toString()); profils.setSecurityname(SecuName.getText()); profils.setAuthprot(authBox.getSelectedItem().toString()); profils.setAuthpass(AuthPass.getText()); profils.setPrivprot(privBox.getSelectedItem().toString()); profils.setPrivpass(PrivPass.getText()); session.save(profils); session.getTransaction().commit(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField AuthPass; private javax.swing.JTextField PrivPass; private javax.swing.JTextField ProfilName; private javax.swing.JButton SaveButton; private javax.swing.JTextField SecuName; private javax.swing.JComboBox SnmpVersion; private javax.swing.JComboBox authBox; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JComboBox privBox; // End of variables declaration//GEN-END:variables }
package com.orsegrups.splingvendas.fragment; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import com.beardedhen.androidbootstrap.AwesomeTextView; import com.beardedhen.androidbootstrap.BootstrapButton; import com.orsegrups.splingvendas.R; import com.orsegrups.splingvendas.activity.BuscaClientePedidoActivity; import com.orsegrups.splingvendas.activity.NovoItemActivity; import com.orsegrups.splingvendas.dao.PedidoDao; import com.orsegrups.splingvendas.model.Cliente; import com.orsegrups.splingvendas.model.Pedido; import com.orsegrups.splingvendas.model.Produto; import com.orsegrups.splingvendas.util.Alertas; import com.orsegrups.splingvendas.util.Constantes; import com.orsegrups.splingvendas.util.UtilAddItemNoPedido; import java.math.BigDecimal; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import cn.pedant.SweetAlert.SweetAlertDialog; /** * Created by filipeamaralneis on 17/12/16. */ public class NovoPedidoCadastroFragment extends Fragment { private View view; private ScrollView scrollView; private EditText clienteNome, data, hora, totalPedidoText; private Cliente cliente; private AwesomeTextView btAddCliente; private BigDecimal totalPedido = new BigDecimal("0"); private ListView lista; private TextView listaVazia, modalTitulo; private ImageView novoItemButton; private List<Produto> listaProduto = new ArrayList<>(); private SweetAlertDialog caixaDeMenssagem ; private LayoutInflater mInflater; private BaseAdapter baseAdapter; private Dialog dialog; private EditText qtdItem; private BootstrapButton btAddItem; private BootstrapButton btSalvarPedido; public NovoPedidoCadastroFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_novo_pedido_cadastro, container, false); confuguraPedido(); configuraListaItens(); return view; } @Override public void onResume(){ super.onResume(); if(UtilAddItemNoPedido.getCliente()!= null) { cliente = UtilAddItemNoPedido.getCliente(); clienteNome.setText(cliente.getNome()); UtilAddItemNoPedido.setCliente(null); } if(UtilAddItemNoPedido.getP()!= null) { ViewGroup.LayoutParams params = lista.getLayoutParams(); params.height = lista.getHeight() + 430; lista.setLayoutParams(params); lista.requestLayout(); listaProduto.add(UtilAddItemNoPedido.getP()); if(!listaProduto.isEmpty()) { totalPedido = new BigDecimal(0); for (Produto produto : listaProduto) { calculaPrecoTotal(produto); } } if(baseAdapter == null) { baseAdapter = new BaseAdapter() { @Override public int getCount() { return listaProduto.size(); } @Override public Produto getItem(int position) { return listaProduto.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Produto item = listaProduto.get(position); mInflater = LayoutInflater.from(getContext()); view = mInflater.inflate(R.layout.row_item_novo_pedido, null); final int posicao = position; TextView nome; final TextView qtd; final TextView precoUnitario; final TextView precoTotal; ImageView excluirItem; ImageView editarItem; LinearLayout linha = (LinearLayout) view.findViewById(R.id.lyt_parent); nome = (TextView) view.findViewById(R.id.novo_item_pedido_nome); qtd = (TextView) view.findViewById(R.id.novo_item_pedido_qtd); precoUnitario = (TextView) view.findViewById(R.id.novo_item_pedido_preco_unitario); precoTotal = (TextView) view.findViewById(R.id.novo_item_pedido_preco_total); editarItem = (ImageView) view.findViewById(R.id.novo_item_pedido_editar); excluirItem = (ImageView) view.findViewById(R.id.novo_item_pedido_excluir); if (item != null) { nome.setText(item.getIdProduto().toString() + " - " + item.getDescricao()); qtd.setText("Quantidade: " + item.getQtdItens()); precoTotal.setText(getPrecoTotal(item)); precoUnitario.setText( getPrecoUnitario(item)); excluirItem.setTag(posicao); excluirItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeItemLista(v); } }); editarItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog = new Dialog(view.getContext()); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.modal_novo_item); modalTitulo = (TextView) dialog.findViewById(R.id.modal_alimentos_titulo); qtdItem = (EditText) dialog.findViewById(R.id.modal_novo_item_qtd); btAddItem = (BootstrapButton) dialog.findViewById(R.id.modal_novo_item_add); modalTitulo.setText("Informe a quantidade de " + item.getDescricao()); modalTitulo.setTextColor(Color.DKGRAY); btAddItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!qtdItem.getText().toString().isEmpty()) { item.setQtdItens(Integer.parseInt(qtdItem.getText().toString())); UtilAddItemNoPedido.setP(item); dialog.dismiss(); qtd.setText("Quantidade: " + item.getQtdItens()); precoTotal.setText(getPrecoTotal(item)); precoUnitario.setText(getPrecoUnitario(item)); //((Activity)view.getContext()).finish(); } } }); dialog.show(); } }); } else { linha.setVisibility(View.GONE); } return view; } }; lista.setAdapter(baseAdapter); }else{ baseAdapter.notifyDataSetChanged(); } lista.setCacheColorHint(Color.TRANSPARENT); UtilAddItemNoPedido.setP(null); } } public void hideKeyboard() { View view = getActivity().getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public void confuguraPedido(){ totalPedidoText = (EditText) view.findViewById(R.id.novo_pedido_total_pedido); data = (EditText) view.findViewById(R.id.novo_pedido_cadastro_data); hora = (EditText) view.findViewById(R.id.novo_pedido_cadastro_hora); clienteNome = (EditText) view.findViewById(R.id.novo_pedido_cadastro_nome); btAddCliente = (AwesomeTextView) view.findViewById(R.id.novo_pedido_add_cliente); btSalvarPedido = (BootstrapButton) view.findViewById(R.id.novo_pedido_button_salvar); clienteNome.setEnabled(false); clienteNome.setFocusable(false); totalPedidoText.setEnabled(false); totalPedidoText.setFocusable(false); configuraDataHora(); btAddCliente.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getContext(), BuscaClientePedidoActivity.class); startActivity(i); } }); btSalvarPedido.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvarPedido(); } }); } public void configuraListaItens(){ lista = (ListView) view.findViewById(R.id.novo_pedido_item_lista); listaVazia = (TextView) view.findViewById(R.id.listavazia); lista.setEmptyView((TextView) view.findViewById(R.id.listavazia)); novoItemButton = (ImageView) view.findViewById(R.id.novo_pedido_item_novo_item_button); novoItemButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addItemNaLista(v); } }); } private void addItemNaLista(View v){ Intent i = new Intent(view.getContext(), NovoItemActivity.class); startActivity(i); } public void removeItemLista(final View v){ caixaDeMenssagem = new SweetAlertDialog(getContext(), SweetAlertDialog.BUTTON_NEGATIVE); caixaDeMenssagem.setTitleText("Deseja Excluir item ?"); caixaDeMenssagem.setConfirmText("Sim"); caixaDeMenssagem.setCancelText("Não"); caixaDeMenssagem.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { caixaDeMenssagem.dismiss(); } }); caixaDeMenssagem.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { // remove item da lista Object toRemove = baseAdapter.getItem((Integer) v.getTag()); BigDecimal vlrItem = listaProduto.get((Integer) v.getTag()).getValor().multiply(BigDecimal.valueOf(listaProduto.get((Integer) v.getTag()).getQtdItens())); listaProduto.remove(toRemove); UtilAddItemNoPedido.setProdutos(listaProduto); totalPedidoText.setText(NumberFormat.getCurrencyInstance(Constantes.MEU_LOCAL).format(totalPedido)); totalPedido = totalPedido.subtract(vlrItem); caixaDeMenssagem.dismiss(); } }); caixaDeMenssagem.show(); } public String getPrecoTotal(Produto item){ BigDecimal prTotal = item.getValor().multiply(new BigDecimal(item.getQtdItens())); return "Preço total: " + NumberFormat.getCurrencyInstance(Constantes.MEU_LOCAL).format(prTotal); } public String getPrecoUnitario(Produto item){ return "Preço unitario: " + NumberFormat.getCurrencyInstance(Constantes.MEU_LOCAL).format(item.getValor()); } public void calculaPrecoTotal(Produto item){ BigDecimal prTotal = item.getValor().multiply(new BigDecimal(item.getQtdItens())); totalPedido = totalPedido.add(prTotal); totalPedidoText.setText(NumberFormat.getCurrencyInstance(Constantes.MEU_LOCAL).format(totalPedido)); } public void salvarPedido(){ if(cliente == null){ Alertas.menssagemDeErro("Informe um cliente!", getContext()); return; } if(listaProduto.isEmpty()){ Alertas.menssagemDeErro("Informe pelo menos um produto ao pedido!", getContext()); return; } Pedido pedido = new Pedido(); pedido.setValorTotal(this.totalPedido); pedido.setDtCadastro(new Date()); pedido.setDtEmissao(new Date()); pedido.setCliente(cliente); pedido.setItens(listaProduto); PedidoDao dao = new PedidoDao(getContext()); dao.insert(pedido); dao.close(); caixaDeMenssagem = new SweetAlertDialog(getContext(),SweetAlertDialog.NORMAL_TYPE); caixaDeMenssagem.setContentText("Pedido Salvo com sucesso"); caixaDeMenssagem.setTitleText("Pedido"); caixaDeMenssagem.setConfirmText("OK"); caixaDeMenssagem.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { clienteNome.setText(""); totalPedidoText.setText(""); configuraDataHora(); listaProduto = new ArrayList<Produto>(); baseAdapter.notifyDataSetChanged(); ViewGroup.LayoutParams params = lista.getLayoutParams(); params.height = 10; lista.setLayoutParams(params); lista.requestLayout(); caixaDeMenssagem.dismiss(); } }); caixaDeMenssagem.show(); } private void configuraDataHora() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); Date horaf = Calendar.getInstance().getTime(); Date dataf = Calendar.getInstance().getTime(); String horaFormatada = sdf2.format(horaf); String dataFormatada = sdf.format(dataf); data.setText(dataFormatada); hora.setText(horaFormatada); hora.setEnabled(false); hora.setFocusable(false); data.setEnabled(false); data.setFocusable(false); } }
/* * Copyright (C) 2012 www.amsoft.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bnrc.http; import android.os.Handler; import android.os.Message; // TODO: Auto-generated Javadoc /** * 漏 2012 amsoft.cn * 鍚嶇О锛欰bHttpResponseListener.java * 鎻忚堪锛欻ttp鍝嶅簲鐩戝惉鍣� * * @author 杩樺涓�姊︿腑 * @version v1.0 * @date锛�2013-11-13 涓婂崍9:00:52 */ public abstract class AbHttpResponseListener { /** The handler. */ private Handler mHandler; /** * 鏋勯��. */ public AbHttpResponseListener() { super(); } /** * 鎻忚堪锛氳幏鍙栨暟鎹紑濮�. */ public abstract void onStart(); /** * 瀹屾垚鍚庤皟鐢紝澶辫触锛屾垚鍔燂紝璋冪敤. */ public abstract void onFinish(); /** * 閲嶈瘯. */ public void onRetry() {} /** * 鎻忚堪锛氬け璐ワ紝璋冪敤. * * @param statusCode the status code * @param content the content * @param error the error */ public abstract void onFailure(int statusCode, String content,Throwable error); /** * 杩涘害. * * @param bytesWritten the bytes written * @param totalSize the total size */ public void onProgress(int bytesWritten, int totalSize) {} /** * 寮�濮嬫秷鎭�. */ public void sendStartMessage(){ sendMessage(obtainMessage(AbHttpClient.START_MESSAGE, null)); } /** * 瀹屾垚娑堟伅. */ public void sendFinishMessage(){ sendMessage(obtainMessage(AbHttpClient.FINISH_MESSAGE,null)); } /** * 杩涘害娑堟伅. * * @param bytesWritten the bytes written * @param totalSize the total size */ public void sendProgressMessage(int bytesWritten, int totalSize) { sendMessage(obtainMessage(AbHttpClient.PROGRESS_MESSAGE, new Object[]{bytesWritten, totalSize})); } /** * 澶辫触娑堟伅. * * @param statusCode the status code * @param content the content * @param error the error */ public void sendFailureMessage(int statusCode,String content,Throwable error){ sendMessage(obtainMessage(AbHttpClient.FAILURE_MESSAGE, new Object[]{statusCode,content, error})); } /** * 閲嶈瘯娑堟伅. */ public void sendRetryMessage() { sendMessage(obtainMessage(AbHttpClient.RETRY_MESSAGE, null)); } /** * 鍙戦�佹秷鎭�. * @param msg the msg */ public void sendMessage(Message msg) { if (msg != null) { msg.sendToTarget(); } } /** * 鏋勯�燤essage. * @param responseMessage the response message * @param response the response * @return the message */ protected Message obtainMessage(int responseMessage, Object response) { Message msg; if (mHandler != null) { msg = mHandler.obtainMessage(responseMessage, response); } else { msg = Message.obtain(); if (msg != null) { msg.what = responseMessage; msg.obj = response; } } return msg; } /** * Gets the handler. * * @return the handler */ public Handler getHandler() { return mHandler; } /** * 鎻忚堪锛氳缃瓾andler. * * @param handler the new handler */ public void setHandler(Handler handler) { this.mHandler = handler; } }
package co.project.bloodbankmgmt.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import co.project.bloodbankmgmt.models.BloodGroup; /** * Created by Kunal on 26/03/17. */ public class BloodGroupAdapter extends BaseAdapter { private Context context; private List<BloodGroup> bloodGroups; public BloodGroupAdapter(Context context, List<BloodGroup> bloodGroups) { this.context = context; this.bloodGroups = bloodGroups; } public void updateDataSource(List<BloodGroup> bloodGroups) { this.bloodGroups.clear(); this.bloodGroups.addAll(bloodGroups); notifyDataSetChanged(); } @Override public int getCount() { return bloodGroups.size(); } @Override public Object getItem(int i) { return bloodGroups.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View view, ViewGroup viewGroup) { View row = view; if(row == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(android.R.layout.simple_list_item_1, null); } TextView txtBloodGroup = (TextView)row.findViewById(android.R.id.text1); txtBloodGroup.setText(bloodGroups.get(position).getTitle()); return row; } public interface OnBloodGroupSelectedListener { void onBloodGroupSelected(BloodGroup bloodGroupSelected); } }
package com.fotoable.fotoime.ui; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodSubtype; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; import com.android.inputmethod.compat.InputMethodSubtypeCompatUtils; import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; import com.crashlytics.android.core.CrashlyticsCore; import com.fotoable.fotoime.R; import com.fotoable.fotoime.bean.FotoSubTypeBean; import com.fotoable.fotoime.bean.GroupMySubtype; import com.fotoable.fotoime.bean.MyInputMethodSubtype; import com.fotoable.fotoime.dicts.DownloadDictionary; import com.fotoable.fotoime.theme.ThemeTools; import com.fotoable.fotoime.utils.Constants; import com.fotoable.fotoime.utils.FotoSubtypeUtil; import com.fotoable.fotoime.utils.LogUtil; import com.fotoable.fotoime.utils.MobileUtil; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Created by zhanglf on 2016/9/6. */ public class LanguageSettingActivity extends Activity { private static final String TAG = LanguageSettingActivity.class.getSimpleName(); private Context mContext; private SharedPreferences defaultSp; private Set<String> currentLocalSet; private RecyclerView mRecyclerView; private MyAdapter mAdapter; private List<GroupMySubtype> groupSubtypeList; private List<MyInputMethodSubtype> mySubtypesAdded; private List<MyInputMethodSubtype> mySubtypesNoDic; private ImageView iv_back; private TextView tv_title; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 0: mAdapter = new MyAdapter(); mRecyclerView.setAdapter(mAdapter); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.foto_language_setting); initTitle(); // 初始化列表 FotoSubtypeUtil.initLanguageSetting(this); mContext = this; defaultSp = PreferenceManager.getDefaultSharedPreferences(this); currentLocalSet = defaultSp.getStringSet(FotoSubtypeUtil.SUBTYPE_LOCAL_SET, null); if (currentLocalSet == null || currentLocalSet.size() == 0){ return; } // 首次进入,检测所有语言包,加入到选中列表中 if (!defaultSp.getBoolean(Constants.FIRST_LANGUAGE_SETTING, false)) { // 进入到列表中 try { initLangPack(); } catch (Throwable e) { CrashlyticsCore.getInstance().logException(e); } defaultSp.edit().putBoolean(Constants.FIRST_LANGUAGE_SETTING, true).apply(); } mRecyclerView = (RecyclerView)findViewById(R.id.recyclerview_foto_language); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); getData(); } private void initTitle() { getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.foto_theme_more_title); getWindow().setBackgroundDrawable(getResources().getDrawable(R.color.bkcolor)); iv_back = (ImageView) findViewById(R.id.iv_foto_theme_more_back); tv_title = (TextView) findViewById(R.id.tv_foto_theme_more_title); tv_title.setText(R.string.foto_setting_index_language); iv_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /** * 首次打开语言界面 * 将所有安装的语言包设置为选中语言 */ public void initLangPack(){ PackageManager packageManager = getPackageManager(); final SharedPreferences.Editor edit = defaultSp.edit(); final List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0); if (installedPackages != null) { final Iterator<PackageInfo> iterator = installedPackages.iterator(); while (iterator.hasNext()) { final PackageInfo packageInfo = iterator.next(); final String packageName = packageInfo.packageName; if (!TextUtils.isEmpty(packageName) && packageName.startsWith(Constants.LANG_PACKAGE_PREFIX)) { String language = packageName.substring(packageName.lastIndexOf(".") + 1); for (int i = 0; i < Constants.ALL_DICT_LANGUAGE.length; i++){ if (Constants.ALL_DICT_LANGUAGE[i].equals(language)){ currentLocalSet.add(language); edit.putLong(language, System.currentTimeMillis()); if (!new File(MobileUtil.getDictsDir()+"main_"+language).exists()){ MobileUtil.copyAssetDict(this,packageName,"main_"+language); } } } } } edit.putStringSet(FotoSubtypeUtil.SUBTYPE_LOCAL_SET,currentLocalSet); edit.apply(); } } private void getData() { new Thread(new Runnable() { @Override public void run() { groupSubtypeList = FotoSubtypeUtil.getGroupSubtypeList(mContext); if (groupSubtypeList == null || groupSubtypeList.size()<2) return; mySubtypesAdded = groupSubtypeList.get(0).getInputMethodSubtypes(); mySubtypesNoDic = groupSubtypeList.get(1).getInputMethodSubtypes(); if (mySubtypesAdded == null || mySubtypesAdded.size() < 1) return; // if (mySubtypesNoDic == null || mySubtypesNoDic.size() < 1) return; mHandler.sendEmptyMessage(0); } }).start(); } /************* MyAdapter *********************************************************/ class MyAdapter extends RecyclerView.Adapter<MyViewHolder> { public static final int TYPE_TITLE = 0; public static final int TYPE_NORMAL = 1; private final LayoutInflater mInflater; private final MyInputMethodSubtype comparator; public MyAdapter(){ mInflater = LayoutInflater.from(mContext); comparator = new MyInputMethodSubtype(); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_TITLE) { View titleView = mInflater.inflate(R.layout.foto_language_setting_title, parent, false); titleView.setTag(TYPE_TITLE); return new MyViewHolder(titleView); } View normalView = mInflater.inflate(R.layout.foto_language_setting_item, parent, false); normalView.setTag(TYPE_NORMAL); return new MyViewHolder(normalView); } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { if (getItemViewType(position) == TYPE_TITLE) { if (position == 0){ holder.tv_title.setText(R.string.available_lang); }else{ holder.tv_title.setText(R.string.undoanloaded_lang); } }else{ //Added languages if (position <= mySubtypesAdded.size()){ final int realAddedPosition = getRealAddedPosition(position); final MyInputMethodSubtype myInputMethodSubtype = mySubtypesAdded.get(realAddedPosition); final InputMethodSubtype subtype = myInputMethodSubtype.getSubtype(); //String displayName = SubtypeLocaleUtils.getSubtypeLocale(subtype).getDisplayName(); //String fullDisplayName = SpacebarLanguageUtils.getFullDisplayName(subtype); String fullDisplayName = myInputMethodSubtype.getFullDisplayName(); holder.tv_display_name.setText(fullDisplayName == null ? "" : fullDisplayName.trim()); if (myInputMethodSubtype.getState() == MyInputMethodSubtype.State.ENABLED){ //当前可用(选中的) setEnableEvent(holder, myInputMethodSubtype); }else{ //当前不可用(未选中) setDisableEvent(holder, realAddedPosition, myInputMethodSubtype, subtype); } if (holder.cb_enabled.isClickable()){ holder.ll_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //切换,是否选中 holder.cb_enabled.setChecked(!holder.cb_enabled.isChecked()); handleCheckBoxClickEvent(holder.cb_enabled.isChecked(), myInputMethodSubtype); } }); holder.cb_enabled.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //切换,是否选中 handleCheckBoxClickEvent(holder.cb_enabled.isChecked(), myInputMethodSubtype); } }); } }else{ //Available languages final int realNoDicPosition = getRealNoDicPosition(position); final MyInputMethodSubtype myInputMethodSubtype = mySubtypesNoDic.get(realNoDicPosition); final InputMethodSubtype subtype = myInputMethodSubtype.getSubtype(); String fullDisplayName = myInputMethodSubtype.getFullDisplayName(); holder.tv_display_name.setText(fullDisplayName == null ? "" : fullDisplayName.trim()); setAvailableEvent(holder, realNoDicPosition, myInputMethodSubtype, subtype); } } } @Override public int getItemCount() { return mySubtypesAdded.size() + mySubtypesNoDic.size() + 2; } @Override public int getItemViewType(int position) { if (position == 0 || position == mySubtypesAdded.size() + 1){ return TYPE_TITLE; } return TYPE_NORMAL; } private void setAvailableEvent(MyViewHolder holder, final int realNoDicPosition, final MyInputMethodSubtype myInputMethodSubtype, final InputMethodSubtype subtype) { holder.cb_enabled.setVisibility(View.GONE); holder.iv_delete.setVisibility(View.GONE); holder.tv_add.setVisibility(View.VISIBLE); holder.tv_layout.setVisibility(View.GONE); holder.ll_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //添加并排序 myInputMethodSubtype.setState(MyInputMethodSubtype.State.ENABLED); mySubtypesAdded.add(myInputMethodSubtype); //Collections.sort(mySubtypesAdded, comparator); //remove mySubtypesNoDic.remove(realNoDicPosition); //保存到sp String locale = subtype.getLocale(); if(!currentLocalSet.contains(locale)){ currentLocalSet.add(locale); } SharedPreferences.Editor edit = defaultSp.edit(); edit.putStringSet(FotoSubtypeUtil.SUBTYPE_LOCAL_SET, currentLocalSet); edit.putLong(locale, System.currentTimeMillis()); edit.apply(); final String currentLocale = myInputMethodSubtype.getSubtype().getLocale(); final String dictionaryLocale = ThemeTools.getDictionaryLocale(currentLocale); if (dictionaryLocale != null){ DownloadDictionary.downloadDict(getApplicationContext(),dictionaryLocale); } MyAdapter.this.notifyDataSetChanged(); } }); } private void handleCheckBoxClickEvent(boolean isChecked, MyInputMethodSubtype myInputMethodSubtype) { if (isChecked){ myInputMethodSubtype.setState(MyInputMethodSubtype.State.ENABLED); //添加到sp String locale = myInputMethodSubtype.getSubtype().getLocale(); if(!currentLocalSet.contains(locale)){ currentLocalSet.add(locale); } SharedPreferences.Editor edit = defaultSp.edit(); edit.putStringSet(FotoSubtypeUtil.SUBTYPE_LOCAL_SET, currentLocalSet); edit.putLong(locale, System.currentTimeMillis()); edit.apply(); }else{ //移除locale的存储时间 myInputMethodSubtype.setState(MyInputMethodSubtype.State.DISABLED); String locale = myInputMethodSubtype.getSubtype().getLocale(); SharedPreferences.Editor edit = defaultSp.edit(); edit.remove(locale); edit.apply(); //取消的时候,如果是当前语言,则改变当前语言值 String currentSubtypeLocale = FotoSubtypeUtil.getCurrentSubtypeLocale(defaultSp); if (locale.equals(currentSubtypeLocale)){ SharedPreferences.Editor edit2 = defaultSp.edit(); List<FotoSubTypeBean> enabledFotoSubTypes = FotoSubtypeUtil.getEnabledFotoSubTypeListByLocalSet(mContext, currentLocalSet); currentSubtypeLocale = enabledFotoSubTypes.get(0).getLocal(); edit2.putString(FotoSubtypeUtil.CURRENT_SUBTYPE_LOCALE, currentSubtypeLocale); edit2.apply(); LogUtil.i(TAG, "currentSubtypeLocale: " + enabledFotoSubTypes.get(0).getLocal()); } } MyAdapter.this.notifyDataSetChanged(); } private void setDisableEvent(MyViewHolder holder, final int realAddedPosition, final MyInputMethodSubtype myInputMethodSubtype, final InputMethodSubtype subtype) { holder.cb_enabled.setVisibility(View.VISIBLE); holder.cb_enabled.setChecked(false); holder.iv_delete.setVisibility(View.VISIBLE); holder.tv_add.setVisibility(View.GONE); holder.tv_layout.setVisibility(View.GONE); holder.iv_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //设置为Available languages //add并排序 myInputMethodSubtype.setState(MyInputMethodSubtype.State.NO_DICTIONARY); mySubtypesNoDic.add(myInputMethodSubtype); Collections.sort(mySubtypesNoDic, comparator); //remove mySubtypesAdded.remove(realAddedPosition); MyAdapter.this.notifyDataSetChanged(); //保存到sp String locale = subtype.getLocale(); if (currentLocalSet.contains(locale)){ currentLocalSet.remove(locale); } SharedPreferences.Editor edit = defaultSp.edit(); edit.putStringSet(FotoSubtypeUtil.SUBTYPE_LOCAL_SET, currentLocalSet); edit.remove(locale); edit.apply(); } }); } private void setEnableEvent(final MyViewHolder holder, final MyInputMethodSubtype mySubtype) { holder.cb_enabled.setVisibility(View.VISIBLE); holder.cb_enabled.setChecked(true); holder.iv_delete.setVisibility(View.GONE); holder.tv_add.setVisibility(View.GONE); if (!InputMethodSubtypeCompatUtils.isAsciiCapable(mySubtype.getSubtype())){ holder.tv_layout.setVisibility(View.GONE); }else{ //如果keyboardLayout可选 holder.tv_layout.setVisibility(View.VISIBLE); holder.tv_layout.setText(mySubtype.getLayout()); holder.tv_layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showKeyboardLayoutDialog(mySubtype); } }); } //判断是否仅有的一个语言,是仅有的一个 不可取消 if (FotoSubtypeUtil.isTheOnlyLanguage(mContext, currentLocalSet)){ holder.cb_enabled.setClickable(false); holder.ll_container.setClickable(false); }else{ holder.cb_enabled.setClickable(true); holder.ll_container.setClickable(true); } } private void showKeyboardLayoutDialog(final MyInputMethodSubtype mySubtype) { //showDialog final AlertDialog mDialog = new AlertDialog.Builder(mContext).create(); mDialog.setCanceledOnTouchOutside(true); mDialog.setCancelable(true); mDialog.show(); Window window = mDialog.getWindow(); window.setContentView(R.layout.foto_language_setting_dialog); final RadioButton rb_1 = (RadioButton)window.findViewById(R.id.rb_foto_language_dialog_1); final RadioButton rb_2 = (RadioButton)window.findViewById(R.id.rb_foto_language_dialog_2); final RadioButton rb_3 = (RadioButton)window.findViewById(R.id.rb_foto_language_dialog_3); String layout = mySubtype.getLayout(); if (TextUtils.isEmpty(layout)){ rb_1.setChecked(true); }else if(layout.equals(MyInputMethodSubtype.Layout.QWERTY)){ rb_1.setChecked(true); }else if(layout.equals(MyInputMethodSubtype.Layout.QWERTZ)){ rb_2.setChecked(true); }else{ rb_3.setChecked(true); } TextView tv_ok = (TextView)window.findViewById(R.id.tv_foto_language_dialog_ok); tv_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String selectedLayout = null; if (rb_1.isChecked()){ selectedLayout = rb_1.getText().toString(); }else if (rb_2.isChecked()){ selectedLayout = rb_2.getText().toString(); }else{ selectedLayout = rb_3.getText().toString(); } mDialog.cancel(); if (TextUtils.isEmpty(selectedLayout) || selectedLayout.equals(mySubtype.getLayout())){ LogUtil.i(TAG, "--- selectedLayout.equals(mySubtype.getLayout())"); return; } mySubtype.setLayout(selectedLayout); mAdapter.notifyDataSetChanged(); //保存到sp saveAdditionalSubtypesToSp(selectedLayout, mySubtype); } }); } /** * 把某种AdditionalSubtype写入sp. * 写入逻辑: 先拿到所有的getAdditionalSubtypes,再添加当前的AdditionalSubtype,再保存到sp * @param selectedLayout * @param mySubtype */ private void saveAdditionalSubtypesToSp(String selectedLayout, MyInputMethodSubtype mySubtype) { //获取到切换后的additionalSubtype InputMethodSubtype[] additionalSubtypes = FotoSubtypeUtil.getAdditionalSubtypesInSp(mContext); ArrayList<InputMethodSubtype> subtypeList = new ArrayList<>(); for (int i = 0; i< additionalSubtypes.length; i++){ InputMethodSubtype additionalSubtype = additionalSubtypes[i]; if (!additionalSubtype.getLocale().equals(mySubtype.getSubtype().getLocale())){ subtypeList.add(additionalSubtype); } } InputMethodSubtype selectedAdditionalSubtype = AdditionalSubtypeUtils.createAsciiEmojiCapableAdditionalSubtype( mySubtype.getSubtype().getLocale(), selectedLayout.toLowerCase()); subtypeList.add(selectedAdditionalSubtype); InputMethodSubtype[] newAdditionalSubtypes = subtypeList.toArray(new InputMethodSubtype[subtypeList.size()]); //写入sp FotoSubtypeUtil.saveAddtionalSubtypesToSp(mContext, newAdditionalSubtypes); //mRichImm.setAdditionalInputMethodSubtypes(subtypes); } public int getRealAddedPosition(int position) { int realPosition = position - 1; return realPosition < 0 ? 0 : realPosition; } public int getRealNoDicPosition(int position) { int realPosition = position - mySubtypesAdded.size() - 2; return realPosition; } } class MyViewHolder extends RecyclerView.ViewHolder { TextView tv_title; LinearLayout ll_container; TextView tv_display_name; TextView tv_add; TextView tv_layout; ImageView iv_delete; CheckBox cb_enabled; public MyViewHolder(View itemView) { super(itemView); int tag = (int)itemView.getTag(); if(tag == MyAdapter.TYPE_TITLE){ tv_title = (TextView) itemView.findViewById(R.id.tv_foto_language_setting_title); }else{ ll_container = (LinearLayout) itemView.findViewById(R.id.ll_foto_language_item_container); tv_display_name = (TextView) itemView.findViewById(R.id.tv_foto_language_item_display_name); tv_add = (TextView) itemView.findViewById(R.id.tv_foto_language_item_add); tv_layout = (TextView) itemView.findViewById(R.id.tv_foto_language_item_layout); cb_enabled = (CheckBox) itemView.findViewById(R.id.cb_foto_language_item_enabled); iv_delete = (ImageView) itemView.findViewById(R.id.iv_foto_language_item_delete); } } } }
//package com.appspot.smartshop.ui.user; // //import java.io.ByteArrayInputStream; //import java.io.DataInputStream; //import java.io.DataOutputStream; //import java.io.File; //import java.io.FileInputStream; //import java.io.FileNotFoundException; //import java.io.IOException; //import java.io.InputStream; //import java.net.HttpURLConnection; //import java.net.MalformedURLException; //import java.net.URL; //import java.util.Calendar; //import java.util.Date; //import java.util.regex.Pattern; // //import org.anddev.android.filebrowser.AndroidFileBrowser; //import org.json.JSONException; //import org.json.JSONObject; // //import android.app.Activity; //import android.app.AlertDialog; //import android.app.DatePickerDialog; //import android.app.Dialog; //import android.content.DialogInterface; //import android.content.Intent; //import android.os.Bundle; //import android.util.Log; //import android.view.View; //import android.view.View.OnClickListener; //import android.widget.Button; //import android.widget.DatePicker; //import android.widget.EditText; //import android.widget.TextView; //import android.widget.Toast; // //import com.appspot.smartshop.R; //import com.appspot.smartshop.dom.UserInfo; //import com.appspot.smartshop.map.MapDialog; //import com.appspot.smartshop.map.MapService; //import com.appspot.smartshop.map.MapDialog.UserLocationListener; //import com.appspot.smartshop.utils.Global; //import com.appspot.smartshop.utils.JSONParser; //import com.appspot.smartshop.utils.RestClient; //import com.appspot.smartshop.utils.StringUtils; //import com.appspot.smartshop.utils.URLConstant; //import com.appspot.smartshop.utils.Utils; //import com.appspot.smartshop.utils.capture.ImageCaptureActivity; //import com.google.android.maps.GeoPoint; //import com.google.android.maps.MapActivity; //import com.google.gson.JsonObject; // //public class UserActivity extends MapActivity { // public static final String TAG = "[UserActivity]"; // // private static final String PATTERN_EMAIL = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private static final String PATTERN_LONGER_6 = "^[_A-Za-z0-9-]{6}[_A-Za-z0-9-]*"; // // private static final int FILE_BROWSER_ID = 0; // private static final int IMAGE_CAPTURE_ID = 1; // // public static final int REGISTER_USER = 0; // public static final int EDIT_USER_PROFILE = 1; // // static final int DATE_DIALOG_ID = 0; // private int mode = REGISTER_USER; // // private TextView lblUsername; // private EditText txtUsername; // private TextView lblOldPassword; // private EditText txtOldPassword; // private TextView lblPassword; // private EditText txtPassword; // private TextView lblConfirm; // private EditText txtConfirm; // private TextView lblFirstName; // private EditText txtFirstName; // private TextView lblLastName; // private EditText txtLastName; // private TextView lblEmail; // private EditText txtEmail; // private TextView lblAddress; // private EditText txtAddress; // private TextView lblPhoneNumber; // private EditText txtPhoneNumber; // private TextView lblAvatar; // private EditText txtAvatar; // private TextView lblBirthday; // private Button btnPhoto; // private Button btnBrowser; // // private EditText txtBirthday; // // private int mYear; // private int mMonth; // private int mDay; // // private double lat; // private double lng; // // private UserInfo userInfo = null; // // private String[] imageFilter = new String[] { "jpg", "jpe", "jpeg", "jpg", // "bmp", "ico", "gif", "png" }; // private InputStream inputStreamAvatar; // private String fileName; // // private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { // // public void onDateSet(DatePicker view, int year, int monthOfYear, // int dayOfMonth) { // mYear = year - 1900; // mMonth = monthOfYear; // mDay = dayOfMonth; // // txtBirthday // .setText(Global.df.format(new Date(mYear, mMonth, mDay))); // } // }; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.user); // // // label width // int width = Utils.getScreenWidth(); // int labelWidth = (int) (width * 0.4); // int textWidth = width - labelWidth; // // // set up textviews // lblUsername = (TextView) findViewById(R.id.lblUsername); // lblUsername.setWidth(labelWidth); // txtUsername = (EditText) findViewById(R.id.txtUsername); // txtUsername.setWidth(textWidth); // // lblPassword = (TextView) findViewById(R.id.lblPassword); // lblPassword.setWidth(labelWidth); // txtPassword = (EditText) findViewById(R.id.txtPassword); // txtPassword.setWidth(textWidth); // // lblConfirm = (TextView) findViewById(R.id.lblConfirm); // lblConfirm.setWidth(labelWidth); // txtConfirm = (EditText) findViewById(R.id.txtConfirm); // txtConfirm.setWidth(textWidth); // // lblFirstName = (TextView) findViewById(R.id.lblFirstName); // lblFirstName.setWidth(labelWidth); // txtFirstName = (EditText) findViewById(R.id.txtFirstName); // txtFirstName.setWidth(textWidth); // // lblLastName = (TextView) findViewById(R.id.lblLastName); // lblLastName.setWidth(labelWidth); // txtLastName = (EditText) findViewById(R.id.txtLastName); // txtLastName.setWidth(textWidth); // // lblEmail = (TextView) findViewById(R.id.lblEmail); // lblEmail.setWidth(labelWidth); // txtEmail = (EditText) findViewById(R.id.txtEmail); // txtEmail.setWidth(textWidth); // // lblAddress = (TextView) findViewById(R.id.lblAddress); // lblAddress.setWidth(labelWidth); // txtAddress = (EditText) findViewById(R.id.txtAddress); // txtAddress.setWidth(textWidth); // // lblAvatar = (TextView) findViewById(R.id.lblAvatar); // lblAvatar.setWidth(labelWidth); // txtAvatar = (EditText) findViewById(R.id.txtAvatar); // txtAvatar.setWidth(textWidth); // // lblPhoneNumber = (TextView) findViewById(R.id.lblPhoneNumber); // lblPhoneNumber.setWidth(labelWidth); // txtPhoneNumber = (EditText) findViewById(R.id.txtPhoneNumber); // txtPhoneNumber.setWidth(textWidth); // // lblBirthday = (TextView) findViewById(R.id.lblBirthday); // lblBirthday.setWidth(labelWidth); // txtBirthday = (EditText) findViewById(R.id.txtBirthday); // txtBirthday.setWidth(textWidth); // // btnPhoto = (Button) findViewById(R.id.btnPhoto); // btnBrowser = (Button) findViewById(R.id.btnBrowser); // // lblOldPassword = (TextView) findViewById(R.id.lblOldPassword); // lblOldPassword.setWidth(labelWidth); // txtOldPassword = (EditText) findViewById(R.id.txtOldPassword); // txtOldPassword.setWidth(textWidth); // // btnBrowser.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // if (inputStreamAvatar != null) { // DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // Intent intent = new Intent(UserActivity.this, // AndroidFileBrowser.class); // intent.putExtra(Global.FILTER_FILE, imageFilter); // intent.setAction(Global.FILE_BROWSER_ACTIVITY); // startActivityForResult(intent, FILE_BROWSER_ID); // } // }; // DialogInterface.OnClickListener cancelButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // } // }; // // // Show an Alert with the ButtonListeners we created // AlertDialog ad = new AlertDialog.Builder(UserActivity.this) // .setTitle(getString(R.string.notice)) // .setMessage( // getString(R.string.do_you_want_to_change_avatar)) // .setPositiveButton(getString(R.string.yes), // okButtonListener).setNegativeButton( // getString(R.string.no), // cancelButtonListener).create(); // ad.show(); // } else { // Intent intent = new Intent(UserActivity.this, // AndroidFileBrowser.class); // intent.setAction(Global.FILE_BROWSER_ACTIVITY); // intent.putExtra(Global.FILTER_FILE, imageFilter); // startActivityForResult(intent, FILE_BROWSER_ID); // } // } // }); // // btnPhoto.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // if (inputStreamAvatar != null) { // DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // Intent intent = new Intent(UserActivity.this, // ImageCaptureActivity.class); // intent.setAction(Global.IMAGE_CAPURE_ACTIVITY); // startActivityForResult(intent, IMAGE_CAPTURE_ID); // } // }; // DialogInterface.OnClickListener cancelButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // } // }; // // // Show an Alert with the ButtonListeners we created // AlertDialog ad = new AlertDialog.Builder(UserActivity.this) // .setTitle(getString(R.string.notice)) // .setMessage( // getString(R.string.do_you_want_to_change_avatar)) // .setPositiveButton(getString(R.string.yes), // okButtonListener).setNegativeButton( // getString(R.string.no), // cancelButtonListener).create(); // ad.show(); // } else { // Intent intent = new Intent(UserActivity.this, // ImageCaptureActivity.class); // intent.setAction(Global.IMAGE_CAPURE_ACTIVITY); // startActivityForResult(intent, IMAGE_CAPTURE_ID); // } // } // }); // // // setup data for text field if in edit/view user profile mode // Bundle bundle = getIntent().getExtras(); // if (bundle != null) { // mode = EDIT_USER_PROFILE; // userInfo = (UserInfo) bundle.get(Global.USER_INFO); // // // fill user info to form // txtUsername.setText(userInfo.username); //// txtPassword.setText(userInfo.password); //// txtConfirm.setText(userInfo.password); // txtFirstName.setText(userInfo.first_name); // txtLastName.setText(userInfo.last_name); // txtEmail.setText(userInfo.email); // txtAddress.setText(userInfo.address); // txtPhoneNumber.setText(userInfo.phone); // txtBirthday.setText(Global.df.format(userInfo.birthday)); // // // some fields of user info must be uneditable // Utils.setEditableEditText(txtUsername, false); // Utils.setEditableEditText(txtFirstName, true); // txtBirthday.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // showDialog(DATE_DIALOG_ID); // } // }); // // lblOldPassword.setVisibility(View.VISIBLE); // txtOldPassword.setVisibility(View.VISIBLE); // lblPassword.setVisibility(View.VISIBLE); // txtPassword.setVisibility(View.VISIBLE); // lblConfirm.setVisibility(View.VISIBLE); // txtConfirm.setVisibility(View.VISIBLE); // }else{ // lblOldPassword.setVisibility(View.GONE); // txtOldPassword.setVisibility(View.GONE); //// lblPassword.setVisibility(View.GONE); //// txtPassword.setVisibility(View.GONE); //// lblConfirm.setVisibility(View.GONE); //// txtConfirm.setVisibility(View.GONE); // } // // /********************************** Listeners *******************************/ // // input value //// txtUsername.setFilters(Global.usernameInputFilters); //// txtFirstName.setFilters(Global.usernameInputFilters); //// txtLastName.setFilters(Global.usernameInputFilters); // // // buttons // Button btnRegister = (Button) findViewById(R.id.btnRegister); // if (mode != REGISTER_USER) { // btnRegister.setText(getString(R.string.lblUpdate)); // } // btnRegister.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // switch (mode) { // case REGISTER_USER: // registerNewUser(); // break; // // case EDIT_USER_PROFILE: // editUserProfile(); // break; // // } // } // }); // // Button btnCancel = (Button) findViewById(R.id.btnCancel); // btnCancel.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // finish(); // } // }); // // Button btnTagAddressOnMap = (Button) findViewById(R.id.btnTagAddressOnMap); // btnTagAddressOnMap.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // tagAddressOnMap(); // } // }); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // System.out.println("Result"); // switch (requestCode) { // case FILE_BROWSER_ID: // if (resultCode == Activity.RESULT_OK) { // if (data != null) { // File file = (File) data // .getSerializableExtra(Global.FILE_INTENT_ID); // if (file != null) { // try { // inputStreamAvatar = new FileInputStream(file); // fileName = file.getName(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // } // txtAvatar.setText(file.getName()); // } // // } // break; // // case IMAGE_CAPTURE_ID: // // Return array of byte // if (resultCode == RESULT_OK) { // if (data != null) { // byte[] arrBytes = data // .getByteArrayExtra(Global.BYTE_ARRAY_INTENT_ID); // if (arrBytes != null) { // inputStreamAvatar = new ByteArrayInputStream(arrBytes); // fileName = Global.dfTimeStamp.format(new Date()) // + ".jpg"; // txtAvatar.setText(fileName); // } // } // } // break; // // default: // break; // } // } // // /** // * // * @return Server Response // */ // private String doFileUpload() { // DataOutputStream dos; // HttpURLConnection conn = null; // dos = null; // DataInputStream inStream = null; // // String lineEnd = "\r\n"; // String twoHyphens = "--"; // String boundary = "*****"; // // int bytesRead, bytesAvailable, bufferSize; // // byte[] buffer; // int maxBufferSize = 1 * 1024 * 1024; // // try { // // ------------------ CLIENT REQUEST // // // open a URL connection to the Servlet // URL url = new URL(String.format(URLConstant.HOST_IMG, // userInfo.username)); // // // Open a HTTP connection to the URL // conn = (HttpURLConnection) url.openConnection(); // // // Allow Inputs // conn.setDoInput(true); // // // Allow Outputs // conn.setDoOutput(true); // // // Don't use a cached copy. // conn.setUseCaches(false); // // // Use a post method. // conn.setRequestMethod("POST"); // conn.setRequestProperty("Connection", "Keep-Alive"); // conn.setRequestProperty("Content-Type", // "multipart/form-data;boundary=" + boundary); // // dos = new DataOutputStream(conn.getOutputStream()); // dos.writeBytes(twoHyphens + boundary + lineEnd); // dos // .writeBytes("Content-Disposition:\"form-data\"; name=\"uploadedfile\";filename=\"" // + fileName + "\"" + lineEnd); // dos.writeBytes(lineEnd); // Log.e("MediaPlayer", "Headers are written"); // // // create a buffer of maximum size // bytesAvailable = inputStreamAvatar.available(); // bufferSize = Math.min(bytesAvailable, maxBufferSize); // buffer = new byte[bufferSize]; // // // read file and write it into form... // bytesRead = inputStreamAvatar.read(buffer, 0, bufferSize); // // while (bytesRead > 0) { // dos.write(buffer, 0, bufferSize); // bytesAvailable = inputStreamAvatar.available(); // bufferSize = Math.min(bytesAvailable, maxBufferSize); // bytesRead = inputStreamAvatar.read(buffer, 0, bufferSize); // } // // // send multipart form data necesssary after file data... // dos.writeBytes(lineEnd); // dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // // // close streams // Log.e(TAG, "File is written"); // inputStreamAvatar.close(); // dos.flush(); // // } catch (MalformedURLException ex) { // Log.e(TAG, "error: " + ex.getMessage(), ex); // } // // catch (IOException ioe) { // Log.e(TAG, "error: " + ioe.getMessage(), ioe); // } // // // ------------------ read the SERVER RESPONSE // try { // inStream = new DataInputStream(conn.getInputStream()); // String str; // StringBuilder strBuilder = new StringBuilder(); // // while ((str = inStream.readLine()) != null) { // strBuilder.append(str); // } // // Log.d(TAG, "Host Image response: " + strBuilder.toString()); // inStream.close(); // // return strBuilder.toString(); // } catch (IOException ioex) { // Log.e(TAG, "error: " + ioex.getMessage(), ioex); // } // // if (dos != null) // try { // dos.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // private void collectUserInfo() { // userInfo = new UserInfo(); // // update user info // userInfo.username = txtUsername.getText().toString(); // userInfo.oldPassword = txtOldPassword.getText().toString(); // // md5 is served in server // userInfo.password = txtPassword.getText().toString(); // userInfo.first_name = txtFirstName.getText().toString(); // userInfo.last_name = txtLastName.getText().toString(); // userInfo.email = txtEmail.getText().toString(); // userInfo.address = txtAddress.getText().toString(); // userInfo.phone = txtPhoneNumber.getText().toString(); // userInfo.birthday = new Date(mYear, mMonth, mDay); // userInfo.lat = lat; // userInfo.lng = lng; // } // // protected void registerNewUser() { // // if (StringUtils.isEmptyOrNull(err = getErrorMessage())) { // collectUserInfo(); // // if (StringUtils.isEmptyOrNull(userInfo.avatarLink) // && inputStreamAvatar != null) { // String response = doFileUpload(); // // Log.e("Upload", response); // String[] data = response.split(";"); // int errCode = -1; // try { // errCode = Integer.parseInt(data[0]); // } catch (Exception e) { // } // switch (errCode) { // case 0: // // Upload successfully // userInfo.avatarLink = data[1]; // break; // // case 1: // Toast.makeText(this, data[1], Toast.LENGTH_SHORT); // break; // // default: // DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // registerNewUser(); // } // }; // DialogInterface.OnClickListener cancelButtonListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // inputStreamAvatar = null; // fileName = null; // } // }; // // // Show an Alert with the ButtonListeners we created // AlertDialog ad = new AlertDialog.Builder(this).setTitle( // getString(R.string.notice)).setMessage( // getString(R.string.cant_upload_image_try_again)) // .setPositiveButton(getString(R.string.yes), // okButtonListener).setNegativeButton( // getString(R.string.no), cancelButtonListener) // .create(); // ad.show(); // break; // } // } // // // Log.d(TAG, Global.gsonDateWithoutHour.toJson(userInfo)); // RestClient.postData(URLConstant.REGISTER, Global.gsonDateWithoutHour // .toJson(userInfo), new JSONParser() { // // @Override // public void onFailure(String message) { // Log.e(TAG, message); // } // // @Override // public void onSuccess(JSONObject json) throws JSONException { // int errCode = json.getInt("errCode"); // String message = json.getString("message"); // switch (errCode) { // case Global.SUCCESS: // Toast.makeText(UserActivity.this, message, // Toast.LENGTH_SHORT).show(); // Intent intent = new Intent(UserActivity.this, // LoginActivity.class); // startActivity(intent); // // break; // // case Global.ERROR: // Toast.makeText(UserActivity.this, message, // Toast.LENGTH_SHORT).show(); // Global.isLogin = false; // // default: // Toast.makeText(UserActivity.this, // getString(R.string.err_register_message), // Toast.LENGTH_SHORT).show(); // Global.isLogin = false; // break; // } // } // }); // } // // protected void editUserProfile() { // String err = ""; // // if (StringUtils.isEmptyOrNull(err = getErrorMessage())) { // collectUserInfo(); // // Log.d(TAG, userInfo +""); // RestClient.postData(URLConstant.EDIT_PROFILE, Global.gsonDateWithoutHour.toJson(userInfo), new JSONParser() { // // @Override // public void onSuccess(JSONObject json) throws JSONException { // int errCode = Integer.parseInt(json // .get("errCode").toString()); // String message = json.get("message").toString(); // switch (errCode) { // case Global.SUCCESS: // Toast.makeText(UserActivity.this, message, // Toast.LENGTH_SHORT).show(); // break; // // default: // Toast.makeText(UserActivity.this, message, // Toast.LENGTH_SHORT).show(); // break; // } // } // // @Override // public void onFailure(String message) { // Toast.makeText(UserActivity.this, message, // Toast.LENGTH_SHORT).show(); // } // }); // // } else { // // Toast.makeText(UserActivity.this, err, Toast.LENGTH_SHORT).show(); // // } // } // // protected Dialog onCreateDialog(int id) { // switch (id) { // case DATE_DIALOG_ID: // if (mode == REGISTER_USER) { // Calendar cal = Calendar.getInstance(); // mDay = cal.get(Calendar.DAY_OF_MONTH); // mMonth = cal.get(Calendar.MONTH); // mYear = cal.get(Calendar.YEAR) - 18; // } else { // mDay = userInfo.birthday.getDate(); // mMonth = userInfo.birthday.getMonth(); // mYear = userInfo.birthday.getYear() + 1900; // } // // return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, // mDay); // } // // return null; // } // // @Override // protected void onPrepareDialog(int id, Dialog dialog) { // switch (id) { // case DATE_DIALOG_ID: // ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay); // break; // } // } // // protected void chooseBirthday() { // showDialog(DATE_DIALOG_ID); // } // // protected void tagAddressOnMap() { // GeoPoint point = null; // if (Global.isLogin) { // point = new GeoPoint((int) (Global.userInfo.lat * 1E6), // (int) (Global.userInfo.lng * 1E6)); // } else if (userInfo != null) { // point = new GeoPoint((int) (userInfo.lat * 1E6), // (int) (userInfo.lng * 1E6)); // } else { // String location = txtAddress.getText().toString(); // if (location == null || location.trim().equals("")) { // Toast.makeText(this, // getString(R.string.warn_must_enter_address), // Toast.LENGTH_SHORT).show(); // return; // } // point = MapService.locationToGeopoint(location); // } // Log.d(TAG, "user point = " + point); // // MapDialog.createLocationDialog(this, point, new UserLocationListener() { // // @Override // public void processUserLocation(GeoPoint point) { // if (mode == REGISTER_USER || mode == EDIT_USER_PROFILE) { // if (point != null) { // lat = point.getLatitudeE6(); // lng = point.getLongitudeE6(); // } // Log.d(TAG, "user location = " + point); // } // } // }).show(); // } // // @Override // protected boolean isRouteDisplayed() { // return false; // } // // private String getErrorMessage() { // String result = null; // // if (StringUtils.isEmptyOrNull(txtUsername.getText().toString()) // || !Pattern.matches(PATTERN_LONGER_6, txtUsername.getText() // .toString())) // result = getString(R.string.username_longer_6_chars); // else if (StringUtils.isEmptyOrNull(txtPassword.getText().toString()) // || !Pattern.matches(PATTERN_LONGER_6, txtPassword.getText() // .toString())) // result = getString(R.string.password_longer_6_chars); // else if (StringUtils.isEmptyOrNull(txtConfirm.getText().toString()) // || !txtPassword.getText().toString().equals( // txtConfirm.getText().toString())) // result = getString(R.string.password_not_match); // else if (StringUtils.isEmptyOrNull(txtFirstName.getText().toString()) // || !Pattern.matches(PATTERN_LONGER_6, txtFirstName.getText() // .toString())) // result = getString(R.string.first_name_longer_6_chars); // else if (StringUtils.isEmptyOrNull(txtEmail.getText().toString()) // || !Pattern.matches(PATTERN_EMAIL, txtEmail.getText() // .toString())) // result = getString(R.string.email_invalid); // // return result; // } //}
package com.exmertec.elvis.scal.controller; public class SimpleRequestControllerTest { }
package example.com.twitterdemo.Adapter; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; import example.com.twitterdemo.Entity.HomeEntity; import example.com.twitterdemo.R; /** * Created by admin on 1/23/2018. */ public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.CategoryViewHolder> { private Activity mActivity; ArrayList<HomeEntity> list; public HomeAdapter(Activity activity, ArrayList<HomeEntity> homeentity) { this.mActivity=activity; list=homeentity; } @Override public HomeAdapter.CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.category_adapter_xml,parent,false); return new HomeAdapter.CategoryViewHolder(view); } @Override public void onBindViewHolder(HomeAdapter.CategoryViewHolder holder, int position) { holder.textView.setText(list.get(position).getTitle()); holder.textView1.setText(list.get(position).getMessage()); holder.imageView.setImageResource(list.get(position).getUser()); holder.imageView1.setImageResource(list.get(position).getImage()); } @Override public int getItemCount() { return list.size(); } public class CategoryViewHolder extends RecyclerView.ViewHolder { CircleImageView imageView; AppCompatTextView textView; AppCompatTextView textView1; AppCompatImageView imageView1; public CategoryViewHolder(View itemView) { super(itemView); imageView=itemView.findViewById(R.id.imguser); textView=itemView.findViewById(R.id.tvUser); imageView1=itemView.findViewById(R.id.image); textView1=itemView.findViewById(R.id.tvMessage); } } }
package com.keepmoving.to.coordinatetest.model; /** * Created by caihanyuan on 2017/11/15. * <p> * 省市区实体类的基类 */ public class BaseBean { protected String name; protected String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLastLevelId() { return ""; } }