text stringlengths 10 2.72M |
|---|
package com.esum.framework.security.smime.encrypt;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.bouncycastle.mail.smime.SMIMEException;
abstract public class SMIMEEncrypt {
private static SMIMEEncrypt mSMIMEEncrypt = null;
public static synchronized SMIMEEncrypt getInstance() {
if (mSMIMEEncrypt == null) {
mSMIMEEncrypt = new SMIMEEncryptWithBC();
}
return mSMIMEEncrypt;
}
abstract public MimeBodyPart decrypt(String traceId, MimeBodyPart part,
X509Certificate cert, PrivateKey key) throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
abstract public MimeBodyPart encrypt(MimeBodyPart data,
X509Certificate receiver, String algorithm)
throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
abstract public MimeBodyPart encrypt(MimeMessage data, X509Certificate receiver,
String algorithm) throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
abstract public MimeMultipart sign(MimeBodyPart data,
X509Certificate senderCert, PrivateKey senderKey, String digest)
throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
abstract public MimeBodyPart verifySignature(String traceID,
X509Certificate cert, MimeBodyPart part)
throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
abstract public MimeBodyPart verifySignature(String traceID, X509Certificate cert, MimeMultipart part)
throws SMIMEEncryptException, GeneralSecurityException, MessagingException, SMIMEException;
} |
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.sql.rowset.serial.SerialBlob;
public class PostAssignmentControl {
private DataManager dataManager;
public PostAssignmentControl(DataManager dm) {
this.dataManager = dm;
}
public boolean postAssignment(String courseNumber, String assName, File pdfFile, java.util.Date dueDate) {
boolean success = true;
Blob blobFile = null;
try {
byte[] pdfData = new byte[(int) pdfFile.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(pdfFile));
dis.readFully(pdfData);
dis.close();
blobFile = new SerialBlob(pdfData);
java.sql.Date sqlDate = new java.sql.Date(dueDate.getTime());
dataManager.uploadAssignment(courseNumber, assName, blobFile, sqlDate);
} catch (FileNotFoundException e) {
success = false;
} catch (IOException e) {
success = false;
} catch (SQLException e) {
success = false;
}
return success;
}
public ArrayList<String> getCourseNames(){
return dataManager.requestCourseNames();
}
}
|
package br.com.salon.carine.lima.functional.cliente;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class ListaClientePage {
private WebDriver driver;
public ListaClientePage(WebDriver driver) {
this.driver = driver;
}
public void acessarListaCliente() {
driver.navigate().refresh();
driver.findElement(By.xpath("//*[@id=\"clientes-dropdown\"]")).click();
driver.findElement(By.xpath("//*[@id=\"listar-cliente\"]")).click();
}
}
|
package com.puneragroups.punerainvestmart;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.jetbrains.annotations.NotNull;
import java.util.Calendar;
public class MainActivity extends BaseActivity {
public static final String PREFS_NAME = "MyPrefsFile";
private static final String SELECTED_ITEM = "arg_selected_item";
int mSelectedItem;
String user_id;
FirebaseDatabase database;
DatabaseReference mUserDatabase, mFeedDatabase;
ProgressBar progressbar;
CardView returns, plans;
ImageView img_returns;
Button btn_returns;
private RecyclerView recyclerView, stock;
int mMonth, mYear, dMonth, dYear;
private LinearLayoutManager linearLayoutManager, linearLayoutManager1;
private myadapter adapter;
private myadapter1 adapter1;
ImageView img_graph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressbar = findViewById(R.id.progressbar);
returns = findViewById(R.id.returns);
img_returns = findViewById(R.id.img_returns);
plans = findViewById(R.id.plans);
recyclerView = findViewById(R.id.recycler_view);
stock = findViewById(R.id.stock);
btn_returns = findViewById(R.id.btn_returns);
img_graph = findViewById(R.id.img_graph);
progressbar.setVisibility(View.VISIBLE);
SharedPreferences shared = getSharedPreferences("myAppPrefs", MODE_PRIVATE);
user_id = (shared.getString("user_id", ""));
database = FirebaseDatabase.getInstance();
mUserDatabase = database.getReference("Users");
plans.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent nextActivity = new Intent(MainActivity.this, PlanAndRevenue.class);
nextActivity.putExtra("user_id", user_id);
startActivity(nextActivity);
}
});
Glide.with(img_returns.getContext())
.load(R.drawable.return1)
.placeholder(R.drawable.return1)
.into(img_returns);
mFeedDatabase = FirebaseDatabase.getInstance().getReference().child("Feed");
linearLayoutManager1 = new LinearLayoutManager(MainActivity.this);
stock.setLayoutManager(linearLayoutManager1);
stock.setNestedScrollingEnabled(false);
FirebaseRecyclerOptions<MarketDataSetGet> options1 =
new FirebaseRecyclerOptions.Builder<MarketDataSetGet>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Market_indices"), MarketDataSetGet.class)
.build();
adapter1 = new myadapter1(options1);
adapter1.startListening();
stock.setAdapter(adapter1);
mFeedDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
if (snapshot.hasChildren()) {
linearLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setNestedScrollingEnabled(false);
FirebaseRecyclerOptions<ListSetGet1> options =
new FirebaseRecyclerOptions.Builder<ListSetGet1>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Feed"), ListSetGet1.class)
.build();
adapter = new myadapter(options);
adapter.startListening();
recyclerView.setAdapter(adapter);
} else {
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
}
});
returns.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Dialog,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
//pick_expire_date.setText((monthOfYear + 1)+"/"+year);
mMonth = monthOfYear + 1;
mYear = year;
Intent intent = new Intent(MainActivity.this, IntrestReturnsActivity.class);
intent.putExtra("month", mMonth);
intent.putExtra("year", mYear);
intent.putExtra("user_id", user_id);
startActivity(intent);
}
},
cyear, cmonth, cday);
datePickerDialog.setTitle("View Interest return");
datePickerDialog.setMessage("Select Month And Year");
datePickerDialog.getDatePicker().findViewById(getResources().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
datePickerDialog.show();
}
});
btn_returns.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Dialog,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
//pick_expire_date.setText((monthOfYear + 1)+"/"+year);
mMonth = monthOfYear + 1;
mYear = year;
Intent intent = new Intent(MainActivity.this, IntrestReturnsActivity.class);
intent.putExtra("month", mMonth);
intent.putExtra("year", mYear);
intent.putExtra("user_id", user_id);
startActivity(intent);
}
},
cyear, cmonth, cday);
datePickerDialog.setTitle("View Interest return");
datePickerDialog.setMessage("Select Month And Year");
datePickerDialog.getDatePicker().findViewById(getResources().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
datePickerDialog.show();
}
});
// img = findViewById(R.id.graphimg);
//img.setImageResource(R.drawable.graph);
//img.setMaxZoom(4f);
//setContentView(img);
FirebaseDatabase.getInstance().getReference().child("Graph").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Glide.with(getApplicationContext()).
load(snapshot.child("img").getValue().toString())
.placeholder(R.drawable.graph)
.into(img_graph);
img_graph.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,fullScreenImg.class);
intent.putExtra("url",snapshot.child("img").getValue().toString());
startActivity(intent);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
progressbar.setVisibility(View.GONE);
}
public class myadapter extends FirebaseRecyclerAdapter<ListSetGet1, myadapter.myviewholder> {
public myadapter(@NonNull FirebaseRecyclerOptions<ListSetGet1> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull myadapter.myviewholder holder, final int position, @NonNull ListSetGet1 model) {
final String Id = getRef(position).getKey();
Glide.with(getApplicationContext()).
load(model.getImg())
.placeholder(R.drawable.loading)
.into(holder.img);
holder.des.setText(model.getDes());
}
@NonNull
@Override
public myadapter.myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feeds_list, parent, false);
return new myadapter.myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder {
TextView des;
ImageView img;
public myviewholder(@NonNull View itemView) {
super(itemView);
des = (TextView) itemView.findViewById(R.id.des);
img = (ImageView) itemView.findViewById(R.id.img);
}
}
}
public class myadapter1 extends FirebaseRecyclerAdapter<MarketDataSetGet, myadapter1.myviewholder> {
public myadapter1(@NonNull FirebaseRecyclerOptions<MarketDataSetGet> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull myadapter1.myviewholder holder, final int position, @NonNull MarketDataSetGet model) {
final String Id = getRef(position).getKey();
if (model.getState().equals("up")) {
holder.fluctuation.setText(String.valueOf(model.getFluc()));
} else {
holder.fluctuation.setText(String.valueOf(model.getFluc()));
holder.fluctuation.setTextColor(Color.parseColor("#ff0000"));
holder.fluctuation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_baseline_arrow_downward_24, 0, 0, 0);
}
holder.name.setText(model.getName().toString());
holder.value.setText(String.valueOf(model.getValue()));
}
@NonNull
@Override
public myadapter1.myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.market_list, parent, false);
return new myadapter1.myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder {
TextView name, value, fluctuation;
public myviewholder(@NonNull View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
value = (TextView) itemView.findViewById(R.id.value);
fluctuation = (TextView) itemView.findViewById(R.id.fluctuation);
}
}
}
@Override
int getContentViewId() {
return R.layout.activity_main;
}
@Override
int getNavigationMenuItemId() {
return R.id.homee;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
finishAffinity();
}
} |
package com.sinoway.sinowayCrawer.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.sinoway.sinowayCrawer.entitys.CreditNoOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.CreditOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.HousingNoOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.HousingOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.LoanNoOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.LoanOverdueAccountDetail;
import com.sinoway.sinowayCrawer.entitys.institutionQueryDetails;
import com.sinoway.sinowayCrawer.entitys.personalQueryDetails;
import com.sinoway.sinowayCrawer.entitys.reportAppt;
import com.sinoway.sinowayCrawer.service.ApptService;
import com.sinoway.sinowayCrawer.service.UpDownService;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateNotFoundException;
@Controller
public class SearchController {
/*
* 得到cardid,查出报告list,展示到result.jsp
*/
@Autowired
private ApptService apptservice;
@Autowired
private UpDownService ud;
// @RequestMapping(value="/Excel.action")
// public void excel(HttpServletResponse res){
// ud.download(res, "/jiacu.xml");
// }
@RequestMapping(value="/search.action")
@ResponseBody
public Map<String, Object> search(HttpServletRequest req,HttpServletResponse response) throws ServletException, IOException{
String cardId=req.getParameter("cardid");
System.out.println("search.action");
System.out.println(req.getParameter("cardid"));
//查询report-appt,返回list结果集合;
List<reportAppt> list=apptservice.getList(cardId);
System.out.println(list.size());
// System.out.println(list.get(0).getRequestTime());
// req.setAttribute("list", list);
// req.getRequestDispatcher("/result.jsp").forward(req, response);
System.out.println(req.getServletContext().getRealPath("/"));
Map<String, Object> map1= new HashMap<>();
map1.put("result", list);
System.out.println(map1.toString());
// System.out.println(list.get(0).getRequestTime());
// req.setAttribute("list", list);
// req.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(req, response);
//System.out.println(req.getServletContext().getRealPath("/"));
return map1;
}
//得到模板需要的数据
@RequestMapping(value="/getdata.action")
public void getdata(HttpServletRequest req,HttpServletResponse response){
System.out.println("getdata.action------");
System.out.println("得到reportID"+req.getParameter("rid"));
//得到reportID
String reportId=req.getParameter("rid");
List<reportAppt> list=apptservice.selectallbyReportId(reportId);
// System.out.println("wotddddded" + idnumber);
System.out.println("已经找到此行数据,名字为:" + list.get(0).getQueriedName());
String name=list.get(0).getQueriedName();
String time1=list.get(0).getRequestTime();
String idnumber=list.get(0).getQueriedNumber();
List<HousingNoOverdueAccountDetail> listHN=apptservice.gethousingNo(reportId);
List<HousingOverdueAccountDetail> listH =apptservice.gethousing(reportId);
List<LoanOverdueAccountDetail> listL =apptservice.getloan(reportId);
List<LoanNoOverdueAccountDetail> listLN =apptservice.getloanNo(reportId);
List<CreditNoOverdueAccountDetail> listCN =apptservice.getcreditNo(reportId);
List<CreditOverdueAccountDetail> listC =apptservice.getcredit(reportId);
List<personalQueryDetails> listP =apptservice.getpersonQ(reportId);
List<institutionQueryDetails> listI =apptservice.getinstituteQ(reportId);
// System.out.println(listHN.get(0).getDetail());
//generate datamap
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("reportId", reportId);
dataMap.put("name", name);
System.out.println("name = " + name);
dataMap.put("idnumber", idnumber);
dataMap.put("time1", time1);
dataMap.put("userList1",listHN);
dataMap.put("userList2",listH);
dataMap.put("userList3",listL);
dataMap.put("userList4",listLN);
dataMap.put("userList5",listCN);
dataMap.put("userList6",listC);
dataMap.put("userList7",listP);
dataMap.put("userList8",listI);
//调processT
ProcessT2 p= new ProcessT2();
try {
p.init();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.process(dataMap,req);
} catch (TemplateNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedTemplateNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ud.download(response, "/demo1.xml");
}
}
|
package com.cdkj.util;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* PackageName:com.cdkj.common.util<br/>
* Descript:XML转换类 <br/>
* Date: 2016-04-19 <br/>
* User: Bovine
* version 1.0
*/
public class XmlConverUtil {
protected static Logger logger = LoggerFactory.getLogger(XmlConverUtil.class);
/**
* map to xml xml <node><key label="key1">value1</key><key
* label="key2">value2</key>......</node>
*
* @param map
* @return
*/
public static String maptoXml(Map map) {
Document document = DocumentHelper.createDocument();
Element nodeElement = document.addElement("node");
for (Object obj : map.keySet()) {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(obj));
keyElement.setText(String.valueOf(map.get(obj)));
}
return doc2String(document);
}
/**
* list to xml xml <nodes><node><key label="key1">value1</key><key
* label="key2">value2</key>......</node><node><key
* label="key1">value1</key><key
* label="key2">value2</key>......</node></nodes>
*
* @param list
* @return
*/
public static String listtoXml(List list) throws Exception {
Document document = DocumentHelper.createDocument();
Element nodesElement = document.addElement("nodes");
int i = 0;
for (Object o : list) {
Element nodeElement = nodesElement.addElement("node");
if (o instanceof Map) {
for (Object obj : ((Map) o).keySet()) {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(obj));
keyElement.setText(String.valueOf(((Map) o).get(obj)));
}
} else {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(i));
keyElement.setText(String.valueOf(o));
}
i++;
}
return doc2String(document);
}
/**
* json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver
* <o><node class="object"><key class="object"
* label="key1">value1</key></node></o>
*
* @param json
* @return
*/
public static String jsontoXml(String json) {
try {
XMLSerializer serializer = new XMLSerializer();
JSON jsonObject = JSONSerializer.toJSON(json);
return serializer.write(jsonObject);
} catch (Exception e) {
logger.error("run error", e);
}
return null;
}
/**
* xml to map xml <node><key label="key1">value1</key><key
* label="key2">value2</key>......</node>
*
* @param xml
* @return
*/
public static Map xmltoMap(String xml) {
Map<String, Object> map = new HashMap<>();
if (StringUtil.isEmpty(xml)) {
return map;
}
try {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
Element e = (Element) iterator.next();
//System.out.println(e.getName());
List list = e.elements();
if (list.size() > 0) {
map.put(e.getName(), Dom2Map(e));
} else
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
logger.error("xmltoMap.run error", e);
}
return map;
}
/**
* xml to map xml <node><key label="key1">value1</key><key
* label="key2">value2</key>......</node>
*
* @param xml
* @return
*/
public static Map xmltoLinkMap(String xml) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
if (StringUtil.isEmpty(xml)) {
return map;
}
try {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
Element e = (Element) iterator.next();
//System.out.println(e.getName());
List list = e.elements();
if (list.size() > 0) {
map.put(e.getName(), Dom2Map(e));
} else
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
logger.error("xmltoMap.run error", e);
}
return map;
}
public static Map Dom2Map(Element e) {
Map map = new HashMap();
List list = e.elements();
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if (iter.elements().size() > 0) {
Map m = Dom2Map(iter);
if (map.get(iter.getName()) != null) {
Object obj = map.get(iter.getName());
if (!obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if (obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
} else
map.put(iter.getName(), m);
} else {
if (map.get(iter.getName()) != null) {
Object obj = map.get(iter.getName());
if (!obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if (obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
} else
map.put(iter.getName(), iter.getText());
}
}
} else
map.put(e.getName(), e.getText());
return map;
}
/**
* xml to list xml <nodes><node><key label="key1">value1</key><key
* label="key2">value2</key>......</node><node><key
* label="key1">value1</key><key
* label="key2">value2</key>......</node></nodes>
*
* @param xml
* @return
*/
public static List xmltoList(String xml) {
try {
List<Map> list = new ArrayList<Map>();
Document document = DocumentHelper.parseText(xml);
Element nodesElement = document.getRootElement();
List nodes = nodesElement.elements();
for (Iterator its = nodes.iterator(); its.hasNext(); ) {
Element nodeElement = (Element) its.next();
Map map = xmltoMap(nodeElement.asXML());
list.add(map);
map = null;
}
nodes = null;
nodesElement = null;
document = null;
return list;
} catch (Exception e) {
logger.error("run error", e);
}
return null;
}
/**
* xml to json <node><key label="key1">value1</key></node> 转化为
* {"key":{"@label":"key1","#text":"value1"}}
*
* @param xml
* @return
*/
public static String xmltoJson(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer();
return xmlSerializer.read(xml).toString();
}
/**
* @param document
* @return
*/
public static String doc2String(Document document) {
String s = "";
try {
// 使用输出流来进行转化
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用UTF-8编码
OutputFormat format = new OutputFormat(" ", true, "UTF-8");
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
s = out.toString("UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return s;
}
/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
*
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if (null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
org.jdom.Document doc = builder.build(in);
org.jdom.Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while (it.hasNext()) {
org.jdom.Element e = (org.jdom.Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
return m;
}
/**
* 获取子结点的xml
*
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
org.jdom.Element e = (org.jdom.Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
/**
* @param parameters 请求参数
* @return
* @Description:将请求参数转换为xml格式的string
*/
public static String getRequestXml(SortedMap<String, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
String k = entry.getKey();
Object v = entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
}
|
package com.company.exercise;
import java.util.ArrayList;
/**
* Created by judit on 14.05.17.
*/
public class CodecoolClass {
private String name;
private ArrayList<Team> teamList;
public CodecoolClass(String name) {
this.name = name;
}
public void addToteamList(Team team) {
teamList.add(team);
}
public String getName() {
return name;
}
public void setId(String name) {
this.name = name;
}
public ArrayList<Team> getTeamList() {
return teamList;
}
public void setTeamList(ArrayList<Team> teamList) {
this.teamList = teamList;
}
}
|
package exemplos.aula13;
public class TesteMetodosStringBuilder{
public static void main(String[] args){
//capacaity, ensureCapacity e length
StringBuilder builder = new StringBuilder("Test builder");
System.out.println(builder.length());
System.out.println(builder.capacity());
builder.ensureCapacity(200);
System.out.println(builder.capacity());
//charAt, setCharAt, getChars, reverse
System.out.println(builder.charAt(0));
builder.setCharAt(2, 'z');
System.out.println(builder);
char [] caracteres = new char[5];
builder.getChars(0, 5, caracteres, 0);
for(char c : caracteres){
System.out.print(c);
}
System.out.println();
builder.reverse();
System.out.println(builder);
builder.reverse();
//append, insert, delete, deleteCharAt
Object o = " cde ";
Integer x = 10;
double z = 2.5;
builder.append(" abc").append(o).append(x).append(" ").append(z);
System.out.println(builder);
builder.insert(10, " efg ").insert(0,caracteres,0,5);
System.out.println(builder);
builder.delete(0, 10);
System.out.println(builder);
builder.deleteCharAt(0);
System.out.println(builder);
}
}
|
package com.loneless.controller;
public class ControllerException extends Exception{
private String exception="";
public ControllerException(String exception){
this.exception+=exception;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
}
|
package es.codeurjc.gameweb.rest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.hibernate.engine.jdbc.BlobProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import es.codeurjc.gameweb.models.*;
import es.codeurjc.gameweb.repositories.PostRepository;
import es.codeurjc.gameweb.services.*;
import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.annotation.JsonView;
@RestController
@RequestMapping("/api/posts")
public class PostsControllerREST {
private static final String POSTS_FOLDER = "posts";
@Autowired
private PostService pService;
@Autowired
private GameService gamePostService;
@Autowired
private PostRepository postRepo;
@Autowired
private ImageService imageService;
interface PostDetail extends Post.postBasic,Post.games,Game.gameBasico{}
@JsonView(PostDetail.class)
@GetMapping("/")
public Collection<Post> getPosts(){
return pService.findAll();
}
@JsonView(PostDetail.class)
@GetMapping("/games")
public Collection<Post> getPostsOfGame(@RequestParam int gameID){
Game myGame=gamePostService.findById(gameID).get();
return pService.findPostOfGame(myGame);
}
@JsonView(PostDetail.class)
@GetMapping("/types")
public Collection<Post> getPostsOfType(@RequestParam String theType,@RequestParam int gameID,@RequestParam int numPage){
Game myGame=gamePostService.findById(gameID).get();
PostType type=null;
switch(theType){
case "News":
type=PostType.News;
break;
case "Updates":
type=PostType.Updates;
break;
case "Guides":
type=PostType.Guides;
break;
}
ArrayList<Post> aux=new ArrayList<Post>();
List<Post> thePosts=pService.findPostOfGamePage(myGame,PageRequest.of(numPage, 4));
for(Post p : thePosts){
aux.add(p);
}
return pService.findPostOfType(aux,type);
}
@JsonView(PostDetail.class)
@GetMapping("/{id}")
public ResponseEntity<Post> getIndividualPost(@PathVariable long id){
Post post=pService.findById(id).get();
if(post!=null){
return ResponseEntity.ok(post);
}
else{
return ResponseEntity.notFound().build();
}
}
@PostMapping("/")
public ResponseEntity<Post> createPost(@RequestBody Post post){
Game game=gamePostService.findById(post.getFromGameID()).get();
if(game!=null){
post.setFromGame(game);
pService.save(post);
URI location=fromCurrentRequest().path("/{id}").buildAndExpand(post.getId()).toUri();
String imgPath="https://localhost:8443/api/posts/"+post.getId()+"/images";
post.setImagePath(imgPath);
return ResponseEntity.created(location).body(post);
}
else{
return ResponseEntity.notFound().build();
}
}
@PutMapping("/{id}")
public ResponseEntity<Post> editPost(@PathVariable long id, @RequestBody Post newPost) {
Post p = pService.findById(id).get();
if (p != null) {
Game g=gamePostService.findById(p.getFromGameID()).get();
newPost.setFromGameID(p.getFromGameID());
newPost.setFromGame(g);
newPost.setId(id);
pService.save(newPost);
return ResponseEntity.ok(p);
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Post> deletePost(@PathVariable long id){
Post post=pService.findById(id).get();
if(post!=null){
pService.deleteById(id);
return ResponseEntity.ok(post);
}
else{
return ResponseEntity.notFound().build();
}
}
@PostMapping("/{id}/images")
public ResponseEntity<Object> uploadImage(@PathVariable long id, @RequestParam MultipartFile imageFile) throws IOException, SQLException {
Post post=pService.findById(id).get();
if(post!=null){
URI location = fromCurrentRequest().build().toUri();
post.setImagePath(location.toString());
post.setImageFile(BlobProxy.generateProxy(imageFile.getInputStream(), imageFile.getSize()));
pService.save(post);
//imageService.saveImage(POSTS_FOLDER, game.getId(), imageFile);
return ResponseEntity.created(location).build();
}
else{
return ResponseEntity.notFound().build();
}
}
@GetMapping("/{id}/images")
public ResponseEntity<Object> downloadImage(@PathVariable long id) throws MalformedURLException, SQLException {
Post post=pService.findById(id).get();
if(post!=null){
Resource file=new InputStreamResource(post.getImageFile().getBinaryStream());
return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, "image/jpeg").contentLength(post.getImageFile().length()).body(file);
}
else{
return ResponseEntity.notFound().build();
}
}
} |
package cc.xidian.GeoHash;
/**
* Created by hadoop on 2016/9/10.
*/
public class RectanglePrefix {
public long prefix;//前缀码
public int length;//前缀码的位数,该位数为前缀码的二进制位数
public RectanglePrefix(){
this.prefix = 0;
this.length = 0;
}
public RectanglePrefix(long prefix,int length){
this.prefix = prefix;
this.length = length;
}
/**
* 函数说明:前缀码最低位补1操作,得到新的子前缀码
* @return 得到新的子前缀码
*/
public RectanglePrefix attachOne() {
long bit = 0x8000000000000000L >>> length;//>>>为Java中的无符号位移,高位补0
return new RectanglePrefix(prefix | bit, length + 1);
}
/**
* 函数说明:前缀码最低位补0操作,得到新的子前缀码
* @return 新的子前缀码
*/
public RectanglePrefix attachZero(){
return new RectanglePrefix(prefix,length+1);
}
public String toString(){
return this.prefix+"#"+this.length;
}
}
|
package net.edzard.kinetic;
/**
* Markup interface for all fill styles
* @author Ed
*/
public interface FillStyle {
// Empty
}
|
package cn.jpush.impl.crash;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.jpush.Record;
import cn.jpush.kafka.Scheme;
public class CrashLogScheme implements Scheme {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(CrashLogScheme.class);
protected DateFormat df = new SimpleDateFormat("yyyyMMddHH");
@Override
public Record deserialize(byte[] ser) {
long current = System.currentTimeMillis();
String itime = df.format(new Date(current));
if(null == ser) {
LOG.error("ser is null.");
return new Record(itime, null);
}
try {
String message = new String(ser);
Record record = new Record(df.format(new Date(current)), message);
return record;
} catch (Exception e) {
LOG.error("processMessage error", e);
return new Record(itime, null);
}
}
}
|
package DAO;
public class Venda {
private int notaFiscal;
private String dataVenda;
private Cliente cliente;
private Funcionario vendedor;
public int getNotaFiscal() {
return notaFiscal;
}
public void setNotaFiscal(int id) {
this.notaFiscal = id;
}
public String getDataVenda() {
return dataVenda;
}
public void setDataVenda(String dataVenda) {
this.dataVenda = dataVenda;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Funcionario getVendedor() {
return vendedor;
}
public void setVendedor(Funcionario vendedor) {
this.vendedor = vendedor;
}
private AbstractDAO<Venda> getDAO(){
return new VendaDAO();
}
public boolean salvar() {
boolean salvou;
salvou = this.getDAO().adicionar(this);
return salvou;
}
public boolean atualizar() {
boolean atualizou;
atualizou = this.getDAO().atualizar(this);
return atualizou;
}
public boolean deletar(int id) {
boolean deletar;
deletar = this.getDAO().remover(id);
return deletar;
}
private Venda encontrar(int id) {
Venda venda= null;
venda = this.getDAO().encontrarPorId(id);
return venda;
}
}
|
package com.github.fierioziy.particlenativeapi.core.mocks.nms.common;
public interface Packet {}
|
package Reverse_array;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Reverse_array {
public static void main(String[] args) {
String[]str= {"1","2"};
Arrays.sort(str,Collections.reverseOrder());
System.out.println(Arrays.toString(str));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server.utils;
import client.remote.ClientRemote;
import java.util.HashMap;
/**
*
* @author luisburgos
*/
public class ClientsHandler {
public HashMap<String, ClientRemote> clientsMap;
public ClientsHandler(){
clientsMap = new HashMap();
}
public void notifyAll(int eventID, int seatIndex) {
}
public void register(String newClientKey, ClientRemote client) {
clientsMap.put(newClientKey, client);
}
public void unregister(String clientKey, ClientRemote client) {
clientsMap.remove(clientKey, client);
}
public ClientRemote getClient(String key){
return clientsMap.get(key);
}
}
|
package br.assembleia.dao.impl;
import br.assembleia.dao.DespesaDAO;
import br.assembleia.entidades.Despesa;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
@Repository
public class DespesaDAOImpl implements DespesaDAO {
@PersistenceContext
private EntityManager entityManager;
@Override
public Despesa getById(Long id) {
return entityManager.find(Despesa.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List<Despesa> listarTodos() {
return entityManager.createQuery("FROM " + Despesa.class.getName())
.getResultList();
}
@Override
public void salvar(Despesa despesa) {
entityManager.merge(despesa);
entityManager.flush();
}
@Override
public void editar(Despesa despesa) {
entityManager.merge(despesa);
entityManager.flush();
}
@Override
public void deletar(Despesa despesa) {
despesa = getById(despesa.getId());
entityManager.remove(despesa);
entityManager.flush();
}
@Override
public void deletarId(final Long id) {
Despesa despesa = getById(id);
entityManager.remove(despesa);
entityManager.flush();
}
@Override
public BigDecimal valorDespesaPeriodo(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select SUM(r.valor) from Despesa r ");
sql.append("Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public List<Despesa> listarDespesasMesAno(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select r from Despesa r ");
sql.append(" Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
List<Despesa> result = q.getResultList();
return result;
}
@Override
public BigDecimal listarDespesasPagas() {
StringBuilder sql = new StringBuilder();
sql.append("Select sum(d.valor) from Despesa d ");
sql.append("where d.pago = true ");
Query q = entityManager.createQuery(sql.toString());
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public List<Despesa> despesasPagarVisaoGeral(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select r from Despesa r ");
sql.append(" Where extract(MONTH FROM r.data) = ? "
+ "and extract(YEAR FROM r.data) = ? AND r.pago = false ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
List<Despesa> result = q.getResultList();
return result;
}
@Override
public BigDecimal buscarDespesaGrafico(Integer mes, Integer ano) {
StringBuilder sql = new StringBuilder();
sql.append("Select SUM(r.valor) from Despesa r ");
sql.append("Where extract(MONTH FROM r.data) = ? and extract(YEAR FROM r.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, mes);
q.setParameter(2, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
@Override
public BigDecimal listarDespesasCategoriaMesAno(Integer mes, Integer ano, Long id) {
StringBuilder sql = new StringBuilder();
sql.append("Select sum(d.valor) from Despesa d ");
sql.append("Where d.categoria.id = ? and extract(MONTH FROM d.data) = ? and extract(YEAR FROM d.data) = ? ");
Query q = entityManager.createQuery(sql.toString());
q.setParameter(1, id);
q.setParameter(2, mes);
q.setParameter(3, ano);
BigDecimal result = (BigDecimal) q.getSingleResult();
return result;
}
}
|
package com.zeke.FirstAngularProject.service;
import java.util.List;
import java.util.Optional;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zeke.FirstAngularProject.exception.UserNotFoundException;
import com.zeke.FirstAngularProject.model.Employee;
@RestController
@RequestMapping("/employee")
public class EmployeeResource {
private final EmployeeService employeeService;
@Autowired
public EmployeeResource(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping("/list")
public List<Employee> getAllEmployees(){
return employeeService.findAllEmployees();
}
@GetMapping("/list/{id}")
public Employee findEmployee(@PathVariable("id") Long id) throws UserNotFoundException{
Employee employee = employeeService.findEmployeeById(id);
return employee;
}
@PostMapping("/add")
public Employee addEmployee(@RequestBody Employee employee) {
Employee employee2 = employeeService.addEmployee(employee);
return employee2;
}
@PutMapping("/update")
public Employee updateEmployee(@RequestBody Employee employee) {
Employee employee2 = employeeService.addEmployee(employee);
return employee2;
}
@DeleteMapping("/delete/{id}")
public void deleteEmployee(@PathVariable("id") Long id) {
employeeService.deleteEmployee(id);
}
}
|
package com.shkhan.jobnpxs;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class SupportActivity extends AppCompatActivity {
private AdView madView;
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
setTitle("Support");
madView=findViewById(R.id.adView);
//ads start
MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713"); // App id//initialize mobile ad
mInterstitialAd= new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");//interstitial
AdRequest adRequest = new AdRequest.Builder().build();//ad request
madView.loadAd(adRequest);//load banner ads
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() { //interestitial ad listener
@Override
public void onAdClosed() {
// Load the next interstitial.
}
@Override
public void onAdLoaded() {
mInterstitialAd.show();
}
public void onAdOpened() {
// Code to be executed when the ad is displayed.
Toast.makeText(SupportActivity.this, "Don't Click !!", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
Toast.makeText(SupportActivity.this, "Wrong Task !!", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
});
//ads end
}
}
|
package com.hotel.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.hotel.model.HPackage;
import com.hotel.model.*;
public class PackageDAO {
public static Connection con;
public static Statement st;
public static ResultSet rs;
public static HPackage pk;
public static ArrayList<HPackage> getPackages() {
try {
String query = "SELECT id, name, mprice, nprice, persons, description, features, img FROM Packages";
ArrayList<HPackage> packages = new ArrayList<HPackage>();
con = SetConnection.setConnection();
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()) {
HPackage pk = new HPackage();
int id = Integer.parseInt(rs.getString("id"));
String name = rs.getString("name");
double mPrice = Double.valueOf(rs.getString("mprice"));
double nPrice = Double.valueOf(rs.getString("nprice"));
int persons = Integer.parseInt(rs.getString("persons"));
String description = rs.getString("description");
String features = rs.getString("features");
String img = rs.getString("img");
pk.setPackageId(id);
pk.setPackageName(name);
pk.setDescription(description);
pk.setFeatures(features);
pk.setMonthPrice(mPrice);
pk.setNightPrice(nPrice);
pk.setPersons(persons);
pk.setImg(img);
packages.add(pk);
}
return packages;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package work.binder.ui.job;
import java.util.Iterator;
import java.util.List;
import work.binder.ui.Package;
import work.binder.ui.LayoutReloadComponent;
import work.binder.ui.PackageCommands;
import work.binder.ui.PackageData;
import work.binder.ui.UserContext;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Label;
public class PackageSendingProcessor extends LayoutReloadComponent implements
ClickListener {
private static final long serialVersionUID = 7839304209716296708L;
private static final String SPACE = " ";
private static final String COMMA = ",";
private PackagesSelectionForNewJob _packagesSelectionForNewJob;
private IPsSelectionForNewJob _iPsSelectionForNewJob;
private PackageCommands _commandsForPackages;
public PackageSendingProcessor(
PackagesSelectionForNewJob selectionJarsForNewJob,
IPsSelectionForNewJob iPsSelectionForNewJob,
PackageCommands commandsForPackages) {
setPackagesSelectionForNewJob(selectionJarsForNewJob);
setiPsSelectionForNewJob(iPsSelectionForNewJob);
setCommandsForPackages(commandsForPackages);
final Button saveButton = new Button("Send");
saveButton.setDisableOnClick(true);
saveButton.addListener(this);
addComponent(saveButton);
setComponentAlignment(saveButton, Alignment.TOP_RIGHT);
}
public void buttonClick(ClickEvent event) {
Package job = UserContext.getContext().getJob();
List<String> ipAddresses = job.getIpAddresses();
List<String> packagesForSending = job.getPackages();
// TODO2 + check are package and ipAddress set.
if (packagesForSending == null || packagesForSending.isEmpty()) {
getWindow().showNotification("Please choose package.");
} else {
if (ipAddresses == null || ipAddresses.isEmpty()) {
getWindow().showNotification("Please choose IP Address.");
} else {
for (String ipAddressComment : ipAddresses) {
// TODO what if there is already specified IP (with some
// other
// job)
int indexOfAComment = ipAddressComment.indexOf(SPACE);
String ip = null;
if (indexOfAComment < 0) {
ip = ipAddressComment;
} else {
ip = ipAddressComment.substring(0, indexOfAComment);
}
PackageData packageData = UserContext.getContext()
.getPackagesForSending().get(ip);
if (packageData == null) {
packageData = new PackageData();
UserContext.getContext().getPackagesForSending()
.put(ip, packageData);
}
packageData.setPackages(packagesForSending);
synchronized (this) {
UserContext.getContext().getAvailableIPs().remove(ip);
UserContext.getContext().getBusyIPs()
.put(ip, packagesForSending);
UserContext.getContext().getIpsForStartingJob()
.put(ip, true);
}
// Show text that the save operation has been completed
StringBuilder packages = new StringBuilder();
Iterator<String> packageIterator = packagesForSending
.iterator();
while (packageIterator.hasNext()) {
packages.append(packageIterator.next());
if (packageIterator.hasNext()) {
packages.append(COMMA);
packages.append(SPACE);
}
}
addComponent(new Label(
String.format(
"In a few moments chosen packages (%s) will be sent to the chosen computer (%s).",
packages, ip)));
}
getPackagesSelectionForNewJob().reload();
getiPsSelectionForNewJob().reload();
getCommandsForPackages().reload();
}
}
event.getButton().setEnabled(true);
// TODO7 add OK button
}
@Override
public void reload() {
}
private PackageCommands getCommandsForPackages() {
return _commandsForPackages;
}
private IPsSelectionForNewJob getiPsSelectionForNewJob() {
return _iPsSelectionForNewJob;
}
private PackagesSelectionForNewJob getPackagesSelectionForNewJob() {
return _packagesSelectionForNewJob;
}
private void setCommandsForPackages(PackageCommands commandsForPackages) {
_commandsForPackages = commandsForPackages;
}
private void setiPsSelectionForNewJob(
IPsSelectionForNewJob iPsSelectionForNewJob) {
_iPsSelectionForNewJob = iPsSelectionForNewJob;
}
private void setPackagesSelectionForNewJob(
PackagesSelectionForNewJob packagesSelectionForNewJob) {
_packagesSelectionForNewJob = packagesSelectionForNewJob;
}
} |
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.web;
import java.io.File;
import net.datacrow.core.DataCrow;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* The web server. This is the wrapper around the Jetty server.
*
* @author Robert Jan van der Waals
*/
public class DcWebServer {
private static final String context = "/datacrow";
private static DcWebServer instance = new DcWebServer();
private int port;
private boolean isRunning;
private Server server;
/**
* Returns the instance of the web server.
*/
public static DcWebServer getInstance() {
return instance;
}
public void setPort(int port) {
this.port = port;
}
/**
* Creates a new instance.
*/
private DcWebServer() {}
/**
* Indicates if the server is currently up and running.
*/
public boolean isRunning() {
return isRunning;
}
/**
* Stops the server.
* @throws Exception
*/
public void stop() throws Exception {
server.stop();
isRunning = false;
}
/**
* Starts the Web Server. The port is configurable.
*/
public void start() throws Exception {
server = server == null ? new Server() : server;
Connector connector = new SelectChannelConnector();
connector.setPort(port);
server.setConnectors(new Connector[]{connector});
String baseDir = DataCrow.webDir;
File contextDir = new File(baseDir, context);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(context);
webapp.setWar(contextDir.toString());
webapp.setDefaultsDescriptor(new File(contextDir, "/WEB-INF/webdefault.xml").toString());
server.setHandler(webapp);
server.start();
isRunning = true;
}
}
|
package Array;
public class ArrayRainFallBlockMeasue {
public static int evalRainFall(int[] buildingGroup)
{
//Will move from first building if other building is bigger
int highestbuildingIndex = 0;
//check the amount of water clog happend
int waterClog = 0, heightDifference = 0, maxWaterClog = 0 ;
for(int i=1; i<buildingGroup.length;i++)
{
if(buildingGroup[highestbuildingIndex] > buildingGroup[i])
{
System.out.println("largest building is : "+highestbuildingIndex);
heightDifference = buildingGroup[highestbuildingIndex] - buildingGroup[i];
System.out.println("Water clog between "+highestbuildingIndex+
" and "+ i +" is "+ heightDifference);
waterClog += heightDifference;
System.out.println("Total Water clog between "+highestbuildingIndex+
" and "+ i +" is "+ waterClog);
}
else if(buildingGroup[highestbuildingIndex] <= buildingGroup[i])
{
System.out.println();
System.out.println("Now largest building is : "+i);
highestbuildingIndex = i;
if(maxWaterClog < waterClog)
maxWaterClog = waterClog;
waterClog = 0;
System.out.println("waterClog Happend till now : "+waterClog);
System.out.println("maxWaterClog Happend : "+maxWaterClog);
System.out.println();
}
}
return maxWaterClog;
}
public static void main(String[] args)
{
int[] array = {3,2,1,3,1,1,1,1,3};
/*System.out.println("Maximum water clog at the end is "+ evalRainFall(array));*/
int[] array1 = {1,2,3,1,1,3};
System.out.println("Maximum water clog at the end is "+ evalRainFall(array1));
/*
| | | | |
|| | | || |
||||||||| ||||||
012345678
*/ }
}
|
package com.san.medicineInLanguage;
import com.san.language.Language;
import com.san.medicine.Medicine;
import com.san.textTranslated.TextTranslated;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@IdClass(MedicineInLanguagePK.class)
public class MedicineInLanguage {
@Id
@ManyToOne
private Language language;
@Id
@ManyToOne
private Medicine medicine;
@ManyToOne
private TextTranslated medicine_translated;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp medicine_in_language_created_at;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Timestamp medicine_in_language_updated_at;
public MedicineInLanguage() {
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public Medicine getMedicine() {
return medicine;
}
public void setMedicine(Medicine medicine) {
this.medicine = medicine;
}
public TextTranslated getMedicine_translated() {
return medicine_translated;
}
public void setMedicine_translated(TextTranslated medicine_translated) {
this.medicine_translated = medicine_translated;
}
public Timestamp getMedicine_in_language_created_at() {
return medicine_in_language_created_at;
}
public void setMedicine_in_language_created_at(Timestamp medicine_in_language_created_at) {
this.medicine_in_language_created_at = medicine_in_language_created_at;
}
public Timestamp getMedicine_in_language_updated_at() {
return medicine_in_language_updated_at;
}
public void setMedicine_in_language_updated_at(Timestamp medicine_in_language_updated_at) {
this.medicine_in_language_updated_at = medicine_in_language_updated_at;
}
} |
package JavaPackage;
public class DataConversion {
public static void main(String[] args) {
// String x = "100A";
// System.out.println(x+20); // 10020
//
// // Convert string to integer:
// int i = Integer.parseInt(x);
// System.out.println(i+20); // 120
// String x = "100A";
// System.out.println(x+20);
// int i = Integer.parseInt(x); //for "100A" conversion, will get "main" java.lang.NumberFormatException:
//string to double
String y="12.33";
System.out.println(y+20); // 12.3320
double d = Double.parseDouble(y);
//System.out.println(d); // 12.33
System.out.println(d+20); // 32.33
//integer to String
int p = 100;
System.out.println(p+20);
String p1 = String.valueOf(p);
System.out.println(p1+20);
}
}
|
package util;
/**
* Created by Qin Liu on 2016/12/10.
*/
public enum SortType {
Price, //按价格排序
StarLevel, //按星级排序
Score; //按评分排序
}
|
package com.alibaba.druid.bvt.hibernate;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import junit.framework.TestCase;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import com.alibaba.druid.bvt.hibernate.entity.Sample;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcUtils;
/**
* @author yinheli [yinheli@gmail.com]
* @date 2012-11-26 下午11:41
*/
public class HibernateCRUDTest extends TestCase {
private static final Logger log = LoggerFactory.getLogger(HibernateCRUDTest.class);
private DruidDataSource dataSource;
private SessionFactory sessionFactory;
@Override
public void setUp() throws Exception {
/*init dataSource*/
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:h2:file:~/.h2/HibernateCRUDTest;AUTO_SERVER=TRUE");
dataSource.setUsername("sa");
dataSource.setPassword("");
dataSource.setDefaultAutoCommit(false);
dataSource.setFilters("log4j");
/*init sessionFactory*/
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource);
Properties prop = new Properties();
prop.put("hibernate.show_sql", "true");
//prop.put("hibernate.format_sql", "true");
prop.put("hibernate.hbm2ddl.auto", "create");
prop.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
factoryBean.setHibernateProperties(prop);
factoryBean.setAnnotatedClasses(new Class<?>[]{Sample.class});
try {
factoryBean.afterPropertiesSet();
} catch (IOException e) {
e.printStackTrace();
}
sessionFactory = factoryBean.getObject();
}
@Override
public void tearDown() throws Exception {
sessionFactory.close();
JdbcUtils.close(dataSource);
}
private void doCreate(Session session) {
Sample sample = new Sample();
sample.setId(1L);
sample.setDesc("sample");
sample.setCreateTime(new Date());
session.save(sample);
}
private void doGet(Session session) {
Sample sample = (Sample) session.get(Sample.class, 1L);
log.debug("**sample:{}", sample);
assert sample != null;
}
private void doUpdate(Session session) {
Sample sample = (Sample) session.get(Sample.class, 1L);
assert sample != null;
sample.setDesc("update sample");
sample.setUpdateTime(new Date());
session.update(sample);
}
private void doDelete(Session session) {
Sample sample = (Sample) session.get(Sample.class, 1L);
assert sample != null;
session.delete(sample);
}
/*-------- test start --------*/
public void test_create() {
Session session = null;
try {
session = sessionFactory.openSession();
doCreate(session);
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_get() {
Session session = null;
try {
session = sessionFactory.openSession();
doCreate(session);
doGet(session);
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_update() {
Session session = null;
try {
session = sessionFactory.openSession();
doCreate(session);
doUpdate(session);
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_delete() {
Session session = null;
try {
session = sessionFactory.openSession();
doCreate(session);
doDelete(session);
} finally {
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_transactional_create() {
Session session = null;
Transaction tran = null;
try {
session = sessionFactory.openSession();
tran = session.beginTransaction();
doCreate(session);
} finally {
if (tran != null) {
tran.commit();
}
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_transactional_update() {
Session session = null;
Transaction tran = null;
try {
session = sessionFactory.openSession();
tran = session.beginTransaction();
doCreate(session);
doUpdate(session);
} finally {
if (tran != null) {
tran.commit();
}
if (session != null) {
session.flush();
session.close();
}
}
}
public void test_transactional_delete() {
Session session = null;
Transaction tran = null;
try {
session = sessionFactory.openSession();
tran = session.beginTransaction();
doCreate(session);
doDelete(session);
} finally {
if (tran != null) {
tran.commit();
}
if (session != null) {
session.flush();
session.close();
}
}
}
} |
/**
*외주관리시스템의 빈
*<p> 제목:CpQnaBean.java</p>
*<p> 설명:외주관리Qna 빈</p>
*<p> Copyright: Copright(c)2004</p>
*<p> Company: VLC</p>
*@author 박준현
*@version 1.0
*/
package com.ziaan.cp;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Vector;
import com.ziaan.common.MChannelConnect;
import com.ziaan.library.ConfigSet;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.FileManager;
import com.ziaan.library.ListSet;
import com.ziaan.library.Log;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.library.StringManager;
public class CpQnaBean {
private ConfigSet config;
private int row;
private String v_type = "AB";
public CpQnaBean() {
try {
config = new ConfigSet();
row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다
} catch( Exception e ) {
e.printStackTrace();
}
}
/**
* QNA화면 리스트
* @param box receive from the form object and session
* @return ArrayList QNA 리스트
* @throws Exception
*/
public ArrayList selectListQna(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String sql1 = "";
DataBox dbox = null;
String v_searchtext = box.getString("p_searchtext");
String v_select = box.getString("p_select");
int v_pageno = box.getInt("p_pageno");
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql1 = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql1);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
list = new ArrayList();
sql += " select a.seq , a.types, a.title, a.contents, a.indate, a.inuserid, ";
sql += " a.upfile, a.isopen, a.luserid, a.ldate, b.name,a.cnt,";
sql += " (select count(realfile) from tz_boardfile where tabseq = " + v_tabseq + ") filecnt,";
sql += " (select count(*) from TZ_HOMEQNA where tabseq =" +v_tabseq + " and seq = seq and types > 0) replystate ";
sql += " from TZ_HOMEQNA a, tz_member b";
sql += " where a.inuserid = b.userid( +)";
sql += " and tabseq = " + v_tabseq;
if ( !v_searchtext.equals("") ) { // 검색어가 있으면
v_pageno = 1; // 검색할 경우 첫번째 페이지가 로딩된다
if ( v_select.equals("title") ) { // 제목으로 검색할때
sql += " and title like " + StringManager.makeSQL("%" + v_searchtext + "%");
}
else if ( v_select.equals("contents") ) { // 내용으로 검색할때
sql += " and contents like " + StringManager.makeSQL("%" + v_searchtext + "%"); // Oracle 9i 용
}
}
sql += " order by seq desc, types asc ";
ls = connMgr.executeQuery(sql);
ls.setPageSize(row); // 페이지당 row 갯수를 세팅한다
ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다.
int total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다
int total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다
while ( ls.next() ) {
dbox = ls.getDataBox();
dbox.put("d_dispnum", new Integer(total_row_count - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(total_page_count));
dbox.put("d_rowcount", new Integer(row));
list.add(dbox);
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* QNA 등록할때(질문)
* @param box receive from the form object and session
* @return isOk 1:insert success,0:insert fail
* @throws Exception
*/
public int insertQnaQue(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
PreparedStatement pstmt1 = null;
String sql = "";
String sql1 = "";
String sql2 = "";
int isOk1 = 1;
int isOk2 = 1;
String v_title = box.getString("p_title");
String v_contents = StringManager.replace(box.getString("content"),"&","&");
String v_realMotionName = box.getRealFileName("p_motion");
String v_newMotionName = box.getNewFileName("p_motion");
String v_types = "0";
String s_userid = "";
String s_usernm = "";
String s_gadmin = box.getSession("gadmin");
if ( s_gadmin.equals("A1") ) {
s_usernm = "운영자";
} else {
s_usernm = box.getSession("name");
}
if ( s_gadmin.equals("A1") ) {
s_userid = "운영자";
} else {
s_userid = box.getSession("userid");
}
String v_isopen = "Y";
Vector newFileNames = box.getNewFileNames("p_file");
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
// ---------------------- 게시판 번호 가져온다 ----------------------------
sql = "select nvl(max(seq), 0) from TZ_HOMEQNA";
ls = connMgr.executeQuery(sql);
ls.next();
int v_seq = ls.getInt(1) + 1;
ls.close();
// ------------------------------------------------------------------------------------
if ( newFileNames.size() != 0) {
//// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// ///
sql1 = "insert into TZ_HOMEQNA(tabseq, seq, types, title, contents, indate, inuserid, isopen, luserid, ldate, upfile) ";
sql1 += " values (?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?) ";
pstmt1 = connMgr.prepareStatement(sql1);
pstmt1.setInt(1, v_tabseq);
pstmt1.setInt(2, v_seq);
pstmt1.setString(3, v_types);
pstmt1.setString(4, v_title);
pstmt1.setString(5, v_contents);
pstmt1.setString(6, s_userid);
pstmt1.setString(7, v_isopen);
pstmt1.setString(8, s_userid);
pstmt1.setString(9, (String)newFileNames.elementAt(0));
} else {
//// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// ///
sql1 = "insert into TZ_HOMEQNA(tabseq, seq, types, title, contents, indate, inuserid, isopen, luserid, ldate) ";
sql1 += " values (?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) ";
pstmt1 = connMgr.prepareStatement(sql1);
pstmt1.setInt(1, v_tabseq);
pstmt1.setInt(2, v_seq);
pstmt1.setString(3, v_types);
pstmt1.setString(4, v_title);
pstmt1.setString(5, v_contents);
pstmt1.setString(6, s_userid);
pstmt1.setString(7, v_isopen);
pstmt1.setString(8, s_userid);
}
isOk1 = pstmt1.executeUpdate(); // 먼저 해당 content 에 empty_clob()을 적용하고 나서 값을 스트림으로 치환한다.
if ( pstmt1 != null ) { pstmt1.close(); }
isOk2 = this.insertUpFile(connMgr, v_seq, box);
if ( isOk1 > 0 && isOk2 > 0 ) {
// == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
/*
질물 등록시 총괄관리자에게 메신져보내기
*/
MChannelConnect mchannel = null;
try {
connMgr = new DBConnectionManager();
// connMgr.setAutoCommit(false);
mchannel = new MChannelConnect();
String message = "";
String sender_name = "";
String sender_id = "";
String target_id = "";
String target_name = "";
String sql3 = "";
String url = "";
int isOk112 = 0;
ArrayList list = null;
DataBox dbox = null;
sql3 = "SELECT TZ_MANAGER.GADMIN,TZ_MEMBER.CONO,TZ_MEMBER.NAME FROM TZ_MEMBER,TZ_MANAGER";
sql3 += " WHERE (TZ_MEMBER.USERID = TZ_MANAGER.USERID) and tz_manager.gadmin = 'A1'";
list = new ArrayList();
ls = connMgr.executeQuery(sql3);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
for ( int i = 0; i < list.size() ;i++ ) {
dbox = (DataBox)list.get(i);
target_id = dbox.getString("d_cono");
target_name= dbox.getString("d_name");
// message += v_contents;
sender_name = box.getSession("name");
sender_id = box.getSession("userid");
url = "http:// cp.hkhrd.com";
message = "외주관리 시스템 Q&A에 " +sender_name + "님이 아래와 같은 제목으로 질문을 남겼습니다.\n\r\n\r";
message += v_title;
isOk112 = mchannel.sendMessage(sender_id, sender_name, target_id, target_name, message,url );
}
ls.close();
} catch ( Exception ex ) { ex.printStackTrace();
}finally {
// if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( mchannel != null ) { try { mchannel.freeConnection(); } catch ( Exception e10 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
// *///== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
}
} catch ( Exception ex ) {
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
FileManager.deleteFile(v_newMotionName);
ErrorManager.getErrorStackTrace(ex, box, sql1);
throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() );
} finally {
// if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1*isOk2;
}
/**
* QNA 등록할때(답변)
* @param box receive from the form object and session
* @return isOk 1:insert success,0:insert fail
* @throws Exception
*/
public int insertQnaAns(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
PreparedStatement pstmt = null;
String sql = "";
String sql1 = "";
int isOk = 0;
int isOk2 = 0;
int isOk3 = 0;
int v_seq = box.getInt("p_seq");
String v_types = "";
String v_title = box.getString("p_title");
String v_contents = StringManager.replace(box.getString("content"),"&","&");
String v_isopen = "Y";
String s_userid = "";
String s_usernm = "";
String s_gadmin = box.getSession("gadmin");
if ( s_gadmin.equals("A1") ) {
s_usernm = "운영자";
} else {
s_usernm = box.getSession("name");
}
if ( s_gadmin.equals("A1") ) {
s_userid = "운영자";
} else {
s_userid = box.getSession("userid");
}
Vector newFileNames = box.getNewFileNames("p_file");
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql1 = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql1);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
sql = " select max(to_number(types)) from TZ_HOMEQNA ";
sql += " where tabseq = " + v_tabseq + " and seq = " + v_seq;
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_types = String.valueOf(( ls.getInt(1) + 1));
} else {
v_types = "1";
}
if ( newFileNames.size() != 0) {
//// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// ///
sql1 = "insert into TZ_HOMEQNA(tabseq, seq, types, title, contents, indate, inuserid, isopen, luserid, ldate, upfile) ";
sql1 += " values (?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setInt(1, v_tabseq);
pstmt.setInt(2, v_seq);
pstmt.setString(3, v_types);
pstmt.setString(4, v_title);
pstmt.setString(5, v_contents);
pstmt.setString(6, s_userid);
pstmt.setString(7, v_isopen);
pstmt.setString(8, s_userid);
pstmt.setString(9, (String)newFileNames.elementAt(0));
} else {
//// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// ///
sql1 = "insert into TZ_HOMEQNA(tabseq, seq, types, title, contents, indate, inuserid, isopen, luserid, ldate) ";
sql1 += " values (?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setInt(1, v_tabseq);
pstmt.setInt(2, v_seq);
pstmt.setString(3, v_types);
pstmt.setString(4, v_title);
pstmt.setString(5, v_contents);
pstmt.setString(6, s_userid);
pstmt.setString(7, v_isopen);
pstmt.setString(8, s_userid);
}
isOk = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
isOk2 = this.insertUpFile(connMgr, v_seq, box); // 파일첨부했다면 파일table에 insert
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql1);
throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk * isOk2;
}
/**
* QNA 수정하여 저장할때
* @param box receive from the form object and session
* @return isOk 1:update success,0:update fail
* @throws Exception
*/
public int updateQna(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
String sql = "";
String sql1 = "";
ListSet ls = null;
int isOk = 0;
int isOk2 = 0;
int isOk3 = 0;
int v_seq = box.getInt("p_seq");
String v_types = box.getString("p_types");
String v_title = box.getString("p_title");
String v_contents = StringManager.replace(box.getString("content"),"&","&");
String v_isopen = "Y";
String v_savemotion = box.getString("p_savemotion");
Vector newFileNames = box.getNewFileNames("p_file");
String s_userid = "";
String s_usernm = "";
String s_gadmin = box.getSession("gadmin");
if ( s_gadmin.equals("A1") ) {
s_usernm = "운영자";
} else {
s_usernm = box.getSession("name");
}
if ( s_gadmin.equals("A1") ) {
s_userid = "운영자";
} else {
s_userid = box.getSession("userid");
}
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql1 = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql1);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
if ( newFileNames.size() == 0) {
sql = " update TZ_HOMEQNA set title = ? , contents = ?, isopen = ? , ";
sql += " luserid = ? , ldate = to_char(sysdate, 'YYYYMMDDHH24MISS') ";
sql += " where tabseq = ? and seq = ? and types = ? ";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, v_title);
pstmt.setCharacterStream(2, new StringReader(v_contents), v_contents.length() );
pstmt.setString(3, v_isopen);
pstmt.setString(4, s_userid);
pstmt.setInt(5, v_tabseq);
pstmt.setInt(6, v_seq);
pstmt.setString(7, v_types);
isOk = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
} else {
sql = " update TZ_HOMEQNA set title = ? , contents = ?, isopen = ? , ";
sql += " luserid = ? , ldate = to_char(sysdate, 'YYYYMMDDHH24MISS'), upfile = ? ";
sql += " where tabseq = ? and seq = ? and types = ? ";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, v_title);
pstmt.setCharacterStream(2, new StringReader(v_contents), v_contents.length() );
pstmt.setString(3, v_isopen);
pstmt.setString(4, s_userid);
pstmt.setString(5, (String)newFileNames.elementAt(0));
pstmt.setInt(6, v_tabseq);
pstmt.setInt(7, v_seq);
pstmt.setString(8, v_types);
isOk = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
}
isOk2 = this.insertUpFile(connMgr, v_seq, box); // 파일첨부했다면 파일table에 insert
isOk3 = this.deleteUpFile(connMgr, box); // 삭제할 파일이 있다면 파일table에서 삭제
if ( isOk > 0 && isOk2 > 0 && isOk3 > 0 ) {
if ( v_savemotion != null ) {
FileManager.deleteFile(v_savemotion); // DB 에서 모든처리가 완료되면 해당 첨부파일 삭제
}
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
}
Log.info.println(this, box, "update process to " + v_seq);
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
/**
* QNA 삭제할때
* @param box receive from the form object and session
* @return isOk 1:delete success,0:delete fail
* @throws Exception
*/
public int deleteQna(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
String sql = "";
String sql1 = "";
String sql2 = "";
int isOk1 = 1;
int isOk2 = 1;
int v_seq = box.getInt("p_seq");
String v_types = box.getString("p_types");
Vector savefile = box.getVector("p_savefile");
String v_savemotion = box.getString("p_savemotion");
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
if ( v_types.equals("0") ) { // 질문삭제시 답변동시삭제
sql1 = " delete from TZ_HOMEQNA ";
sql1 += " where tabseq = ? and seq = ?";
pstmt1 = connMgr.prepareStatement(sql1);
pstmt1.setInt(1, v_tabseq);
pstmt1.setInt(2, v_seq);
} else {
sql1 = " delete from TZ_HOMEQNA";
sql1 += " where tabseq = ? and seq = ? and types = ? ";
pstmt1 = connMgr.prepareStatement(sql1);
pstmt1.setInt(1, v_tabseq);
pstmt1.setInt(2, v_seq);
pstmt1.setString(3, v_types);
}
isOk1 = pstmt1.executeUpdate();
if ( pstmt1 != null ) { pstmt1.close(); }
for ( int i = 0; i < savefile.size() ;i++ ) {
String str = (String)savefile.elementAt(i);
if ( !str.equals("") ) {
isOk2 = this.deleteUpFile(connMgr, box);
}
}
if ( isOk1 > 0 && isOk2 > 0 ) {
if ( savefile != null ) {
FileManager.deleteFile(savefile); // 첨부파일 삭제
}
if ( v_savemotion != null ) {
FileManager.deleteFile(v_savemotion);
}
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
Log.info.println(this, box, "delete process to " + v_seq);
}
} catch ( Exception ex ) {
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
ErrorManager.getErrorStackTrace(ex, box, sql1);
throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } }
if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1 * isOk2;
}
//// //// //// //// //// //// //// //// //// //// //// //// //// /// 파일 테이블 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// /
/**
* Q&A 파일 입력하기
* @param box receive from the form object and session
* @return isOk2 입력에 성공하면 1을 리턴한다
*/
public int insertUpFile(DBConnectionManager connMgr, int p_seq, RequestBox box) throws Exception {
ListSet ls = null;
PreparedStatement pstmt2 = null;
String sql = "";
String sql2 = "";
int isOk2 = 1;
// ---------------------- 업로드되는 파일 --------------------------------
Vector realFileNames = box.getRealFileNames("p_file");
Vector newFileNames = box.getNewFileNames("p_file");
// ----------------------------------------------------------------------------------------------------------------------------
String s_userid = box.getSession("userid");
try {
if ( realFileNames != null ) {
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
// ---------------------- 자료 번호 가져온다 ----------------------------
sql = "select nvl(max(fileseq), 0) from tz_boardfile where tabseq = " + v_tabseq ;
ls = connMgr.executeQuery(sql);
ls.next();
int v_fileseq = ls.getInt(1) + 1;
ls.close();
// ------------------------------------------------------------------------------------
//// //// //// //// //// //// //// //// // 파일 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// ///
sql2 = "insert into tz_boardfile(tabseq, seq, fileseq, realfile, savefile, luserid, ldate)";
sql2 += " values (?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'))";
pstmt2 = connMgr.prepareStatement(sql2);
for ( int i = 0; i < realFileNames.size(); i++ ) {
pstmt2.setInt(1, v_tabseq);
pstmt2.setInt(2, p_seq);
pstmt2.setInt(3, v_fileseq);
pstmt2.setString(4, (String)realFileNames.elementAt(i));
pstmt2.setString(5, (String)newFileNames.elementAt(i));
pstmt2.setString(6, s_userid);
isOk2 = pstmt2.executeUpdate();
v_fileseq++;
}
}
} catch ( Exception ex ) {
FileManager.deleteFile(newFileNames); // 일반파일, 첨부파일 있으면 삭제..
ErrorManager.getErrorStackTrace(ex, box, sql2);
throw new Exception("sql = " + sql2 + "\r\n" + ex.getMessage() );
} finally {
if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } }
}
return isOk2;
}
/**
* Q&A 파일 삭제하기
* @param box receive from the form object and session
* @return isOk3 삭제에 성공하면 1을 리턴한다
*/
public int deleteUpFile(DBConnectionManager connMgr, RequestBox box) throws Exception {
PreparedStatement pstmt3 = null;
String sql = "";
String sql3 = "";
int isOk3 = 1;
ListSet ls = null;
int v_seq = box.getInt("p_seq");
Vector v_savefileVector = box.getVector("p_savefile");
String v_types = box.getString("p_types");
try {
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
sql3 = "delete from tz_boardfile where tabseq = " + v_tabseq + " and seq = ? and savefile = ?";
pstmt3 = connMgr.prepareStatement(sql3);
if ( v_types.equals("0") ) {
for ( int i = 0; i < v_savefileVector.size(); i++ ) {
String v_savefile = (String)v_savefileVector.elementAt(i);
pstmt3.setInt(1, v_seq);
pstmt3.setString(2, v_savefile);
isOk3 = pstmt3.executeUpdate();
}
if ( pstmt3 != null ) { pstmt3.close(); }
} else {
for ( int i = 0; i < v_savefileVector.size(); i++ ) {
if ( v_savefileVector.size() == Integer.parseInt(v_types)) {
String v_savefile = (String)v_savefileVector.elementAt(i);
pstmt3.setInt(1, v_seq);
pstmt3.setString(2, v_savefile);
isOk3 = pstmt3.executeUpdate();
}
}
}
if ( pstmt3 != null ) { pstmt3.close(); }
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql3);
throw new Exception("sql = " + sql3 + "\r\n" + ex.getMessage() );
} finally {
if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e ) { } }
}
return isOk3;
}
/**
* Q&A 상세보기
* @param box receive from the form object and session
* @return DataBox 조회한 값을 DataBox에 담아 리턴
*/
public DataBox selectQna(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
String sql = "";
DataBox dbox = null;
int v_seq = box.getInt("p_seq");
String v_types = box.getString("p_types");
String v_fileseq = box.getString("p_fileseq");
Vector realfileVector = new Vector();
Vector savefileVector = new Vector();
try {
connMgr = new DBConnectionManager();
// ---------------------- 어떤게시판인지정보를 가져와 tabseq를 리턴한다 ----------------------------
sql = "select tabseq from tz_bds where type = " + SQLString.Format(v_type);
ls = connMgr.executeQuery(sql);
ls.next();
int v_tabseq = ls.getInt(1);
ls.close();
// ------------------------------------------------------------------------------------
sql = "select a.types, a.seq, a.inuserid, a.title, a.contents, b.realfile, b.savefile, a.indate ,c.name";
sql += " from tz_homeqna a, tz_boardfile b, tz_member c";
sql += " where a.tabseq = b.tabseq( +) and a.seq = b.seq( +) ";
sql += " and a.inuserid = c.userid( +)";
sql += "and a.upfile = b.savefile( +) ";
sql += "and a.tabseq = " + v_tabseq + " and a.seq = " +v_seq + " and types = " + v_types;
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
// ------------------- 2003.12.25 변경 -------------------------------------------------------------------
dbox = ls.getDataBox();
realfileVector.addElement( ls.getString("realfile") );
savefileVector.addElement( ls.getString("savefile") );
}
connMgr.executeUpdate("update tz_homeqna set cnt = cnt + 1 where tabseq = " + v_tabseq + " and seq = " +v_seq + "and types = " + v_types);
dbox.put("d_realfile", realfileVector);
dbox.put("d_savefile", savefileVector);
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }}
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return dbox;
}
}
|
package com.sunny.netty.chat.client.handler;
import com.sunny.netty.chat.protocol.response.LogoutResponsePacket;
import com.sunny.netty.chat.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2018/10/27 14:15 <br>
* @see com.sunny.netty.chat.client.handler <br>
*/
public class LogoutResponseHandler extends SimpleChannelInboundHandler<LogoutResponsePacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, LogoutResponsePacket logoutResponsePacket) {
SessionUtil.unBindSession(ctx.channel());
}
} |
package com.oracle.notebookserver.model;
public class CodeServerRequest {
private String code;
private String sessionId;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public CodeServerRequest(String code, String sessionId) {
super();
this.code = code;
this.sessionId = sessionId;
}
public CodeServerRequest() {
// TODO Auto-generated constructor stub
}
}
|
package BookView;
import BookView.AllBookView;
import BookView.BookFindingView;
import CartelView.CartelRegistrationView;
import LibraryManagementFunctionFactory.BookFactory;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import model.Book;
import model.Employee;
import views.HomeView;
import views.PaymentTypeView;
public class BuyBookView {
private Employee currentUser;
private Book currentBook;
public BuyBookView(Employee currentUser) {
this.currentUser = currentUser;
}
// public BookFindingView(Book currentBook) {
// this.currentBook = currentBook;
// }
public BuyBookView() {
}
public Scene execute(Stage stage) {
GridPane root1 = new GridPane();
root1.setHgap(10);
root1.setVgap(10);
root1.setPadding(new Insets(10, 10, 10, 10));
root1.setAlignment(Pos.TOP_CENTER);
Label bookISBNLabel = new Label("ISBN Of Book: ");
bookISBNLabel.setTextFill(Color.web("white"));
bookISBNLabel.setStyle("-fx-font-weight: bold;");
TextField bookISBNField = new TextField();
root1.add(bookISBNLabel, 3, 1);
root1.add(bookISBNField, 4, 1);
Button buyBookButton = new Button("-Buy-");
buyBookButton.setTextFill(Color.web("black"));
buyBookButton.setStyle("-fx-font-weight: bold;");
buyBookButton.setId("buyBookButton-button");
buyBookButton.setStyle("-fx-background-color:#09eab6;");
HBox h = new HBox();
h.getChildren().add(buyBookButton);
root1.add(buyBookButton, 4, 6);
buyBookButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
String isbn = bookISBNField.getText();
//String description = descriptionArea.getText();
// boolean isRememberMe = remember.isSelected();
BookFactory bookFactory = new BookFactory();
Book findBook = bookFactory.findBooksByISBN(isbn);
if (findBook == null && findBook.getQuantity() <= 0) {
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("There was an error");
errorAlert.setContentText("Book not available");
errorAlert.showAndWait();
} else {
Alert successAlert = new Alert(Alert.AlertType.CONFIRMATION);
successAlert.setHeaderText("Book Found");
successAlert.setContentText("The Credentials are okay");
findBook.setQuantity(findBook.getQuantity()-1);
// bookFactory.editBook(findBook);
stage.setScene(new CartelRegistrationView(findBook).execute(stage));
if (findBook.getQuantity() <= 5) {
successAlert.setContentText("Book Is Found..." + "\n"
+ "Time To Buy New Books ! " + "\n"
+ "Quantity Left Is Limited: " + findBook.getQuantity() + "\n"
+ "You Paid: " + findBook.getPrice() + "-ALL");
} else {
successAlert.setContentText("Book Is Found..." + "\n"
+ "Quantity Left: " + findBook.getQuantity() + "\n"
+ "You Paid: " + findBook.getPrice() + "-ALL");
}
successAlert.showAndWait();
successAlert.close();
}
}
});
BorderPane mainPane = new BorderPane();
MenuBar menuBar = new MenuBar();
Label backLabel = new Label("Back");
backLabel.setStyle("-fx-font-weight: bold;");
Menu back = new Menu("", backLabel);
backLabel.setOnMouseClicked(e -> {
PaymentTypeView paymentTypeView = new PaymentTypeView();
stage.setScene(paymentTypeView.showView(stage));
});
menuBar.getMenus().add(back);
mainPane.setTop(menuBar);
Label allBooksViewLabel = new Label("All Books");
Menu allBookViews = new Menu("", allBooksViewLabel);
allBooksViewLabel.setOnMouseClicked(e -> {
AllBookView allBookView = new AllBookView(currentUser);
stage.setScene(allBookView.showView(stage));
});
menuBar.getMenus().add(allBookViews);
mainPane.setTop(menuBar);
Label findBookViewLabel = new Label("Find Books");
Menu findBook = new Menu("", findBookViewLabel);
findBookViewLabel.setOnMouseClicked(e -> {
BookFindingView bookFindingView = new BookFindingView(currentUser);
stage.setScene(bookFindingView.execute(stage));
});
menuBar.getMenus().add(findBook);
mainPane.setTop(menuBar);
root1.setStyle("-fx-background-image: url('buyBackGround.png')");
mainPane.setCenter(root1);
Scene scene = new Scene(mainPane, 563, 209);
scene.getStylesheets().add("style.css");
stage.setScene(scene);
stage.setTitle("Welcome to GONLINE Vending Machine");
stage.show();
return scene;
}
}
|
package productManager.service.product;
import com.fasterxml.jackson.annotation.JsonIgnore;
import productManager.service.evaluation.Evaluation;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "Produtos")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Column(name = "Nome")
private String name;
@Column(name = "Preço")
private double price;
@ManyToMany(cascade =
{CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name="Avaliação_Produto",
joinColumns=
@JoinColumn(name="Produto_ID", referencedColumnName="id"),
inverseJoinColumns=
@JoinColumn(name="Avaliação_ID", referencedColumnName="id")
)
@JsonIgnore
public Set<Evaluation> evaluations = new HashSet<>();
public Product(){
}
public Product(Long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Set<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(Set<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
|
package by.epam.aliaksei.litvin.service.impl;
import by.epam.aliaksei.litvin.domain.*;
import by.epam.aliaksei.litvin.service.AuditoriumService;
import by.epam.aliaksei.litvin.service.BookingService;
import by.epam.aliaksei.litvin.service.EventService;
import by.epam.aliaksei.litvin.service.UserService;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class BookingServiceImpl implements BookingService {
private int vipSeatModifier;
private UserService userService;
@Override
public double getTicketsPrice(@Nonnull Event event, @Nonnull LocalDateTime dateTime, @Nullable User user, @Nonnull Set<Long> seats) {
double basePrice = event.getBasePrice();
double ratingModifier = getPriceModifierBasedOnEventRating(event.getRating());
Auditorium auditorium = event.getAuditoriums().get(dateTime);
int vipSeatsNumber = (int) auditorium.countVipSeats(seats);
int regularSeatsNumber = seats.size() - vipSeatsNumber;
return basePrice * ratingModifier * regularSeatsNumber + basePrice * ratingModifier * vipSeatModifier * vipSeatsNumber;
}
@Override
public void bookTickets(@Nonnull Set<Ticket> tickets) {
tickets.forEach(ticket -> userService.save(ticket.getUser()));
}
@Nonnull
@Override
public Set<Ticket> getPurchasedTicketsForEvent(@Nonnull Event event, @Nonnull LocalDateTime dateTime) {
Set<Ticket> purchasedTickets = new HashSet<>();
userService.getAll().forEach(user -> {
Set<Ticket> tickets = user.getTickets().stream()
.filter(ticket -> ticket.getEvent().equals(event))
.filter(ticket -> ticket.getDateTime().equals(dateTime))
.collect(Collectors.toSet());
purchasedTickets.addAll(tickets);
});
return purchasedTickets;
}
private double getPriceModifierBasedOnEventRating(EventRating rating) {
switch (rating) {
case HIGH:
return 1.2;
case MID:
return 1;
case LOW:
return 0.8;
default:
throw new IllegalArgumentException("Illegal rating value");
}
}
public int getVipSeatModifier() {
return vipSeatModifier;
}
public void setVipSeatModifier(int vipSeatModifier) {
this.vipSeatModifier = vipSeatModifier;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
|
package ffm.slc.model.enums;
/**
* The category of LEA/district. For example: Independent or Charter
*/
public enum LEACategoryType {
INDEPENDENT("Independent"),
CHARTER("Charter");
private String prettyName;
LEACategoryType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
package com.ymhd.mifen.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import com.ymhd.mifei.tool.DataUri;
import android.util.Log;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
/**
* #{TODO} <一个用于连接服务器的工具类>
*
* @author ljw
*
*/
public class APP_url {
public static String APP_URL = "http://api.mefans.hk/";
public static String token_path = APP_URL + "token";
public static String Login_path = APP_URL + "/V1/member/login";
public static String area_get = APP_URL + "/V1/area";
public static String signup_username = APP_URL + "V1/member/register/username";
public static String signup_tellphone = APP_URL + "V1/member/register/cellphone";
public static String ad_get = APP_URL + "/V1/ad/index";
public static String SMS_get = APP_URL + "/V1/sms";
public static String SMS_verify = APP_URL + "/V1/sms/verify";
public static String member_info = APP_URL + "/V1/member/info";
public static String shopcar_get = APP_URL + "/V1/cart";
/**
* ${TODO} <获取token>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject token(String appid, String appSelect, String now)
throws ParseException, IOException, JSONException {
Log.e("URL", token_path);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "client_credentials");
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(token_path);
request.addHeader("Authorization", "basic " + headrtoken(appid, appSelect, now).replace("\n", ""));
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <用户名注册>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject signup_username(String bearertoken, String username, String password, String confirm,
String remId, String reComId) throws ParseException, IOException, JSONException {
Log.e("URL", signup_username);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("userName", username);
params.put("password", password);
params.put("confirm", confirm);
params.put("remId", remId);
params.put("reComId", reComId);
params.put("from", "" + 2);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(signup_username);
request.addHeader("Authorization", "bearer " + bearertoken);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <手机注册>
* 如果remid和reComId不存在,则保存空字节,不能乱填参数
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject signup_tellphone(String bearertoken, String tellphone, String imei, String password,
String confirm, String remId, String reComId) throws ParseException, IOException, JSONException {
Log.e("URL", signup_tellphone);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("cellphone", tellphone);
params.put("imei", imei);
params.put("password", password);
params.put("confirm", confirm);
params.put("remId", remId);
params.put("reComId", reComId);
params.put("from", "" + 2);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(signup_tellphone);
request.addHeader("Authorization", "bearer " + bearertoken);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <登陆验证>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject Login(String bearertoken, String username, String password)
throws ParseException, IOException, JSONException {
Log.e("URL", Login_path);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("from", "" + 2);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(Login_path);
request.addHeader("Authorization", "bearer " + bearertoken);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <token过时,重新申请认证,反参与login一致>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject refreh_token(String appid, String appSelect, String now, String refresh_token)
throws ParseException, IOException, JSONException {
Log.e("URL", token_path);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "refresh_token");
params.put("refresh_token", refresh_token);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(token_path);
request.addHeader("Authorization", "basic " + headrtoken(appid, appSelect, now).replace("\n", ""));
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <获取地域>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject area(String token) throws ParseException, IOException, JSONException {
Log.e("URL", area_get);
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(area_get);
request.addHeader("Authorization", "bearer " + token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
if (code == 200) {
result2 = EntityUtils.toString(httpResponse.getEntity());
} else {
return null;
}
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <获取广告>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject getAD(String token) throws ParseException, IOException, JSONException {
Log.e("URL", ad_get);
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(ad_get);
request.addHeader("Authorization", "bearer " + token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
if (code == 200) {
result2 = EntityUtils.toString(httpResponse.getEntity());
} else {
return null;
}
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <获取购物车列表>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject getShopcar(String token) throws ParseException, IOException, JSONException {
Log.e("URL", shopcar_get);
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(shopcar_get);
request.addHeader("Authorization", "bearer " + token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <获取短信>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject getSMS(String token, String cellphone) throws ParseException, IOException, JSONException {
Log.e("URL", SMS_get);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("cellPhone", cellphone);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPost request = new HttpPost(SMS_get);
request.addHeader("Authorization", "bearer " + token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <获取用户扩展信息>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject getMemberinfo(String login_token) throws ParseException, IOException, JSONException {
Log.e("URL", member_info);
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(member_info);
request.addHeader("Authorization", "bearer " + login_token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
/**
* ${TODO} <验证短信>
*
* @return JSONObject
* @throws ParseException
* @throws IOException
* @throws JSONException
*/
public JSONObject verifySMS(String token, String cellphone, String code_y)
throws ParseException, IOException, JSONException {
Log.e("URL", SMS_verify);
HttpClient httpClient = new DefaultHttpClient();
Map<String, String> params = new HashMap<String, String>();
params.put("verifyCode", code_y);
params.put("cellphone", cellphone);
StringBuilder sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpPut request = new HttpPut(SMS_verify);
request.addHeader("Authorization", "bearer " + token);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(sb.toString()));
HttpResponse httpResponse = httpClient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
String result2 = null;
result2 = EntityUtils.toString(httpResponse.getEntity());
Log.e("=============", result2);
new JSONObject();
JSONObject result1 = JSONObject.fromObject(result2);
return result1;
}
public String headrtoken(String appid, String appSelect, String now) {
String str = DataUri.base64(appid + ":" + now) + ":" + DataUri.sha256(appid, appSelect, now);
String str2 = DataUri.base64(str.replace("\n", ""));
return str2;
}
}
|
@javax.xml.bind.annotation.XmlSchema(namespace = "http://pku/iaaa/webservice", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package cn.pku.eecs.yips.server.iaaa;
|
package com.example.elevatorrestservice.service;
import java.util.List;
import com.example.elevatorrestservice.model.ElevatorState;
import com.example.elevatorrestservice.model.Passenger;
public interface ElevatorService {
public static final int TOTAL_FLOORS = 11; // Number of floors
public static final int TOTAL_ELEVATORS = 3; // Number of elevators
List<ElevatorState> lowCostSchedule(List<Passenger> passengers);
List<ElevatorState> reset();
}
|
package io.github.seregaslm.jsonapi.simple.resolver;
import io.github.seregaslm.jsonapi.simple.annotation.RequestJsonApiFieldSet;
import io.github.seregaslm.jsonapi.simple.request.FieldSet;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class JsonApiSpreadFieldSetArgumentResolver implements HandlerMethodArgumentResolver {
private static final String REQUEST_FIELD_SET_KEY_BRACKET_START = "[";
private static final String REQUEST_FIELD_SET_KEY_BRACKET_END = "]";
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(RequestJsonApiFieldSet.class) != null;
}
public Object resolveArgument(final MethodParameter methodParameter,
final ModelAndViewContainer modelAndViewContainer,
final NativeWebRequest nativeWebRequest,
final WebDataBinderFactory webDataBinderFactory) {
final RequestJsonApiFieldSet requestJsonApiFieldSet = methodParameter.getParameterAnnotation(RequestJsonApiFieldSet.class);
final Map<String, Set<String>> fieldSet = new HashMap<>();
final String fieldSetKeyStart = requestJsonApiFieldSet.name() + REQUEST_FIELD_SET_KEY_BRACKET_START;
nativeWebRequest.getParameterMap()
.entrySet()
.stream()
.filter(entry -> entry.getKey().startsWith(fieldSetKeyStart)
&& entry.getKey().contains(REQUEST_FIELD_SET_KEY_BRACKET_END))
.forEach(entry -> {
final String[] items = entry.getKey().split("\\" + REQUEST_FIELD_SET_KEY_BRACKET_START);
final String resourceType = items[1].replace(REQUEST_FIELD_SET_KEY_BRACKET_END, "");
if (!StringUtils.hasText(resourceType)) {
throw new IllegalArgumentException(
"Could not prepare spread fields set! " +
"Argument format wrong! Valid format example: fields[resource-type]=field_1,field_2"
);
} else if (entry.getValue().length == 1) {
fieldSet.put(resourceType, Set.of(entry.getValue()[0].split(",")));
} else {
fieldSet.put(resourceType, Collections.emptySet());
}
});
return new FieldSet(fieldSet);
}
}
|
package algorithms.sorting.quick.pivot;
import java.util.Random;
/**
* Created by Chen Li on 2018/1/31.
*/
public class RandomPivotSelector<T extends Comparable<T>> implements PivotSelector<T> {
private Random random = new Random();
@Override
public int pivot(T[] arr, int low, int high) {
return low + random.nextInt(high - low + 1);
}
}
|
package gov.polisen.orm.models;
public class PermissionsOnDeploymentKey {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column permissions_on_deployments.deployment_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
private Integer deploymentId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column permissions_on_deployments.user_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
private Integer userId;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table permissions_on_deployments
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public PermissionsOnDeploymentKey(Integer deploymentId, Integer userId) {
this.deploymentId = deploymentId;
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column permissions_on_deployments.deployment_id
*
* @return the value of permissions_on_deployments.deployment_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public Integer getDeploymentId() {
return deploymentId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column permissions_on_deployments.user_id
*
* @return the value of permissions_on_deployments.user_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public Integer getUserId() {
return userId;
}
} |
package dakrory.a7med.cargomarine.Models.encryption;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class encrypt {
private String algorithm = "MD5";
public String encodePassword(String rawPass, Object salt) {
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
MessageDigest messageDigest = getMessageDigest();
byte[] digest;
try {
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
// "stretch" the encoded value if configured to do so
for (int i = 1; i < iterations; i++) {
digest = messageDigest.digest(digest);
}
if (getEncodeHashAsBase64()) {
return new String(Base64.encode(digest));
} else {
return new String(Hex.encode(digest));
}
}
//~ Instance fields ================================================================================================
private boolean encodeHashAsBase64 = false;
private int iterations = 1;
//~ Methods ========================================================================================================
public boolean getEncodeHashAsBase64() {
return encodeHashAsBase64;
}
/**
* The encoded password is normally returned as Hex (32 char) version of the hash bytes. Setting this
* property to true will cause the encoded pass to be returned as Base64 text, which will consume 24 characters.
*
* @param encodeHashAsBase64 set to true for Base64 output
*/
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
this.encodeHashAsBase64 = encodeHashAsBase64;
}
protected final MessageDigest getMessageDigest() throws IllegalArgumentException {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
}
}
protected String mergePasswordAndSalt(String password, Object salt, boolean strict) {
if (password == null) {
password = "";
}
if (strict && (salt != null)) {
if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
}
}
if ((salt == null) || "".equals(salt)) {
return password;
} else {
return password + "{" + salt.toString() + "}";
}
}
}
|
/**
*
*/
package com.ccloud.oa.common.utils;
import org.springframework.util.CollectionUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author breeze
* @since 2020-08-19
*/
public class DateUtils {
static final TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");
/**
* 日期格式yyyy-MM-dd HH:mm:ss字符串常量
*/
public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 日期格式yyyy-MM-dd字符串常量
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 日期格式yyyyMMdd字符串常量
*/
public static final String DATE_NORMAL_FORMAT = "yyyyMMdd";
/**
* 日期格式yyyy-MM字符串常量
*/
public static final String MONTH_FORMAT = "yyyyMM";
/**
* 时间格式是HH:mm:ss字符串常量
*/
public static final String TIME_FORMAT = "HH:mm:ss";
/**
* 一天的开始与结束
*/
public static final String DATETIME_FORMAT_START = "yyyy-MM-dd 00:00:00";
public static final String DATETIME_FORMAT_END = "yyyy-MM-dd 23:59:59";
/**
* 日期格式HH:mm:ss字符串常量
*/
public static final String HOUR_FORMAT = "HH:mm:ss";
private static SimpleDateFormat sdf_datetime_format = new SimpleDateFormat(DATETIME_FORMAT);
private static SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT);
private static SimpleDateFormat sdf_hour_format = new SimpleDateFormat(TIME_FORMAT);
private static SimpleDateFormat sdf_month_format = new SimpleDateFormat(MONTH_FORMAT);
/**
* 将时间转为字符串 格式:yyyy-MM-dd HH:mm:ss
* @param date
* @return
*/
public static String getDatetimeFormat(Date date) {
return sdf_datetime_format.format(date);
}
/**
* 将时间转为字符串 格式为:yyyy-MM-dd
* @param date
* @return
*/
public static String getDateFormat(Date date) {
return sdf_date_format.format(date);
}
/**
* 将时间转为字符串 格式: 自定义pattern
* @param pattern
* @param date
* @return
*/
public static String format(String pattern, Date date) {
return new SimpleDateFormat(pattern).format(date);
}
/**
* 获得服务器当前日期及时间,以格式为:yyyy-MM-dd HH:mm:ss的
* @return
*/
public static String getNowDateTime() {
return sdf_datetime_format.format(new Date());
}
/**
* 获得服务器当前日期及时间,以格式为:yyyy-MM-dd
* @return
*/
public static String getNowDate() {
return sdf_date_format.format(new Date());
}
/**
* 获取当前时间
* @return
*/
public static String getDate() {
Calendar calendar = Calendar.getInstance();
calendar = setTimeZone(calendar);
SimpleDateFormat dfNew = new SimpleDateFormat(DATETIME_FORMAT);
return dfNew.format(calendar.getTime());
}
/**
* 设置时间
* @param calendar
* @return
*/
public static Calendar setTimeZone(Calendar calendar) {
TimeZone.setDefault(timeZone);
calendar.setTimeZone(TimeZone.getDefault());
return calendar;
}
/**
* 获得服务器当前时间 以格式为:HH:mm:ss的
* @return 日期字符串形式返回
*/
public static String getTime() {
String temp = " ";
temp += sdf_hour_format.format(new Date());
return temp;
}
/**
* 获取今天的开始时间 yyyy-MM-dd 00:00:00
* @return
*/
public static String getTodayStartTime() {
return new SimpleDateFormat(DATETIME_FORMAT_START).format(new Date());
}
/**
* 获取今天的结束时间 yyyy-MM-dd 23:59:59
* @return
*/
public static String getTodayEndTime() {
return new SimpleDateFormat(DATETIME_FORMAT_END).format(new Date());
}
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 将 日期字符串按
* 指定格式转换成
* 日期类型
* pattern 指定的日期格式,如:yyyy-MM-dd
* sdate 待转换的日期字符串
*
* @Param: [pattern, sdate]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:44 AM
*/
public static Date format(String pattern, String sdate) {
SimpleDateFormat df = new SimpleDateFormat(pattern);;
Date date = null;
try {
date = df.parse(sdate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 格式化数据
* sdate yyyy-MM-dd hh:mm:ss
*
*
* @Param: [sdate]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:44 AM
*/
public static Date format(String sdate) {
Date date = null;
try {
date = sdf_datetime_format.parse(sdate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
*
* @param date
* @param day
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 日期加减
* date 日期
* day 天
*
* @Param: [date, day]
* @return: java.lang.String
* @Author: share Author
* @Date: 9:45 AM
*/
public static String getAddDay(Date date, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.format(date);
return sdf.format(date);
}
public static int getWeekOfYear(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(7);
c.setTime(date);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
*
*
* @param year
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 得到
* 某一年
* 周的总数
*
* @Param: [year]
* @return: int
* @Author: share Author
* @Date: 9:45 AM
*/
public static int getMaxWeekNumOfYear(int year) {
Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
return getWeekOfYear(c.getTime());
}
/**
*
*
* @param year
* @param week
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 得到
* 某年某周的
* 第一天
*
*
*
* @Param: [year, week]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:45 AM
*/
public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getFirstDayOfWeek(cal.getTime());
}
/**
*
*
* @param year
* @param week
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 得到
* 某年某周的
* 最后一天
*
* @Param: [year, week]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:46 AM
*/
public static Date getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getLastDayOfWeek(cal.getTime());
}
/**
*
*
* @param date
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 取得
* 指定日期
* 所在周的
* 第一天
*
*
* @Param: [date]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:46 AM
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime();
}
/**
*
*
* @param date
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 取得
* 指定日期
* 所在
* 周的
* 最后一天
*
* @Param: [date]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:46 AM
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
/**
*
*
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 取得
* 当前日期
* 所在
* 周的
* 第一天
*
* @Param: []
* @return: java.util.Date
* @Author: share Author
* @Date: 9:47 AM
*/
public static Date getFirstDayOfWeek() {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime();
}
/**
*
*
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 取得
* 当前日期
* 所在
* 周的
* 最后一天
*
* @Param: []
* @return: java.util.Date
* @Author: share Author
* @Date: 9:47 AM
*/
public static Date getLastDayOfWeek() {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
/**
* @param day 增加天数
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 增加天数
*
* @Param: [date, day]
* @return: java.util.Date
* @Author: share Author
* @Date: 9:47 AM
*/
public static Date addDay(Date date, int day) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, day);
return c.getTime();
}
/**
* 验证时间格式是否是 yyyy-MM-dd 格式
* @param date
* @return
*/
/**
* @Description: "This method is very strange.
* I advise you to think it over carefully before you change it.
* Unless the God does not know the ghost,
* if you want to know clearly, please see the method described below."
* 验证时间
* 格式是否是
* yyyy-MM-dd
* 格式
*
* @Param: [date]
* @return: boolean
* @Author: share Author
* @Date: 9:47 AM
*/
public static boolean matches(String date) {
Pattern pattern = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}");
Matcher matcher = pattern.matcher(date);
return matcher.matches();
}
/**
* 比较两个日期相差天数
* @param date1
* @param date2
* @return
*/
public static int differDays(Date date1, Date date2) {
SimpleDateFormat df = new SimpleDateFormat(DATETIME_FORMAT_START);
date1 = DateUtils.format(df.format(date1));
date2 = DateUtils.format(df.format(date2));
int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
return days;
}
/**
* 比较两个时间相差多少小时 - 当天的
* @param startTime
* @param endTime
* @return
* @throws ParseException
*/
public static double differHours(Date startTime, Date endTime) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
String startFormat = simpleDateFormat.format(startTime);
String endFormat = simpleDateFormat.format(endTime);
Date start = simpleDateFormat.parse(startFormat);
Date end = simpleDateFormat.parse(endFormat);
double hours = (double) (end.getTime() - start.getTime()) / (1000 * 3600);
return Math.floor(hours*10)/10;
}
/**
* 获取月份第一天
* @param day
* @return
*/
public static Date getFisrtDayOfMonth(String day) {
Calendar cal = getCalendar(day);
//获取某月最小天数
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最小天数
cal.set(Calendar.DAY_OF_MONTH, firstDay);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 获取某月的最后一天
* @Title:getLastDayOfMonth
* @Description:
* @param:@param day
* @param:@return
* @return:String
* @throws
*/
public static Date getLastDayOfMonth(String day) {
Calendar cal = getCalendar(day);
//获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
private static Calendar getCalendar(String day) {
int year = Integer.parseInt(day.substring(0, 4));
int month = Integer.parseInt(day.substring(4, 6));
Calendar cal = Calendar.getInstance();
//设置年份
cal.set(Calendar.YEAR, year);
//设置月份
cal.set(Calendar.MONTH, month - 1);
return cal;
}
/**
* 显示日期 天数
* @param showDay
* @return
*/
public static String getDateDay(Date showDay) {
Calendar c = Calendar.getInstance();
c.setTime(showDay);
int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
//0 周日 1 2 3 4 5 6 周一到周六
switch (weekday) {
case 0:
return "日";
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
}
return "";
}
/**
* 获取最大天数
* @param monthDate
* @return
*/
public static int lastDayOfMonth(Date monthDate) {
Calendar calendar = getCalendar(DateUtils.format(DATE_NORMAL_FORMAT, monthDate));
//获取某月最大天数
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获取最大天数
* @param monthDate
* @return
*/
public static boolean isFirstDayOfMonth(Date monthDate) {
if (monthDate == null) {
return false;
}
String dayStirng = DateUtils.format("dd", monthDate);
return "01".equals(dayStirng);
}
/**
* 是否月份最后一天
* @param monthDate
* @return
*/
public static boolean isLastDayOfMonth(Date monthDate) {
Calendar calendar = getCalendar(DateUtils.format(DATE_NORMAL_FORMAT, monthDate));
//获取某月最大天数
String dayStirng = DateUtils.format("dd", monthDate);
return dayStirng.equals(calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + "");
}
/**
* 获取最大天数
* @param dateOne
* @param dateTwo
* @return
*/
public static boolean isSameMonth(Date dateOne, Date dateTwo) {
if (dateOne == null || dateTwo == null) {
return false;
}
return DateUtils.format("MM", dateOne).equals(DateUtils.format("MM", dateTwo));
}
/**
* 获取两个日期的区间列表
*
* @param startDate 起始日期
* @param endDate 结束日期
* @return
*/
public static List<Date> getDateDiffList(Date startDate, Date endDate) {
//日期开始
List<Date> listDate = new ArrayList<>();
Date LS = startDate;
Calendar Date = Calendar.getInstance();//获得通用对象
Date.setTime(startDate);
while (LS.getTime() < endDate.getTime()) {
LS = Date.getTime();
LS = removeDateHHmmSS(LS);
listDate.add(LS);
Date.add(Calendar.DAY_OF_MONTH, 1);//天数加上1
}
return listDate;
}
/**
* 获取时间段内的日期列表
* @param startTime
* @param endTime
* @return
*/
public static List<Date> getDateDiffListWithoutEndTime(Date startTime, Date endTime) {
List<Date> dateDiffList = DateUtils.getDateDiffList(startTime, endTime);
if (CollectionUtils.isEmpty(dateDiffList)) {
return null;
}
dateDiffList.remove(dateDiffList.size() - 1);
return dateDiffList;
}
/**
* 获取两个区间的星期 和每天的日期
*
* @param startDate
* @param endDate
* @return
*/
public static List<Map<String, Object>> getDateDiffWeekAndDayNameList(Date startDate, Date endDate) {
//日期开始
List<Map<String, Object>> dateList = new ArrayList<>();
Date LS = startDate;
Calendar Date = Calendar.getInstance();//获得通用对象
Date.setTime(startDate);
Date nowDate = removeDateHHmmSS(new Date());
while (LS.getTime() < endDate.getTime()) {
Map<String, Object> map = new HashMap<>();
LS = Date.getTime();
// String allWeekName = format("EE", LS);
// String weekName = allWeekName.substring(2);
if (LS.compareTo(nowDate) == 0) {
map.put("isCurrentDay", true);
}
map.put("day", format("d", LS));
map.put("week", getDateDay(LS));
map.put("date", LS);
dateList.add(map);
Date.add(Calendar.DAY_OF_MONTH, 1);//天数加上1
}
return dateList;
}
/**
* 将date时分秒变成0
*
* @param date
* @return
*/
public static Date removeDateHHmmSS(Date date) {
if (date == null) {
return null;
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date);
// 将时分秒,毫秒域清零
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
return cal1.getTime();
}
/**
* @Description: 比较时间是否在区间内
* @Author: Mei
* @date: 2019/10/28 14:23
* @param startDate
* @param endDate
* @param compareDate
* @exception:
* @return: boolean
* @Version: 1.0
*/
public static boolean compareBelong(Date startDate, Date endDate, Date compareDate) {
if (compareDate.after(startDate) && compareDate.before(endDate)) {
return true;
} else if (compareDate.compareTo(startDate) == 0 || compareDate.compareTo(endDate) == 0) {
return true;
} else {
return false;
}
}
/**
* @Description: 时间段是否有交集
* @Author: Mei
* @date: 2019/10/29 20:07
* @param start
* @param end
* @param fromTime
* @param toTime
* @exception:
* @return: boolean
* @Version: 1.0
*/
public static boolean comparaWith(Date start, Date end, Date fromTime, Date toTime) {
// if(!(toTime.before(start) || fromTime.after(end))){
if (!start.after(toTime) && !end.before(fromTime)) {
return true;
} else {
return false;
}
}
}
|
package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private int inventory;
private int safeinventory;
private String dector;
private String company;
private String date;
private int price;
// JoinColumn refers to the column name in the table
@ManyToOne
@JoinColumn(name = "category")
private BookCategory bookCategory;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getInventory(){
return inventory;
}
public void setInventory(int inventory){
this.inventory = inventory;
}
public int getSafeinventory(){
return safeinventory;
}
public void setSafeinventory(int safeinventory){
this.safeinventory = safeinventory;
}
public String getDector(){
return dector;
}
public void setDector(String dector){
this.dector = dector;
}
public String getCompany(){
return company;
}
public void setCompany(String company){
this.company = company;
}
public String getDate(){
return date;
}
public void setDate(String date){
this.date = date;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public BookCategory getBookCategory() {
return bookCategory;
}
public void setBookCategory(BookCategory bookCategory) {
this.bookCategory = bookCategory;
}
}
|
package pl.edu.agh.cyberwej.data.dao.implementations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
import pl.edu.agh.cyberwej.data.dao.interfaces.GroupDAO;
import pl.edu.agh.cyberwej.data.dao.interfaces.PaymentDAO;
import pl.edu.agh.cyberwej.data.dao.interfaces.PaymentParticipationDAO;
import pl.edu.agh.cyberwej.data.dao.interfaces.UserDAO;
import pl.edu.agh.cyberwej.data.objects.Group;
import pl.edu.agh.cyberwej.data.objects.Payment;
import pl.edu.agh.cyberwej.data.objects.PaymentParticipation;
import pl.edu.agh.cyberwej.data.objects.User;
@ContextConfiguration(locations = { "TestContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class PaymentParticipationDAOImplTest {
@Autowired
private PaymentParticipationDAO paymentParticipationDAO;
@Autowired
private UserDAO userDAO;
@Autowired
private PaymentDAO paymentDAO;
@Autowired
private GroupDAO groupDAO;
private Group group;
private final String groupName = "Pierwsza grupa";
private User user;
private final String name = "Marek";
private final String surname = "Markowski";
private final String mail = "marek@markowie.pl";
private final String login = "Marek";
private Payment payment;
private Date date;
private final String description = "Wyjscie na 2 pizze";
private final float amount = 3.45f;
private final float newAmount = 2.50f;
@BeforeTransaction
public void setUp() {
this.user = new User();
this.user.setSurname(this.surname);
this.user.setName(this.name);
this.user.setLogin(this.login);
this.user.setMail(this.mail);
this.payment = new Payment();
this.payment.setDate(this.date);
this.payment.setDescription(this.description);
this.group = new Group();
this.group.setName(this.groupName);
this.userDAO.saveUser(this.user);
this.groupDAO.saveGroup(this.group);
this.groupDAO.addGroupPayment(this.group, this.payment);
this.paymentDAO.addPaymentParticipation(this.payment, this.user, this.amount);
}
@Test
@Transactional
@Rollback(true)
public void testSave() {
Group retrievedGroup = this.groupDAO.getGroupByName(this.groupName);
assertNotNull(retrievedGroup);
assertNotNull(retrievedGroup.getPayments());
assertFalse(retrievedGroup.getPayments().isEmpty());
for (Payment payment : retrievedGroup.getPayments()) {
assertFalse(payment.getParticipations().isEmpty());
for (PaymentParticipation paymentParticipation : payment.getParticipations()) {
assertEquals(paymentParticipation.getAmount(), this.amount, 0.0f);
paymentParticipation.setAmount(this.newAmount);
this.paymentParticipationDAO.save(paymentParticipation);
}
}
retrievedGroup = this.groupDAO.getGroupByName(this.groupName);
assertNotNull(retrievedGroup);
assertNotNull(retrievedGroup.getPayments());
assertFalse(retrievedGroup.getPayments().isEmpty());
for (Payment payment : retrievedGroup.getPayments()) {
assertFalse(payment.getParticipations().isEmpty());
for (PaymentParticipation paymentParticipation : payment.getParticipations())
assertEquals(paymentParticipation.getAmount(), this.newAmount, 0.0f);
}
}
@AfterTransaction
public void clean() {
Group group = this.groupDAO.getGroupByName(this.groupName);
this.groupDAO.removeGroup(group);
this.userDAO.removeUser(this.user);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Modelo.TelefoneModelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import util.ConexaoBD;
/**
*
* @author azm
*/
public class TelefoneDAO
{
private Connection conexaoBD;
public TelefoneDAO () throws ClassNotFoundException, SQLException
{
this.conexaoBD = new ConexaoBD ().getConnection ();
}
public boolean inserirTelefone (TelefoneModelo telefoneModelo) throws SQLException
{
String sql = "INSERT INTO public.telefone(\n"
+ " numero)\n"
+ " VALUES (?);";
try (PreparedStatement pst = conexaoBD.prepareStatement (sql))
{
pst.setString (1, telefoneModelo.getNumero ());
pst.execute ();
pst.close ();
}
return false;
}
public int pegarUltimoTelefone () throws SQLException
{
try (PreparedStatement pst = this.conexaoBD.prepareStatement ("SELECT MAX(PUBLIC.telefone.telefone_pk) FROM PUBLIC.telefone"))
{
ResultSet rs = pst.executeQuery ();
rs.next ();
return rs.getInt (1);
}
}
public TelefoneModelo getTelefone (int telefone_pk) throws SQLException
{
try (PreparedStatement pst = conexaoBD.prepareStatement ("SELECT * FROM public.telefone WHERE telefone_pk=" + telefone_pk))
{
ResultSet rs = pst.executeQuery ();
rs.next ();
if (rs.getInt ("telefone_pk") > 0)
{
TelefoneModelo telefoneModelo = new TelefoneModelo ();
telefoneModelo.setTelefone_pk (rs.getInt ("telefone_pk"));
telefoneModelo.setNumero (rs.getString ("numero"));
return telefoneModelo;
}
}
return null;
}
}
|
package com.company;
public class Ijedos extends Panda {
public void action(Jatek j) {//Ha megijed
logger.depthP();
logger.writeMessage(this.toString()+".Action("+j.toString()+")");
if (getHand1() != null)
{
release();//Elengedi a kezeket
}
logger.depthM();
}
}
|
package dw2.projetweb.servlets;
import dw2.projetweb.beans.Fichier;
import dw2.projetweb.forms.FormFichier;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
@WebServlet("/FichierUpload")
@MultipartConfig(maxFileSize = 10485760, maxRequestSize = 52428800,fileSizeThreshold = 1048576)
public class FichierUpload extends HttpServlet
{
public static final String VUE = "/WEB-INF/Site/editeurP.jsp";
public static final String CHEMIN = "chemin";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
this.getServletContext().getRequestDispatcher(VUE).forward(req, res);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Path path = Paths.get(req.getServletContext().getRealPath("Documents"));
FormFichier f = new FormFichier();
Fichier file = f.saveFile(req, path);
req.setAttribute("form", f);
req.setAttribute("fichier", file);
this.getServletContext().getRequestDispatcher(VUE).forward(req, res);
}
}
|
package home_work_2.txt.arrays;
public class Txt_4_3_TestSortUtills {
public static void main(String[] args) {
SortUtils sort = new SortUtils();
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {1, 1, 1, 1};
int[] arr3 = {9, 1, 5, 99, 9, 9};
int[] arr4 = {};
//пузырек
System.out.println("Пузырек");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.bubbleSorter(arr1);
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr2) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.bubbleSorter(arr2);
for (int i : arr2) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr3) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.bubbleSorter(arr3);
for (int i : arr3) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr4) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.bubbleSorter(arr4);
for (int i : arr4) {
System.out.print(i + " ");
}
System.out.println();
// шейкерная
System.out.println("Шейкерная");
int[] arr5 = {1, 2, 3, 4, 5, 6};
int[] arr6 = {1, 1, 1, 1};
int[] arr7 = {9, 1, 5, 99, 9, 9};
int[] arr8 = {};
for (int i : arr5) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.shakerSorter(arr5);
for (int i : arr5) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr6) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.shakerSorter(arr6);
for (int i : arr6) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr7) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.shakerSorter(arr7);
for (int i : arr7) {
System.out.print(i + " ");
}
System.out.println();
for (int i : arr8) {
System.out.print(i + " ");
}
System.out.print("-> ");
sort.shakerSorter(arr8);
for (int i : arr8) {
System.out.print(i + " ");
}
System.out.println();
}
}
|
package it.sevenbits.codecorrector.formatter;
import it.sevenbits.codecorrector.reader.IReader;
import it.sevenbits.codecorrector.reader.ReaderException;
import it.sevenbits.codecorrector.writer.IWriter;
import it.sevenbits.codecorrector.writer.WriterException;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
/**
* Class NewFormatterTest
* Tests NewFormatter class
*/
public class NewFormatterTest {
@Test
public void testFormatIncorrectString() throws Exception {
String testUnformattedString = "package blablabla;" +
" import blablabla; " +
"public static void main(){{\tblablabla ;\n" +
"int[] array = new int[]{12, 14, 15, 16, 17, 123};" +
"if (check == true){;return blabla;}int index = 0;}";
StringBuilder testFormatResult = new StringBuilder();
IReader mockReader = mock(IReader.class);
when(mockReader.read()).thenAnswer(new Answer<Character>() {
private int index = 0;
public Character answer(InvocationOnMock invocation) {
return testUnformattedString.charAt(index++);
}
});
when(mockReader.hasNext()).thenAnswer(new Answer<Boolean>() {
private int index = 0;
public Boolean answer(InvocationOnMock invocation) {
return index++ < testUnformattedString.length();
}
});
IWriter mockWriter = mock(IWriter.class);
doAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
testFormatResult.append(invocation.getArguments()[0]);
return testFormatResult.toString();
}
}).when(mockWriter).write(anyString());
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
when(mockProperties.getSpace()).thenReturn(" ");
when(mockProperties.getEndLine()).thenReturn("\n");
when(mockProperties.getIndentStartLevel()).thenReturn(0);
NewFormatter formatter = new NewFormatter(mockProperties);
formatter.format(mockReader, mockWriter);
assertEquals("wrong result.",
"package blablabla;\n" +
"import blablabla;\n" +
"public static void main() {\n" +
" blablabla;\n" +
" int[] array = new int[] {\n" +
" 12, 14, 15, 16, 17, 123\n" +
" };\n" +
" if (check == true) {\n" +
" return blabla;\n" +
" }\n" +
" int index = 0;\n" +
"}", testFormatResult.toString());
}
@Test
public void testFormatCorrectString() throws Exception {
String testUnformattedString = "package blablabla;\n" +
"import blablabla;\n" +
"public static void main() {\n" +
" blablabla;\n" +
" int[] array = new int[] {\n" +
" 12, 14, 15, 16, 17, 123\n" +
" };\n" +
" if (check == true) {\n" +
" return blabla;\n" +
" }\n" +
"}";
StringBuilder testFormatResult = new StringBuilder();
IReader mockReader = mock(IReader.class);
when(mockReader.read()).thenAnswer(new Answer<Character>() {
private int index = 0;
public Character answer(InvocationOnMock invocation) {
return testUnformattedString.charAt(index++);
}
});
when(mockReader.hasNext()).thenAnswer(new Answer<Boolean>() {
private int index = 0;
public Boolean answer(InvocationOnMock invocation) {
return index++ < testUnformattedString.length();
}
});
IWriter mockWriter = mock(IWriter.class);
doAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
testFormatResult.append(invocation.getArguments()[0]);
return testFormatResult.toString();
}
}).when(mockWriter).write(anyString());
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
when(mockProperties.getSpace()).thenReturn(" ");
when(mockProperties.getEndLine()).thenReturn("\n");
when(mockProperties.getIndentStartLevel()).thenReturn(0);
NewFormatter formatter = new NewFormatter(mockProperties);
formatter.format(mockReader, mockWriter);
assertEquals("wrong result.",
"package blablabla;\n" +
"import blablabla;\n" +
"public static void main() {\n" +
" blablabla;\n" +
" int[] array = new int[] {\n" +
" 12, 14, 15, 16, 17, 123\n" +
" };\n" +
" if (check == true) {\n" +
" return blabla;\n" +
" }\n" +
"}", testFormatResult.toString());
}
@Test
public void testFormatEmptyString() throws Exception {
String testUnformattedString = "";
StringBuilder testFormatResult = new StringBuilder();
IReader mockReader = mock(IReader.class);
when(mockReader.read()).thenAnswer(new Answer<Character>() {
private int index = 0;
public Character answer(InvocationOnMock invocation) {
return testUnformattedString.charAt(index++);
}
});
when(mockReader.hasNext()).thenAnswer(new Answer<Boolean>() {
private int index = 0;
public Boolean answer(InvocationOnMock invocation) {
return index++ < testUnformattedString.length();
}
});
IWriter mockWriter = mock(IWriter.class);
doAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
testFormatResult.append(invocation.getArguments()[0]);
return testFormatResult.toString();
}
}).when(mockWriter).write(anyString());
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
when(mockProperties.getSpace()).thenReturn(" ");
when(mockProperties.getEndLine()).thenReturn("\n");
when(mockProperties.getIndentStartLevel()).thenReturn(0);
NewFormatter formatter = new NewFormatter(mockProperties);
formatter.format(mockReader, mockWriter);
assertEquals("wrong result.",
"", testFormatResult.toString());
}
@Test(expected = FormatException.class)
public void testCatchReaderExceptionFormatString() throws Exception {
IReader mockReader = mock(IReader.class);
when(mockReader.read()).thenThrow(new ReaderException());
when(mockReader.hasNext()).thenThrow(new ReaderException());
IWriter mockWriter = mock(IWriter.class);
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
when(mockProperties.getSpace()).thenReturn(" ");
when(mockProperties.getEndLine()).thenReturn("\n");
when(mockProperties.getIndentStartLevel()).thenReturn(0);
NewFormatter formatter = new NewFormatter(mockProperties);
formatter.format(mockReader, mockWriter);
fail();
}
@Test(expected = FormatException.class)
public void testCatchWriterExceptionFormatString() throws Exception {
IReader mockReader = mock(IReader.class);
when(mockReader.read()).thenReturn('a', 'b', ';');
when(mockReader.hasNext()).thenReturn(true, true, true, false);
IWriter mockWriter = mock(IWriter.class);
doThrow(new WriterException()).when(mockWriter).write(anyString());
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
when(mockProperties.getSpace()).thenReturn(" ");
when(mockProperties.getEndLine()).thenReturn("\n");
when(mockProperties.getIndentStartLevel()).thenReturn(0);
NewFormatter formatter = new NewFormatter(mockProperties);
formatter.format(mockReader, mockWriter);
fail();
}
}
|
package forms;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
public class PriorityForm {
private int id;
private int version;
private String titleES;
private String titleEN;
public int getId() {
return this.id;
}
public void setId(final int id) {
this.id = id;
}
public int getVersion() {
return this.version;
}
public void setVersion(final int version) {
this.version = version;
}
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getTitleES() {
return this.titleES;
}
public void setTitleES(final String titleES) {
this.titleES = titleES;
}
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getTitleEN() {
return this.titleEN;
}
public void setTitleEN(final String titleEN) {
this.titleEN = titleEN;
}
}
|
package com.zhouqi.schedule.util;
import java.util.Collection;
public class CollectionHelper {
public static <T, S, C extends Collection<T>, D extends Collection<S>> C filter(D source, C target, IFilter<S, T> filter) {
if (source == null || source.size() == 0)
return target;
int index = 0;
for (S v : source) {
T tv = filter.filter(v, index++);
if (tv != null) {
target.add(tv);
}
}
return target;
}
}
|
package uk.ac.ebi.intact.view.webapp.controller.browse;
import org.apache.myfaces.orchestra.conversation.annotations.ConversationName;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import uk.ac.ebi.intact.bridges.ontologies.term.OntologyTerm;
import uk.ac.ebi.intact.dataexchange.psimi.solr.FieldNames;
import uk.ac.ebi.intact.dataexchange.psimi.solr.ontology.OntologySearcher;
import uk.ac.ebi.intact.view.webapp.util.RootTerm;
/**
* Browser for annotation topic
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>03/09/12</pre>
*/
@Controller("annotationTopicBrowser")
@Scope("conversation.access")
@ConversationName("general")
public class AnnotationTopicBrowser extends OntologyBrowserController {
public static final String FIELD_NAME = FieldNames.INTERACTION_ANNOTATIONS;
public AnnotationTopicBrowser(){
super();
this.useName = true;
}
@Override
// give the first root term because we need to add terms which are not considered as children of interaction attributes
protected OntologyTerm createRootTerm(OntologySearcher ontologySearcher) {
final RootTerm rootTerm = new RootTerm( ontologySearcher, "Interaction annotation topics" );
rootTerm.addChild("MI:0664", "interaction attribute name");
// not real interaction attributes in the ontology but are used as interaction annotation topics
rootTerm.addChild("MI:1045", "curation content");
rootTerm.addChild("MI:0954", "curation quality");
// annotations normally at the level of publication but are copied to interaction
rootTerm.addChild("MI:1093", "bibliographic attribute name");
return rootTerm;
}
@Override
public String getFieldName() {
return FIELD_NAME;
}
}
|
package com.mediafire.sdk;
public interface MediaFireHttpRequester {
MediaFireHttpResponse get(MediaFireHttpRequest request) throws MediaFireException;
MediaFireHttpResponse post(MediaFireHttpRequest request) throws MediaFireException;
MediaFireHttpsAgent getHttpsAgent();
}
|
package sty.studyAOP;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Aspect
@Order(1) //数字越小优先级越高
public class LoggingAspect {
/**
* 声明切入点表达式
*/
@Pointcut("execution(* sty.studyAOP.*.*(..))")
public void declarePointCut(){}
/**
* 前置通知
*/
@Before(value = "declarePointCut()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("LoggingAspect===> The Method " + methodName + " begin.");
}
/**
* 后置通知
*/
@After(value = "execution(* sty.studyAOP.*.*(..))")//可以作用于该包下的任意方法
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logging Aspect===> The Method " + methodName + " end.");
}
/**
* 返回通知
*/
@AfterReturning(value = "execution(* sty.studyAOP.*.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Logging Aspect===> the method " + methodName + " end with:" + result);
}
/**
* 异常通知
*/
@AfterThrowing(value = "execution(* sty.studyAOP.*.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) {
String name = joinPoint.getSignature().getName();
System.out.println("Logging Aspect===> the method " + name + " occurs Exception: " + ex);
}
/**
* 环绕通知
*/
@Around(value = "execution(* sty.studyAOP.*.*(..))")
public Object aroundMehod(ProceedingJoinPoint pjp) {
try {
//前置通知
Object obj = pjp.proceed();
//返回通知
return obj;
} catch (Throwable throwable) {
//异常通知
throwable.printStackTrace();
} finally {
//后置通知
}
return null;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Presentation;
import Domain.Controller;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
/**
*
* @author Aaron
*/
public class GUI extends javax.swing.JFrame {
Controller con = new Controller();
DefaultListModel model1, model2, model3, model4, model5, model6, model7, model8, model9;
private int userRank;
private boolean lockCustomer;
/**
* Creates new form GUI
*/
public GUI() {
initComponents();
con.buildUserList();
model1 = new DefaultListModel();
model2 = new DefaultListModel();
model3 = new DefaultListModel();
model4 = new DefaultListModel();
model5 = new DefaultListModel();
model6 = new DefaultListModel();
model7 = new DefaultListModel();
model8 = new DefaultListModel();
model9 = new DefaultListModel();
LogInPanel.setVisible(true);
MainPanel.setVisible(false);
CustomerPanel.setVisible(false);
ProductPanel.setVisible(false);
OrderPanel.setVisible(false);
EditOrderPanel.setVisible(false);
PickUpOrTruckOrderPanel.setVisible(false);
PackagePanel.setVisible(false);
EditPackagePanel.setVisible(false);
NavigationDropMenu.setEnabled(false);
AdminDropMenu.setEnabled(false);
}
/**
* 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() {
jMenuItem1 = new javax.swing.JMenuItem();
MainPanel = new javax.swing.JPanel();
CustomerMenuButton = new javax.swing.JButton();
ProductMenuButton = new javax.swing.JButton();
OrderMenuButton = new javax.swing.JButton();
MainMenuLabel = new javax.swing.JLabel();
PackageMenuButton = new javax.swing.JButton();
CustomerPanel = new javax.swing.JPanel();
CustomerMenuLabel = new javax.swing.JLabel();
CutomerIDLabel = new javax.swing.JLabel();
CustomerIDField = new javax.swing.JTextField();
CustomerNameLabel = new javax.swing.JLabel();
CustomerNameField = new javax.swing.JTextField();
CustomerAddressLabel = new javax.swing.JLabel();
CustomerAddressField = new javax.swing.JTextField();
CustomerEmailLabel = new javax.swing.JLabel();
CustomerEmailField = new javax.swing.JTextField();
CustPhoneLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
CustPhoneTextArea = new javax.swing.JTextArea();
AddCustomerButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
CustomerJList = new javax.swing.JList();
ExistingCustLabel = new javax.swing.JLabel();
AddEditPhoneButton = new javax.swing.JButton();
SaveCustomerChangeButton = new javax.swing.JButton();
GetCustomerButton = new javax.swing.JButton();
EditCustomerButton = new javax.swing.JButton();
DeleteCustomerbutton = new javax.swing.JButton();
ProductPanel = new javax.swing.JPanel();
ProductMenuLabel = new javax.swing.JLabel();
ProductIDField = new javax.swing.JTextField();
ProductIDLabel = new javax.swing.JLabel();
ProductNameLabel = new javax.swing.JLabel();
ProductNameField = new javax.swing.JTextField();
ProductVolumeLabel = new javax.swing.JLabel();
ProductVolumeField = new javax.swing.JTextField();
ProductQtyLabel = new javax.swing.JLabel();
ProductQuantityField = new javax.swing.JTextField();
ProductPriceLabel = new javax.swing.JLabel();
ProductPriceField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
ProductDescriptionField = new javax.swing.JTextField();
AddProductButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
ProductJList = new javax.swing.JList();
productListLabel = new javax.swing.JLabel();
GetProductsButton = new javax.swing.JButton();
DeleteProductButton = new javax.swing.JButton();
EditProductButton = new javax.swing.JButton();
SaveProductChangesButton = new javax.swing.JButton();
SearchForAProduct = new javax.swing.JPanel();
ProductSearchID = new javax.swing.JLabel();
ProductIDSearchField = new javax.swing.JTextField();
ProductSearchName = new javax.swing.JLabel();
ProductNameSearchField = new javax.swing.JTextField();
SearchForProductIDButton = new javax.swing.JButton();
SearchForProductNameButton = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
OrderPanel = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
CustIDField = new javax.swing.JTextField();
CustNameField = new javax.swing.JTextField();
jScrollPane10 = new javax.swing.JScrollPane();
CustDetailsArea = new javax.swing.JTextArea();
jLabel9 = new javax.swing.JLabel();
GetCustomersButton = new javax.swing.JButton();
jScrollPane12 = new javax.swing.JScrollPane();
jScrollPane11 = new javax.swing.JScrollPane();
ExistingCustomersList = new javax.swing.JList();
CreateOrderButton = new javax.swing.JButton();
AddCutomerToOrderButton = new javax.swing.JButton();
OrderStartDateField = new javax.swing.JTextField();
OrderStartDateLabel = new javax.swing.JLabel();
OrderEndDateLabel = new javax.swing.JLabel();
OrderEndDateField = new javax.swing.JTextField();
EditOrderPanel = new javax.swing.JPanel();
OrderMenuLabel = new javax.swing.JLabel();
OrderProductNameSearchField = new javax.swing.JTextField();
OrdergetAllProductsButton = new javax.swing.JButton();
OrderProductNameLabel = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
OrderProductsList = new javax.swing.JList();
jScrollPane5 = new javax.swing.JScrollPane();
OrderProductsInOrderList = new javax.swing.JList();
OrderQuantitySpinner = new javax.swing.JSpinner();
OrderProductQuantityLabel = new javax.swing.JLabel();
OrderAddProductToOrderButton = new javax.swing.JButton();
OrderRemoveFromOrderButton = new javax.swing.JButton();
OrderCustomerIDField = new javax.swing.JTextField();
OrderCustomerIDLabel = new javax.swing.JLabel();
OrderSaveOrderButton = new javax.swing.JButton();
OrderIDLabel = new javax.swing.JLabel();
OrderIDField = new javax.swing.JTextField();
OrderProductSearchButton = new javax.swing.JButton();
runningTotalField = new javax.swing.JTextField();
runningTotalLabel = new javax.swing.JLabel();
PickUpOrTruckOrderPanel = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
StartDateField = new javax.swing.JTextField();
FinishDateField = new javax.swing.JTextField();
jScrollPane13 = new javax.swing.JScrollPane();
AvailableTrucksList = new javax.swing.JList();
GetAvailableTrucksButton = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
PickUpOrderButton = new javax.swing.JButton();
TruckOrderButton = new javax.swing.JButton();
PackagePanel = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
PackageIDLabel = new javax.swing.JLabel();
PackageIDField = new javax.swing.JTextField();
PackageNameLabel = new javax.swing.JLabel();
PackageNameField = new javax.swing.JTextField();
PackageDiscLabel = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
PackageDescTextArea = new javax.swing.JTextArea();
PackagePriceLabel = new javax.swing.JLabel();
PackagePriceField = new javax.swing.JTextField();
AddPackageButton = new javax.swing.JButton();
ExistingPackLabel = new javax.swing.JLabel();
jScrollPane7 = new javax.swing.JScrollPane();
PackageJList = new javax.swing.JList();
ExistingPackageButton = new javax.swing.JButton();
EditPackageButton = new javax.swing.JButton();
EditPackProdButton = new javax.swing.JButton();
DeletePackageButton = new javax.swing.JButton();
EditPackagePanel = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
PackageIDLabel2 = new javax.swing.JLabel();
PackageIDField2 = new javax.swing.JTextField();
PackageNameLabel2 = new javax.swing.JLabel();
PackageNameField2 = new javax.swing.JTextField();
PackageGetAllProductButton = new javax.swing.JButton();
OrderProductNameLabel1 = new javax.swing.JLabel();
PackProductNameSearchField = new javax.swing.JTextField();
jScrollPane8 = new javax.swing.JScrollPane();
PackProductsList = new javax.swing.JList();
OrderProductQuantityLabel1 = new javax.swing.JLabel();
OrderQuantitySpinner1 = new javax.swing.JSpinner();
AddProductToPackageButton = new javax.swing.JButton();
RemoveFromPackageButto = new javax.swing.JButton();
jScrollPane9 = new javax.swing.JScrollPane();
ProductsInPackageList = new javax.swing.JList();
SavePackageButton = new javax.swing.JButton();
PackageSearchProductButton = new javax.swing.JButton();
LogInPanel = new javax.swing.JPanel();
LoginMenuLabel = new javax.swing.JLabel();
UserNameLabel = new javax.swing.JLabel();
PasswordLabel = new javax.swing.JLabel();
UserNameField = new javax.swing.JTextField();
PasswordField = new javax.swing.JTextField();
LoginButton = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
FileDropMenu = new javax.swing.JMenu();
ExitDrop = new javax.swing.JMenuItem();
LogOutDrop = new javax.swing.JMenuItem();
NavigationDropMenu = new javax.swing.JMenu();
MainNavDrop = new javax.swing.JMenuItem();
CustNavDrop = new javax.swing.JMenuItem();
ProdNavDrop = new javax.swing.JMenuItem();
OrdNavDrop = new javax.swing.JMenuItem();
PackNavDrop = new javax.swing.JMenuItem();
AdminDropMenu = new javax.swing.JMenu();
UsersDrop = new javax.swing.JMenuItem();
UserRankDrop = new javax.swing.JMenuItem();
jMenuItem1.setText("jMenuItem1");
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setBounds(new java.awt.Rectangle(200, 50, 950, 700));
setMinimumSize(new java.awt.Dimension(950, 700));
getContentPane().setLayout(null);
CustomerMenuButton.setText("Customers");
CustomerMenuButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustomerMenuButtonActionPerformed(evt);
}
});
ProductMenuButton.setText("Products");
ProductMenuButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProductMenuButtonActionPerformed(evt);
}
});
OrderMenuButton.setText("Orders");
OrderMenuButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderMenuButtonActionPerformed(evt);
}
});
MainMenuLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
MainMenuLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
MainMenuLabel.setText("Main Menu");
PackageMenuButton.setText("Packages");
PackageMenuButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackageMenuButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout MainPanelLayout = new javax.swing.GroupLayout(MainPanel);
MainPanel.setLayout(MainPanelLayout);
MainPanelLayout.setHorizontalGroup(
MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(MainPanelLayout.createSequentialGroup()
.addGap(290, 290, 290)
.addGroup(MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainMenuLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(MainPanelLayout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(CustomerMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ProductMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OrderMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PackageMenuButton, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(325, Short.MAX_VALUE))
);
MainPanelLayout.setVerticalGroup(
MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(MainPanelLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(MainMenuLabel)
.addGap(64, 64, 64)
.addComponent(CustomerMenuButton, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ProductMenuButton, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(OrderMenuButton, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(PackageMenuButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(218, Short.MAX_VALUE))
);
getContentPane().add(MainPanel);
MainPanel.setBounds(0, 0, 900, 650);
CustomerMenuLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
CustomerMenuLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
CustomerMenuLabel.setText("Customer Menu");
CutomerIDLabel.setText("Customer ID");
CustomerIDField.setEditable(false);
CustomerIDField.setBackground(new java.awt.Color(204, 204, 255));
CustomerNameLabel.setText("Customer Name");
CustomerAddressLabel.setText("Customer Address");
CustomerEmailLabel.setText("Customer Email");
CustPhoneLabel.setText("Customer Phone Numbers");
CustPhoneTextArea.setColumns(20);
CustPhoneTextArea.setRows(5);
jScrollPane1.setViewportView(CustPhoneTextArea);
AddCustomerButton.setText("Add Customer");
AddCustomerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddCustomerButtonActionPerformed(evt);
}
});
jScrollPane2.setViewportView(CustomerJList);
ExistingCustLabel.setText("Existing Cutomers");
AddEditPhoneButton.setText("Add / Edit Phone Number");
AddEditPhoneButton.setEnabled(false);
SaveCustomerChangeButton.setText("Save Changes");
SaveCustomerChangeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveCustomerChangeButtonActionPerformed(evt);
}
});
GetCustomerButton.setText("Get Exisitng Customer List");
GetCustomerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GetCustomerButtonActionPerformed(evt);
}
});
EditCustomerButton.setText("Edit Selected Customer");
EditCustomerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EditCustomerButtonActionPerformed(evt);
}
});
DeleteCustomerbutton.setText("Delete Selected Customer");
DeleteCustomerbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeleteCustomerbuttonActionPerformed(evt);
}
});
javax.swing.GroupLayout CustomerPanelLayout = new javax.swing.GroupLayout(CustomerPanel);
CustomerPanel.setLayout(CustomerPanelLayout);
CustomerPanelLayout.setHorizontalGroup(
CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGap(219, 219, 219)
.addComponent(CustomerMenuLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(CustPhoneLabel)
.addComponent(CustomerEmailLabel)
.addComponent(CutomerIDLabel)
.addComponent(CustomerIDField, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustomerNameLabel)
.addComponent(CustomerNameField)
.addComponent(CustomerAddressLabel)
.addComponent(CustomerAddressField)
.addComponent(CustomerEmailField)
.addComponent(jScrollPane1)
.addComponent(AddCustomerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AddEditPhoneButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SaveCustomerChangeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(50, 50, 50)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ExistingCustLabel)
.addComponent(GetCustomerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EditCustomerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeleteCustomerbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap(143, Short.MAX_VALUE))
);
CustomerPanelLayout.setVerticalGroup(
CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(CustomerMenuLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CutomerIDLabel)
.addComponent(ExistingCustLabel))
.addGap(18, 18, 18)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addComponent(CustomerIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(CustomerNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustomerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(CustomerAddressLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustomerAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(CustomerEmailLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustomerEmailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(CustPhoneLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(AddCustomerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AddEditPhoneButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SaveCustomerChangeButton))
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addComponent(GetCustomerButton)
.addGroup(CustomerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(EditCustomerButton)
.addGap(18, 18, 18)
.addComponent(DeleteCustomerbutton))
.addGroup(CustomerPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(71, Short.MAX_VALUE))
);
getContentPane().add(CustomerPanel);
CustomerPanel.setBounds(0, 0, 900, 620);
ProductPanel.setMinimumSize(new java.awt.Dimension(850, 700));
ProductMenuLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
ProductMenuLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
ProductMenuLabel.setText("Product Menu");
ProductIDField.setEditable(false);
ProductIDField.setBackground(new java.awt.Color(204, 204, 255));
ProductIDLabel.setText("Product ID");
ProductNameLabel.setText("Product Name");
ProductVolumeLabel.setText("Product Volume");
ProductQtyLabel.setText("Product Quantity ");
ProductPriceLabel.setText("Product Price");
jLabel1.setText("Product Description");
AddProductButton.setText("Add New Product");
AddProductButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddProductButtonActionPerformed(evt);
}
});
jScrollPane3.setViewportView(ProductJList);
productListLabel.setText("Existing Product list");
GetProductsButton.setText("Get Product List");
GetProductsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GetProductsButtonActionPerformed(evt);
}
});
DeleteProductButton.setText("Delete Product");
DeleteProductButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeleteProductButtonActionPerformed(evt);
}
});
EditProductButton.setText("Edit Selected Product");
EditProductButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EditProductButtonActionPerformed(evt);
}
});
SaveProductChangesButton.setText("Save Changes");
SaveProductChangesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveProductChangesButtonActionPerformed(evt);
}
});
SearchForAProduct.setBorder(javax.swing.BorderFactory.createEtchedBorder());
ProductSearchID.setText("Product ID:");
ProductSearchName.setText("Product Name:");
ProductNameSearchField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProductNameSearchFieldActionPerformed(evt);
}
});
SearchForProductIDButton.setText("Search By ID");
SearchForProductIDButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SearchForProductIDButtonActionPerformed(evt);
}
});
SearchForProductNameButton.setText("Search By Name");
SearchForProductNameButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SearchForProductNameButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout SearchForAProductLayout = new javax.swing.GroupLayout(SearchForAProduct);
SearchForAProduct.setLayout(SearchForAProductLayout);
SearchForAProductLayout.setHorizontalGroup(
SearchForAProductLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SearchForAProductLayout.createSequentialGroup()
.addContainerGap()
.addGroup(SearchForAProductLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SearchForAProductLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(ProductSearchID)
.addComponent(ProductIDSearchField)
.addComponent(ProductSearchName)
.addComponent(ProductNameSearchField, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE))
.addComponent(SearchForProductIDButton, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SearchForProductNameButton, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
SearchForAProductLayout.setVerticalGroup(
SearchForAProductLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SearchForAProductLayout.createSequentialGroup()
.addComponent(ProductSearchID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductIDSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SearchForProductIDButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(ProductSearchName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductNameSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SearchForProductNameButton)
.addGap(20, 20, 20))
);
jLabel4.setText("Search For Product");
javax.swing.GroupLayout ProductPanelLayout = new javax.swing.GroupLayout(ProductPanel);
ProductPanel.setLayout(ProductPanelLayout);
ProductPanelLayout.setHorizontalGroup(
ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ProductPanelLayout.createSequentialGroup()
.addContainerGap(50, Short.MAX_VALUE)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ProductPanelLayout.createSequentialGroup()
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(ProductIDLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProductNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProductVolumeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddProductButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ProductDescriptionField)
.addComponent(ProductPriceField)
.addComponent(ProductQuantityField)
.addComponent(ProductVolumeField)
.addComponent(ProductIDField, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProductNameField)
.addComponent(ProductQtyLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProductPriceLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SaveProductChangesButton, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(74, 74, 74)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(productListLabel)
.addGroup(ProductPanelLayout.createSequentialGroup()
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(GetProductsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(DeleteProductButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EditProductButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SearchForAProduct, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ProductPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProductMenuLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(272, 272, 272)))
.addGap(34, 34, 34))
);
ProductPanelLayout.setVerticalGroup(
ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ProductPanelLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(ProductMenuLabel)
.addGap(26, 26, 26)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(productListLabel)
.addComponent(ProductIDLabel))
.addGap(7, 7, 7)
.addGroup(ProductPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ProductPanelLayout.createSequentialGroup()
.addComponent(ProductIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ProductNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ProductVolumeLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductVolumeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ProductQtyLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductQuantityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ProductPriceLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ProductDescriptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(AddProductButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(SaveProductChangesButton))
.addGroup(ProductPanelLayout.createSequentialGroup()
.addComponent(GetProductsButton)
.addGap(15, 15, 15)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 395, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(ProductPanelLayout.createSequentialGroup()
.addComponent(SearchForAProduct, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(EditProductButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(DeleteProductButton)))
.addContainerGap(139, Short.MAX_VALUE))
);
getContentPane().add(ProductPanel);
ProductPanel.setBounds(0, 0, 850, 700);
OrderPanel.setMinimumSize(new java.awt.Dimension(910, 707));
OrderPanel.setLayout(null);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel5.setText("Order Menu");
OrderPanel.add(jLabel5);
jLabel5.setBounds(324, 39, 214, 44);
jLabel6.setText("Customer ID:");
OrderPanel.add(jLabel6);
jLabel6.setBounds(570, 180, 90, 14);
jLabel7.setText("Customer name:");
OrderPanel.add(jLabel7);
jLabel7.setBounds(570, 240, 110, 14);
jLabel8.setText("Customer details:");
OrderPanel.add(jLabel8);
jLabel8.setBounds(570, 380, 110, 14);
CustIDField.setEditable(false);
OrderPanel.add(CustIDField);
CustIDField.setBounds(570, 200, 130, 30);
CustNameField.setEditable(false);
OrderPanel.add(CustNameField);
CustNameField.setBounds(570, 260, 230, 30);
CustDetailsArea.setEditable(false);
CustDetailsArea.setColumns(20);
CustDetailsArea.setRows(5);
CustDetailsArea.setWrapStyleWord(true);
jScrollPane10.setViewportView(CustDetailsArea);
OrderPanel.add(jScrollPane10);
jScrollPane10.setBounds(570, 400, 240, 170);
jLabel9.setText("Existing customers:");
OrderPanel.add(jLabel9);
jLabel9.setBounds(50, 190, 120, 14);
GetCustomersButton.setText("Get Customers");
GetCustomersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GetCustomersButtonActionPerformed(evt);
}
});
OrderPanel.add(GetCustomersButton);
GetCustomersButton.setBounds(50, 160, 220, 23);
jScrollPane11.setViewportView(ExistingCustomersList);
jScrollPane12.setViewportView(jScrollPane11);
OrderPanel.add(jScrollPane12);
jScrollPane12.setBounds(50, 210, 260, 410);
CreateOrderButton.setText("Create Order");
CreateOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreateOrderButtonActionPerformed(evt);
}
});
OrderPanel.add(CreateOrderButton);
CreateOrderButton.setBounds(570, 590, 119, 23);
AddCutomerToOrderButton.setText("Add Customer To Order");
AddCutomerToOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddCutomerToOrderButtonActionPerformed(evt);
}
});
OrderPanel.add(AddCutomerToOrderButton);
AddCutomerToOrderButton.setBounds(360, 360, 170, 23);
OrderPanel.add(OrderStartDateField);
OrderStartDateField.setBounds(640, 300, 104, 30);
OrderStartDateLabel.setText("Start Date:");
OrderPanel.add(OrderStartDateLabel);
OrderStartDateLabel.setBounds(570, 310, 61, 14);
OrderEndDateLabel.setText("End Date:");
OrderPanel.add(OrderEndDateLabel);
OrderEndDateLabel.setBounds(570, 350, 61, 14);
OrderPanel.add(OrderEndDateField);
OrderEndDateField.setBounds(640, 340, 104, 30);
getContentPane().add(OrderPanel);
OrderPanel.setBounds(0, 0, 910, 707);
EditOrderPanel.setMinimumSize(new java.awt.Dimension(850, 700));
EditOrderPanel.setPreferredSize(new java.awt.Dimension(850, 700));
OrderMenuLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
OrderMenuLabel.setText("Edit Order Menu");
OrdergetAllProductsButton.setText("Get All Products");
OrdergetAllProductsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrdergetAllProductsButtonActionPerformed(evt);
}
});
OrderProductNameLabel.setText("Product Name:");
jScrollPane4.setViewportView(OrderProductsList);
jScrollPane5.setViewportView(OrderProductsInOrderList);
OrderProductQuantityLabel.setText("Quantity:");
OrderAddProductToOrderButton.setText("Add selected to Order -->");
OrderAddProductToOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderAddProductToOrderButtonActionPerformed(evt);
}
});
OrderRemoveFromOrderButton.setText("Remove selected form order");
OrderRemoveFromOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderRemoveFromOrderButtonActionPerformed(evt);
}
});
OrderCustomerIDField.setEditable(false);
OrderCustomerIDField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderCustomerIDFieldActionPerformed(evt);
}
});
OrderCustomerIDLabel.setText("CustomerID:");
OrderSaveOrderButton.setText("Save Order");
OrderSaveOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderSaveOrderButtonActionPerformed(evt);
}
});
OrderIDLabel.setText("OrderID:");
OrderIDField.setEditable(false);
OrderIDField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderIDFieldActionPerformed(evt);
}
});
OrderProductSearchButton.setText("Search");
OrderProductSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderProductSearchButtonActionPerformed(evt);
}
});
runningTotalField.setEditable(false);
runningTotalField.setText("0");
runningTotalLabel.setText("Total:");
javax.swing.GroupLayout EditOrderPanelLayout = new javax.swing.GroupLayout(EditOrderPanel);
EditOrderPanel.setLayout(EditOrderPanelLayout);
EditOrderPanelLayout.setHorizontalGroup(
EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(291, 291, 291)
.addComponent(OrderMenuLabel))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(OrderProductQuantityLabel)
.addGap(4, 4, 4)
.addComponent(OrderQuantitySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(OrdergetAllProductsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addComponent(OrderProductNameLabel)
.addGap(4, 4, 4)
.addComponent(OrderProductNameSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(10, 10, 10)
.addComponent(OrderProductSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(6, 6, 6)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderAddProductToOrderButton, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderRemoveFromOrderButton))
.addGap(18, 18, 18)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(OrderSaveOrderButton))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(OrderCustomerIDLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(runningTotalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OrderIDLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderIDField, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCustomerIDField, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(runningTotalField, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGap(34, 34, 34))
);
EditOrderPanelLayout.setVerticalGroup(
EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(OrderMenuLabel)
.addGap(13, 13, 13)
.addComponent(OrdergetAllProductsButton)
.addGap(6, 6, 6)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(OrderProductNameLabel))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderProductNameSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderProductSearchButton)))
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderIDLabel)
.addComponent(OrderIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(4, 4, 4)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(OrderProductQuantityLabel))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(OrderQuantitySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(OrderAddProductToOrderButton)
.addGap(67, 67, 67)
.addComponent(OrderRemoveFromOrderButton))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditOrderPanelLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(OrderCustomerIDLabel))
.addComponent(OrderCustomerIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(EditOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(runningTotalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(runningTotalLabel))
.addGap(152, 152, 152)
.addComponent(OrderSaveOrderButton))))
);
getContentPane().add(EditOrderPanel);
EditOrderPanel.setBounds(0, 0, 850, 700);
PickUpOrTruckOrderPanel.setMinimumSize(new java.awt.Dimension(700, 500));
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel10.setText("Pick Up Or Truck Order");
jScrollPane13.setViewportView(AvailableTrucksList);
GetAvailableTrucksButton.setText("Get Trucks");
GetAvailableTrucksButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GetAvailableTrucksButtonActionPerformed(evt);
}
});
jLabel11.setText("Startdate:");
jLabel12.setText("Finishdate:");
PickUpOrderButton.setText("Order Pick Up");
PickUpOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PickUpOrderButtonActionPerformed(evt);
}
});
TruckOrderButton.setText("Order TruckDelivery");
TruckOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
TruckOrderButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout PickUpOrTruckOrderPanelLayout = new javax.swing.GroupLayout(PickUpOrTruckOrderPanel);
PickUpOrTruckOrderPanel.setLayout(PickUpOrTruckOrderPanelLayout);
PickUpOrTruckOrderPanelLayout.setHorizontalGroup(
PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addComponent(GetAvailableTrucksButton)
.addGap(278, 278, 278)
.addComponent(PickUpOrderButton))
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane13)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addComponent(StartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(FinishDateField))))
.addGap(116, 116, 116)
.addComponent(TruckOrderButton))))
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGap(183, 183, 183)
.addComponent(jLabel10)))
.addContainerGap(196, Short.MAX_VALUE))
);
PickUpOrTruckOrderPanelLayout.setVerticalGroup(
PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(jLabel10)
.addGap(51, 51, 51)
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(jLabel12))
.addGap(18, 18, 18)
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(StartDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(FinishDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(PickUpOrTruckOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(GetAvailableTrucksButton)
.addComponent(PickUpOrderButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane13, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41))
.addGroup(PickUpOrTruckOrderPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(TruckOrderButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
getContentPane().add(PickUpOrTruckOrderPanel);
PickUpOrTruckOrderPanel.setBounds(0, 0, 799, 554);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel2.setText("Packages Menu");
PackageIDLabel.setText("Package ID");
PackageIDField.setEditable(false);
PackageIDField.setBackground(new java.awt.Color(204, 204, 204));
PackageNameLabel.setText("Package Name");
PackageNameField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackageNameFieldActionPerformed(evt);
}
});
PackageDiscLabel.setText("Package Description");
PackageDescTextArea.setColumns(20);
PackageDescTextArea.setRows(5);
jScrollPane6.setViewportView(PackageDescTextArea);
PackagePriceLabel.setText("Package Price");
AddPackageButton.setText("Add Package");
AddPackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddPackageButtonActionPerformed(evt);
}
});
ExistingPackLabel.setText("Existing Packages");
jScrollPane7.setViewportView(PackageJList);
ExistingPackageButton.setText("Get Existing Packages");
ExistingPackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExistingPackageButtonActionPerformed(evt);
}
});
EditPackageButton.setText("Edit Selected Package");
EditPackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EditPackageButtonActionPerformed(evt);
}
});
EditPackProdButton.setText("Add/Edit Products in Package");
EditPackProdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EditPackProdButtonActionPerformed(evt);
}
});
DeletePackageButton.setText("Delete Package");
DeletePackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeletePackageButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout PackagePanelLayout = new javax.swing.GroupLayout(PackagePanel);
PackagePanel.setLayout(PackagePanelLayout);
PackagePanelLayout.setHorizontalGroup(
PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PackagePanelLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PackagePanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38))
.addGroup(PackagePanelLayout.createSequentialGroup()
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(PackagePriceLabel)
.addComponent(PackageDiscLabel)
.addComponent(PackageNameLabel)
.addComponent(PackageIDLabel)
.addComponent(PackageIDField, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PackageNameField)
.addComponent(jScrollPane6)
.addComponent(PackagePriceField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddPackageButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EditPackProdButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(DeletePackageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(ExistingPackLabel)
.addComponent(ExistingPackageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(EditPackageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(246, Short.MAX_VALUE))
);
PackagePanelLayout.setVerticalGroup(
PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PackagePanelLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PackageIDLabel)
.addComponent(ExistingPackLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PackageIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ExistingPackageButton))
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PackagePanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(PackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PackagePanelLayout.createSequentialGroup()
.addComponent(PackageNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PackageNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(PackageDiscLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PackagePriceLabel)
.addGap(16, 16, 16)
.addComponent(PackagePriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(AddPackageButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EditPackProdButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(DeletePackageButton)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane7)))
.addGroup(PackagePanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(EditPackageButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 384, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(67, 67, 67))
);
getContentPane().add(PackagePanel);
PackagePanel.setBounds(0, 0, 910, 620);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel3.setText("Edit Package Menu");
PackageIDLabel2.setText("Package ID");
PackageIDField2.setEditable(false);
PackageIDField2.setBackground(new java.awt.Color(204, 204, 204));
PackageNameLabel2.setText("Package Name");
PackageNameField2.setEditable(false);
PackageNameField2.setBackground(new java.awt.Color(204, 204, 204));
PackageNameField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackageNameField2ActionPerformed(evt);
}
});
PackageGetAllProductButton.setText("Get All Products");
PackageGetAllProductButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackageGetAllProductButtonActionPerformed(evt);
}
});
OrderProductNameLabel1.setText("Product Name:");
jScrollPane8.setViewportView(PackProductsList);
OrderProductQuantityLabel1.setText("Quantity:");
AddProductToPackageButton.setText("Add selected to Package -->");
AddProductToPackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddProductToPackageButtonActionPerformed(evt);
}
});
RemoveFromPackageButto.setText("Remove selected form Package");
RemoveFromPackageButto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RemoveFromPackageButtoActionPerformed(evt);
}
});
jScrollPane9.setViewportView(ProductsInPackageList);
SavePackageButton.setText("Save Package");
SavePackageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SavePackageButtonActionPerformed(evt);
}
});
PackageSearchProductButton.setText("Search");
PackageSearchProductButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackageSearchProductButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout EditPackagePanelLayout = new javax.swing.GroupLayout(EditPackagePanel);
EditPackagePanel.setLayout(EditPackagePanelLayout);
EditPackagePanelLayout.setHorizontalGroup(
EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(283, 283, 283)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(9, 9, 9)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addComponent(OrderProductNameLabel1)
.addGap(4, 4, 4)
.addComponent(PackProductNameSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PackageSearchProductButton))
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addComponent(OrderProductQuantityLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OrderQuantitySpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(AddProductToPackageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(RemoveFromPackageButto)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, EditPackagePanelLayout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(SavePackageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(18, 18, 18)
.addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addComponent(PackageIDLabel2)
.addGap(10, 10, 10)
.addComponent(PackageIDField2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(58, 58, 58)
.addComponent(PackageNameLabel2)
.addGap(56, 56, 56)
.addComponent(PackageNameField2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(PackageGetAllProductButton, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(203, Short.MAX_VALUE))
);
EditPackagePanelLayout.setVerticalGroup(
EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PackageIDField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PackageIDLabel2)
.addComponent(PackageNameLabel2))))
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addComponent(PackageNameField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)))
.addGap(8, 8, 8)
.addComponent(PackageGetAllProductButton)
.addGap(10, 10, 10)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(OrderProductNameLabel1))
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PackProductNameSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PackageSearchProductButton)))
.addGap(12, 12, 12)
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
.addComponent(jScrollPane8)
.addGroup(EditPackagePanelLayout.createSequentialGroup()
.addGroup(EditPackagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderProductQuantityLabel1)
.addComponent(OrderQuantitySpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddProductToPackageButton))
.addGap(41, 41, 41)
.addComponent(RemoveFromPackageButto)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SavePackageButton)
.addGap(20, 20, 20)))
.addContainerGap(181, Short.MAX_VALUE))
);
getContentPane().add(EditPackagePanel);
EditPackagePanel.setBounds(-8, 0, 910, 693);
LogInPanel.setLayout(null);
LoginMenuLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
LoginMenuLabel.setText("Login Menu.");
LogInPanel.add(LoginMenuLabel);
LoginMenuLabel.setBounds(288, 83, 240, 70);
UserNameLabel.setText("User Name:");
LogInPanel.add(UserNameLabel);
UserNameLabel.setBounds(216, 204, 110, 20);
PasswordLabel.setText("Password:");
LogInPanel.add(PasswordLabel);
PasswordLabel.setBounds(206, 240, 120, 20);
LogInPanel.add(UserNameField);
UserNameField.setBounds(360, 190, 180, 30);
PasswordField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PasswordFieldActionPerformed(evt);
}
});
LogInPanel.add(PasswordField);
PasswordField.setBounds(360, 230, 180, 30);
LoginButton.setText("Login");
LoginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginButtonActionPerformed(evt);
}
});
LogInPanel.add(LoginButton);
LoginButton.setBounds(350, 303, 90, 40);
getContentPane().add(LogInPanel);
LogInPanel.setBounds(0, 0, 900, 600);
FileDropMenu.setText("File");
ExitDrop.setText("Exit");
ExitDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitDropActionPerformed(evt);
}
});
FileDropMenu.add(ExitDrop);
LogOutDrop.setText("Log Out");
LogOutDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogOutDropActionPerformed(evt);
}
});
FileDropMenu.add(LogOutDrop);
jMenuBar1.add(FileDropMenu);
NavigationDropMenu.setText("Navigation");
MainNavDrop.setText("Main Menu");
MainNavDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MainNavDropActionPerformed(evt);
}
});
NavigationDropMenu.add(MainNavDrop);
CustNavDrop.setText("Customers");
CustNavDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustNavDropActionPerformed(evt);
}
});
NavigationDropMenu.add(CustNavDrop);
ProdNavDrop.setText("Products");
ProdNavDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProdNavDropActionPerformed(evt);
}
});
NavigationDropMenu.add(ProdNavDrop);
OrdNavDrop.setText("Orders");
OrdNavDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrdNavDropActionPerformed(evt);
}
});
NavigationDropMenu.add(OrdNavDrop);
PackNavDrop.setText("Packages");
PackNavDrop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PackNavDropActionPerformed(evt);
}
});
NavigationDropMenu.add(PackNavDrop);
jMenuBar1.add(NavigationDropMenu);
AdminDropMenu.setText("Admin");
UsersDrop.setText("Users");
AdminDropMenu.add(UsersDrop);
UserRankDrop.setText("Set User Ranks");
AdminDropMenu.add(UserRankDrop);
jMenuBar1.add(AdminDropMenu);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>//GEN-END:initComponents
private void MainNavDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MainNavDropActionPerformed
selectPanel(2);
}//GEN-LAST:event_MainNavDropActionPerformed
private void ExitDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitDropActionPerformed
System.exit(0);
}//GEN-LAST:event_ExitDropActionPerformed
private void CustomerMenuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustomerMenuButtonActionPerformed
selectPanel(3);
AddCustomerButton.setEnabled(true);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(false);
EditCustomerButton.setEnabled(false);
GetCustomerButton.setEnabled(true);
SaveCustomerChangeButton.setEnabled(false);
}//GEN-LAST:event_CustomerMenuButtonActionPerformed
private void OrderMenuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderMenuButtonActionPerformed
selectPanel(8);
CreateOrderButton.setEnabled(false);
}//GEN-LAST:event_OrderMenuButtonActionPerformed
private void CustNavDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustNavDropActionPerformed
selectPanel(3);
AddCustomerButton.setEnabled(true);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(false);
EditCustomerButton.setEnabled(false);
GetCustomerButton.setEnabled(true);
SaveCustomerChangeButton.setEnabled(false);
}//GEN-LAST:event_CustNavDropActionPerformed
private void OrdNavDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrdNavDropActionPerformed
selectPanel(8);
CreateOrderButton.setEnabled(false);
}//GEN-LAST:event_OrdNavDropActionPerformed
private void ProductMenuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProductMenuButtonActionPerformed
selectPanel(4);
clearProductFields();
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(false);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_ProductMenuButtonActionPerformed
private void ProdNavDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProdNavDropActionPerformed
selectPanel(4);
clearProductFields();
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(false);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_ProdNavDropActionPerformed
private void GetCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetCustomerButtonActionPerformed
model1.clear();
CustomerJList.setModel(model1);
con.clearCustomerList();
con.buildCustomerList();
for (int i = 0; i < con.getCustomerListSize(); i++) {
model1.addElement(con.getCustomerID(i) + "-" + con.getCustomerName(i));
}
CustomerJList.setModel(model1);
AddCustomerButton.setEnabled(true);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(false);
EditCustomerButton.setEnabled(true);
GetCustomerButton.setEnabled(true);
SaveCustomerChangeButton.setEnabled(false);
}//GEN-LAST:event_GetCustomerButtonActionPerformed
private void EditCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditCustomerButtonActionPerformed
if (con.lockCustomer(con.getCustomerID(CustomerJList.getSelectedIndex())) && !lockCustomer) {
lockCustomer = true;
System.out.println("lockCusID" + con.getCustomerID(CustomerJList.getSelectedIndex()));
System.out.println("locked");
CustomerIDField.setText("" + con.getCustomerID(CustomerJList.getSelectedIndex()));
CustomerNameField.setText(con.getCustomerName(CustomerJList.getSelectedIndex()));
CustomerAddressField.setText(con.getCustomerAddress(CustomerJList.getSelectedIndex()));
CustomerEmailField.setText(con.getCustomerEmail(CustomerJList.getSelectedIndex()));
}
AddCustomerButton.setEnabled(false);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(true);
EditCustomerButton.setEnabled(true);
GetCustomerButton.setEnabled(false);
SaveCustomerChangeButton.setEnabled(true);
}//GEN-LAST:event_EditCustomerButtonActionPerformed
private void DeleteCustomerbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteCustomerbuttonActionPerformed
int cusID = con.getCustomerID(CustomerJList.getSelectedIndex());
con.deleteCustomer(cusID);
GetCustomerButtonActionPerformed(evt);
clearCustomerFields();
AddCustomerButton.setEnabled(true);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(false);
EditCustomerButton.setEnabled(true);
GetCustomerButton.setEnabled(true);
SaveCustomerChangeButton.setEnabled(false);
}//GEN-LAST:event_DeleteCustomerbuttonActionPerformed
private void AddCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddCustomerButtonActionPerformed
String cusName = CustomerNameField.getText();
String cusAddress = CustomerAddressField.getText();
String cusEmail = CustomerEmailField.getText();
con.addCustomer(cusName, cusAddress, cusEmail);
GetCustomerButtonActionPerformed(evt);
clearCustomerFields();
}//GEN-LAST:event_AddCustomerButtonActionPerformed
private void SaveCustomerChangeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveCustomerChangeButtonActionPerformed
int cusID = Integer.parseInt(CustomerIDField.getText());
String cusName = CustomerNameField.getText();
String cusAddress = CustomerAddressField.getText();
String cusEmail = CustomerEmailField.getText();
if (lockCustomer) {
try {
con.saveEditedCustomer(cusID, cusName, cusAddress, cusEmail);
} catch (SQLException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
lockCustomer = false;
}
GetCustomerButtonActionPerformed(evt);
clearCustomerFields();
AddCustomerButton.setEnabled(true);
AddEditPhoneButton.setEnabled(false);
DeleteCustomerbutton.setEnabled(false);
EditCustomerButton.setEnabled(true);
GetCustomerButton.setEnabled(true);
SaveCustomerChangeButton.setEnabled(false);
}//GEN-LAST:event_SaveCustomerChangeButtonActionPerformed
private void AddProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddProductButtonActionPerformed
String name = ProductNameField.getText();
int volume = Integer.parseInt(ProductVolumeField.getText());
int quantity = Integer.parseInt(ProductQuantityField.getText());
String description = ProductDescriptionField.getText();
int price = Integer.parseInt(ProductPriceField.getText());
con.addProduct(name, volume, quantity, description, price);
GetProductsButtonActionPerformed(evt);
clearProductFields();
}//GEN-LAST:event_AddProductButtonActionPerformed
private void GetProductsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetProductsButtonActionPerformed
con.clearProductList();
con.buildProductList();
int counter = 0;
model3.clear();
while (counter < con.getProductListSize()) {
model3.addElement(con.getProductId(counter) + "-" + con.getProductName(counter));
counter++;
}
ProductJList.setModel(model3);
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_GetProductsButtonActionPerformed
private void DeleteProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteProductButtonActionPerformed
int prodID = Integer.parseInt(ProductIDField.getText());
con.deleteProduct(prodID);
GetProductsButtonActionPerformed(evt);
clearProductFields();
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_DeleteProductButtonActionPerformed
private void EditProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditProductButtonActionPerformed
int searchID = Integer.parseInt(("" + ProductJList.getSelectedValue()).substring(0, 5));
System.out.println(searchID);
int index = con.searchProdByIDinArray(searchID);
ProductIDField.setText("" + con.getProductId(index));
ProductNameField.setText(con.getProductName(index));
ProductVolumeField.setText("" + con.getProductVolume(index));
ProductQuantityField.setText("" + con.getProductQuantiy(index));
ProductPriceField.setText("" + con.getProductPrice(index));
ProductDescriptionField.setText(con.getProductDescription(index));
AddProductButton.setEnabled(false);
DeleteProductButton.setEnabled(true);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(true);
}//GEN-LAST:event_EditProductButtonActionPerformed
private void SaveProductChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveProductChangesButtonActionPerformed
int ID = Integer.parseInt(ProductIDField.getText());
String name = ProductNameField.getText();
int volume = Integer.parseInt(ProductVolumeField.getText());
int quantity = Integer.parseInt(ProductQuantityField.getText());
String description = ProductDescriptionField.getText();
int price = Integer.parseInt(ProductPriceField.getText());
con.saveEditedProduct(ID, name, volume, quantity, description, price);
GetProductsButtonActionPerformed(evt);
clearProductFields();
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(true);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_SaveProductChangesButtonActionPerformed
private void SearchForProductIDButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchForProductIDButtonActionPerformed
con.clearProductList();
con.buildProductList();
int searchID = Integer.parseInt(ProductIDSearchField.getText());
int index = con.searchProdByIDinArray(searchID);
if (index >= 0) {
model3.clear();
model3.addElement(con.getProductId(index) + "-" + con.getProductName(index));
ProductJList.setModel(model3);
}
ProductJList.setModel(model3);
ProductNameSearchField.setText(null);
ProductIDSearchField.setText(null);
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(false);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_SearchForProductIDButtonActionPerformed
private void OrdergetAllProductsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrdergetAllProductsButtonActionPerformed
con.clearProductList();
con.buildProductList();
int counter = 0;
model3.clear();
while (counter < con.getProductListSize()) {
model3.addElement(con.getProductId(counter) + "-" + con.getProductName(counter));
counter++;
}
OrderProductsList.setModel(model3);
}//GEN-LAST:event_OrdergetAllProductsButtonActionPerformed
private void OrderAddProductToOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderAddProductToOrderButtonActionPerformed
int searchID = Integer.parseInt(("" + OrderProductsList.getSelectedValue()).substring(0, 5));
int quantityForOrder = (Integer)OrderQuantitySpinner.getValue();
int index = con.searchProdByIDinArray(searchID);
con.addItemToOrderList(con.getProductId(index), con.getProductName(index), con.getProductVolume(index),
quantityForOrder, con.getProductDescription(index),
con.getProductPrice(index), con.getProductQuantiy(index));
int counter = 0;
model6.clear();
while (counter < con.getCurrentOrderProductListSize()) {
model6.addElement(con.getOrderProductID(counter) + "-" + con.getOrderProductName(counter) + " QTY: " + con.getOrderProductQTY(counter));
counter++;
}
OrderProductsInOrderList.setModel(model6);
runningTotalField.setText(""+con.getOrderBalance());
}//GEN-LAST:event_OrderAddProductToOrderButtonActionPerformed
private void OrderRemoveFromOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderRemoveFromOrderButtonActionPerformed
int searchID = Integer.parseInt(("" + OrderProductsInOrderList.getSelectedValue()).substring(0, 5));
int index = con.searchOrderProdByIDinArray(searchID);// this needs to be changed so it goes through right arraylist
con.removeFromOrderList(index);
int counter = 0;
model6.clear();
while (counter < con.getCurrentOrderProductListSize()) {
model6.addElement(con.getOrderProductID(counter) + "-" + con.getOrderProductName(counter) + " QTY: " + con.getOrderProductQTY(counter));
counter++;
}
OrderProductsInOrderList.setModel(model6);
runningTotalField.setText(""+con.getOrderBalance());
}//GEN-LAST:event_OrderRemoveFromOrderButtonActionPerformed
private void OrderSaveOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderSaveOrderButtonActionPerformed
int customerID = Integer.parseInt(OrderCustomerIDField.getText());
System.out.println("Customer ID="+customerID);
String startDate = OrderStartDateField.getText();
System.out.println("startdate="+startDate);
String finishDate = OrderEndDateField.getText();
System.out.println("finishdate="+finishDate);
int orderID = Integer.parseInt(OrderIDField.getText());
con.editCustomerOrder(customerID, startDate, finishDate, con.getOrderBalance());
con.addOrder(orderID);
StartDateField.setText(OrderStartDateField.getText());
FinishDateField.setText(OrderEndDateField.getText());
selectPanel(9);
}//GEN-LAST:event_OrderSaveOrderButtonActionPerformed
private void AddPackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddPackageButtonActionPerformed
String name = PackageNameField.getText();
String descrip = PackageDescTextArea.getText();
int price = Integer.parseInt(PackagePriceField.getText());
con.addPackage(name, descrip, price);
con.buildPackageList();
//packID = con.getNewPackageID(name, descrip, price);
clearPackageFields();
ExistingPackageButtonActionPerformed(evt);
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(false);
DeletePackageButton.setEnabled(false);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(false);
}//GEN-LAST:event_AddPackageButtonActionPerformed
private void PackageMenuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackageMenuButtonActionPerformed
selectPanel(6);
clearPackageFields();
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(false);
DeletePackageButton.setEnabled(false);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(false);
}//GEN-LAST:event_PackageMenuButtonActionPerformed
private void PackNavDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackNavDropActionPerformed
selectPanel(6);
clearPackageFields();
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(false);
DeletePackageButton.setEnabled(false);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(false);
}//GEN-LAST:event_PackNavDropActionPerformed
private void PackageNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackageNameFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_PackageNameFieldActionPerformed
private void ExistingPackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExistingPackageButtonActionPerformed
con.clearPackageList();
con.buildPackageList();
model7.clear();
for (int i = 0; i < con.getPackageListSize(); i++) {
model7.addElement(con.getPackageID(i) + "-" + con.getPackageName(i));
}
PackageJList.setModel(model7);
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(false);
DeletePackageButton.setEnabled(false);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(true);
}//GEN-LAST:event_ExistingPackageButtonActionPerformed
private void EditPackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditPackageButtonActionPerformed
PackageIDField.setText(""+con.getPackageID(PackageJList.getSelectedIndex()));
PackageNameField.setText("" + con.getPackageName(PackageJList.getSelectedIndex()));
PackageDescTextArea.setText("" + con.getPackageDiscription(PackageJList.getSelectedIndex()));
PackagePriceField.setText("" + con.getPackagePrice(PackageJList.getSelectedIndex()));
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(true);
DeletePackageButton.setEnabled(true);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(true);
}//GEN-LAST:event_EditPackageButtonActionPerformed
private void PackageGetAllProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackageGetAllProductButtonActionPerformed
con.clearProductList();
con.buildProductList();
int counter = 0;
model3.clear();
while (counter < con.getProductListSize()) {
model3.addElement(con.getProductId(counter) + "-" + con.getProductName(counter));
counter++;
}
PackProductsList.setModel(model3);
}//GEN-LAST:event_PackageGetAllProductButtonActionPerformed
private void EditPackProdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditPackProdButtonActionPerformed
selectPanel(7);
model6.clear();
int packID = Integer.parseInt(PackageIDField.getText());
PackageIDField2.setText(""+packID);
PackageNameField2.setText(PackageNameField.getText());
System.out.println(packID);
con.loadPackageProducts(packID);
for (int i = 0; i < con.getPackageProductListSize(); i++) {
model6.addElement(con.getPackageProductID(i) + "-" + con.getPackageProductName(i) + " QTY: " + con.getPackageProductQTY(i));
}
ProductsInPackageList.setModel(model6);
con.buildProductList();
clearPackageFields();
}//GEN-LAST:event_EditPackProdButtonActionPerformed
private void AddProductToPackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddProductToPackageButtonActionPerformed
int searchID = Integer.parseInt(("" + PackProductsList.getSelectedValue()).substring(0, 5));
int quantityForOrder = (Integer)OrderQuantitySpinner1.getValue();
int index = con.searchProdByIDinArray(searchID);
con.addItemToPackageList(con.getProductId(index), con.getProductName(index), con.getProductVolume(index),
quantityForOrder, con.getProductDescription(index),
con.getProductPrice(index));
int counter = 0;
model6.clear();
while (counter < con.getPackageProductListSize()) {
model6.addElement(con.getPackageProductID(counter) + "-" + con.getPackageProductName(counter) + " QTY: " + con.getPackageProductQTY(counter));
counter++;
}
ProductsInPackageList.setModel(model6);
}//GEN-LAST:event_AddProductToPackageButtonActionPerformed
private void RemoveFromPackageButtoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveFromPackageButtoActionPerformed
int searchID = Integer.parseInt(("" + ProductsInPackageList.getSelectedValue()).substring(0, 5));
int index = con.searchPackProdByIDinArray(searchID);
con.removeFromPackageList(index);
int counter = 0;
model6.clear();
while (counter < con.getPackageProductListSize()) {
model6.addElement(con.getProductId(counter) + "-" + con.getProductName(counter) + " QTY: " + con.getProductQuantiy(counter));
counter++;
}
ProductsInPackageList.setModel(model6);
}//GEN-LAST:event_RemoveFromPackageButtoActionPerformed
private void PackageNameField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackageNameField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_PackageNameField2ActionPerformed
private void SavePackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SavePackageButtonActionPerformed
int packID = Integer.parseInt(PackageIDField2.getText());
con.deletePackageProducts(packID);
if (con.addProductsToPackageInDB()) {
JOptionPane.showMessageDialog(this, "Order saved to Data Base!", "SAVED!", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Could not save truck order to Data Base!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_SavePackageButtonActionPerformed
private void DeletePackageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeletePackageButtonActionPerformed
int packID = Integer.parseInt(PackageIDField.getText());
con.deletePackageProducts(packID);
con.deletePackage(packID);
AddPackageButton.setEnabled(true);
EditPackProdButton.setEnabled(false);
DeletePackageButton.setEnabled(false);
ExistingPackageButton.setEnabled(true);
EditPackageButton.setEnabled(true);
}//GEN-LAST:event_DeletePackageButtonActionPerformed
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
userRank = 0;
String UserID = UserNameField.getText();
String UserPass = PasswordField.getText();
if (con.checkUserNPw(UserID, UserPass)) {
NavigationDropMenu.setEnabled(true);
AdminDropMenu.setEnabled(true);
selectPanel(2);
userRank = con.getCurrUserRank();
UserNameField.setText(null);
PasswordField.setText(null);
if (userRank > 1) {
AdminDropMenu.setEnabled(false);
ProdNavDrop.setEnabled(false);
PackNavDrop.setEnabled(false);
ProductMenuButton.setEnabled(false);
PackageMenuButton.setEnabled(false);
}
} else {
JOptionPane.showMessageDialog(null, "Wrong User/Password", "Fail", JOptionPane.ERROR_MESSAGE);
UserNameField.setText(null);
PasswordField.setText(null);
}
}//GEN-LAST:event_LoginButtonActionPerformed
private void PasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PasswordFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_PasswordFieldActionPerformed
private void LogOutDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogOutDropActionPerformed
selectPanel(1);
NavigationDropMenu.setEnabled(false);
AdminDropMenu.setEnabled(false);
AdminDropMenu.setEnabled(false);
ProdNavDrop.setEnabled(true);
PackNavDrop.setEnabled(true);
ProductMenuButton.setEnabled(true);
PackageMenuButton.setEnabled(true);
}//GEN-LAST:event_LogOutDropActionPerformed
private void ProductNameSearchFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProductNameSearchFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ProductNameSearchFieldActionPerformed
private void SearchForProductNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchForProductNameButtonActionPerformed
con.clearProductList();
con.buildProductList();
String searchName = ProductNameSearchField.getText();
if (con.searchProdByNameinArray(searchName)) {
int counter = 0;
model3.clear();
while (counter < con.getProductSearchListsize()) {
model3.addElement(con.getSearchProductId(counter) + "-" + con.getSearchProductName(counter));
counter++;
}
ProductJList.setModel(model3);
}
ProductJList.setModel(model3);
ProductNameSearchField.setText(null);
ProductIDSearchField.setText(null);
AddProductButton.setEnabled(true);
DeleteProductButton.setEnabled(false);
EditProductButton.setEnabled(true);
GetProductsButton.setEnabled(false);
SaveProductChangesButton.setEnabled(false);
}//GEN-LAST:event_SearchForProductNameButtonActionPerformed
private void GetCustomersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetCustomersButtonActionPerformed
model8.clear();
ExistingCustomersList.setModel(model8);
con.clearCustomerList();
con.buildCustomerList();
for (int i = 0; i < con.getCustomerListSize(); i++) {
model8.addElement(con.getCustomerID(i) + "-" + con.getCustomerName(i));
}
ExistingCustomersList.setModel(model8);
}//GEN-LAST:event_GetCustomersButtonActionPerformed
private void CreateOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateOrderButtonActionPerformed
con.addCustomerOrder(Integer.parseInt(CustIDField.getText()), OrderStartDateField.getText(), OrderEndDateField.getText());
con.buildOrderList();
OrderIDField.setText("" + con.getNewOrderID(Integer.parseInt(CustIDField.getText()), OrderStartDateField.getText(), OrderEndDateField.getText()));
selectPanel(5);
OrderCustomerIDField.setText(CustIDField.getText());
}//GEN-LAST:event_CreateOrderButtonActionPerformed
private void AddCutomerToOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddCutomerToOrderButtonActionPerformed
CustIDField.setText("" + con.getCustomerID(ExistingCustomersList.getSelectedIndex()));
CustNameField.setText(con.getCustomerName(ExistingCustomersList.getSelectedIndex()));
CustDetailsArea.setText("" + con.getCustomerAddress(ExistingCustomersList.getSelectedIndex()) + "\n" + con.getCustomerEmail(ExistingCustomersList.getSelectedIndex()));
CreateOrderButton.setEnabled(true);
}//GEN-LAST:event_AddCutomerToOrderButtonActionPerformed
private void OrderCustomerIDFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderCustomerIDFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_OrderCustomerIDFieldActionPerformed
private void GetAvailableTrucksButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetAvailableTrucksButtonActionPerformed
model9.clear();
con.buildTruckList();
con.buildTruckOrderList();
con.checkFreeTrucks(StartDateField.getText());
for (int i = 0; i < con.getAvailableTruckListSize(); i++) {
model9.addElement(con.getAvailableTruck(i));
}
AvailableTrucksList.setModel(model9);
}//GEN-LAST:event_GetAvailableTrucksButtonActionPerformed
private void PickUpOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PickUpOrderButtonActionPerformed
if (con.addPickUp(Integer.parseInt(CustIDField.getText()), Integer.parseInt(OrderCustomerIDField.getText()), StartDateField.getText(), FinishDateField.getText())) {
JOptionPane.showMessageDialog(null, "Saved PickUp Order!", "Saved", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Error Saving PickUP Order!", "Error", JOptionPane.ERROR_MESSAGE);
}
selectPanel(2);
}//GEN-LAST:event_PickUpOrderButtonActionPerformed
private void TruckOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TruckOrderButtonActionPerformed
con.addTruckOrder(Integer.parseInt(OrderIDField.getText()),
con.getAvailableTruck(AvailableTrucksList.getSelectedIndex()),
"Delivery", StartDateField.getText());
selectPanel(2);
}//GEN-LAST:event_TruckOrderButtonActionPerformed
private void OrderIDFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderIDFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_OrderIDFieldActionPerformed
private void OrderProductSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderProductSearchButtonActionPerformed
con.clearProductList();
con.buildProductList();
String searchName = OrderProductNameSearchField.getText();
if (con.searchProdByNameinArray(searchName)) {
int counter = 0;
model3.clear();
while (counter < con.getProductSearchListsize()) {
model3.addElement(con.getSearchProductId(counter) + "-" + con.getSearchProductName(counter));
counter++;
}
OrderProductsList.setModel(model3);
}
}//GEN-LAST:event_OrderProductSearchButtonActionPerformed
private void PackageSearchProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PackageSearchProductButtonActionPerformed
con.clearProductList();
con.buildProductList();
String searchName = PackProductNameSearchField.getText();
if (con.searchProdByNameinArray(searchName)) {
int counter = 0;
model3.clear();
while (counter < con.getProductSearchListsize()) {
model3.addElement(con.getSearchProductId(counter) + "-" + con.getSearchProductName(counter));
counter++;
}
PackProductsList.setModel(model3);
}
}//GEN-LAST:event_PackageSearchProductButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
public void selectPanel(int panel) {
LogInPanel.setVisible(false);
MainPanel.setVisible(false);
CustomerPanel.setVisible(false);
ProductPanel.setVisible(false);
OrderPanel.setVisible(false);
EditOrderPanel.setVisible(false);
PickUpOrTruckOrderPanel.setVisible(false);
PackagePanel.setVisible(false);
EditPackagePanel.setVisible(false);
switch (panel) {
case 1:
LogInPanel.setVisible(true);
break;
case 2:
MainPanel.setVisible(true);
break;
case 3:
CustomerPanel.setVisible(true);
break;
case 4:
ProductPanel.setVisible(true);
break;
case 5:
EditOrderPanel.setVisible(true);
break;
case 6:
PackagePanel.setVisible(true);
break;
case 7:
EditPackagePanel.setVisible(true);
break;
case 8:
OrderPanel.setVisible(true);
break;
case 9:
PickUpOrTruckOrderPanel.setVisible(true);
break;
}
}
public void clearCustomerFields() {
CustomerIDField.setText(null);
CustomerNameField.setText(null);
CustomerAddressField.setText(null);
CustPhoneTextArea.setText(null);
CustomerEmailField.setText(null);
}
public void clearPackageFields() {
PackageIDField.setText(null);
PackageNameField.setText(null);
PackageDescTextArea.setText(null);
PackagePriceField.setText(null);
}
public void clearProductFields() {
ProductIDField.setText(null);
ProductNameField.setText(null);
ProductQuantityField.setText(null);
ProductVolumeField.setText(null);
ProductPriceField.setText(null);
ProductDescriptionField.setText(null);
}
public void setVisibleItemsInOrderPane(boolean state) {
OrderProductNameSearchField.setVisible(state);
OrdergetAllProductsButton.setVisible(state);
OrderProductNameLabel.setVisible(state);
OrderProductsList.setVisible(state);
OrderProductQuantityLabel.setVisible(state);
OrderQuantitySpinner.setVisible(state);
OrderAddProductToOrderButton.setVisible(state);
OrderProductsInOrderList.setVisible(state);
OrderRemoveFromOrderButton.setVisible(state);
OrderCustomerIDLabel.setVisible(state);
OrderCustomerIDField.setVisible(state);
OrderEndDateLabel.setVisible(state);
OrderEndDateField.setVisible(state);
OrderStartDateLabel.setVisible(state);
OrderStartDateField.setVisible(state);
OrderSaveOrderButton.setVisible(state);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton AddCustomerButton;
private javax.swing.JButton AddCutomerToOrderButton;
private javax.swing.JButton AddEditPhoneButton;
private javax.swing.JButton AddPackageButton;
private javax.swing.JButton AddProductButton;
private javax.swing.JButton AddProductToPackageButton;
private javax.swing.JMenu AdminDropMenu;
private javax.swing.JList AvailableTrucksList;
private javax.swing.JButton CreateOrderButton;
private javax.swing.JTextArea CustDetailsArea;
private javax.swing.JTextField CustIDField;
private javax.swing.JTextField CustNameField;
private javax.swing.JMenuItem CustNavDrop;
private javax.swing.JLabel CustPhoneLabel;
private javax.swing.JTextArea CustPhoneTextArea;
private javax.swing.JTextField CustomerAddressField;
private javax.swing.JLabel CustomerAddressLabel;
private javax.swing.JTextField CustomerEmailField;
private javax.swing.JLabel CustomerEmailLabel;
private javax.swing.JTextField CustomerIDField;
private javax.swing.JList CustomerJList;
private javax.swing.JButton CustomerMenuButton;
private javax.swing.JLabel CustomerMenuLabel;
private javax.swing.JTextField CustomerNameField;
private javax.swing.JLabel CustomerNameLabel;
private javax.swing.JPanel CustomerPanel;
private javax.swing.JLabel CutomerIDLabel;
private javax.swing.JButton DeleteCustomerbutton;
private javax.swing.JButton DeletePackageButton;
private javax.swing.JButton DeleteProductButton;
private javax.swing.JButton EditCustomerButton;
private javax.swing.JPanel EditOrderPanel;
private javax.swing.JButton EditPackProdButton;
private javax.swing.JButton EditPackageButton;
private javax.swing.JPanel EditPackagePanel;
private javax.swing.JButton EditProductButton;
private javax.swing.JLabel ExistingCustLabel;
private javax.swing.JList ExistingCustomersList;
private javax.swing.JLabel ExistingPackLabel;
private javax.swing.JButton ExistingPackageButton;
private javax.swing.JMenuItem ExitDrop;
private javax.swing.JMenu FileDropMenu;
private javax.swing.JTextField FinishDateField;
private javax.swing.JButton GetAvailableTrucksButton;
private javax.swing.JButton GetCustomerButton;
private javax.swing.JButton GetCustomersButton;
private javax.swing.JButton GetProductsButton;
private javax.swing.JPanel LogInPanel;
private javax.swing.JMenuItem LogOutDrop;
private javax.swing.JButton LoginButton;
private javax.swing.JLabel LoginMenuLabel;
private javax.swing.JLabel MainMenuLabel;
private javax.swing.JMenuItem MainNavDrop;
private javax.swing.JPanel MainPanel;
private javax.swing.JMenu NavigationDropMenu;
private javax.swing.JMenuItem OrdNavDrop;
private javax.swing.JButton OrderAddProductToOrderButton;
private javax.swing.JTextField OrderCustomerIDField;
private javax.swing.JLabel OrderCustomerIDLabel;
private javax.swing.JTextField OrderEndDateField;
private javax.swing.JLabel OrderEndDateLabel;
private javax.swing.JTextField OrderIDField;
private javax.swing.JLabel OrderIDLabel;
private javax.swing.JButton OrderMenuButton;
private javax.swing.JLabel OrderMenuLabel;
private javax.swing.JPanel OrderPanel;
private javax.swing.JLabel OrderProductNameLabel;
private javax.swing.JLabel OrderProductNameLabel1;
private javax.swing.JTextField OrderProductNameSearchField;
private javax.swing.JLabel OrderProductQuantityLabel;
private javax.swing.JLabel OrderProductQuantityLabel1;
private javax.swing.JButton OrderProductSearchButton;
private javax.swing.JList OrderProductsInOrderList;
private javax.swing.JList OrderProductsList;
private javax.swing.JSpinner OrderQuantitySpinner;
private javax.swing.JSpinner OrderQuantitySpinner1;
private javax.swing.JButton OrderRemoveFromOrderButton;
private javax.swing.JButton OrderSaveOrderButton;
private javax.swing.JTextField OrderStartDateField;
private javax.swing.JLabel OrderStartDateLabel;
private javax.swing.JButton OrdergetAllProductsButton;
private javax.swing.JMenuItem PackNavDrop;
private javax.swing.JTextField PackProductNameSearchField;
private javax.swing.JList PackProductsList;
private javax.swing.JTextArea PackageDescTextArea;
private javax.swing.JLabel PackageDiscLabel;
private javax.swing.JButton PackageGetAllProductButton;
private javax.swing.JTextField PackageIDField;
private javax.swing.JTextField PackageIDField2;
private javax.swing.JLabel PackageIDLabel;
private javax.swing.JLabel PackageIDLabel2;
private javax.swing.JList PackageJList;
private javax.swing.JButton PackageMenuButton;
private javax.swing.JTextField PackageNameField;
private javax.swing.JTextField PackageNameField2;
private javax.swing.JLabel PackageNameLabel;
private javax.swing.JLabel PackageNameLabel2;
private javax.swing.JPanel PackagePanel;
private javax.swing.JTextField PackagePriceField;
private javax.swing.JLabel PackagePriceLabel;
private javax.swing.JButton PackageSearchProductButton;
private javax.swing.JTextField PasswordField;
private javax.swing.JLabel PasswordLabel;
private javax.swing.JPanel PickUpOrTruckOrderPanel;
private javax.swing.JButton PickUpOrderButton;
private javax.swing.JMenuItem ProdNavDrop;
private javax.swing.JTextField ProductDescriptionField;
private javax.swing.JTextField ProductIDField;
private javax.swing.JLabel ProductIDLabel;
private javax.swing.JTextField ProductIDSearchField;
private javax.swing.JList ProductJList;
private javax.swing.JButton ProductMenuButton;
private javax.swing.JLabel ProductMenuLabel;
private javax.swing.JTextField ProductNameField;
private javax.swing.JLabel ProductNameLabel;
private javax.swing.JTextField ProductNameSearchField;
private javax.swing.JPanel ProductPanel;
private javax.swing.JTextField ProductPriceField;
private javax.swing.JLabel ProductPriceLabel;
private javax.swing.JLabel ProductQtyLabel;
private javax.swing.JTextField ProductQuantityField;
private javax.swing.JLabel ProductSearchID;
private javax.swing.JLabel ProductSearchName;
private javax.swing.JTextField ProductVolumeField;
private javax.swing.JLabel ProductVolumeLabel;
private javax.swing.JList ProductsInPackageList;
private javax.swing.JButton RemoveFromPackageButto;
private javax.swing.JButton SaveCustomerChangeButton;
private javax.swing.JButton SavePackageButton;
private javax.swing.JButton SaveProductChangesButton;
private javax.swing.JPanel SearchForAProduct;
private javax.swing.JButton SearchForProductIDButton;
private javax.swing.JButton SearchForProductNameButton;
private javax.swing.JTextField StartDateField;
private javax.swing.JButton TruckOrderButton;
private javax.swing.JTextField UserNameField;
private javax.swing.JLabel UserNameLabel;
private javax.swing.JMenuItem UserRankDrop;
private javax.swing.JMenuItem UsersDrop;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
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.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane13;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
private javax.swing.JLabel productListLabel;
private javax.swing.JTextField runningTotalField;
private javax.swing.JLabel runningTotalLabel;
// End of variables declaration//GEN-END:variables
}
|
package com.esum.framework.net.mail;
public class MailConfigConstants {
public static String SERVER_IP = null;
public static String FROM_EMAIL = null;
public static boolean USE_AUTH = false;
public static String AUTH_ID = null;
public static String AUTH_PWD = null;
}
|
package com.metoo.core.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.metoo.core.constant.Globals;
import com.metoo.core.tools.database.DatabaseTools;
import com.metoo.foundation.domain.Evaluate;
import com.metoo.foundation.domain.Goods;
import com.metoo.foundation.service.IEvaluateService;
import com.metoo.foundation.service.IGoodsService;
import com.metoo.module.app.buyer.domain.Result;
/**
*
* <p>
* Title: ExcelUtil.java
* <p>
*
* <p>
* Description: 该类适用导入excel进行批量操作数据
* </p>
*
* <p>
* Copyright: Copyright (c) 2020
* </p>
*
* <p>
* Company: 觅通科技
* </p>
*
* @author 46075
*
*/
@Controller
public class ExcelUtil {
@Autowired
private IGoodsService goodsService;
@Autowired
private IEvaluateService evaluateService;
@Autowired
private DatabaseTools databaseTools;
/**
* 刷评-计算好评率
* @param request
* @param response
*/
@RequestMapping("hssf_import.json")
public void hssf_export(HttpServletRequest request,
HttpServletResponse response, String goods_ids, String path, String excel_name){
String file = request.getServletContext().getRealPath("/") + path + File.separator + excel_name;
//File file = new File(path);
//File file = new File("C:\\Users\\46075\\Desktop\\metoo\\评论2020-8-06(1)(1)(1).xls");
Result result = null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
//获取系统文档
POIFSFileSystem fspoi = new POIFSFileSystem(fileInputStream);
//创建工作簿对象
HSSFWorkbook wb = new HSSFWorkbook(fspoi);
//创建工作表
HSSFSheet sheet1 = wb.getSheet("Sheet1");
//得到Excel表格
// HSSFRow row = sheet1.getRow(2);
//得到Excel工作表指定行的单元格
//HSSFCell cell = row.getCell(2);
List list = new ArrayList();
for(int i = 1; i < sheet1.getPhysicalNumberOfRows(); i ++ ){
List list1 = new ArrayList();
HSSFRow row = sheet1.getRow(i);
for(int j = 0; j < row.getLastCellNum(); j ++){
// map.put(sheet1.getRow(1).getCell(j), row.getCell(j));
list1.add(row.getCell(j));
}
list.add(list1);
}
String[] ids = goods_ids.split(",");
/* String[] ids = new String[]{"5884", "5928", "5875", "5867"};*/
String[] date = new String[]{"6", "7", "8"};
int[] number = new int[]{3,4,5};
int[] dateNumber = new int[]{1,2,3,4,};
for(int i=0; i < list.size(); i++){
List list2 = (List)list.get(i);
for(int j = 0; j < list2.size(); j++ ){
Goods goods = this.goodsService.getObjById(CommUtil.null2Long(ids[new Random().nextInt(ids.length)]));
Evaluate eva = new Evaluate();
goods.setEvaluate_count(goods.getEvaluate_count() + 1);
eva.setAddTime(CommUtil.formatDate("2020-" + date[new Random().nextInt(date.length)] + "-" + (int)(Math.random()*(29-1+1) + 1),"yyyy-MM-dd"));
eva.setEvaluate_goods(goods);
eva.setEvaluate_info(list2.size() == 1 ? "" : CommUtil.null2String(list2.get(j+1)));
//eva.setEvaluate_photos(request.getParameter("evaluate_photos"));
eva.setEvaluate_buyer_val(number[new Random().nextInt(number.length)]);
eva.setDescription_evaluate(CommUtil.null2BigDecimal(number[new Random().nextInt(number.length)]));
eva.setService_evaluate(CommUtil.null2BigDecimal(number[new Random().nextInt(number.length)]));
eva.setShip_evaluate(CommUtil.null2BigDecimal(number[new Random().nextInt(number.length)]));
eva.setEvaluate_type("Brush");
eva.setUser_name(CommUtil.null2String(list2.get(j)) == "" ? "Khalidi" : CommUtil.null2String(list2.get(j)));
eva.setReply_status(0);
this.goodsService.update(goods);
this.evaluateService.save(eva);
break;
}
}
//计算商品好评率
Map params = new HashMap();
List<Goods> goods_list = new ArrayList<Goods>();
for(String str : ids){
Goods obj = this.goodsService.getObjById(CommUtil.null2Long(str));
goods_list.add(obj);
}
for (Goods goods : goods_list) {
// 统计所有商品的描述相符评分
double description_evaluate = 0;
params.clear();
params.put("evaluate_goods_id", goods.getId());
List<Evaluate> eva_list = this.evaluateService
.query("select obj from Evaluate obj where obj.evaluate_goods.id=:evaluate_goods_id",
params, -1, -1);
//[add 浮点数据加法]
for (Evaluate eva : eva_list) {
description_evaluate = CommUtil.add(
eva.getDescription_evaluate(), description_evaluate);
}
//[div 浮点数除法运算]
description_evaluate = CommUtil.div(description_evaluate,
eva_list.size());
goods.setDescription_evaluate(BigDecimal
.valueOf(description_evaluate));
if (eva_list.size() > 0) {// 商品有评价情况下
// 统计所有商品的好评率
double well_evaluate = 0;
double well_evaluate_num = 0;
params.clear();
params.put("evaluate_goods_id", goods.getId());
//params.put("evaluate_buyer_val", 5);
String id = CommUtil.null2String(goods.getId());
//星级率
int num = this.databaseTools.queryNum("select SUM(evaluate_buyer_val) from "
+ Globals.DEFAULT_TABLE_SUFFIX
+ "evaluate where evaluate_goods_id="
+ id
+ " and evaluate_buyer_val BETWEEN 1 AND 5 ");
well_evaluate_num = CommUtil.mul(5, eva_list.size());
well_evaluate = CommUtil.div(num, well_evaluate_num);
goods.setWell_evaluate(BigDecimal.valueOf(well_evaluate));
// 统计所有商品的中评率
double middle_evaluate = 0;
params.clear();
params.put("evaluate_goods_id", goods.getId());
//params.put("evaluate_buyer_val", 3);
List<Evaluate> middle_list = this.evaluateService
.query("select obj from Evaluate obj where obj.evaluate_goods.id=:evaluate_goods_id and obj.evaluate_buyer_val BETWEEN 2 AND 3",
params, -1, -1);
middle_evaluate = CommUtil.div(middle_list.size(),
eva_list.size());
goods.setMiddle_evaluate(BigDecimal.valueOf(middle_evaluate));
// 统计所有商品的差评率
double bad_evaluate = 0;
params.clear();
params.put("evaluate_goods_id", goods.getId());
params.put("evaluate_buyer_val", 1);
List<Evaluate> bad_list = this.evaluateService
.query("select obj from Evaluate obj where obj.evaluate_goods.id=:evaluate_goods_id and obj.evaluate_buyer_val=:evaluate_buyer_val",
params, -1, -1);
bad_evaluate = CommUtil.div(bad_list.size(), eva_list.size());
goods.setBad_evaluate(BigDecimal.valueOf(bad_evaluate));
}
this.goodsService.update(goods);
}
result = new Result(0, "Successfully");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = new Result(0, "error");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = new Result(0, "error");
}
try {
response.getWriter().print(Json.toJson(result, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping("importExcel.json")
public void importExcel(HttpServletRequest request,
HttpServletResponse response, String excel, MultipartFile file) throws IOException{
InputStream input = null;
HSSFWorkbook wb = null;
List<List<String>> data = null;
input = file.getInputStream();
wb = new HSSFWorkbook(input);
HSSFSheet sheet1 = wb.getSheet("Sheet1");
data = new ArrayList<List<String>>();
for(int i = 1; i < sheet1.getPhysicalNumberOfRows(); i ++ ){
List<String> rowCell = new ArrayList<String>();
HSSFRow row = sheet1.getRow(i);
System.out.println(i);
for(int j = 0; j < row.getLastCellNum(); j ++){
try {
rowCell.add(row.getCell(j).toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
data.add(rowCell);
}
/*String extend = file.getOriginalFilename()
.substring(file.getOriginalFilename().lastIndexOf(".") + 1)
.toLowerCase();*/
try {
response.getWriter().print(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.leevicente.alertme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Register extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public void buttonClickRegister(View v){
Intent i;
if (v.getId() == R.id.backLogin) {
i = new Intent(this, Login.class);
startActivity(i);
} else if (v.getId() == R.id.nextPage) {
i = new Intent(this, Register2.class);
startActivity(i);
}
}
}
|
package baseline;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.Scanner;
/*
* UCF COP3330 Fall 2021 Assignment 3 Solutions
* Copyright 2021 Federico Abreu Seymour
*/
public class Solution32 {
private final Random rand = SecureRandom.getInstanceStrong();
public Solution32() throws NoSuchAlgorithmException {
}
public String difficultyOfNumber(int difficulty, int randomNumber) {
int totalAttempts = 0;
int guess;
while (true) {
Scanner input = new Scanner(System.in);
//if 1 play from number 1-10
if (difficulty == 1)
//set random number from range math.random*10+1
randomNumber = this.rand.nextInt(10)+1;
//else if 2 play from numbers 1-100
else if (difficulty == 2)
//set random number from range math.random*100+1
randomNumber = this.rand.nextInt(100)+1;
//else if 3 play from numbers 1-1000
else
//set random number from range math.random*1000+1
randomNumber = this.rand.nextInt(1000)+1;
try{
//Display I have my number What's your guess?:
System.out.print("I have my number. What's your guess? ");
//do Scan input as int
do {
guess = Integer.parseInt(input.next());
//totalTrys++
totalAttempts++;
//If Guess == RandomNumber Display You got it in "total" guesses!
if (guess == randomNumber)
System.out.println("You got it in " + totalAttempts + " guesses!");
//else if guess < RandomNumber Display Too low. Guess again:
else if (guess < randomNumber)
System.out.print("Too low. Guess again: ");
//else if guess > RandomNumber Display Too high. Guess again:
else System.out.print("Too high. Guess again: ");
}
//while guess != RandomNumber Display you wish to play again (Y/N)? Scan as Char
while (guess != randomNumber);
System.out.print("\nDo you wish to play again (Y/N)? ");
char choice = input.next().charAt(0);
//if choice is N or n break
if (choice == 'N' || choice == 'n')
break;
}catch (Exception e){
System.out.println("This is not a valid input and It will count as a guess, please try again.");
}
}
return null;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
Scanner input = new Scanner(System.in);
Random r = new Random();
Solution32 sol = new Solution32();
//Display Let's play Guess the Number!
System.out.println("Let's play Guess the Number! ");
//while true try
while(true){
try{
//Display Enter difficulty level (1,2,3): Scan int
System.out.print("Enter the difficulty level (1, 2, or 3): ");
int difficulty = Integer.parseInt(input.next());
int randomNumber = r.nextInt(999)+1;
sol.difficultyOfNumber(difficulty,randomNumber);
break;
//Catch Exception e Display Please Enter a valid input:
}catch (Exception e){
System.out.println("Sorry. That's not valid input, Please try again: ");
}
}
}
}
|
package cn.edu.cqut.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.util.Date;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author CQUT SE 2020
* @since 2020-06-10
*/
public class Permission extends Model<Permission> {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("permission")
private String permission;
@TableField("url")
private String url;
@TableField("description")
private String description;
@TableField("create_time")
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Permission{" +
"id=" + id +
", permission=" + permission +
", url=" + url +
", description=" + description +
", createTime=" + createTime +
"}";
}
}
|
package problems.repeated;
public class RepeatedIntegersProblem {
public void solve(int[] nums) {
// O(N)
for (int i = 0; i < nums.length; i++) {
// if this value is positive we have to flip
if (nums[Math.abs(nums[i])] > 0) {
nums[Math.abs(nums[i])] = -nums[Math.abs(nums[i])];
// otherwise it is negative: it means repetition
} else {
System.out.println(Math.abs(nums[i]) + " is a repetition!");
}
}
}
}
|
package com.flower.common.DTO;
/**
* @author cyk
* @date 2018/7/30/030 13:26
* @email choe0227@163.com
* @desc
* @modifier
* @modify_time
* @modify_remark
*/
public class BaseDTO<T> {
private Long startTime;
private Long endTime;
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Long getEndTime() {
return endTime;
}
public void setEndTime(Long endTime) {
this.endTime = endTime;
}
}
|
package benchmark.java.metrics.json;
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
import java.io.InputStream;
import java.io.OutputStream;
import benchmark.java.Config;
import benchmark.java.entities.PersonCollection;
import benchmark.java.metrics.AMetric;
import benchmark.java.metrics.Info;
public class JsonIOMetric extends AMetric {
private final Info info = new Info(Config.Format.JSON, "Json-io", "https://github.com/jdereg/json-io", "4.9.5");
@Override
public Info getInfo() {
return info;
}
@Override
public boolean serialize(Object data, OutputStream output) throws Exception {
JsonWriter jsonWriter = new JsonWriter(output);
jsonWriter.write(data);
return true;
}
@Override
public Object deserialize(InputStream input, byte[] bytes) throws Exception {
PersonCollection personCollection = (PersonCollection) JsonReader.jsonToJava(input, null);
return personCollection;
}
}
|
package light.c;
import java.io.IOException;
import javafx.stage.StageStyle;
import javafx.scene.paint.Paint;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.Parent;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.application.Application;
public class LightC extends Application
{
private double initX;
private double initY;
static Stage k;
public void start(final Stage stage) throws IOException {
LightC.k = stage;
final FXMLLoader lod = new FXMLLoader(this.getClass().getResource("mainscr.fxml"));
final Parent root = (Parent)lod.load();
final Scene k = new Scene(root, (Paint)Color.TRANSPARENT);
k.getStylesheets().addAll((Object[])new String[] { this.getClass().getResource("j.css").toExternalForm() });
stage.setScene(k);
stage.setTitle("Light C");
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
}
public static void main(final String[] args) {
launch(args);
}
}
|
package com.hr.personnel.controller;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.hr.login.model.LoginModel;
import com.hr.personnel.model.DepartmentDetail;
import com.hr.personnel.service.DepartmentService;
@Controller
public class DepartmentController {
@Autowired
DepartmentService departmentService;
@GetMapping(path="/department")
public String department() {
return "/personnel/departmentDetail";
}
/**
* This controller is meant to find the table of department name and the name of the manager of the department
* @return
*/
@GetMapping(path="/departmentDetail", produces="application/json")
public @ResponseBody Map<Integer, Map<String, String>> editDepartmentDetail() {
Map<Integer, Map<String, String>> map = new HashMap<Integer, Map<String, String>>();
map = departmentService.findAllDepartmentDetail();
return map;
}
@PutMapping(path="/departmentManagerNoUpdate", produces="application/json", consumes="application/json")
public @ResponseBody Map<Integer, Map<String, String>> departmentManagerIdUpdate(
@RequestBody Map<String, String> inputMap
) {
Map<Integer, Map<String, String>> map = new HashMap<Integer, Map<String, String>>();
map = departmentService.findAllDepartmentDetailWithReplacementOfNewManager(inputMap);
return map;
}
@GetMapping(path="/addNewDepartment")
public String addNewDepartment() {
return "/personnel/addNewDepartment";
}
@PostMapping(path="/createNewDepartment", consumes="application/json", produces="application/json")
public @ResponseBody Map<String, String> createNewDepartment(
@RequestBody Map<Integer, Map<String, String>> inputMap
) {
boolean flowCheck = false;
flowCheck = departmentService.insertNewDepartments(inputMap);
Map<String, String> map = new HashMap<String, String>();
if(flowCheck) {
map.put("result", "Update success");
return map;
}
map.put("result", "Update failure");
return map;
}
} |
package 飞毛腿外卖团;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
//确认下单界面
public class placeOrder {
private Menu m;
private long userId;
private Order o;
private JFrame f,f1;
private JPanel jp1,jp2,jp3;
private JButton ok,cencel,okbala,ddok,okinput;
private JLabel name,tel,address,amount,price,tittle,sum,dishname,remark,bala,jlbala,ddtip,jlinput;
private JTextField tfname,tftel,tfaddress,tfamount,tfprice,tfsum,tfdishname,tfbala;
private JTextArea taremark;
private JDialog jdbala,ddjd,jdinput;
public placeOrder(JFrame f1,Menu m,long userId)
{
this.userId = userId;
this.m = m;
this.f1 = f1;
f1.setVisible(false);
init();
}
public void init()
{
f = new JFrame("下单");
f.setBounds(500,150,300,470);
f.setResizable(false);
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//设置窗口中的主题提示
tittle = new JLabel("<html><font size = '20'>确认下单</font><br><br>请完善您的信息</p><br><br></html>");
tittle.setFont(new Font("黑体",Font.BOLD,15));
jp1.add(tittle);
name = new JLabel(" 姓 名 ");
tel = new JLabel(" 电 话 ");
dishname = new JLabel(" 菜 名 ");
price = new JLabel(" 价 格 ");
amount = new JLabel(" 数 量 ");
sum = new JLabel(" 总 额 ");
bala = new JLabel(" 余 额 ");
address = new JLabel(" 地 址 ");
remark = new JLabel(" 备 注 ");
tfname = new JTextField(15);
tftel = new JTextField(15);
tfdishname = new JTextField(15);
tfdishname.setText(" " + m.getFoodName());
tfdishname.setEditable(false);
tfprice = new JTextField(15);
tfprice.setEditable(false);
tfprice.setText(String.valueOf( " " + m.getPrice()) + " 元/份");
tfamount = new JTextField(15);
taremark = new JTextArea(3,15);
tfsum = new JTextField(15);
tfsum.setEditable(false);
tfbala = new JTextField(15);
tfbala.setEditable(false);
tfbala.setText(" "+getBalance(userId));
tfaddress = new JTextField(15);
jp2.add(name);
jp2.add(tfname);
jp2.add(tel);
jp2.add(tftel);
jp2.add(dishname);
jp2.add(tfdishname);
jp2.add(price);
jp2.add(tfprice);
jp2.add(amount);
jp2.add(tfamount);
jp2.add(sum);
jp2.add(tfsum);
jp2.add(bala);
jp2.add(tfbala);
jp2.add(address);
jp2.add(tfaddress);
jp2.add(remark);
jp2.add(taremark);
jdbala = new JDialog(f,true);
jdbala.setBounds(570, 300, 200, 150);
jdbala.setTitle("提示");
jlbala = new JLabel("<html><br>余 额 不 足,请 充 值 !<br><br></html>");
okbala = new JButton("确定");
jdbala.add(jlbala);
jdbala.add(okbala);
jdbala.setLayout(new FlowLayout());
jdinput = new JDialog(f,true);
jdinput.setBounds(560, 300, 240, 150);
jdinput.setTitle("提示");
jlinput = new JLabel("<html><br> 您 的 输 入 有 误 , 请 重 新 输 入 !<br><br></html>");
okinput = new JButton("确定");
jdinput.add(jlinput);
jdinput.add(okinput);
jdinput.setLayout(new FlowLayout());
ddjd = new JDialog(f,true);
ddjd.setBounds(560, 270, 230, 290);
ddjd.setLayout(new FlowLayout());
ddok = new JButton("完成");
ddtip = new JLabel();
ok = new JButton("提 交");
cencel = new JButton("返 回");
jp3.add(ok);
jp3.add(cencel);
f.add(jp1,BorderLayout.NORTH);
f.add(jp2,BorderLayout.CENTER);
f.add(jp3,BorderLayout.SOUTH);
myEvent();
f.setVisible(true);
}
public void myEvent()
{
//设置输入的数量的键盘监听
tfamount.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e)
{
//判断是否输入了回车键,如果输入了回车键则自动生成总额
if(e.getKeyCode() == KeyEvent.VK_ENTER){
String a = tfamount.getText();
char c = a.charAt(0);
if(c > '0' && c <= '9' && a.length() <= 1)
{
int count = Integer.parseInt(a);
int p = m.getPrice();
//将总额自动生成在总额的文本框中
tfsum.setText(" " + String.valueOf(count*p) + " 元");
}else{
tfsum.setText("请输入 1~9 份外卖!");
}
}
}
});
cencel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
f.setVisible(false);
f1.setVisible(true);
}
});
//确定键的活动监听
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String nn = tfname.getText();
String tt = tftel.getText();
String aa = tfaddress.getText();
String am = tfamount.getText();
//判断输入内容的格式是否正确
if(nn != null && tt != null && aa != null && am != null && tt.length() == 11)
{
int count = Integer.parseInt(am);
int p = m.getPrice();
int sum = count * p;
long tel = Long.parseLong(tt);
//判断总额是否大于余额
if(sum > getBalance(userId))
{
jdbala.setVisible(true);
}else if(sum <= getBalance(userId)){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String ddTime = sdf.format(date);
long orderId = getOrderId();
o = new Order(userId,orderId, m.getPrice(),count, sum,tfname.getText(),tel, tfaddress.getText(), ddTime,
taremark.getText(),m.getId());
//判断生成订单是否成功
if(generOrder(o,sum))
{
ddtip.setText("<html><font size = '10' > 恭 喜 你 </font><br><br><font size = '4' >订单成功!<br><br>您 的 订 单 号 为 :</font><br><font size = '8' > " + orderId + " </font><br><br><html>");
ddjd.add(ddtip);
ddjd.add(ddok);
ddjd.setVisible(true);
tfname.setText("");
tftel.setText("");
tfaddress.setText("");
tfamount.setText("");
taremark.setText("");
f.setVisible(false);
}else{
jdinput.setVisible(true);
}
}
}else{
jdinput.setVisible(true);
}
}
});
okbala.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
jdbala.setVisible(false);
}
});
//订单成功的提示的确定按钮的监听
ddok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ddjd.setVisible(false);
}
});
okinput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
jdinput.setVisible(false);
}
});
}
//获取账号为userId的余额
public int getBalance(long userId)
{
//连接数据库
GetConnection getcon = new GetConnection();
Statement st = getcon.getStatement();
String sql = "select * from 用户表 where 账号 = "+userId;
ResultSet rs = null;
try {
rs = st.executeQuery(sql);
//判断账号是否存在
if(rs.next())
{
//返回该账号对应的余额
return rs.getInt("余额");
}
} catch (SQLException e) {
e.printStackTrace();
}
//释放资源
getcon.releaseAll(rs);
return 0;
}
//获取订单号
public long getOrderId()
{
//连接数据库
GetConnection getcon = new GetConnection();
Statement st = getcon.getStatement();
//获取订单表中订单号列中的最大值
String sql = "select max(订单号) from 订单表";
ResultSet rs = null;
try {
rs = st.executeQuery(sql);
if(rs.next()){
long id = rs.getLong(1);
return id + 1;
}
} catch (SQLException e) {
e.printStackTrace();
}
getcon.releaseAll(rs);
return 0;
}
//生成订单
public boolean generOrder(Order o,int sum)
{
if(o == null)
{
return false;
}
//连接数据库
GetConnection getcon = new GetConnection();
Statement st = getcon.getStatement();
//添加订单
String sql1 = "insert into 订单表 values ("+ o.getUserId() + ","
+ getOrderId()+ ","+o.getPrice()+"," + o.getAmount() +","
+o.getSum()+ ",'" + o.getDdName() +"',"+o.getDdTel()
+",'" + o.getDdAddress() + "','" +o.getDdTime()+"','" + o.getRemark()
+"','" + o.getMenuId() + "')";
//扣除余额
String sql2 = "update 用户表 set 余额 ="+getbala(userId,sum) + " where 账号 =" +userId;
int v1 = 0;
int v2 = 0;
try {
v1 = st.executeUpdate(sql1);
v2 = st.executeUpdate(sql2);
} catch (SQLException e) {
e.printStackTrace();
}
getcon.release();
if(v1 > 0 && v2 > 0)
return true;
else
return false;
}
//获取userId对应的余额及将该用户的余额扣除sum;
public int getbala(long userId,int sum)
{
GetConnection getcon = new GetConnection();
Statement st = getcon.getStatement();
String sql = "select 余额 from 用户表 where 账号="+userId;
ResultSet rs = null;
try {
rs = st.executeQuery(sql);
if(rs.next())
return rs.getInt("余额")-sum;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
//判断字符串是否为数字
public boolean isNumber(String str)
{
if(str.length() <= 0)
return false;
for(int i = 0;i < str.length();i++)
{
if(!Character.isDigit(i))
return false;
}
return true;
}
}
|
package ideablog.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@Controller
public class ErrorController {
@RequestMapping(value = "/error", method = GET)
public String error(){
return "error";
}
}
|
package com.example.kuno.popupmenuex;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
/*
PopupMenu
- 팝업 메뉴를 제공
- 특정 위치에 팝업되어 서브 메뉴로 사용할 수 있는 메뉴를 의미한다.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnPopup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPopup = (Button) findViewById(R.id.btnPopup);
btnPopup.setOnClickListener(this);
}
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "클릭된 팝업 메뉴: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
|
package controller;
import model.DAO.UserDAO;
import model.utils.MailSender;
import model.utils.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet( "/forgetPassword")
public class ForgetPassword extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// set up response
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
// get user email
String userEmail = request.getParameter("email");
// processing
boolean checkEmail = UserDAO.checkEmail(userEmail);
boolean checkTime = UserDAO.checkGetPassTimeByEmail(userEmail, 30 * 60 * 1000);
printWriter.println(checkAndSendEmail(userEmail, checkEmail, checkTime));
}
private String checkAndSendEmail(String userEmail, boolean checkEmail, boolean checkTime) {
// email không có trong Database
if (!checkEmail) {
return "Email không đúng! Vui lòng kiểm tra lại Email!";
}
// đã gửi link lấy lại mật khẩu trong 30 gần đây
if (checkTime) {
return "Vui lòng truy cập vào email của bạn để lấy lại mật khẩu!";
}
// gửi link mới
else {
new Thread(new Runnable() {
@Override
public void run() {
// tạo chuỗi ngẫu nhiên
String randomKey = new Random().createRandomString(120);
// đặt thời gian lấy lại mật khẩu và chuỗi ngẫu nhiên vào bảng user
new UserDAO().setGetPassTimeAndRandomKeyByEmail(userEmail, randomKey);
// tạo link đổi mật khẩu
String link = "http://localhost:8080//QuanLyThuVien/resetPassword?email=" + userEmail + "&key=" + randomKey + "\n";
// gửi mail
new MailSender().sendForgetPassMail(userEmail, link);
}
}).start();
// thông báo
return "Vui lòng truy cập vào email của bạn để lấy lại mật khẩu!";
}
}
}
|
/**
*
*/
package my_searched_dir;
/**
* @author Aloy A Sen
*
*/
public class Host_per_Addr {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.serpientesescaleras.principal;
import java.io.Serializable;
/**
*
* @author nroda
*/
public class Principal implements Serializable{
public static void main(String[] args) {
Principio principio = new Principio();
}
}
|
package br.edu.fsma.fiscalizacao.main.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import br.edu.fsma.fiscalizacao.main.model.UnidadeFederativa;
public interface UnidadeFederativaRepository extends JpaRepository<UnidadeFederativa, String>{
Optional<UnidadeFederativa> findByNomeAndSigla(String nome, String sigla);
Optional<UnidadeFederativa> findByNome(String nome);
Optional<UnidadeFederativa> findBySigla(String sigla);
}
|
package br.com.sgcraft.comandos;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import br.com.sgcraft.Main;
public class ComandoX9 implements CommandExecutor {
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
if (cmd.getName().equalsIgnoreCase("x9")) {
final Player p = (Player)sender;
if (p.hasPermission("sgcraft.invsee")) {
if (args.length == 0) {
p.sendMessage(String.valueOf(Main.prefix) + " §bUtilize: §c/x9 <nick>");
}
else if (args.length == 1) {
final Player t = Bukkit.getPlayer(args[0]);
if (t == null) {
p.sendMessage(String.valueOf(Main.prefix) + Main.playerNotOnline);
return true;
}
if(t == p) {
p.sendMessage(String.valueOf(Main.prefix) + " §cVoce nao pode abrir seu inventario!");
}
else {
final Inventory inv = Bukkit.createInventory((InventoryHolder)null, 54, "§8Inventário");
inv.setItem(0, t.getInventory().getHelmet());
inv.setItem(1, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 15));
inv.setItem(2, t.getInventory().getChestplate());
inv.setItem(3, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 15));
inv.setItem(6, t.getInventory().getLeggings());
inv.setItem(5, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 15));
inv.setItem(8, t.getInventory().getBoots());
inv.setItem(7, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 15));
final ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)3);
final SkullMeta sk = (SkullMeta)skull.getItemMeta();
sk.setOwner(t.getName());
sk.setDisplayName("§b"+t.getName());
ArrayList<String> sklore = new ArrayList<>();
sklore.add("§fDinheiro: §a");
sk.setLore(sklore);
skull.setItemMeta((ItemMeta)sk);
inv.setItem(4, skull);
inv.setItem(9, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(10, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(11, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(12, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(13, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(14, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(15, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(16, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
inv.setItem(17, GiveItem(Material.STAINED_GLASS_PANE, "§3", 1, 14));
int a = 18;
for (int i = 0; i < t.getInventory().getContents().length; ++i) {
inv.setItem(a, t.getInventory().getItem(i));
++a;
}
Main.open.put(p, t);
p.openInventory(inv);
}
}
else {
p.sendMessage(String.valueOf(Main.prefix) + Main.use);
}
}
else {
p.sendMessage(String.valueOf(Main.prefix) + Main.no_perm);
}
}
return false;
}
public static ItemStack GiveItem(final Material mat, final String Name, final int amo, final int subid) {
final ItemStack is = new ItemStack(mat, amo, (short)subid);
final ItemMeta im = is.getItemMeta();
im.setDisplayName(Name);
is.setItemMeta(im);
return is;
}
}
|
package com.maliang.core.arithmetic.function;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.ComparatorUtils;
import com.maliang.core.arithmetic.AE;
import com.maliang.core.service.MapHelper;
import com.maliang.core.util.StringUtil;
import com.maliang.core.util.Utils;
public class MergeFunction {
public static void main(String[] args) {
String s = "{ps:[{product:'111',num:1},{product:'222',num:2}],"
+ "merge:[{product:'333',num:3},{product:'444',num:4},{product:'111',num:5,name:'feadasf'}]}";
s = "{ps:[{product:'111',stores:[{warehouse:'蓝天园仓库',num:1000},{warehouse:'六合仓库',num:2000}]},"
+ "{product:'333',stores:[{warehouse:'蓝天园仓库',num:1000},{warehouse:'六合仓库',num:2000}]}],"
+ "merge:[{product:'333',stores:[{warehouse:'蓝天园仓库',num:1000},{warehouse:'六合仓库',num:2000}]}]}";
// Object v = AE.execute(s);
//
// s = "ps.merge({merge:merge,on:'this.product=merge.product'})";
//
// v = AE.execute(s,(Map)v);
// System.out.println("v : " + v);
//
// v = MapHelper.expand(Utils.toArray(v), "stores".split("\\."));
// for(Object oo : (Object[])v){
// System.out.println(oo);
// }
s = "{o1:{name:'尺寸', items:'S,M', id:'5ae7f57d9f7b0310c270eb59'},o2:{name:'大小', items:'S,M', id:'FDAFDSAFSDA'}}";
s = "{ps:[{spec:'S,黑',price:100,weight:300},{spec:'M,黑',price:100},{spec:'S,红',price:100},{spec:'M,红'}],l:[{spec:'S,黑',id:'5ae7f57d9f7b0310c270eb59',price:100,store:20},{spec:'M,黑',price:100,store:20}]}";
Object v = AE.execute(s,null);
System.out.println(" v : " + v);
s = "[ps.merge({merge:l,id:['spec','price']})]";
//s = "[ps.find(spec='S,黑')]";
Object o2 = AE.execute(s,(Map<String,Object>)v);
System.out.println("ps : " + ((Map<String,Object>)v).get("ps"));
//System.out.println("o2 : " + o2);
//System.out.println("o2 : " + o2);
// s = "{ps:{product:'aaa'},merge:{product:'333',stores:[{warehouse:'蓝天园仓库',num:1000},{warehouse:'六合仓库',num:2000}}";
//
// v = AE.execute(s);{name:'大小', items:['X','L'], id:'FDAFDSAFSDA'}
//
// s = "ps.merge({merge:merge})";O
//
// v = AE.execute(s,(Map)v);
// System.out.println("----- v : " + v);
String sss = "S,黑";
int i = sss.indexOf("S");
System.out.println(" i : " + i);
List ls = new ArrayList();
ls.add(0);
ls.add(8);
boolean is = Utils.isIntegers("");
System.out.println("is : " + is);
}
public static Object execute(Function function,Map<String,Object> params){
Object val = function.getKeyValue();
Collection results = null;
if(val instanceof Collection){
results = (Collection)val;
}else if(val instanceof Object[]){
results = new ArrayList();
for(Object obj : (Object[])val){
results.add(obj);
}
}
val = function.executeExpression(params);
if(Utils.isArray(val)){
for(Object obj : Utils.toArray(val)){
results.add(obj);
}
}else if(val instanceof Map){
Object merge = MapHelper.readValue(val,"merge");
Object on = MapHelper.readValue(val,"on");
Object filter = ((Map)val).get("filter");
boolean isOn = false;
boolean isFilter = false;
if(on instanceof String && !StringUtil.isEmpty((String)on)){
isOn = true;
}else if(filter instanceof String && !StringUtil.isEmpty((String)filter)){
isFilter = true;
}
for(Object obj : Utils.toArray(merge)){
Map newParams = new HashMap();
newParams.put("merge",obj);
boolean insert = true;
for(Object oo:results){
newParams.put("this",oo);
if(isOn){
insert = false;
if(match((String)on,newParams)){
insert = true;
break;
}
}else if(isFilter){
if(match((String)filter,newParams)){
insert = false;
break;
}
}
}
if(insert){
results.add(obj);
}
}
}
return results;
}
public static Object merge(Function function,Map<String,Object> params){
Object kv = function.getKeyValue();
Object ev = function.executeExpression(params);
Object merge = readMergeValue(ev);
Object id = readIDValue(ev);
Object append = readValue(ev,"append");
doMerge(merge,kv,id,append);
return kv;
}
private static void doMerge(Object from,Object to,Object id,Object append) {
boolean canAppend = canAppend(append);
if(to instanceof List) {
if(from instanceof Map) {
boolean merged = false;
for(Object o : (List)to) {
if(o instanceof Map) {
if(matchID((Map)o,(Map)from,id)) {
((Map)o).putAll((Map)from);
merged = true;
}
}
}
if(!merged && canAppend) {
((List)to).add(from);
}
}else if(from instanceof List) {
for(Object mo : (List)from) {
doMerge(mo,to,id,append);
}
}else {
if(canAppend) {
((List)to).add(from);
}
}
}else if(to instanceof Map) {
if(from instanceof Map) {
if(matchID((Map)to,(Map)from,id)) {
((Map)to).putAll((Map)from);
}
}
}
}
private static boolean canAppend(Object append) {
if(append == null) {
return false;
}
if(append instanceof Boolean) {
return (Boolean)append;
}
return false;
}
private static boolean matchID(Map m1,Map m2,Object id) {
if(Utils.isEmpty(m1)|| Utils.isEmpty(m2)) {
return false;
}
if(Utils.isEmpty(id)) {
return true;
}
if(id instanceof List) {
boolean match = false;
for(Object oi : (List)id) {
match = matchID(m1,m2,oi);
if(!match) {
return false;
}
}
return true;
}else {
Object v1 = ((Map)m1).get(id);
Object v2 = ((Map)m2).get(id);
return v1 != null && v1.equals(v2);
}
}
public static Object readMergeValue(Object val) {
Object v = MapHelper.readValue(val,"merge");
if(v == null) {
return val;
}
return v;
}
public static Object readIDValue(Object val) {
return readValue(val,"id");
}
public static Object readValue(Object val,String key) {
if(val != null && val instanceof Map) {
if(((Map)val).containsKey("merge")) {
return ((Map)val).get(key);
}
}
return null;
}
public static Object mapMerge(Map sMap,Map merge){
if(Utils.isEmpty(sMap) || Utils.isEmpty(merge)) {
return sMap;
}
sMap.putAll(merge);
return sMap;
}
static boolean match(String str,Map params){
Object v = AE.execute(str, params);
return v != null && (v instanceof Boolean) && (Boolean)v;
}
}
|
package com.esum.ebms.v2.xmldsig;
public class EbXMLDSignerFactory {
// private static EbXMLDSigner mEbXMLDSigner = new EbXMLDSigner();
public static EbXMLDSigner getInstance() {
return new EbXMLDSigner();
}
}
|
package mf.fssq.mf_part_one;
import android.Manifest;
import android.content.Intent;
import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mf.fssq.mf_part_one.util.AndroidBug5497Workaround;
import mf.fssq.mf_part_one.util.DiaryDatabaseHelper;
import mf.fssq.mf_part_one.util.ImageUtils;
import mf.fssq.mf_part_one.util.ScreenUtils;
public class RecordActivity extends AppCompatActivity {
private TextView tv_week, tv_date;
private Map<String, String> map = new HashMap<>();
private EditText et_content;
private ImageView iv_picture;
private ImageView iv_save;
private int id;
//请求外部存储,请求码
private static final int REQUEST_EXTERNAL_STORAGE = 1;
//外部读写权限
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//插入图片的Activity的返回的code
private static final int IMAGE_CODE = 99;
//开启沉浸模式
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
//打开或关闭软键盘,使底部标签栏复位
// RecordActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//获取数据
Intent intent = getIntent();
//从intent取出bundle
Bundle bundle = intent.getBundleExtra("Database_id");
//获取id
id = Integer.parseInt(Objects.requireNonNull(bundle.getString("id")));
Log.w("test", "查询id " + id);
//初始化控件
findId();
/*
* 解决全屏模式下android:windowSoftInputMode="adjustPan"失效问题
* 参考网址:https://www.diycode.cc/topics/383
*/
AndroidBug5497Workaround.assistActivity(this);
//返回界面数据
returnData();
//初始化控件点击事件
initWidge();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//参考网址:http://blog.csdn.net/abc__d/article/details/51790806
// Bitmap bm = null;
// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
// ContentResolver resolver = getContentResolver();
if (requestCode == IMAGE_CODE) {
try {
// 获得图片的uri
Uri originalUri = data.getData();
// bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
String[] proj = {MediaStore.Images.Media.DATA};
// 好像是android多媒体数据库的封装接口,具体的看Android文档
android.database.Cursor cursor = getContentResolver().query(Objects.requireNonNull(originalUri), proj, null, null, null);
// 按我个人理解 这个是获得用户选择的图片的索引值
int column_index = Objects.requireNonNull(cursor).getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// 将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
// 最后根据索引值获取图片路径
String path = cursor.getString(column_index);
Log.w("picture"," path:"+path);
//插入图片
insertImg(path);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(RecordActivity.this, "图片插入失败", Toast.LENGTH_SHORT).show();
}
}
}
//region 插入图片
private void insertImg(String path) {
//为图片路径加上<img>标签
String tagPath = "<img src=\"" + path + "\"/>";
Log.w("picture"," tagPath:"+tagPath);
//图片解码->bitmap
Bitmap bitmap = BitmapFactory.decodeFile(path);
if (bitmap != null) {
//如果不为空,加载图片
SpannableString ss = getBitmapMime(path, tagPath);
//调用方法,将图片插入到edit text中
insertPhotoToEditText(ss);
//输出一个换行符
et_content.append("\n");
} else {
Toast.makeText(RecordActivity.this, "插入失败,无读写存储权限,请到权限中心开启", Toast.LENGTH_LONG).show();
}
}
//region 将图片插入到EditText中
private void insertPhotoToEditText(SpannableString ss) {
//先获取edit text内容
Editable et = et_content.getText();
//设置起始坐标
int start = et_content.getSelectionStart();
//设置插入位置
et.insert(start, ss);
//把et添加到edit text中
et_content.setText(et);
//设置光标在最后显示
et_content.setSelection(start + ss.length());
//Touch获取焦点
et_content.setFocusableInTouchMode(true);
//获取焦点
et_content.setFocusable(true);
}
//region 根据图片路径利用SpannableString和ImageSpan来加载图片
private SpannableString getBitmapMime(String path, String tagPath) {
//这里使用加了<img>标签的图片路径
SpannableString ss = new SpannableString(tagPath);
//获取屏幕宽度
int width = ScreenUtils.getScreenWidth(RecordActivity.this);
//获取屏幕高度
// int height = ScreenUtils.getScreenHeight(RecordActivity.this);
BitmapFactory.Options options = new BitmapFactory.Options();
//对图片进行解码
//↓等同于:Bitmap bitmap = BitmapFactory.decodeFile(path);
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
Log.w("picture", "缩放前图片宽:" + bitmap.getWidth() + "高:" + bitmap.getHeight());
//缩放比例,设置插入图片占满屏宽,高自适应调整
bitmap = ImageUtils.zoomImage(bitmap, (width - 36) * 0.93, (bitmap.getHeight() * ((width - 36) * 0.93)) / bitmap.getWidth());
Log.w("picture", "缩放后图片宽:" + bitmap.getWidth() + "高:" + bitmap.getHeight());
/*
* setSpan(what, start, end, flags)
* - what传入各种Span类型的实例;
* - start和end标记要替代的文字内容的范围;
* - flags是用来标识在Span范围内的文本前后输入新的字符时是否把它们也应用这个效果
* */
ImageSpan imageSpan = new ImageSpan(this, bitmap);
ss.setSpan(imageSpan, 0, tagPath.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return ss;
}
//region 初始化控件点击事件
private void initWidge() {
//图片点击事件
iv_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//调用图库
callGallery();
}
});
//保存点击事件
iv_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveBack();
}
});
}
//region 监听返回事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
saveBack();
}
return super.onKeyDown(keyCode, event);
}
//region 保存数据
private void saveBack() {
//SQLCipher初始化时需要初始化库
SQLiteDatabase.loadLibs(this);
DiaryDatabaseHelper mDiaryDatabaseHelper = new DiaryDatabaseHelper(this, "Diary.db", null, 1);
SQLiteDatabase db = mDiaryDatabaseHelper.getWritableDatabase("token");
String sql="update Diary set content=? where id=?";
db.beginTransaction();
db.execSQL(sql,new Object[]{et_content.getText().toString(),id});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
// Intent intent = new Intent(context, MainActivity.class);
// startActivity(intent);
Intent intent=new Intent();
setResult( 666,intent);
finish();
}
//region 调用图库
private void callGallery() {
//检查读写权限->Intent打开相册
int permission_WRITE = ActivityCompat.checkSelfPermission(RecordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permission_READ = ActivityCompat.checkSelfPermission(RecordActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permission_WRITE != PackageManager.PERMISSION_GRANTED || permission_READ != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(RecordActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
//读取相册图片
Intent getAlbum = new Intent(Intent.ACTION_PICK);
getAlbum.setType("image/*");
startActivityForResult(getAlbum, IMAGE_CODE);
}
//region 返回界面数据
private void returnData() {
DiaryDatabaseHelper mDiaryDatabaseHelper = new DiaryDatabaseHelper(this, "Diary.db", null, 1);
SQLiteDatabase db = mDiaryDatabaseHelper.getWritableDatabase("token");
//查询
String sql = "select title,week,content from Diary where id =?" ;
Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(id)});
if (cursor.moveToFirst()) {
String date = cursor.getString(cursor.getColumnIndex("title"));
String week = cursor.getString(cursor.getColumnIndex("week"));
String content = cursor.getString(cursor.getColumnIndex("content"));
map.put("title", date);
map.put("week", week);
map.put("content", content);
}
tv_date.setText(map.get("title"));
tv_week.setText(map.get("week"));
cursor.close();
db.close();
initContent();
}
private void initContent(){
//input是获取将被解析的字符串
String input = map.get("content");
//将图片那一串字符串解析出来,即<img src=="xxx" />
Pattern p = Pattern.compile("<img src=\".*?\"/>");
Matcher m = p.matcher(input);
//使用SpannableString了,这个不会可以看这里哦:http://blog.sina.com.cn/s/blog_766aa3810100u8tx.html#cmt_523FF91E-7F000001-B8CB053C-7FA-8A0
SpannableString spannable = new SpannableString(input);
while(m.find()){
//这里s保存的是整个式子,即<img src="xxx"/>,start和end保存的是下标
String s = m.group();
int start = m.start();
int end = m.end();
//path是去掉<img src=""/>的中间的图片路径
String path = s.replaceAll("<img src=\"|\"/>","").trim();
//利用spannableString和ImageSpan来替换掉这些图片
int width = ScreenUtils.getScreenWidth(RecordActivity.this);
// int height = ScreenUtils.getScreenHeight(RecordActivity.this);
Bitmap bitmap = BitmapFactory.decodeFile(path, null);
bitmap = ImageUtils.zoomImage(bitmap, (width - 36) * 0.93, (bitmap.getHeight() * ((width - 36) * 0.93)) / bitmap.getWidth());
// Bitmap bitmap = ImageUtils.getSmallBitmap(path,width,480);
ImageSpan imageSpan = new ImageSpan(this, bitmap);
spannable.setSpan(imageSpan,start,end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
et_content.setText(spannable);
et_content.append("\n");
//Log.d("YYPT_RGX_SUCCESS",content.getText().toString());
}
//region 初始化控件
private void findId() {
tv_week = findViewById(R.id.tv_week);
tv_date = findViewById(R.id.tv_date);
et_content = findViewById(R.id.et_content);
iv_picture = findViewById(R.id.iv_picture);
iv_save = findViewById(R.id.iv_save);
}
}
|
package io.cde.account.dao;
import io.cde.account.domain.Account;
import io.cde.account.domain.Mobile;
/**
* @author lcl
*/
public interface MobileDao {
/**
* 根据用户id和邮箱id判断用户是否关联该电话.
*
* @param accountId 用户id
* @param mobileId 电话id
* @return 返回用户信息
*/
Account findAccountByMobileId(String accountId, String mobileId);
/**
* 根据电话号码检查电话号码是否被使用过.
*
* @param mobile 电话号码
* @return 查询到返回true,否则返回false
*/
boolean isMobileExisted(String mobile);
/**
* 修改电话信息.
*
* @param accountId 用户id
* @param mobileId 电话信息id
* @param isVerified 要修改的电话信息
* @return 修改成功返回1,否则返回-1
*/
int updateMobile(String accountId, String mobileId, boolean isVerified);
/**
* 修改默认电话是否为公开.
*
* @param accountId 用户id
* @param isPublic 是否公开
* @return 修改成功返回1,否则返回-1
*/
int updatePublicMobile(String accountId, boolean isPublic);
/**
* 添加电话信息.
*
* @param accountId 用户id
* @param mobile 电话信息
* @return 操作成功返回1,否则返回-1
*/
int addMobile(String accountId, Mobile mobile);
/**
* 删除电话信息.
*
* @param accountId 用户id
* @param mobileId 邮箱id
* @return 操作成功返回1,否则返回-1
*/
int deleteMobile(String accountId, String mobileId);
}
|
package com.maxkuzmenchuk.new_releases_bot.repository.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(schema = "new_releases_bot", name = "user_channels")
public class Channel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "channel_name")
private String channelName;
@Column(name = "channel_id")
private Long channelId;
}
|
package com.bjit.spring.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.bjit.spring.model.Category;
import com.bjit.spring.model.Product;
import com.bjit.spring.repository.CategoryRepository;
import com.bjit.spring.repository.ProductRepository;
@Controller
public class CategoryController {
@Autowired
private CategoryRepository categoryRepository;
@GetMapping(value = "/allcategories")
public String getCategories() {
List<Category> categories = new ArrayList<>();
categoryRepository.findAll().forEach(categories::add);
for (Category category : categories) {
System.out.println(category);
}
return "index_page";
}
public List<Category> getAllCategories(){
List<Category> categories = new ArrayList<>();
categoryRepository.findAll().forEach(categories::add);
return categories;
}
}
|
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class WordNetTests {
@Test
public void constructor_Throws_WhenArgNull() {
// Arrange
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> new WordNet(null, null));
assertThrows(IllegalArgumentException.class, () -> new WordNet(null, ""));
assertThrows(IllegalArgumentException.class, () -> new WordNet("", null));
}
@Test
public void isNoun_Throws_WhenArgNull() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> wordNet.isNoun(null));
}
@Test
public void isNoun_ReturnsTrue_IfWordInAnySynset() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
List<String> nouns = Arrays.asList("'hood", "1780s", "genus_Acheta", "zymolysis", "zymosis");
List<Boolean> result = new ArrayList<>();
// Act
for (String noun : nouns) {
result.add(wordNet.isNoun(noun));
}
// Assert
for (boolean b : result) {
assertTrue(b);
}
}
@Test
public void isNoun_ReturnsFalse_IfWordNotInAnySynset() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
List<String> nouns = Arrays.asList("asd54dddd", "54dsfs46df", "78sd98f723s", "1sdf3s1d2f3", "a7a77asdd");
List<Boolean> result = new ArrayList<>();
// Act
for (String noun : nouns) {
result.add(wordNet.isNoun(noun));
}
// Assert
for (boolean b : result) {
assertFalse(b);
}
}
@Test
public void distance_Throws_WhenArgNull() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> wordNet.distance(null, null));
assertThrows(IllegalArgumentException.class, () -> wordNet.distance(null, ""));
assertThrows(IllegalArgumentException.class, () -> wordNet.distance("", null));
}
@Test
public void distance_Throws_WhenArgNotWordNetNoun() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> wordNet.distance("zymosis", "1a5d45ff"));
assertThrows(IllegalArgumentException.class, () -> wordNet.distance("1a5d45ff", "1a5d45ff"));
assertThrows(IllegalArgumentException.class, () -> wordNet.distance("1a5d45ff", "zymosis"));
}
@Test
public void distance_ReturnsDistance_WhenInput1() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
int distance = wordNet.distance("zymosis", "'hood");
// Assert
assertEquals(11, distance);
}
@Test
public void sap_Throws_WhenArgNull() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> wordNet.sap(null, null));
assertThrows(IllegalArgumentException.class, () -> wordNet.sap(null, ""));
assertThrows(IllegalArgumentException.class, () -> wordNet.sap("", null));
}
@Test
public void sap_Throws_WhenArgNotWordNetNoun() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
// Assert
assertThrows(IllegalArgumentException.class, () -> wordNet.sap("zymosis", "1a5d45ff"));
assertThrows(IllegalArgumentException.class, () -> wordNet.sap("1a5d45ff", "1a5d45ff"));
assertThrows(IllegalArgumentException.class, () -> wordNet.sap("1a5d45ff", "zymosis"));
}
@Test
public void nouns_ReturnsNouns_WhenCalled() {
// Arrange
WordNet wordNet = WordNetFactory.getWordNet();
// Act
Iterable<String> nouns = wordNet.nouns();
int count = 0;
for (String noun : nouns) {
count++;
}
// Assert
assertEquals(119188, count);
}
}
|
/*
* 文件名:xx.java
* 版权:Copyright 2015 Yiba Tech. Co. Ltd. All Rights Reserved.
* 描述: xx.java
* 修改人:wuchenhui
* 修改时间:2015-2-9
* 修改内容:新增
*/
package com.zjf.myself.codebase.thirdparty.calendar;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.zjf.myself.codebase.R;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author wuchenhui
*/
public class CalendarWindow extends FrameLayout implements View.OnClickListener{
private Animation mExpandAnimation;
private Animation mCollapseAnimation;
private boolean mIsExpand;
private View contentView;
private CalendarView calendarView;
private TextView txtMonth;
private CalendarView.OnTimeSelectListener onTimeSelectListener;
public CalendarWindow(Context context) {
this(context,null);
}
public CalendarWindow(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public CalendarWindow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
contentView= LayoutInflater.from(getContext()).inflate(R.layout.view_calendar,null);
calendarView= (CalendarView) contentView.findViewById(R.id.calendarView);
txtMonth= (TextView) contentView.findViewById(R.id.txtMonth);
contentView.findViewById(R.id.btnNextMonth).setOnClickListener(this);
contentView.findViewById(R.id.btnLastMonth).setOnClickListener(this);
contentView.findViewById(R.id.layoutBottom).setOnClickListener(this);
calendarView.setOnTimeSelectListener(new CalendarView.OnTimeSelectListener() {
@Override
public void onTimeSelect(long time) {
Date date=new Date(time);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM月");
txtMonth.setText(simpleDateFormat.format(date));
if(onTimeSelectListener !=null)
onTimeSelectListener.onTimeSelect(time);
collapse();
}
});
calendarView.setOnCalendarDateChangedListener(new CalendarView.OnCalendarDateChangedListener() {
@Override
public void onCalendarDateChanged(int year, int month) {
txtMonth.setText(month+"月");
}
});
setContentView(contentView);
calendarView.setSelectTime(System.currentTimeMillis());
Date date=new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM月");
txtMonth.setText(simpleDateFormat.format(date));
}
public void setSelectTime(long time){
calendarView.setSelectTime(time);
}
public void setOnTimeSelectListener(CalendarView.OnTimeSelectListener onTimeSelectListener) {
this.onTimeSelectListener = onTimeSelectListener;
}
public void setContentView(View view){
if(view==null)
return;
addView(view);
setVisibility(GONE);
initAnimation();
}
public void show() {
if (!mIsExpand) {
// view.setBackground(getResources().getDrawable(R.drawable.icon_cale_label_left));
mIsExpand = true;
clearAnimation();
startAnimation(mExpandAnimation);
}else {
collapse();
// view.setBackground(getResources().getDrawable(R.drawable.icon_cale_label));
}
}
private void collapse() {
if (mIsExpand) {
mIsExpand = false;
clearAnimation();
startAnimation(mCollapseAnimation);
}
}
public boolean isExpand() {
return mIsExpand;
}
private void initAnimation() {
mExpandAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.expand);
mExpandAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
});
mCollapseAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.collapse);
mCollapseAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
setVisibility(View.GONE);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnNextMonth:
calendarView.nextMonth();
break;
case R.id.btnLastMonth:
calendarView.lastMonth();
break;
case R.id.layoutBottom:
collapse();
break;
}
}
}
|
package net.tanpeng.database.c3p0;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Created by peng.tan on 18/2/1.
*/
public class C3P0Test {
public static void main(String[] args) {
Connection conn = JDBCUtil.getConnection();
System.out.println("连接成功");
//插入信息的sql语句
String sql = "select * from skill";
try {
//获取PreparedStatement对象
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getRow());
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭数据库连接
JDBCUtil.close(conn);
}
}
} |
package com.example.constraitlayout;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ActivityLihatData extends Activity {
TextView tvnama, tvnomor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lihat_data);
tvnama = (TextView) findViewById(R.id.NamaKontak);
tvnomor = (TextView) findViewById(R.id.NomorTelepon);
Bundle bundle = getIntent().getExtras();
String nama = bundle.getString("a");
switch (nama){
case "Fundik":
tvnama.setText("Fundik J");
tvnomor.setText("088809700501");
break;
case "Ilham":
tvnama.setText("M Ilham");
tvnomor.setText("08878801478");
break;
case "Lutfi":
tvnama.setText("Lutfi H");
tvnomor.setText("088211011592");
break;
case "Ali":
tvnama.setText("Ali A");
tvnomor.setText("0881025221787");
break;
case "Yoyok":
tvnama.setText("Yoyok");
tvnomor.setText("0881025221789");
break;
case "Syahra":
tvnama.setText("Syahra Q");
tvnomor.setText("08025331516");
break;
case "Rosa":
tvnama.setText("Rosa D");
tvnomor.setText("082122717100");
break;
case "Anna":
tvnama.setText("Anna");
tvnomor.setText("082122717148");
break;
case "Vian":
tvnama.setText("Vian A");
tvnomor.setText("088281191579");
break;
case "Windah":
tvnama.setText("Windah B");
tvnomor.setText("08818191429");
break;
}
}
}
|
package com.demo.helloController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ExceptionController {
@RequestMapping("/admissionform")
public ModelAndView getAdmission() throws Exception{
String exceptionOccured = "NULL_POINTER";
if(exceptionOccured.equals("NULL_POINTER"))
{
throw new NullPointerException("Null Pointer");
}
ModelAndView mv= new ModelAndView("AdmissionPage");
return mv;
}
/* @ExceptionHandler(value = NullPointerException.class)
public String handleNullPointerException(Exception e)
{
System.out.print("handling Null Pointer Exception");
return "NullPointerExceptionPage";
}
*/ //used in GLobalExceptionHandler Class
}
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.ballerinalang.net.kafka.nativeimpl.actions.producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.KafkaException;
import org.ballerinalang.bre.Context;
import org.ballerinalang.connector.api.AbstractNativeAction;
import org.ballerinalang.connector.api.ConnectorFuture;
import org.ballerinalang.model.types.TypeKind;
import org.ballerinalang.model.values.BConnector;
import org.ballerinalang.model.values.BMap;
import org.ballerinalang.model.values.BString;
import org.ballerinalang.model.values.BStruct;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.nativeimpl.actions.ClientConnectorFuture;
import org.ballerinalang.natives.annotations.Argument;
import org.ballerinalang.natives.annotations.BallerinaAction;
import org.ballerinalang.net.kafka.Constants;
import org.ballerinalang.net.kafka.KafkaUtils;
import org.ballerinalang.util.exceptions.BallerinaException;
import java.util.Properties;
/**
* Native action ballerina.net.kafka:<init> hidden action which initializes a producer instance for connector.
*/
@BallerinaAction(packageName = "ballerina.net.kafka",
actionName = "<init>",
connectorName = Constants.PRODUCER_CONNECTOR_NAME,
args = {
@Argument(name = "c",
type = TypeKind.CONNECTOR)
})
public class Init extends AbstractNativeAction {
@Override
public ConnectorFuture execute(Context context) {
BConnector producerConnector = (BConnector) getRefArgument(context, 0);
BStruct producerStruct = ((BStruct) producerConnector.getRefField(0));
BMap<String, BValue> producerBalConfig = (BMap<String, BValue>) producerStruct.getRefField(0);
Properties producerProperties = KafkaUtils.processKafkaProducerConfig(producerBalConfig);
try {
KafkaProducer<byte[], byte[]> kafkaProducer = new KafkaProducer<>(producerProperties);
if (producerProperties.get(ProducerConfig.TRANSACTIONAL_ID_CONFIG) != null) {
kafkaProducer.initTransactions();
}
BMap producerMap = (BMap) producerConnector.getRefField(1);
producerStruct.addNativeData(Constants.NATIVE_PRODUCER, kafkaProducer);
producerMap.put(new BString(Constants.NATIVE_PRODUCER), producerStruct);
} catch (IllegalStateException | KafkaException e) {
throw new BallerinaException("Failed to initialize the producer " + e.getMessage(), e, context);
}
ClientConnectorFuture future = new ClientConnectorFuture();
future.notifySuccess();
return future;
}
@Override
public boolean isNonBlockingAction() {
return false;
}
}
|
package com.biblio.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication /*implements ApplicationRunner*/ {
/*private static final Logger logger = LogManager.getLogger(ApiApplication.class);*/
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
} |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* Created by saif on 15/09/2016.
*/
public class Joueur {
private static int numero_joueur=0;
private int id_joueur;
private int i;
private int j;
private ArrayList liste_route;
private ArrayList ensemble_depart;
private ArrayList ensemble_arrive;
public Joueur(){
this.liste_route=new ArrayList();
Joueur.numero_joueur++;
this.id_joueur=Joueur.numero_joueur;
this.ensemble_arrive=new ArrayList();
this.ensemble_depart=new ArrayList();
}
public int getId_joueur() {
return this.id_joueur;
}
public void setId_joueur(int id_joueur) {
this.id_joueur = id_joueur;
}
public ArrayList getListe_route() {
return liste_route;
}
public void setListe_route(ArrayList liste_route) {
this.liste_route = liste_route;
}
public void ajouter_Route(Route route){
this.liste_route.add(route);
}
public ArrayList getEnsemble_depart() {
return ensemble_depart;
}
public void setEnsemble_depart(ArrayList ensemble_depart) {
this.ensemble_depart = ensemble_depart;
}
public ArrayList getEnsemble_arrive() {
return ensemble_arrive;
}
public void setEnsemble_arrive(ArrayList ensemble_arrive) {
this.ensemble_arrive = ensemble_arrive;
}
}
|
package Learn;
public class L21 {
public static void main(String args[]){
grade(76.5);
}
public static void grade(double score){
if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}
|
package com.baizhi.mapper;
import com.baizhi.entity.User;
public interface UserMapper {
public User queryOne(String username);
public void insert(User user);
}
|
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by Daniel on 13-May-17.
*/
public class App {
public static void main(String[] args) {
Dictionary dict = new Dictionary();
Collection<String> paths = new ArrayList<>();
paths.add("C:\\Users\\Daniel\\Source\\Repos\\Ex\\Dictionary\\file.txt");
paths.add("C:\\Users\\Daniel\\Source\\Repos\\Ex\\Dictionary\\file3.txt");
paths.add("C:\\Users\\Daniel\\Source\\Repos\\Ex\\Dictionary\\file2.txt");
dict.loadFiles2(paths);
dict.display();
}
}
|
package com.unisports.entities;
import com.unisports.enums.SportType;
import java.util.UUID;
import javax.persistence.*;
@Entity
public class Sport {
@Id
private UUID id;
private String name;
private SportType type;
public Sport(){
this.id = UUID.randomUUID();
}
public Sport(UUID id){
this.id = id;
}
public UUID getId(){
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setType(SportType type){
this.type = type;
}
public SportType getType(){
return this.type;
}
}
|
package com.ifeng.recom.mixrecall.prerank.tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by zhaohh @ 2017-12-13 11:16
**/
public class MediaEvalLevelCacheManager {
private final static Logger logger = LoggerFactory.getLogger(MediaEvalLevelCacheManager.class);
private static MediaEvalLevelCache cache = null;
public static void init() {
cache = new MediaEvalLevelCache();
cache.init();
}
public static MediaEvalLevelCache getInstance() {
if (cache == null) {
cache = new MediaEvalLevelCache();
cache.init();
}
return cache;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import org.springframework.instrument.classloading.LoadTimeWeaver;
/**
* Interface to be implemented by
* {@link org.springframework.context.annotation.Configuration @Configuration}
* classes annotated with {@link EnableLoadTimeWeaving @EnableLoadTimeWeaving}
* that wish to customize the {@link LoadTimeWeaver} instance to be used.
*
* <p>See {@link org.springframework.scheduling.annotation.EnableAsync @EnableAsync}
* for usage examples and information on how a default {@code LoadTimeWeaver}
* is selected when this interface is not used.
*
* @author Chris Beams
* @since 3.1
* @see LoadTimeWeavingConfiguration
* @see EnableLoadTimeWeaving
*/
public interface LoadTimeWeavingConfigurer {
/**
* Create, configure and return the {@code LoadTimeWeaver} instance to be used.
* Note that it is unnecessary to annotate this method with {@code @Bean}
* because the object returned will automatically be registered as a bean by
* {@link LoadTimeWeavingConfiguration#loadTimeWeaver()}
*/
LoadTimeWeaver getLoadTimeWeaver();
}
|
/**
Final version of supplementary class for phone book entries consisting of
name and number fields.
@author Simon Jones (based on original code by Kenneth J. Turner)
@version 16/11/2015
*/
public class Entry { // directory entry as record
/** Subscriber name */
private String name;
/** Subscribe phone number */
private String number;
/** Constructor for phone book entry.
@param person name of person
@param phone number of person
*/
public Entry(String person, String phone) {
name = person; // initialise name
number = phone; // initialise number
}
/**
Get the name for a phone book entry.
@return name for entry
*/
public String getName() {
return(name); // return name
}
/**
Get the number for a phone book entry.
@return number for entry
*/
public String getNumber() {
return(number); // return number
}
}
|
package com.zantong.mobilecttx.user.dto;
/**
* 提交邀请码 实体
* @author Sandy
* create at 16/6/8 下午11:48
*/
public class PersonInfoDTO {
private String usrid; //用户id
private String phoenum; //用户手机号
private String devicetoken; //用户设备号
private int pushswitch; //是否推送 0不 1推
private String recdphoe; //邀请码 推荐人手机号
private String getdate; //首次领证日期
public String getUsrid() {
return usrid;
}
public void setUsrid(String usrid) {
this.usrid = usrid;
}
public String getPhoenum() {
return phoenum;
}
public void setPhoenum(String phoenum) {
this.phoenum = phoenum;
}
public String getDevicetoken() {
return devicetoken;
}
public void setDevicetoken(String devicetoken) {
this.devicetoken = devicetoken;
}
public String getRecdphoe() {
return recdphoe;
}
public void setRecdphoe(String recdphoe) {
this.recdphoe = recdphoe;
}
public int getPushswitch() {
return pushswitch;
}
public void setPushswitch(int pushswitch) {
this.pushswitch = pushswitch;
}
public String getGetdate() {
return getdate;
}
public void setGetdate(String getdate) {
this.getdate = getdate;
}
}
|
package com.legaoyi.data.service.impl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.legaoyi.data.mongo.MongoDao;
import com.legaoyi.data.service.CarReportService;
import com.mongodb.client.result.UpdateResult;
@Service("carReportService")
public class CarReportServiceImpl implements CarReportService {
@SuppressWarnings("rawtypes")
@Autowired
private MongoDao mongoDao;
@Override
public void updateCarReport(String date, Map<String, Object> device, Map<String, Object> data) {
String deviceId = (String) device.get("deviceId");
String carId = (String) device.get("carId");
String enterpriseId = (String) device.get("enterpriseId");
String month = date.substring(0, 6);
String id = month.concat("_").concat(deviceId);
Query query = new Query();
// 按月每个设备一条统计信息
query.addCriteria(Criteria.where("_id").is(id));
Update update = new Update();
for (String key : data.keySet()) {
update.set(key, data.get(key));
}
UpdateResult result = mongoDao.getMongoTemplate().updateFirst(query, update, "car_report");
if (result.getMatchedCount() == 0) {
data.put("_id", id);
data.put("month", Integer.parseInt(month));
data.put("year", Integer.parseInt(date.substring(0, 4)));
data.put("devieId", deviceId);
data.put("enterpriseId", enterpriseId);
if (carId != null) {
data.put("carId", carId);
}
mongoDao.getMongoTemplate().insert(data, "car_report");
}
}
@Override
public void incCarReport(String date, Map<String, Object> device, Map<String, Object> data) {
String deviceId = (String) device.get("deviceId");
String carId = (String) device.get("carId");
String enterpriseId = (String) device.get("enterpriseId");
String month = date.substring(0, 6);
String id = month.concat("_").concat(deviceId);
Query query = new Query();
// 按月每个设备一条统计信息
query.addCriteria(Criteria.where("_id").is(id));
Update update = new Update();
for (String key : data.keySet()) {
Object value = data.get(key);
if (value instanceof Long) {
update.inc(key, (Long) value);
} else if (value instanceof Integer) {
update.inc(key, (Integer) value);
} else if (value instanceof Double) {
update.inc(key, (Double) value);
} else if (value instanceof Float) {
update.inc(key, (Float) value);
} else {
update.inc(key, Integer.parseInt(String.valueOf(value)));
}
}
UpdateResult result = mongoDao.getMongoTemplate().updateFirst(query, update, "car_report");
if (result.getMatchedCount() == 0) {
data.put("_id", id);
data.put("month", Integer.parseInt(month));
data.put("year", Integer.parseInt(date.substring(0, 4)));
data.put("devieId", deviceId);
data.put("enterpriseId", enterpriseId);
if (carId != null) {
data.put("carId", carId);
}
mongoDao.getMongoTemplate().insert(data, "car_report");
}
}
}
|
package am.ipc.lesosn1;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class ProfileActivity extends AppCompatActivity {
TextView login_tv;
TextView pass_tv;
TextView age_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
login_tv = (TextView) findViewById(R.id.login_tv);
pass_tv = (TextView) findViewById(R.id.pass_tv);
age_tv = (TextView) findViewById(R.id.age_tv);
login_tv.setText(App.i().getLogin());
pass_tv.setText(App.i().getPassword());
age_tv.setText(""+App.i().getAge());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.settings,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()){
case R.id.settings:
i = new Intent(this, SettingsActivity.class);
startActivity(i);
break;
case R.id.log_out:
App.i().saveRemember(false);
i = new Intent(this, LoginActivity.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
finish();
}
}
|
package auxiliares;
import auxiliares.Punto;
/*
* Clase que modela a un vector de 2 dimensiones, con componentes enteras.
*/
public class Vector {
private Punto punto;
public Vector(Punto punto) {
this.punto = punto;
}
public Vector(int x, int y) {
this(new Punto(x, y));
}
public double norma() {
int x = this.getComponenteX();
int y = this.getComponenteY();
double suma = Math.pow(x, 2) + Math.pow(y, 2);
return Math.sqrt(suma);
}
public int getComponenteX() {
return this.punto.getX();
}
public void setComponenteX(int x) {
this.punto.setX(x);
}
public int getComponenteY() {
return this.punto.getY();
}
public void setComponenteY(int y) {
this.punto.setY(y);
}
public Punto getPunto() {
return punto;
}
public void setPunto(Punto punto) {
this.punto = punto;
}
@Override
public String toString() {
return punto.getX() + "@" + punto.getY();
}
}
|
package com.bham.sso.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
* <p>Title: RootController.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2017</p>
* <p>Company: UOB</p>
* @author RuJia
* @date 2017年1月31日
* @version 1.0
*/
@RestController
public class RootController {
@RequestMapping("/")
public String onRootAccess() {
return "Hello Docker World."
+ "<br />Welcome to <a href='http://www.ehcoo.com'>ehcoo.com</a></li>";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.