text stringlengths 10 2.72M |
|---|
package com.cinema.biz.model.base;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="sim_repair")
public class TSimRepair {
@Id
private String repairId;
private String faultId;
private String repairDesc;
private Date repairTime;
private Date createTime;
private String creator;
private Date updateTime;
private String updator;
public String getRepairId() {
return repairId;
}
public void setRepairId(String repairId) {
this.repairId = repairId == null ? null : repairId.trim();
}
public String getFaultId() {
return faultId;
}
public void setFaultId(String faultId) {
this.faultId = faultId == null ? null : faultId.trim();
}
public String getRepairDesc() {
return repairDesc;
}
public void setRepairDesc(String repairDesc) {
this.repairDesc = repairDesc == null ? null : repairDesc.trim();
}
public Date getRepairTime() {
return repairTime;
}
public void setRepairTime(Date repairTime) {
this.repairTime = repairTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdator() {
return updator;
}
public void setUpdator(String updator) {
this.updator = updator == null ? null : updator.trim();
}
} |
package com.unifacisa.si2.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.unifacisa.si2.domains.BookPublisher;
import com.unifacisa.si2.repositories.BookPublisherRepository;
@Service
public class BookPublisherService {
@Autowired
private BookPublisherRepository bookPublisherRepository;
public BookPublisher createBookPublisher(BookPublisher bookPublisher) {
return bookPublisherRepository.save(bookPublisher);
}
public List<BookPublisher> findAll() {
return bookPublisherRepository.findAll();
}
public BookPublisher findById(Long id) {
return bookPublisherRepository.findById(id).get();
}
public void deleteBookPublisher(Long id) {
bookPublisherRepository.deleteById(id);
}
public BookPublisher findByName(String name) {
return bookPublisherRepository.findByName(name);
}
}
|
/**
*
* This code is provided solely as sample code for using Lucene.
*
*/
package TestIndex;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.similarities.BM25Similarity;
public class LuceneTester {
/** Define the paths for the data file and the lucene index */
public static final String BUSINESSDATA_FILE="./dataset/business.json";
public static final String USERDATA_FILE="./dataset/user.json";
public static final String REVIEWDATA_FILE="./dataset/review.json";
public static final String TIPDATA_FILE="./dataset/tip.json";
public static final String INDEX_PATH="./luceneIndex";
public static final int BOOLEAN_QUERY_TYPE =0;
public static final int DISTANCE_QUERY_TYPE =1;
public static final int RANGE_QUERY_TYPE=2;
public static void main (String[] arg) throws Exception{
//only the first time need to be true
boolean preformIndex=true;
if(preformIndex){
QAIndexer indexer = new QAIndexer(LuceneTester.INDEX_PATH);
String[] indexPaths = {BUSINESSDATA_FILE, USERDATA_FILE, REVIEWDATA_FILE, TIPDATA_FILE};
indexer.indexAllfiles(indexPaths);
}
//search index
QASearcher searcher=new QASearcher(LuceneTester.INDEX_PATH);
ScoreDoc[] hits = null;
List<SearchQuery> queries = new ArrayList<SearchQuery>();
/*----------create 20 queries, and retrieve top 10 results----------*/
//1: Restaurant named Village Juicery
queries.add(new SearchQuery("name", "Village Juicery", 0,"AND"));
//2: Business with stars from 4.5 to 4.8
//queries.add(new SearchQuery("stars", 4.5, 4.9, RANGE_QUERY_TYPE, "OR"));
//3: See the Dentist
//queries.add(new SearchQuery("categories", "Dentists", BOOLEAN_QUERY_TYPE,"AND"));
//4: Find the Location of the place
//queries.add(new SearchQuery("location", 35.0, -80.0, 300000.0, DISTANCE_QUERY_TYPE, "AND"));
// 5: Business with review count from 22 to 100
//queries.add(new SearchQuery("review_count", 22.0, 100.0, RANGE_QUERY_TYPE, "OR"));
//6: Places with free wifi
//queries.add(new SearchQuery("WiFi", "free", BOOLEAN_QUERY_TYPE,"AND"));
//7: Restaurant serving seafood
//queries.add(new SearchQuery("categories", "seafood", BOOLEAN_QUERY_TYPE,"AND"));
//8: Counselling for property management
//queries.add(new SearchQuery("categories", "Property Management", BOOLEAN_QUERY_TYPE,"AND"));
//9: Business near university city
//queries.add(new SearchQuery("neighborhood", "University City", BOOLEAN_QUERY_TYPE,"AND"));
//10: searching for fast food
//queries.add(new SearchQuery("text", "fast food", RANGE_QUERY_TYPE,"AND"));
//11: searching for Haircut
//queries.add(new SearchQuery("text", "Haircut", RANGE_QUERY_TYPE,"AND"));
//12: Restaurant serving buffet
//queries.add(new SearchQuery("text", "buffet", RANGE_QUERY_TYPE,"AND"));
//13: Restaurant serving Chinese Food
//queries.add(new SearchQuery("text", "Chinese Food", RANGE_QUERY_TYPE,"AND"));
//14: Restaurant serving western Food
//queries.add(new SearchQuery("text", "western Food", RANGE_QUERY_TYPE,"AND"));
//15: Iphone purchasing
//queries.add(new SearchQuery("text", "iPhone", RANGE_QUERY_TYPE,"AND"));
//16: Women's Clothing
//queries.add(new SearchQuery("text", "Women's Clothing", RANGE_QUERY_TYPE,"AND"));
//17: Store for sport shoes
//queries.add(new SearchQuery("text", "sport shoes", RANGE_QUERY_TYPE,"AND"));
//18: Medical clinic for human being
//queries.add(new SearchQuery("text", "medical clinic", RANGE_QUERY_TYPE,"AND"));
//19: Massage services
//queries.add(new SearchQuery("text", "massage", RANGE_QUERY_TYPE,"AND"));
//20: Romantic place
//queries.add(new SearchQuery("text", "romantic", RANGE_QUERY_TYPE,"AND"));
SearchQuery[] queryArray = queries.toArray(new SearchQuery[0]);
Query query = searcher.createQuery(queryArray);
/*---------------------2 retrieval model used---------------------*/
System.out.println("Retrieval Model: BM25Similarity");
hits=searcher.search(query, 5, new BM25Similarity());
searcher.printResult(hits);
searcher.explain(query, hits);
System.out.println("Retrieval Model: TFIDFSimilarity");
hits=searcher.search(query, 5, new ClassicSimilarity());
searcher.printResult(hits);
searcher.explain(query, hits);
}
}
|
package io.chark.food.app.account;
import io.chark.food.app.moderate.newsletter.NewsletterModerationService;
import io.chark.food.domain.authentication.account.Account;
import io.chark.food.domain.extras.Color;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
public class AccountController {
private final AccountService accountService;
private final NewsletterModerationService newsletterModerationService;
@Autowired
public AccountController(AccountService accountService, NewsletterModerationService newsletterModerationService) {
this.accountService = accountService;
this.newsletterModerationService = newsletterModerationService;
}
@RequestMapping(value = "/login")
public String login() {
return "account/login";
}
/**
* Get register page and send an empty registration model to the register page.
*/
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Model model) {
model.addAttribute("register", new AccountRegisterModel());
return "account/register";
}
/**
* Register using for validation and models.
*
* @param register registration model.
*/
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@ModelAttribute("register") @Valid AccountRegisterModel register,
BindingResult result,
RedirectAttributes attributes,
Model model) {
// Basic input validation.
register.validate(result);
if (result.hasErrors()) {
return "account/register";
}
// Perform the actual register.
boolean created = accountService.register(
register.getUsername(),
register.getEmail(),
register.getPassword())
.isPresent();
// Email might be taken and etc.
if (!created) {
model.addAttribute("error", "Invalid credentials, please try again");
return "account/register";
}
// Flash attributes are required during redirects!
attributes.addFlashAttribute("success", "Account created, now you can log in");
return "redirect:/login";
}
/**
* View profile details.
*/
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String profile(Model model) {
model.addAttribute("account", accountService.getAccount());
model.addAttribute("newsletters", newsletterModerationService.getPublishedNewsletter());
return "account/profile";
}
/**
* Update account profile details.
*
* @param account details used in updating.
*/
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public String profile(Account account, RedirectAttributes attributes) {
if (!accountService.update(account).isPresent()) {
attributes.addFlashAttribute("error", "Could not update your profile details, the email might be" +
" taken or some error occurred.");
}
attributes.addFlashAttribute("profileTab", true);
return "redirect:/profile";
}
/**
* Accept or ignore invitation to join a restaurant.
*
* @param id invitation id.
* @param accept should the invitation be accepted or ignored.
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/profile/api/invitation/{id}", method = RequestMethod.POST)
public void invitation(@PathVariable long id, @RequestParam boolean accept) {
// Either accept or ignore the invitation.
if (accept) {
accountService.acceptInvitation(id);
} else {
accountService.ignoreInvitation(id);
}
}
} |
/*
* Created by SixKeyStudios
* Added in project Technicalities
* File configmanagers.textures / TextureUnit
* created on 25.5.2019 , 12:44:20
*/
package technicalities.configmanagers.textures;
import java.awt.Point;
/**
*
* @author filip
*/
public class TextureUnit{
public String itemId;
public String spriteSheetId;
public Point start;
public Point end;
public TextureUnit(String itemId, String spriteSheetId, Point start, Point end) {
this.itemId = itemId;
this.spriteSheetId = spriteSheetId;
this.start = start;
this.end = end;
}
@Override
public String toString() {
return itemId + " " + spriteSheetId + " " + start.toString() + " " + end.toString();
}
}
|
/*
* 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 btnhom1;
import java.io.Serializable;
/**
*
* @author Linh Liv
*/
public class PLGV implements Serializable{
private int maPL;
private String tenPL;
public PLGV(int maPL, String tenPL) {
this.maPL = maPL;
this.tenPL = tenPL;
}
public int getMaPL() {
return maPL;
}
public void setMaPL(int maPL) {
this.maPL = maPL;
}
public String getTenPL() {
return tenPL;
}
public void setTenPL(String tenPL) {
this.tenPL = tenPL;
}
@Override
public String toString() {
return "PLGV{" + "maPL=" + maPL + ", tenPL=" + tenPL + '}';
}
}
|
package waslny.task.foursquareexplorer;
import java.util.ArrayList;
import waslny.task.activity.MainActivity;
import waslny.task.activity.VenueInfoActivity;
import android.location.Location;
import android.widget.Toast;
import br.com.condesales.EasyFoursquare;
import br.com.condesales.criterias.CheckInCriteria;
import br.com.condesales.criterias.VenuesCriteria;
import br.com.condesales.listeners.AccessTokenRequestListener;
import br.com.condesales.models.Checkin;
import br.com.condesales.models.Venue;
public class FourSquareOper implements AccessTokenRequestListener
{
private EasyFoursquare sync;
MainActivity actv;
VenueInfoActivity venueActv;
String venue_id;
//private EasyFoursquareAsync async;
public FourSquareOper(VenueInfoActivity venueActv)
{
this.venueActv = venueActv;
sync = new EasyFoursquare(venueActv);
}
public FourSquareOper(MainActivity actv)
{
this.actv = actv;
sync = new EasyFoursquare(actv);
//async = new EasyFoursquareAsync(actv);
}
public void login(String venue_id)
{
System.out.println("IN LOGIIIIN");
this.venue_id = venue_id;
sync.requestAccess(this);
}
@Override
public void onError(String errorMsg)
{
// TODO Auto-generated method stub
Toast.makeText(actv, errorMsg, Toast.LENGTH_LONG).show();
}
@Override
public void onAccessGrant(String accessToken)
{
// TODO Auto-generated method stub
//sync.getUserInfo();
System.out.println("LOGIIN SUCESS, VENUE ID= "+venue_id);
System.out.println("accessTOKEEEN"+accessToken);
checkin(venue_id);
}
public ArrayList<Venue> requestVenusNearby(double ltd, double lng)
{
Location loc = new Location("");
loc.setLatitude(ltd);
loc.setLongitude(lng);
ArrayList<Venue> venuesNearBy =new ArrayList<Venue>();
Venue tempVenue = new Venue();
tempVenue.setName("NoVenues");
VenuesCriteria criteria = new VenuesCriteria();
criteria.setLocation(loc);
venuesNearBy = sync.getVenuesNearby(criteria);
System.out.println("# Venues= "+venuesNearBy.size());
if(venuesNearBy.size() == 0)
venuesNearBy.add(tempVenue);
return venuesNearBy;
}
public void requestVenuDetails(String venue_id)
{
sync.getVenueDetail(venue_id);
}
public void checkin(String venueID)
{
CheckInCriteria criteria = new CheckInCriteria();
criteria.setBroadcast(CheckInCriteria.BroadCastType.PUBLIC);
criteria.setVenueId(venueID);
Checkin ch = sync.checkIn(criteria);
System.out.println("VID= "+venueID);
System.out.println("CHECKIN ID= "+ch.getId());
if(ch.getId().equals(""))
{
Toast.makeText(venueActv, "Can't Check-in!",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(venueActv, "Checked-in successfully!",Toast.LENGTH_LONG).show();
}
}
|
package DesignPatternCodeGenerator;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Mock class to test the functioning of methods of CodeGenerator
*
* @author Harish Venkataraman
*/
class CodeGeneratorMock extends CodeGenerator {
public CodeGeneratorMock(String filename) {
super(filename);
}
public Document buildCode() throws BadLocationException {
this.createTypeDeclaration(this.fileName, false, CodeGenerator.publicKeyword,
false, false, null, null);
// main method
MethodDeclaration mainMethod = this.createMainMethodDeclaration();
// field declaration
FieldDeclaration fieldDeclaration = this.createFieldDeclaration(
"classField",
this.createPrimitiveType(CodeGenerator.intType),
CodeGenerator.privateKeyword,
false
);
// operation method
MethodDeclaration operationMethod = this.declareMethod("operation",
this.createPrimitiveType(CodeGenerator.voidType), CodeGenerator.publicKeyword,
false, false);
Block operationBlock = this.createBlock();
StringLiteral argument = this.abstractSyntaxTree.newStringLiteral();
argument.setLiteralValue("Hello world");
Statement printStatement = this.createPrintStatement(argument);
operationBlock.statements().add(printStatement);
FieldAccess fieldAccess = this.createFieldAccessExpression(
this.abstractSyntaxTree.newSimpleName("classField"));
operationBlock.statements().add(this.abstractSyntaxTree.newExpressionStatement(fieldAccess));
operationMethod.setBody(operationBlock);
// add field to class
this.classDeclaration.bodyDeclarations().add(fieldDeclaration);
// add method to class
this.classDeclaration.bodyDeclarations().add(mainMethod);
this.classDeclaration.bodyDeclarations().add(operationMethod);
// add class to CU
this.compilationUnit.types().add(this.classDeclaration);
// apply edits to document
this.applyEdits();
// return this document
return this.document;
}
}
/**
* Unit test cases for testing specific components of CodeGenerator
*/
public class CodeGeneratorTest {
private CodeGeneratorMock mockCodeGenerator;
private Document mockDocumentObject;
public CodeGeneratorTest() throws BadLocationException {
mockCodeGenerator = new CodeGeneratorMock("MockClassName");
mockDocumentObject = mockCodeGenerator.buildCode();
}
/**
* Tests createTypeDeclaration() method of CodeGenerator
*/
@Test
public void shouldCreateCorrectClass() {
TypeDeclaration retrievedType = mockCodeGenerator.classDeclaration;
String retrievedTypeName = retrievedType.getName().toString();
String retrievedModifier = retrievedType.modifiers().get(0).toString();
assertEquals("name should match", retrievedTypeName, "MockClassName");
assertEquals("should be public", retrievedModifier, "public");
}
/**
* Tests createMainMethod() method of CodeGenerator
*/
@Test
public void shouldAddMainMethod() {
MethodDeclaration retrievedMainMethodDeclaration =
mockCodeGenerator.classDeclaration.getMethods()[0];
String retrievedMethodName = retrievedMainMethodDeclaration.getName().toString();
String retrievedMethodReturnType = retrievedMainMethodDeclaration.getReturnType2().toString();
String retrievedModifier = retrievedMainMethodDeclaration.modifiers().get(0).toString();
assertEquals("should be main", retrievedMethodName, "main");
assertEquals("should be void", retrievedMethodReturnType, "void");
assertEquals("should be public", retrievedModifier, "public");
}
/**
* Tests createFieldDeclaration() method of CodeGenerator
*/
@Test
public void shouldAddField() {
FieldDeclaration retrievedFieldDeclaration =
mockCodeGenerator.classDeclaration.getFields()[0];
String retrievedFieldName = retrievedFieldDeclaration.fragments().get(0).toString();
String retrievedType = retrievedFieldDeclaration.getType().toString();
String retrievedModifier = retrievedFieldDeclaration.modifiers().get(0).toString();
assertEquals("should be classField", retrievedFieldName, "classField");
assertEquals("should be int", retrievedType, "int");
assertEquals("should be private", retrievedModifier, "private");
}
/**
* Tests createBlock() and createPrintStatement() method of CodeGenerator
*/
@Test
public void shouldAddBlock() {
MethodDeclaration operationMethodDeclaration =
mockCodeGenerator.classDeclaration.getMethods()[1];
Block operationMethodBlock = operationMethodDeclaration.getBody();
ExpressionStatement retrievedStatement = (ExpressionStatement) operationMethodBlock.statements().get(0);
MethodInvocation retrievedFunctionCall = (MethodInvocation) retrievedStatement.getExpression();
String retrievedFunctionName = retrievedFunctionCall.getName().toString();
assertEquals("should be println", retrievedFunctionName, "println");
}
/**
* Tests FieldAccess creation of CodeGenerator
*/
@Test
public void shouldAddFieldAcess() {
MethodDeclaration operationMethodDeclaration =
mockCodeGenerator.classDeclaration.getMethods()[1];
Block operationMethodBlock = operationMethodDeclaration.getBody();
ExpressionStatement retrievedStatement = (ExpressionStatement) operationMethodBlock.statements().get(1);
FieldAccess retrievedFieldAccess = (FieldAccess) retrievedStatement.getExpression();
String retrievedFieldName = retrievedFieldAccess.getName().toString();
assertEquals("should be classField", retrievedFieldName, "classField");
}
@AfterClass
public static void displayLogMessage() {
Logger logger = LoggerFactory.getLogger("DesignPatternCodeGenerator.CodeGeneratorTest");
logger.debug("Finished testing");
}
}
|
package com.itheima.bos.web.action;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.itheima.bos.domain.Role;
import com.itheima.bos.web.action.base.BaseAction;
/**
* 角色管理Action
* @author zhaoqx
*
*/
@Controller
@Scope("prototype")
public class RoleAction extends BaseAction<Role>{
private String funcitonIds;//权限ID
/**
* 添加角色方法
*/
public String add(){
roleService.save(model,funcitonIds);
return "list";
}
/**
* 分页查询方法
*/
public String pageQuery(){
roleService.pageQuery(pageBean);
String[] excludes = new String[]{ "currentPage", "pageSize","detachedCriteria","functions","users"};
this.writePageBean2Json(pageBean, excludes );
return NONE;
}
/**
* 查询所有角色,返回json数据
*/
public String listajax(){
List<Role> list = roleService.findAll();
String[] excludes = new String[]{"functions","users"};
this.writeListBean2Json(list, excludes );
return NONE;
}
public void setFuncitonIds(String funcitonIds) {
this.funcitonIds = funcitonIds;
}
}
|
package com.github.ytjojo.supernestedlayout;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/3/4 0004.
*/
public class ViewGroupUtil {
public static void getDescendantRect(ViewGroup parent, View descendant, Rect rect) {
rect.set(0,0,descendant.getMeasuredWidth(),descendant.getMeasuredHeight());
parent.offsetDescendantRectToMyCoords(descendant, rect);
// // already in the same coord system :)
// if (descendant == parent) {
// return;
// }
// ViewParent theParent = descendant.getParent();
//
// // search and offset up to the parent
// while ((theParent != null)
// && (theParent instanceof View)
// && (theParent != parent)) {
//
// rect.offset((int) (descendant.getX() - descendant.getScrollX()),
// (int) (descendant.getY() - descendant.getScrollY()));
//
// descendant = (View) theParent;
// theParent = descendant.getParent();
// }
//
// // now that we are up to this view, need to offset one more time
// // to get into our coordinate space
// if (theParent == parent) {
// rect.offset((int) (descendant.getX() - descendant.getScrollX()),
// (int) (descendant.getY() - descendant.getScrollY()));
// } else {
// throw new IllegalArgumentException("parameter must be a descendant of this view");
// }
}
public static boolean isPointInChild(View parent,View child,int x,int y){
Rect rect = new Rect();
// child.getDrawingRect(rect);
rect.left = parent.getScrollX()+child.getLeft();
rect.top = parent.getScrollY()+child.getTop();
rect.right = parent.getScrollX()+child.getRight();
rect.bottom = parent.getScrollY()+child.getBottom();
return rect.contains(x,y);
}
public static boolean hasChildWithZ(ViewGroup viewGroup) {
final int mChildrenCount = viewGroup.getChildCount();
for (int i = 0; i < mChildrenCount; i++) {
if (viewGroup.getChildAt(i).getZ() != 0) return true;
}
return false;
}
public static View findTouchedChild(SuperNestedLayout parent,int x,int y){
ArrayList<View> orderedList = parent.buildTouchDispatchChildList();
if(orderedList !=null){
int size = orderedList.size();
for(int i=size-1;i>=0;i--){
View child = orderedList.get(i);
if(child.getVisibility() != View.VISIBLE){
continue;
}
if(isPointInChild(parent,child,x,y)){
return child;
}
}
}else{
int size = parent.getChildCount();
for(int i= size-1 ; i >= 0 ; i--){
View child = parent.getChildAt(i);
if(child.getVisibility() != View.VISIBLE){
continue;
}
if(isPointInChild(parent,child,x,y)){
return child;
}
}
}
return null;
}
}
|
package MobileKasse;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import Listener.Artikellistener;
import Schnittstellen.RestSchnittstelle;
import com.kellnersystem.main.Kellnersystem.Tisch.Bestellungen.Bestellung;
import com.kellnersystem.main.Kellnersystem.Tisch.Bestellungen.Bestellung.Artikellist;
public class OF_Bestellung {
List<JButton> buttons = new ArrayList<JButton>();
public Bestellung bestellung = new Bestellung();
int tischNummer;
Kellner kellner;
public OF_Bestellung(int tischNummer,Kellner kellner){
this.tischNummer = tischNummer;
this.kellner = kellner;
bestellung.setArtikellist(new Artikellist());
}
public JPanel artikelliste(){
JPanel panel = new JPanel();
panel.setSize(800,600);
panel.setLayout(null);
//Get alle artikel
int artikelanzahl = kellner.artikelliste.size();
int x = 50;
int y = 50;
JLabel top = new JLabel("Artikelliste");
top.setBounds(0, 0, 800, 70);
top.setFont(new Font("",Font.PLAIN,20));
top.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(top);
JButton ok = new JButton("Bestellen");
ok.setBounds(645, 520, 150, 50);
ok.setFont(new Font("",Font.PLAIN,20));
panel.add(ok);
for(int i=0;i<artikelanzahl;i++){
buttons.add(new JButton(kellner.artikelliste.get(i).getArtikelName()));
if(i%4==0){
y+=60;
x = 0;
}
buttons.get(i).setBounds(x+=140, y, 120, 40);
buttons.get(i).addActionListener(new Artikellistener(kellner.artikelliste.get(i).getArtikelId(),bestellung));
panel.add(buttons.get(i));
}
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
RestSchnittstelle rs = new RestSchnittstelle();
rs.postBestellung(bestellung, tischNummer);
kellner.zeichneOberflaeche();
}
});
return panel;
}
}
|
package com.jgw.supercodeplatform.trace.dao.mapper1.producttesting;
import com.jgw.supercodeplatform.trace.dao.CommonSql;
import com.jgw.supercodeplatform.trace.pojo.producttesting.ProductTesting;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
@Mapper
public interface ProductTestingMapper extends CommonSql {
@Delete({
"delete from trace_ProductTesting",
"where Id = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
@Insert({
"insert into trace_ProductTesting (Id, ProductTestingId, ",
"OrganizationId, ThirdpartyOrganizationId, ",
"ProductID, TraceBatchInfoId, ",
"TestingDate, TestingMan, ",
"CreateMan, CreateTime, ",
"CreateId, TestingType, Excel, CertifyNumber," ,
"TraceBatchInfoName,ProductName,TestingManName, OrganizeId, OrganizationName, organizeName, thirdpartyOrganizationName, SysId)",
"values (#{id,jdbcType=INTEGER}, #{productTestingId,jdbcType=VARCHAR}, ",
"#{organizationId,jdbcType=VARCHAR}, #{thirdpartyOrganizationId,jdbcType=VARCHAR}, ",
"#{productID,jdbcType=VARCHAR}, #{traceBatchInfoId,jdbcType=VARCHAR}, ",
"#{testingDate,jdbcType=VARCHAR}, #{testingMan,jdbcType=VARCHAR}, ",
"#{createMan,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, ",
"#{createId,jdbcType=VARCHAR},#{testingType,jdbcType=INTEGER},#{excel,jdbcType=VARCHAR},#{certifyNumber,jdbcType=VARCHAR}" ,
",#{traceBatchInfoName,jdbcType=VARCHAR},#{productName,jdbcType=VARCHAR},#{testingManName,jdbcType=VARCHAR},#{organizeId,jdbcType=VARCHAR},#{organizationName,jdbcType=VARCHAR},#{organizeName,jdbcType=VARCHAR},#{thirdpartyOrganizationName,jdbcType=VARCHAR}, #{sysId,jdbcType=VARCHAR})"
})
int insert(ProductTesting record);
@Select({
"select",
"Id, ProductTestingId, OrganizationId, ThirdpartyOrganizationId, ProductID, TraceBatchInfoId, ",
"TestingDate, TestingMan, CreateMan, CreateTime, CreateId, TestingType, CertifyNumber,Excel,TraceBatchInfoName,ProductName,TestingManName,ThirdpartyOrganizationName "+
"from trace_ProductTesting",
"where Id = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="Id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="ProductTestingId", property="productTestingId", jdbcType=JdbcType.VARCHAR),
@Result(column="OrganizationId", property="organizationId", jdbcType=JdbcType.VARCHAR),
@Result(column="ThirdpartyOrganizationId", property="thirdpartyOrganizationId", jdbcType=JdbcType.VARCHAR),
@Result(column="ProductID", property="productID", jdbcType=JdbcType.VARCHAR),
@Result(column="TraceBatchInfoId", property="traceBatchInfoId", jdbcType=JdbcType.VARCHAR),
@Result(column="TestingDate", property="testingDate", jdbcType=JdbcType.VARCHAR),
@Result(column="TestingMan", property="testingMan", jdbcType=JdbcType.VARCHAR),
@Result(column="CreateMan", property="createMan", jdbcType=JdbcType.VARCHAR),
@Result(column="CreateTime", property="createTime", jdbcType=JdbcType.TIMESTAMP),
@Result(column="ThirdpartyOrganizationName", property="thirdpartyOrganizationName", jdbcType=JdbcType.VARCHAR),
@Result(column="CreateId", property="createId", jdbcType=JdbcType.VARCHAR)
})
ProductTesting selectByPrimaryKey(Integer id);
@Select({
"select",
"Id, ProductTestingId, OrganizationId, ThirdpartyOrganizationId, ProductID, TraceBatchInfoId, ",
"TestingDate, TestingMan, CreateMan, CreateTime, CreateId, TestingType",
"from trace_ProductTesting"
})
@Results({
@Result(column="Id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="ProductTestingId", property="productTestingId", jdbcType=JdbcType.VARCHAR),
@Result(column="OrganizationId", property="organizationId", jdbcType=JdbcType.VARCHAR),
@Result(column="ThirdpartyOrganizationId", property="thirdpartyOrganizationId", jdbcType=JdbcType.VARCHAR),
@Result(column="ProductID", property="productID", jdbcType=JdbcType.VARCHAR),
@Result(column="TraceBatchInfoId", property="traceBatchInfoId", jdbcType=JdbcType.VARCHAR),
@Result(column="TestingDate", property="testingDate", jdbcType=JdbcType.VARCHAR),
@Result(column="TestingMan", property="testingMan", jdbcType=JdbcType.VARCHAR),
@Result(column="CreateMan", property="createMan", jdbcType=JdbcType.VARCHAR),
@Result(column="CreateTime", property="createTime", jdbcType=JdbcType.TIMESTAMP),
@Result(column="CreateId", property="createId", jdbcType=JdbcType.VARCHAR)
})
List<ProductTesting> selectAll();
@Update({
"update trace_ProductTesting",
"set OrganizationId = #{organizationId,jdbcType=VARCHAR},",
"ThirdpartyOrganizationId = #{thirdpartyOrganizationId,jdbcType=VARCHAR},",
"ProductID = #{productID,jdbcType=VARCHAR},",
"ProductName = #{productName,jdbcType=VARCHAR},",
"TraceBatchInfoId = #{traceBatchInfoId,jdbcType=VARCHAR}," ,
"TraceBatchInfoName = #{traceBatchInfoName,jdbcType=VARCHAR},",
"TestingDate = #{testingDate,jdbcType=VARCHAR},",
"TestingMan = #{testingMan,jdbcType=VARCHAR},",
"ThirdpartyOrganizationName = #{thirdpartyOrganizationName,jdbcType=VARCHAR},",
"TestingType = #{testingType,jdbcType=VARCHAR}",
"where Id = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKey(ProductTesting record);
@Select({
startScript+
"SELECT COUNT(1) FROM trace_ProductTesting a"
+startWhere
+" a.TestingType = #{testingType} "
+ " <if test='organizeId !=null and organizeId != '' '> AND (a.OrganizeId = #{organizeId} OR a.ThirdpartyOrganizationId = #{organizeId}) </if> "
+ " <if test='search !=null and search != '' '> AND ( a.TestingMan LIKE CONCAT('%',#{search},'%') or a.ProductName LIKE CONCAT('%',#{search},'%') or a.TraceBatchInfoName LIKE CONCAT('%',#{search},'%') or a.OrganizationName LIKE CONCAT('%',#{search},'%') or a.ThirdpartyOrganizationName LIKE CONCAT('%',#{search},'%') )</if> "
+endWhere
+page
+orderBy
+endScript
})
int getCountByCondition(Map<String, Object> var1);
@Select({
startScript+
"select "+
"Id, ProductTestingId, OrganizationId, ThirdpartyOrganizationId, ProductID, TraceBatchInfoId, "+
"TestingDate, TestingMan, CreateMan, CreateTime, CreateId, TestingType, CertifyNumber,Excel,TraceBatchInfoName,ProductName,TestingManName, OrganizationName, OrganizeName, ThirdpartyOrganizationName "+
"from trace_ProductTesting a"
+startWhere
+" a.TestingType = #{testingType} "
+ " <if test='organizeId !=null and organizeId != '' '> AND (a.OrganizeId = #{organizeId} OR a.ThirdpartyOrganizationId = #{organizeId}) </if> "
+ " <if test='search !=null and search != '' '> AND ( a.TestingMan LIKE CONCAT('%',#{search},'%') or a.ProductName LIKE CONCAT('%',#{search},'%') or a.TraceBatchInfoName LIKE CONCAT('%',#{search},'%') or a.OrganizationName LIKE CONCAT('%',#{search},'%') or a.ThirdpartyOrganizationName LIKE CONCAT('%',#{search},'%') )</if> "
+endWhere
+orderBy
+page
+endScript
})
List<ProductTesting> selectProductTesting(Map<String, Object> var1);
} |
package ru.otus.sua.L16.sts;
import lombok.extern.slf4j.Slf4j;
import ru.otus.sua.L16.sts.abstractions.Pollable;
import ru.otus.sua.L16.sts.entities.Message;
import java.io.Closeable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@Slf4j
public class CallbackHandler implements Closeable {
private ScheduledExecutorService executorService;
private int initDelay;
private int period;
private Consumer<Message> callback;
private Pollable pollableObject;
private boolean interrupt;
public CallbackHandler(int initDelay, int period, Consumer<Message> consumer, Pollable pollable) {
this.pollableObject = pollable;
this.callback = consumer;
this.initDelay = initDelay;
this.period = period;
this.interrupt = false;
}
private void setInterrupt() {
interrupt = true;
}
public void start() {
executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(this::poller, initDelay, period, TimeUnit.MILLISECONDS);
log.info("Started new worker for polling \'{}\' in period \'{}\' and callback to \'{}\'",
pollableObject, period, callback);
}
@SuppressWarnings("InfiniteLoopStatement")
private void poller() {
while (!interrupt) {
Message message = pollableObject.poll();
if (message != null) {
log.info("traffic: \'{}\'", message);
callback.accept(message);
}
}
}
@Override
public void close() {
setInterrupt();
executorService.shutdownNow();
}
}
|
package swp.service;
import dk.brics.xact.Element;
import dk.brics.xact.Node;
import dk.brics.xact.NodeList;
import dk.brics.xact.XML;
import dk.brics.xact.operations.XMLPrinter;
import swp.model.AuctionPayment;
import swp.model.PaymentKey;
import swp.service.util.WorkDirectory;
import swp.web.exception.AuctionPaymentExistException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* This class implements the AuctionPaymentService. To maintain persistence the AuctionPaymens
* are stored in a XML-file on the hard drive. All methods are synchronized to prevent
* corruption of the file. This implementation will not perform well on a large number of
* AuctionPayments, but is implemented to maintain persistence.
*/
public class LocalFileSystemAuctionPaymentService implements AuctionPaymentService {
private static final File SOURCE_FILE = new File(WorkDirectory.getInstance().getWorkDirectory(), "payments.xml");
public synchronized void create(AuctionPayment payment)
throws AuctionPaymentExistException {
Map<PaymentKey, AuctionPayment> payments = loadPayments();
if (payments.containsKey(payment.getId())) {
throw new AuctionPaymentExistException("The AuctionPayment already exists");
}
payments.put(payment.getId(), payment);
savePayments(payments);
}
public synchronized boolean exists(PaymentKey key) {
return loadPayments().containsKey(key);
}
public synchronized AuctionPayment getPayment(PaymentKey key) {
return loadPayments().get(key);
}
/**
* Returns a list of payments by the given userName. Note that this will concatenate the payments of a user
* regardless of the origin of the auction item
*
* @param username the user name
* @return the list of payments
*/
public synchronized List<AuctionPayment> getPaymentsByUser(String username) {
Map<PaymentKey, AuctionPayment> payments = loadPayments();
List<AuctionPayment> result = new ArrayList<AuctionPayment>();
for (AuctionPayment payment : payments.values()) {
if (payment.getBuyer().equals(username)) {
result.add(payment);
}
}
return result;
}
private void savePayments(Map<PaymentKey, AuctionPayment> map) {
try {
XML result = getWrapper();
for (Entry<PaymentKey, AuctionPayment> keyAuctionPaymentEntry : map.entrySet()) {
result = result.plug("PAYMENT", serializeSingle(keyAuctionPaymentEntry.getValue()));
}
System.out.println(result.getString());
FileOutputStream outStream;
outStream = new FileOutputStream(SOURCE_FILE);
XMLPrinter.print(result, outStream, "UTF-8", false, true);
outStream.close();
} catch (FileNotFoundException e) {
throw new RuntimeException("should never happen", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("should never happen", e);
} catch (IOException e) {
throw new RuntimeException("should never happen", e);
}
}
private Map<PaymentKey, AuctionPayment> loadPayments() {
try {
Map<PaymentKey, AuctionPayment> result = new HashMap<PaymentKey, AuctionPayment>();
if (!SOURCE_FILE.exists()) {
return result;
}
FileInputStream inStream = new FileInputStream(SOURCE_FILE);
XML.getNamespaceMap().put("p", "https://services.brics.dk/java/courseadmin/SWP/payment");
XML source = XML.parseDocument(inStream);
NodeList<Node> list = source.get("//p:payment");
for (Node node : list) {
Element temp = (Element) node;
String buyer = temp.getAttribute("buyer");
URL server = new URL(temp.getAttribute("server"));
String id = temp.getAttribute("item");
PaymentKey key = new PaymentKey(server, id);
AuctionPayment value = new AuctionPayment(key, buyer);
result.put(key, value);
}
inStream.close();
return result;
} catch (FileNotFoundException e) {
throw new RuntimeException("should never happen", e);
} catch (MalformedURLException e) {
throw new RuntimeException("should never happen", e);
} catch (IOException e) {
throw new RuntimeException("should never happen", e);
}
}
private XML getWrapper() {
XML.getNamespaceMap().put("p", "https://services.brics.dk/java/courseadmin/SWP/payment");
return XML.parseTemplate("<p:payments><[PAYMENT]></p:payments>");
}
private XML serializeSingle(AuctionPayment payment) {
XML result = XML.parseTemplate("<p:payment buyer=[BUYER] server=[SERVER] item=[ITEM]/>" +
"<[PAYMENT]>");
result = result.plug("BUYER", payment.getBuyer());
result = result.plug("SERVER", payment.getId().getHost());
result = result.plug("ITEM", payment.getId().getItemId());
return result;
}
}
|
package io.codex.cryptogram.signature;
/**
* MD2WithRSA 签名器
*
* @author 杨昌沛 646742615@qq.com
* 2018/10/17
*/
public class MD2WithRSASignatureProvider extends RSASignatureProvider {
public MD2WithRSASignatureProvider() {
super("MD2WithRSA");
}
}
|
package com.stk123.model;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.stk123.service.StkConstant;
import com.stk123.util.ServiceUtils;
import com.stk123.common.db.util.sequence.SequenceUtils;
import com.stk123.common.util.JdbcUtils;
public class Text {
public final static int TYPE_XUEQIU = 3;
public final static int SUB_TYPE_EARNING_FORECAST = 10;
public final static int SUB_TYPE_ORG_BUY_WITHIN_60 = 20;
public final static int SUB_TYPE_NIU_FUND_ONE_YEAR = 30;
public final static int SUB_TYPE_NIU_FUND_ALL_TIME = 31;
public final static int SUB_TYPE_FIND_REVERSION = 40;
public final static int SUB_TYPE_FIND_GROWTH = 45;
public final static int SUB_TYPE_STK_HOLDER_REDUCE = 50;
public final static int SUB_TYPE_COMPANY_RESEARCH = 100; //公司调研
public final static int SUB_TYPE_INDUSTRY_RESEARCH = 110; //行业分析
public final static int SUB_TYPE_STK_REPORT = 200; //年报季报
public final static int SUB_TYPE_XUEQIU_NOTICE = 300; //雪球公告
public static void insert(Connection conn, String code,String content) throws Exception{
List params = new ArrayList();
long id = SequenceUtils.getSequenceNextValue(SequenceUtils.SEQ_TEXT_ID);
params.add(id);
params.add(code);
params.add(JdbcUtils.createClob(content));
JdbcUtils.insert(conn, "insert into stk_text(id,type,code,code_type,title,text,insert_time,update_time) values (?,1,?,1,null,?,sysdate,null)", params);
}
public static void insert(Connection conn, String code,String content, int subType) throws Exception{
Text.insert(conn, StkConstant.TEXT_TYPE_AUTO, code,null, content, subType);
}
public static void insert(Connection conn,int type, String code,String title, String content, int subType) throws Exception{
List params = new ArrayList();
long id = SequenceUtils.getSequenceNextValue(SequenceUtils.SEQ_TEXT_ID);
params.add(id);
params.add(type);
params.add(code);
params.add(title);
params.add(JdbcUtils.createClob(content));
params.add(subType);
JdbcUtils.insert(conn, "insert into stk_text(id,type,code,code_type,title,text,insert_time,update_time,sub_type) values (?,?,?,1,?,?,sysdate,null,?)", params);
}
public static long insert(Connection conn,int type, String code,String title, String content, int subType, Date insertTime) throws Exception{
List params = new ArrayList();
long id = JdbcUtils.getSequence(conn, SequenceUtils.SEQ_TEXT_ID);
params.add(id);
params.add(type);
params.add(code);
params.add(title);
params.add(JdbcUtils.createClob(conn, content));
params.add(insertTime);
params.add(subType);
params.add(code);
params.add(subType);
params.add(title);
int ret = JdbcUtils.insert(conn, "insert into stk_text(id,type,code,code_type,title,text,insert_time,update_time,sub_type) select ?,?,?,1,?,?,?,null,? from dual where not exists (select 1 from stk_text where code=? and sub_type=? and title=?)", params);
if(ret >= 1){
/*params.clear();
params.add(id);
params.add(StkConstant.DEFAULT_USER_ID);
StkText stext = JdbcUtils.load(conn, StkConstant.SQL_SELECT_TEXT_BY_ID, params, StkText.class);
Search search = new Search(StkConstant.DEFAULT_USER_ID);
search.addDocument(stext);
search.close();*/
return id;
}
return ret;
}
public static long insert(Connection conn,int type, String code,String title, String content, int subType, String insertTime) throws Exception{
return Text.insert(conn, type, code, title, content, subType, ServiceUtils.sf_ymd9.parse(insertTime));
}
public static long insert(Connection conn,int type, String title, String content, int subType, String insertTime) throws Exception{
List params = new ArrayList();
long id = SequenceUtils.getSequenceNextValue(SequenceUtils.SEQ_TEXT_ID);
params.add(id);
params.add(type);
params.add(title);
params.add(JdbcUtils.createClob(conn, content));
params.add(ServiceUtils.sf_ymd9.parse(insertTime));
params.add(subType);
params.add(subType);
params.add(title);
int ret = JdbcUtils.insert(conn, "insert into stk_text(id,type,code,code_type,title,text,insert_time,update_time,sub_type) select ?,?,null,1,?,?,?,null,? from dual where not exists (select 1 from stk_text where sub_type=? and title=?)", params);
if(ret >= 1){
/*params.clear();
params.add(id);
params.add(StkConstant.DEFAULT_USER_ID);
StkText stext = JdbcUtils.load(conn, StkConstant.SQL_SELECT_TEXT_BY_ID, params, StkText.class);
Search search = new Search(StkConstant.DEFAULT_USER_ID);
search.addDocument(stext);
search.close();*/
return id;
}
return ret;
}
public static Integer countByTitle(Connection conn, String title, int days){
return JdbcUtils.load(conn, "select count(1) from stk_text where title=? and insert_time>(sysdate-?)", Integer.class, title, days);
}
}
|
package com.atlassian.theplugin.jira.model;
import com.atlassian.theplugin.commons.jira.api.JiraIssueAdapter;
/**
* IF YOU IMPLEMENT THE INTERFACE REMEMBER THAT:
* Methods should be called in the order listed below!!!
*/
public interface JIRAIssueListModelListener {
void issueUpdated(final JiraIssueAdapter issue);
/**
* That method should be called always whenever model has changed
* Other methods can be called as well
*
* @param model fresh model
*/
void modelChanged(JIRAIssueListModel model);
void issuesLoaded(JIRAIssueListModel model, int loadedIssues);
}
|
package demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
@Configuration
public class DemoApplicationClientConfiguration {
@Bean
HttpInvokerProxyFactoryBean client() {
HttpInvokerProxyFactoryBean client = new HttpInvokerProxyFactoryBean();
client.setServiceUrl("http://localhost:8080/messageService"); // <1>
client.setServiceInterface(MessageService.class); // <2>
return client;
}
}
|
package com.hopu.bigdata.config;
import com.hopu.bigdata.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class CustomLoginAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws ServletException, IOException {
User user = (User) authentication.getPrincipal();
HttpSession session = httpServletRequest.getSession();
session.setAttribute("userid", userService.getUserByName(user.getUsername()).getId());
super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
}
}
|
package com.sirma.itt.javacourse.chat.common.utils;
public enum LANGUAGES {
EN("ENGLISH"), BG("BG");
private final String value;
private LANGUAGES(String value) {
this.value = value;
}
public String toString() {
return value;
}
}; |
package online.lahloba.www.lahloba.ui.interfaces;
import online.lahloba.www.lahloba.data.model.AddressItem;
public interface EditAddressFromFragmentListener {
void onClickEditAddressFromFragment(AddressItem addressItem);
}
|
package com.levimartines.challengefs.dto;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PessoaDTO {
@NotEmpty
private String nome;
@NotEmpty
@Email
private String email;
}
|
package che.panels;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import che.bean.ConvertedBean;
import che.https.HttpConnector;
public class MainFrame extends JFrame {
private final MainFrame mainFrame = this;
// private final LogFrame logFram = new LogFrame();
private final TableFrame tableFrame = new TableFrame();
private final JTextField urlField = new JTextField("http://rapdb.dna.affrc.go.jp/tools/converter/run", 50);
private List<ConvertedBean> result = new LinkedList<ConvertedBean>();
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea textArea = new JTextArea(10,80);
private JTextArea logArea = new JTextArea(10,80);
HttpConnector connector = null;
public MainFrame() {
super("rapdb");
connector = new HttpConnector(mainFrame);
}
private void drawPanel(){
JPanel panel = new JPanel();
panel.add(urlField, BorderLayout.WEST);
JButton queryBtn = new JButton("点击查询");
queryBtn.addActionListener(new QueryBtnHandler());
panel.add(queryBtn, BorderLayout.EAST);
JButton lastResultBtn = new JButton("查看结果");
lastResultBtn.addActionListener(new LastResultBtnhandler());
panel.add(lastResultBtn, BorderLayout.EAST);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
getContentPane().add(panel, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(new JScrollPane(logArea), BorderLayout.SOUTH);
pack();
}
public void draw() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设定按关闭时的操作,这里是关闭窗口,如果不设定,就什么也不会发生
setLocationRelativeTo(null);
setSize(650, 500); //设定大小,按像素来
Toolkit toolkit = Toolkit.getDefaultToolkit();
int x = (int)(toolkit.getScreenSize().getWidth()-this.getWidth())/2;
int y = (int)(toolkit.getScreenSize().getHeight()-this.getHeight())/2;
setLocation(x, y);
drawPanel();
setVisible(true); //显示,如果不设置就什么都看不到
}
public void connectorCallBackk(List<ConvertedBean> result) {
this.result = result;
if(result != null && result.size() > 0){
tableFrame.showTable(result);
}
}
class QueryBtnHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
String inputStr = textArea.getText();
if(inputStr == null || "".equals(inputStr) || "".equals(inputStr.trim())){
alert("请输入查询内容.");
return ;
}else{
inputStr = inputStr.replaceAll("\n", " ").replaceAll(" ", " ").trim();
addLog("---------------------");
connector.setRapdbUrl(urlField.getText());
connector.setRapdbParam(inputStr);
connector.start();
}
}
}
class LastResultBtnhandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(result != null && result.size() > 0){
tableFrame.showTable(result);
}
}
}
public void addLog(String logStr){
// logFram.addLog(logStr + "\n");
logArea.append(logStr + "\n");
}
private void alert(String message){
JOptionPane.showMessageDialog(null, message, "注意", JOptionPane.ERROR_MESSAGE);
}
}
|
/* ProcessingInstruction.java
Purpose:
Description:
History:
2001/10/22 20:53:28, Create, Tom M. Yeh.
Copyright (C) 2001 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.idom;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Collections;
import java.io.IOException;
import org.zkoss.mesg.MCommon;
import org.zkoss.lang.Objects;
import org.zkoss.lang.Strings;
import org.zkoss.lang.SystemException;
import org.zkoss.util.Maps;
import org.zkoss.idom.impl.*;
/**
* The iDOM processing instruction.
*
* @author tomyeh
*/
public class ProcessingInstruction extends AbstractItem
implements org.w3c.dom.ProcessingInstruction {
/** The target. */
protected String _target;
/** The raw data. */
protected String _rawData;
/** Constructor.
*/
public ProcessingInstruction(String target, String data) {
setTarget(target);
setData(data);
}
/** Constructor.
*/
public ProcessingInstruction(String target, Map data) {
setTarget(target);
setData(data);
}
/** Constructor.
*/
protected ProcessingInstruction() {
}
//-- ProcessingInstruction extras --//
public final String getTarget() {
return _target;
}
public final void setTarget(String target) {
if (!Objects.equals(_target, target)) {
Verifier.checkPITarget(target, getLocator());
_target = target;
}
}
public final String getData() {
return _rawData;
}
public final void setData(String data) {
if (data == null)
data = "";
_rawData = data;
}
/** Returns the parsed data in the form of Map (never null).
*/
public final Map parseData() {
return parseToMap(new LinkedHashMap(), getData());
}
/**
* Sets the raw data with a data map.
* Each entry in the data map is a (name, value) pair.
*
* @exception org.zkoss.util.IllegalSyntaxException if name contains
* an invalid character: '=', ' ', '\'', '"'
*/
public final void setData(Map data) {
final String notAllowed = "= '\"";
for (final Iterator it = data.keySet().iterator(); it.hasNext();) {
final String key = (String)it.next();
final int j = Strings.anyOf(key, notAllowed, 0);
if (j < key.length()) { //found
final char cc = key.charAt(j);
throw new SystemException(MCommon.ILLEGAL_CHAR,
cc + " (0x" + Integer.toHexString(cc) + ')');
}
}
setData(Maps.toString(data, '"', ' '));
}
/**
* Parses the raw data into a map.
* Each entry in the data map is a (name, value) pair.
* This method will convert a value to a number, either Integer
* or Double, if appropriate.
*
* <p>Most of characters are considered as ordinary (like 'a'),
* exception '"', '='
*
* <p>Example, the string wil cause ("a12", Intger(12)),
* ("b+3", null), ("345", null), ("c6", "abc=125&3?5"):<br>
* a12 =12 b+3 345 c6=\t'abc=125&3?5'
*
* @return the map (never null)
* @exception org.zkoss.util.IllegalSyntaxException if syntax erros
*/
public static final Map parseToMap(Map map, String rawData) {
if (rawData == null || rawData.trim().length() == 0)
return map != null ? map: Collections.EMPTY_MAP;
map = Maps.parse(map, rawData, ' ', (char)1); //both ' and "
//" and other are not processed by SAXHandler,
//so we have to handle them here
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
final Map.Entry me = (Map.Entry)it.next();
final String val = (String)me.getValue();
StringBuffer sb = null;
for (int i = 0, j = 0, len = val.length();;) {
int k = val.indexOf('&', j);
if (k < 0) {
if (sb != null)
me.setValue(sb.append(val.substring(i)).toString());
break;
}
int l = val.indexOf(';', k);
if (l >= 0) {
final char cc;
final String code = val.substring(k + 1, l);
if ("quot".equals(code)) {
cc = '"';
} else if ("amp".equals(code)) {
cc = '&';
} else if ("lt".equals(code)) {
cc = '<';
} else if ("gt".equals(code)) {
cc = '>';
} else {
//TODO: handle &#nnn; and more
j = l + 1;
continue; //ignore it
}
if (sb == null) sb = new StringBuffer(len);
sb.append(val.substring(i, k)).append(cc);
i = j = l + 1;
} else {
j = k + 1;
}
}
}
return map;
}
//-- Item --//
public final String getName() {
return getTarget();
}
public final void setName(String name) {
setTarget(name);
}
public final String getText() {
return getData();
}
public final void setText(String text) {
setData(text);
}
//-- Node --//
public final short getNodeType() {
return PROCESSING_INSTRUCTION_NODE;
}
//-- org.w3c.dom.ProcessingInstruction --//
//-- Object --//
public String toString() {
StringBuffer sb = new StringBuffer(64)
.append("[PI: ").append(_target);
if (_rawData.length() > 0)
sb.append(' ').append(_rawData);
return sb.append(']').toString();
}
}
|
package org.juxtasoftware.service.importer.jxt;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.juxtasoftware.model.ComparisonSet;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import eu.interedition.text.Range;
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MovesParser {
public List<JxtMoveInfo> parse( final ComparisonSet set, final File movesFile ) throws IOException {
List<JxtMoveInfo> moves = new ArrayList<JxtMoveInfo>();
BufferedReader br = null;
try {
br = new BufferedReader( new FileReader(movesFile));
while ( true ) {
String line = br.readLine();
if ( line == null ) {
break;
}
// only care about the move definition of this xml
// file. these lines look like: '<move .../>'
if ( line.contains("<move ") ) {
JxtMoveInfo info = new JxtMoveInfo();
for (int i=1; i<=2; i++) {
String title = extractValue(line, "doc"+i);
String start = extractValue(line, "start"+i);
String end = extractValue(line, "end"+i);
Range range = new Range(Long.parseLong(start), Long.parseLong(end));
info.addWitnessRange( title, range);
}
moves.add( info );
}
}
} finally {
IOUtils.closeQuietly(br);
}
return moves;
}
private String extractValue(final String line, final String attribName) {
int pos = line.indexOf(attribName);
int quoteStartPos = line.indexOf('"', pos);
int quoteEndPos = line.indexOf('"', quoteStartPos+1);
return line.substring(quoteStartPos+1, quoteEndPos);
}
/**
* Information collected about TRANSPOSITIONS during
* the parse of the moves.xml.
*/
public static class JxtMoveInfo {
private Map<String, Range> witnessRangeMap = new HashMap<String, Range>();
public void addWitnessRange( final String witnessTitle, final Range r) {
this.witnessRangeMap.put(witnessTitle, r);
}
public boolean hasWitnessRange( final String title ) {
return this.witnessRangeMap.containsKey(title);
}
public Set<String> getWitnessTitles() {
return this.witnessRangeMap.keySet();
}
public Range getWitnessRange( final String title) {
return this.witnessRangeMap.get(title);
}
}
}
|
package com.itheima.verify_code;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.apache.commons.beanutils.BeanUtils;
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.lang.reflect.InvocationTargetException;
import java.util.Map;
/*
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码。
* 如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
* 如果验证码输入有误,跳转登录页面,提示:验证码错误
* 如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//从session中获取生成的验证码
String verify_code = (String)request.getSession().getAttribute("VERIFY_CODE");
//获取用户输入的验证码
String user_verify_code = request.getParameter("USER_VERIFY_CODE");
//移除session中存储的验证码,否则会造成验证码二次输入的时候无法验证通过
request.getSession().removeAttribute("VERIFY_CODE");
//判断用户输入的验证码是否正确(忽略大小写)
if (verify_code != null) {
if (verify_code.equalsIgnoreCase(user_verify_code)) {
/*
//验证用户登录信息是否正确
String username = request.getParameter("username"); //获取用户输入的用户名
String password = request.getParameter("password"); //获取用户输入的密码
*/
//获取用户输入信息
Map<String, String[]> map = request.getParameterMap();
//创建User对象,用于封装信息
User user = new User();
//创建UserDao对象,与数据库中用户信息比对,用于验证用户信息正确性
UserDao userDao = new UserDao();
try {
//封装user对象
BeanUtils.populate(user,map);
//验证用户信息是否存在
user = userDao.login(user);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
// if ("zhangsan".equals(username) && "123456".equals(password)) { //验证登录信息是否正确
if (user != null) { //验证登录信息是否正确
//如果信息正确,跳转至登陆成功页面
String username = user.getUsername(); //获取用户名
request.setAttribute("username", username); //将用户名存储到request中
//通过请求转发的形式将用户名传入登陆成功页面
request.getRequestDispatcher("successServlet").forward(request, response);
} else {
//如果登录信息有误,提示用户
request.setAttribute("login_error","用户名或密码有误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
} else {
//提示用户输入的验证码有误
request.setAttribute("vc_error","验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
package Program_Examples;
public class convert_Double_to_String {
public static void main(String[] args) {
/* Method 1: Using valueOf() method of String class */
double dvar1 = 101.11;
String str1 = String.valueOf(dvar1);
System.out.println("String 1 is: "+str1);
/* Method 2: Using toString() method of Double class */
double dvar2 = 200.202;
String str2 = Double.toString(dvar2);
System.out.println("String 2 is: "+str2);
}
}
|
package io.jrevolt.sysmon.client.ui;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import io.jrevolt.sysmon.common.SysmonException;
import io.jrevolt.sysmon.common.Utils;
import io.jrevolt.sysmon.model.SpringBootApp;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import java.net.URL;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
* @version $Id$
*/
@Component @Singleton
public class FxHelper {
static ScheduledExecutorService executor = Executors.newScheduledThreadPool(30);
@PostConstruct
void init() {
System.out.println();
}
@PreDestroy
private void close() {
executor.shutdownNow();
}
static final LinkedList<Runnable> updateQueue = new LinkedList<Runnable>() {{
executor.scheduleAtFixedRate(()-> Platform.runLater(()->{
if (isEmpty()) { return; }
synchronized (updateQueue) {
// System.out.printf("updateQueue.size()=%d%n", size());
while (!isEmpty()) { pop().run(); }
}
}), 1000, 500, TimeUnit.MILLISECONDS);
}};
static public <C extends Base<P>, P extends Pane> C load(Class<C> cls) {
URL url = null;
try {
url = cls.getResource(cls.getSimpleName() + ".fxml");
FXMLLoader loader = new FXMLLoader(url);
loader.setControllerFactory(param -> (C) SpringBootApp.instance().lookup(cls));
P pane = loader.load();
C controller = loader.getController();
controller.pane = pane;
controller.initialize();
return controller;
} catch (Exception e) {
throw new SysmonException(e, "Cannot load %s, %s", cls.getSimpleName(), url);
}
}
static public void fxasync(Runnable runnable) {
Platform.runLater(runnable);
}
static public void fxupdate(Runnable runnable) {
assert runnable != null;
if (Platform.isFxApplicationThread()) {
Utils.runGuarded(runnable);
} else {
synchronized (updateQueue) { updateQueue.add(runnable); }
}
}
static public void async(Runnable runnable) {
executor.submit(()-> Utils.runGuarded(runnable));
}
static public <T> Future<T> async(Callable<T> callable) {
return executor.submit(callable);
}
static public ScheduledExecutorService scheduler() {
return executor;
}
static private StringProperty status = new SimpleStringProperty();
static public StringProperty status() { return status; }
static public boolean isVisible(Node node) {
for (Node n = node; n != null; n = n.getParent()) {
if (!n.isVisible()) { return false; }
}
return true;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DataAccess;
import java.sql.*;
/**
*
* @author TUNT
*/
public class Connect {
private Connection conn;
private static Connect instance;
private String sqlServer = "TUNT-PC";
private String database = "Restaurants";
private String user = "sa";
private String password = "admin";
public static Connect getInstance() {
if (instance == null) {
instance = new Connect();
}
return instance;
}
public Connection getConnect() throws Exception {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String strConnect = "jdbc:sqlserver://" + sqlServer + ";Database=" + database + ";user=" + user + ";password=" + password;
conn = DriverManager.getConnection(strConnect);
return conn;
}
}
|
package com.leetcode.google;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static int[] twoElements(int[] arr, int target) {
int[] res= new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int x=0;x<arr.length;x++) {
if(map.containsKey(target-arr[x])) {
res[0]=x;
res[1]=map.get(target-arr[x]);
break;
}
else {
map.put(arr[x], x);
}
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] response = twoElements(new int[] {2,5,1,9,4,3},7);
for(int y: response) {
System.out.println(y);
}
}
}
|
package exceptions;
public class NoOperationException extends Exception {
}
|
package cellularAutomata.movie;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class Example
{
// ------------------------------------------------------------------------
/**
* Code example written by Werner Randelshofer and modified by David Bahr.
*
* @param args
* the command line arguments
*/
public static void main(String[] args)
{
try
{
example(new File("quicktimedemo-jpg.mov"),
QuickTimeOutputStream.VideoFormat.JPG, 1f);
example(new File("quicktimedemo-png.mov"),
QuickTimeOutputStream.VideoFormat.PNG, 1f);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
/**
* Code example written by Werner Randelshofer and modified by David Bahr.
* <p>
* An example that creates a movie and adds the frames one at a time by
* calling out.writeFrame(img, 1) where img is a BufferedImage. the images
* are simple rectangles.
*
* @param file
* The output file name.
* @param format
* Either QuickTimeOutputStream.VideoFormat.PNG or
* QuickTimeOutputStream.VideoFormat.JPG.
* @param quality
* Between 0.0f and 1.0f. Irrelevant for PNG movies.
* @throws IOException
* If could not create the specified output file.
*/
private static void example(File file,
QuickTimeOutputStream.VideoFormat format, float quality)
throws IOException
{
QuickTimeOutputStream out = null;
Graphics2D g = null;
try
{
out = new QuickTimeOutputStream(file, format);
out.setVideoCompressionQuality(quality);
out.setFrameRate(30); // 30 fps
Random r = new Random();
BufferedImage img = new BufferedImage(320, 160,
BufferedImage.TYPE_INT_RGB);
g = img.createGraphics();
g.setBackground(Color.WHITE);
g.clearRect(0, 0, img.getWidth(), img.getHeight());
for(int i = 0; i < 100; i++)
{
g.setColor(new Color(r.nextInt()));
g.fillRect(r.nextInt(img.getWidth() - 30), r.nextInt(img
.getHeight() - 30), 30, 30);
out.writeFrame(img, 1);
}
}
finally
{
if(g != null)
{
g.dispose();
}
if(out != null)
{
out.close();
}
}
}
}
|
package com.kueblearn.user_service.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RoleDTO {
private Long id;
@NotNull
@Size(max = 255)
private String roleCode;
}
|
package com.madrapps.dagger.subcomponent.simple;
import com.madrapps.dagger.models.Vehicle;
import dagger.Module;
import dagger.Subcomponent;
@Subcomponent(modules = SimpleSubModule.class)
public interface SimpleSubComponent {
Vehicle vehicle();
@Subcomponent.Builder
interface Builder {
Builder module(SimpleSubModule module);
SimpleSubComponent build();
}
@Module(subcomponents = SimpleSubComponent.class)
class InstallSubComponentModule {
}
}
|
package com.tistory.kisspa.comp.diforannotation;
import com.tistory.kisspa.comp.SampleComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SampleForAnnotation implements SampleComponent {
@Override
public String saySomething() {
return "hello, i'm SampleComponent DI Annotation";
}
}
|
package entities.dto;
import entities.Role;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author andreas
*/
public class UserDTO {
private String userName;
private String userPass;
private List<String> roleList = new ArrayList();
private int balance;
public UserDTO(String userName, List<String> roleList) {
this.userName = userName;
this.roleList = roleList;
}
public UserDTO(String userName, String userPass) {
this.userName = userName;
this.userPass = userPass;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<String> getRoleList() {
return roleList;
}
public void setRoleList(List<String> roleList) {
this.roleList = roleList;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
}
|
package corpse;
import java.util.Random;
public final class RandomEntry
{
private static Random random = new Random();
private RandomEntry()
{
}
public static void randomize()
{
random = new Random();
}
public static void setSeed(final long seed)
{
random.setSeed(seed);
}
public static int get(final int max)
{
return (int) (random.nextDouble() * max);
}
// For best results, the standard deviation should be about 1/3 of the maximum value.
public static int getGaussian(double mean, double stdDev, final int max)
{
double x = 0;
while (x < 1 || x > max)
{
double v, w;
do
{
v = 2 * random.nextDouble() - 1;
double v2 = 2 * random.nextDouble() - 1;
w = v * v + v2 * v2;
} while (w > 1);
double y = v * Math.sqrt(-2 * Math.log(w) / w);
x = Math.round(mean + y * stdDev);
}
return (int) x;
}
public static String get(final String tableName, final String subName, String colName, final String filter)
{
// TODO
System.out.println("RandomEntry.get: T[" + tableName + "] S[" + subName + "] C[" + colName + "] F[" + filter + "]");
String entry = null;
Table table = Table.getTable(tableName);
if (table != null)
{
int index = -1;
Subset subset = null;
if (subName != null)
{
subset = table.getSubset(subName);
if (subset != null && !subset.hasFilter())
index = subset.random() - 1;
}
if (filter != null || (subset != null && subset.hasFilter()))
{
index = -1; // subset is no longer valid since we're going to filter the data
// Token format: {# Table:Subset.Column#Filter#}
String token = "{" + tableName;
if (subName == null && colName == null)
token += Constants.ALL_CHAR;
if (subName != null)
token += Constants.SUBSET_CHAR + subName;
if (colName != null)
token += Constants.COLUMN_CHAR + colName;
if (filter != null)
token += Constants.FILTER_CHAR + filter + Constants.FILTER_CHAR;
token += "}";
Table filteredTable = Table.TABLES.get(token);
if (filteredTable == null)
filteredTable = new SubTable(token); // resolve the table before rolling a value
if (filteredTable.size() > 0) // if no filtered entries match, just use the normal table?
{
table = filteredTable;
colName = null; // don't want to apply it twice
}
}
try
{
entry = get(table, index, colName, filter);
}
catch (IndexOutOfBoundsException x)
{
System.err.println(x);
System.err.println("Table: " + table.getName() + "; Subset: " + subName + "; Column: " + colName + "; Filter: "
+ filter + "; Entry: " + index);
x.printStackTrace();
}
}
return entry;
}
public static String get(final Table table, int index, final String colName, final String filter)
{
String entry = null;
if (!table.isEmpty())
{
if (index < 0)
index = RandomEntry.get(table.size());
entry = table.getColumn(index, colName, filter);
if (entry != null)
{
entry = table.resolve(entry, filter);
// trim leading, trailing, and redundant embedded spaces
entry = entry.trim(); // TODO .replaceAll(" +", " ");
}
}
return entry;
}
public static void main(final String[] args)
{
RandomEntry.setSeed(0);
System.out.println("Random numbers (1-9):");
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
System.out.print(RandomEntry.get(9) + 1 + " ");
System.out.println();
}
System.out.println();
// test RandomEntry.getGaussian()
RandomEntry.randomize();
int runs = 1000, range = 10;
double max = 0, total = 0;
int[] count = new int[range];
int mean = 4;
double stdDev = range / 3;
for (int i = 0; i < runs; i++)
{
int r = Math.abs(RandomEntry.getGaussian(mean, stdDev, range));
max = Math.max(max, r);
total += r;
count[r - 1]++;
}
for (int i = 0; i < range; i++)
System.out.println((i + 1) + " = " + count[i]);
System.out.println("Avg (~= " + mean + "): " + (total / runs));
System.out.println("Max (<= " + range + "): " + max);
System.out.println();
CORPSE.init(true);
// String tableName = "TREASURE";
// String tableName = "REAGENT";
String tableName = "INN NAME";
for (int i = 1; i <= 10; i++)
{
String entry = RandomEntry.get(tableName, null, null, null);
System.out.println(tableName + " " + i + ": " + entry);
}
System.out.println();
String entry = RandomEntry.get("TSR Material", "Wand", null, null);
System.out.println("Wand: " + entry);
System.out.println();
System.out.println("Professions starting with I: " + RandomEntry.get("Profession", null, "Profession", "I.*"));
}
}
|
package apptsched.domain;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Logan.Moen on 7/24/2017.
*/
@Entity
public class Appointment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AppointmentId")
private Integer id;
@Version
private Integer version;
private String type;
private String date;
private String roomNumber;
private boolean completed;
@ManyToOne
private Employee employee;
@ManyToOne
private Client client;
public Appointment(){}
public Appointment(String type, String date, String roomNumber, Employee employee, Client client) {
this.type = type;
this.date = date;
this.roomNumber = roomNumber;
this.employee = employee;
this.client = client;
this.completed = false;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public boolean getCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
|
package com.esum.web.ims.soap.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.esum.appetizer.dao.AbstractDao;
import com.esum.appetizer.util.PageUtil;
import com.esum.web.ims.soap.vo.SoapInfo;
public class SoapInfoDao extends AbstractDao {
public SoapInfo select(String interfaceId) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("interfaceId", interfaceId);
return getSqlSession().selectOne("soapInfo.select", param);
}
public List<SoapInfo> selectList(String interfaceId, PageUtil pageUtil) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("interfaceId", escape(interfaceId, PercentAdd.BOTH)); // escape for LIKE
param.put("startRow", pageUtil.getStartRow());
param.put("endRow", pageUtil.getEndRow());
return getSqlSession().selectList("soapInfo.selectPageList", param);
}
public int countList(String interfaceId) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("interfaceId", escape(interfaceId, PercentAdd.BOTH)); // escape for LIKE
return (Integer)getSqlSession().selectOne("soapInfo.countList", param);
}
public int insert(SoapInfo vo) {
return getSqlSession().insert("soapInfo.insert", vo);
}
public int update(SoapInfo vo) {
return getSqlSession().update("soapInfo.update", vo);
}
public int delete(String interfaceId) {
return getSqlSession().delete("soapInfo.delete", interfaceId);
}
}
|
package com.xys.car.service;
import com.xys.car.entity.Order;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xys.car.entity.RootEntity;
/**
* <p>
* 服务类
* </p>
*
* @author zxm
* @since 2020-12-04
*/
public interface IOrderService extends IService<Order> {
RootEntity selectOrder(Order order);
RootEntity insertOrder(Order order);
RootEntity updateOrder(Order order);
RootEntity deleteOrder(Order order);
}
|
package ehc.alfred;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.objdetect.CascadeClassifier;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import ehc.alfred.util.SystemUiHider;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class AlfredUIActivity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "AlfredUI::Activity";
// UI
private static final Scalar FACE_RECT_COLOR = new Scalar(15, 15, 215, 255);
private CameraBridgeViewBase mOpenCvCameraView;
private ImageButton soda_button1;
private ImageButton soda_button2;
private ImageButton soda_button3;
private ImageButton soda_button4;
private ImageButton sodaButtonMap(int button_index) {
switch (button_index) {
case 1:
return soda_button1;
case 2:
return soda_button2;
case 3:
return soda_button3;
case 4:
return soda_button4;
default:
return null;
}
}
// Arduino Sensors
private int IR_SENSOR;
private int ULTRA_SOUND_SENSOR;
private int DISPENSING_COMPLETE_SENSOR;
// Bluetooth
private BluetoothAdapter bAdapter;
private BluetoothDevice bDevice;
private BluetoothSocket bSocket;
private OutputStream bOutput;
// found default online
private static final UUID SPP_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int DISCOVERY_REQUEST = 1;
// OpenCV
private Mat mRgba;
private Mat mGray;
private File mCascadeFile;
private CascadeClassifier mJavaDetector;
private float mRelativeFaceSize = 0.2f;
private int mAbsoluteFaceSize = 0;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
try {
// load cascade file from application resources
InputStream is = getResources().openRawResource(
R.raw.lbpcascade_frontalface);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir,
"lbpcascade_frontalface.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
mJavaDetector = new CascadeClassifier(
mCascadeFile.getAbsolutePath());
if (mJavaDetector.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
mJavaDetector = null;
} else
Log.i(TAG, "Loaded cascade classifier from "
+ mCascadeFile.getAbsolutePath());
cascadeDir.delete();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
}
mOpenCvCameraView.enableView();
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
// Bluetooth Receiver
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
bDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bDevice.getName().equals("BT UART")) {
bAdapter.cancelDiscovery();
try {
bSocket = bDevice
.createRfcommSocketToServiceRecord(SPP_UUID);
bSocket.connect();
logToast("Bluetooth Connected");
} catch (IOException e) {
// TODO Auto-generated catch block
logToast("Socket Connection Failed");
popToast(e.getMessage());
e.printStackTrace();
}
}
}
};
};
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
private class BT_Thread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public BT_Thread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
logToast("Unable to send message: " + bytes.toString());
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
logToast("Unable to recv message");
}
}
}
private void bSocketSend(String msg) {
if (bSocket.isConnected()) {
byte[] byteMsg = msg.getBytes();
byte[] socketMsg = new byte[byteMsg.length + 1];
for (int i = 0; i < byteMsg.length; i++) {
socketMsg[i] = byteMsg[i];
}
socketMsg[socketMsg.length - 1] = '\0';
try {
bOutput = bSocket.getOutputStream();
bOutput.write(socketMsg);
} catch (IOException e) {
e.printStackTrace();
}
} else {
logToast("Socket Disconnected");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alfred_ui);
bluetoothInitialization();
// final View controlsView =
// findViewById(R.id.fullscreen_content_controls);
// final View contentView = findViewById(R.id.fullscreen_content);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.cv_activity_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
soda_button1 = (ImageButton) findViewById(R.id.soda_button1);
soda_button2 = (ImageButton) findViewById(R.id.soda_button2);
soda_button3 = (ImageButton) findViewById(R.id.soda_button3);
soda_button4 = (ImageButton) findViewById(R.id.soda_button4);
soda_button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSodaButton((ImageButton) v, 1);
}
});
soda_button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSodaButton((ImageButton) v, 2);
}
});
soda_button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSodaButton((ImageButton) v, 3);
}
});
soda_button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSodaButton((ImageButton) v, 4);
}
});
}
private void bluetoothInitialization() {
bAdapter = BluetoothAdapter.getDefaultAdapter();
startActivityForResult(new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),
DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bAdapter.startDiscovery();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
@Override
public void onPause() {
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this,
mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mGray = new Mat();
mRgba = new Mat();
}
public void onCameraViewStopped() {
mGray.release();
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
if (mAbsoluteFaceSize == 0) {
int height = mGray.rows();
if (Math.round(height * mRelativeFaceSize) > 0) {
mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize);
}
}
MatOfRect faces = new MatOfRect();
if (mJavaDetector != null)
/*
* CV_HAAR_DO_CANNY_PRUNING 1 CV_HAAR_SCALE_IMAGE 2
* CV_HAAR_FIND_BIGGEST_OBJECT 4 CV_HAAR_DO_ROUGH_SEARCH 8
*/
mJavaDetector.detectMultiScale(mGray, faces, 1.1, 2, 2, new Size(
mAbsoluteFaceSize, mAbsoluteFaceSize), new Size());
Rect[] facesArray = faces.toArray();
for (int i = 0; i < facesArray.length; i++)
Core.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(),
FACE_RECT_COLOR, 3);
return mRgba;
}
private void onSodaButton(ImageButton button, int button_index) {
logToast("Soda Button: " + button_index);
// button.setEnabled(false);
}
private void logToast(String str) {
popToast(str);
Log.i(TAG, str);
}
private void popToast(String str) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
toast.show();
}
}
|
package com.leeheejin.pms.handler;
import java.util.List;
import com.leeheejin.pms.domain.Member;
import com.leeheejin.util.Prompt;
public class MemberLogInHandler extends AbstractMemberHandler {
public MemberLogInHandler(List<Member> memberList) {
super(memberList);
}
@Override
public void service() {
}
public int logIn() {
System.out.println("[ 홈 > 로그인* ]");
System.out.println("(뒤로가기| 빈 문자열)");
while (true) {
String id = Prompt.inputString("아이디: ");
String password = Prompt.inputString("비밀번호: ");
if(exist(id, password)) {
logInAccount = nowLogIn - 1;
accountRemove = 1;
System.out.println("- 로그인 되었습니다. ");
System.out.println();
return 1;
} else if (id.length() == 0 && password.length() == 0) {
break;
} else {
System.out.println("- 회원 정보를 찾을 수 없습니다. ");
System.out.println();
}
}
return 0;
}
}
|
package com.example.administrator.ipcworker;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
public class CsdMessenger implements Parcelable {
private final ICsdMessenger mTarget;
/**
* Create a new Messenger pointing to the given Handler. Any Message
* objects sent through this Messenger will appear in the Handler as if
* {@link Handler#sendMessage(Message) Handler.sendMessage(Message)} had
* been called directly.
*
* @param target The Handler that will receive sent messages.
*/
public CsdMessenger(CsdHandler target) {
mTarget = (ICsdMessenger) target.getIMessenger(false);
}
/**
* Send a Message to this Messenger's Handler.
*
* @param message The Message to send. Usually retrieved through
* {@link Message#obtain() Message.obtain()}.
* @throws RemoteException Throws DeadObjectException if the target
* Handler no longer exists.
*/
public void send(Message message) throws RemoteException {
mTarget.send(message);
}
public Message sendWithRsp(Message message) throws RemoteException {
return mTarget.sendWithRsp(message);
}
/**
* Retrieve the IBinder that this Messenger is using to communicate with
* its associated Handler.
*
* @return Returns the IBinder backing this Messenger.
*/
public IBinder getBinder() {
return mTarget.asBinder();
}
public IBinder getSysBinder(CsdHandler target) {
return ((IInterface) target.getIMessenger()).asBinder();
}
/**
* Comparison operator on two Messenger objects, such that true
* is returned then they both point to the same Handler.
*/
public boolean equals(Object otherObj) {
if (otherObj == null) {
return false;
}
try {
return mTarget.asBinder().equals(((CsdMessenger) otherObj)
.mTarget.asBinder());
} catch (ClassCastException e) {
}
return false;
}
public int hashCode() {
return mTarget.asBinder().hashCode();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeStrongBinder(mTarget.asBinder());
}
public static final Parcelable.Creator<CsdMessenger> CREATOR
= new Parcelable.Creator<CsdMessenger>() {
public CsdMessenger createFromParcel(Parcel in) {
IBinder target = in.readStrongBinder();
return target != null ? new CsdMessenger(target) : null;
}
public CsdMessenger[] newArray(int size) {
return new CsdMessenger[size];
}
};
/**
* Convenience function for writing either a Messenger or null pointer to
* a Parcel. You must use this with {@link #readMessengerOrNullFromParcel}
* for later reading it.
*
* @param messenger The Messenger to write, or null.
* @param out Where to write the Messenger.
*/
public static void writeMessengerOrNullToParcel(CsdMessenger messenger,
Parcel out) {
out.writeStrongBinder(messenger != null ? messenger.mTarget.asBinder()
: null);
}
/**
* Convenience function for reading either a Messenger or null pointer from
* a Parcel. You must have previously written the Messenger with
* {@link #writeMessengerOrNullToParcel}.
*
* @param in The Parcel containing the written Messenger.
* @return Returns the Messenger read from the Parcel, or null if null had
* been written.
*/
public static CsdMessenger readMessengerOrNullFromParcel(Parcel in) {
IBinder b = in.readStrongBinder();
return b != null ? new CsdMessenger(b) : null;
}
/**
* Create a Messenger from a raw IBinder, which had previously been
* retrieved with {@link #getBinder}.
*
* @param target The IBinder this Messenger should communicate with.
*/
public CsdMessenger(IBinder target) {
mTarget = ICsdMessenger.Stub.asInterface(target);
}
}
|
package org.softRoad.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.softRoad.models.query.QueryUtils;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.Instant;
@Entity
@Table(name = "update_requests")
public class UpdateRequest extends SoftRoadModel {
@Transient
public final static String ID = "id";
@Transient
public final static String ACCEPTED = "accepted";
@Transient
public final static String CREATED_DATA = "created_date";
@Transient
public final static String PAYLOAD = "payload";
@Transient
public final static String PROCEDURE = "procedure_id";
@Transient
public final static String USER = "user_id";
@Transient
public final static String TYPE = "type";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
public Boolean accepted;
@Column(name = "created_date", nullable = false)
public Instant createdDate;
@NotNull
@Enumerated(EnumType.STRING)
public Type type;
@NotNull
public String payload;
@ManyToOne
@JoinColumn(name = "procedure_id")
@JsonIgnore
public Procedure procedure;
@ManyToOne
@JoinColumn(name = "user_id")
@JsonIgnoreProperties(value = {"roles", "password", "enabled"})
public User user;
@PrePersist
private void setAccepted() {
this.accepted = false;
}
public void setId(Integer id) {
this.id = id;
presentFields.add("id");
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
this.presentFields.add("accepted");
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
this.presentFields.add("createdDate");
}
public void setPayload(String payload) {
this.payload = payload;
this.presentFields.add("payload");
}
public void setProcedure(Procedure procedure) {
this.procedure = procedure;
this.presentFields.add("procedure");
}
public void setUser(User user) {
this.user = user;
presentFields.add("user");
}
public void setType(Type type) {
this.type = type;
presentFields.add("type");
}
public static String fields(String fieldName, String... fieldNames) {
return QueryUtils.fields(UpdateRequest.class, fieldName, fieldNames);
}
public enum Type {
ADD_STEP,
DELETE_STEP,
EDIT_STEP,
DELETE_PROCEDURE,
EDIT_PROCEDURE
}
}
|
package cn.edu.cqut.util;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Properties;
/**
* <p>
* 代码生成器演示
* </p>
*/
public class MpGenerator {
public static void main(String[] args) throws Exception {
// assert (false) : "代码生成属于危险操作,请确定配置后取消断言执行代码生成!";
AutoGenerator mpg = new AutoGenerator();
Properties properties = ConfigUtil.getProperties();
if (properties == null) {
throw new Exception("Please add a file named config.properties to src/main/resources");
}
String projectDir = properties.getProperty(ConfigUtil.PROJECT_DIR);
if (projectDir == null || projectDir.isEmpty()) {
throw new Exception("Configure your project directory in config.properties");
}
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setAuthor("CQUT SE 2020");
// 对应项目的 src/main/java 目录在磁盘上的真实路径(在 config.properties 文件里配置)
gc.setOutputDir(projectDir + "/src/main/java");
gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
mpg.setGlobalConfig(gc);
Properties appProperties = ConfigUtil.getProperties("application.properties");
if (appProperties == null) return;
String userName = appProperties.getProperty("spring.datasource.username");
if (userName == null || userName.isEmpty()) return;
String pwd = appProperties.getProperty("spring.datasource.password");
if (pwd == null) return;
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(userName); // 数据库用户名(在 application.properties 文件里配置)
dsc.setPassword(pwd); // 数据库密码(在 application.properties 文件里配置)
dsc.setUrl("jdbc:mysql://localhost:3306/cqutcrm?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
mpg.setDataSource(dsc);
String tables = properties.getProperty(ConfigUtil.DATASOURCE_UTIL_TABLES);
if (tables == null || tables.isEmpty()) {
throw new Exception("Configure tables to generate in config.properties");
}
String[] tableNames = tables.split(",");
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(tableNames); // 需要生成的表(在 config.properties 文件里配置)
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("cn.edu.cqut"); //项目的根包(启动类所在的包)
pc.setController("controller"); //Controller类所在的包
pc.setService("service"); //Service接口所在的包
pc.setServiceImpl("service.impl"); //Service实现类所在的包
pc.setMapper("mapper"); //Mapper接口所在的包
pc.setEntity("entity"); //实体类所在的包
pc.setXml("mapper.xml"); //mapper映射文件所在的包
mpg.setPackageInfo(pc);
TemplateConfig tc = new TemplateConfig();
tc.setXml(null); //不生成xml映射文件
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
|
/*
* 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 spartanfinal;
import com.esri.core.runtime.LicenseResult;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.esri.map.JMap;
import com.esri.map.ArcGISTiledMapServiceLayer;
import com.esri.map.ArcGISDynamicMapServiceLayer;
import com.esri.map.LocationOnMap;
import com.esri.core.geometry.*;
import com.esri.core.io.UserCredentials;
import com.esri.core.map.CallbackListener;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureEditResult;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.*;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.map.ArcGISFeatureLayer;
import com.esri.map.GraphicsLayer;
import com.esri.map.MapEvent;
import com.esri.map.MapEventListenerAdapter;
import com.esri.map.MapOptions;
import com.esri.map.MapOptions.MapType;
import com.esri.map.QueryMode;
import com.esri.runtime.ArcGISRuntime;
import com.esri.toolkit.overlays.HitTestOverlay;
import com.esri.toolkit.overlays.NavigatorOverlay;
import com.esri.map.MapOverlay;
import com.esri.toolkit.overlays.HitTestEvent;
import com.esri.toolkit.overlays.HitTestListener;
import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javafx.application.Platform;
import javafx.util.Duration;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import tray.animations.AnimationType;
import tray.notification.NotificationType;
import tray.notification.TrayNotification;
public class esri_map {
public Login login;
private boolean run_once = true;
private Dimension dim;
private Point old;
public JMap map;
private MapOptions mapOptions;
public googleFrame googleF;
private static SpatialReference wgs84 = SpatialReference.create(4326);
private JFrame window;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenu mapMenu = new JMenu("Maps");
private JMenu toolsMenu = new JMenu("Tools");
private JMenu profileMenu = new JMenu("Profile");
private JMenuItem newItem, closeItem, basemap, satellite, googlem, addShapeFile,
identifyFeature, moveSpartan, changeProfile, newProfile; //Here we add more items;
private ImageIcon img;
private boolean runonce = true;
private ArcGISTiledMapServiceLayer TileLayer;
private ArcGISTiledMapServiceLayer SatLayer;
public ArcGISFeatureLayer spartanLayer;
public ArcGISFeatureLayer flagsLayer;
private Symbol special;
private ArcGISDynamicMapServiceLayer StreetLayer;
private JPanel contentPane;
private int [] layer = {1,2,3};
private int layer_loc = 0;
private int getId;
private int count;
private int count2;
private boolean moveOn = false;
private boolean newMoveOn = false;
private boolean readyMove = false;
private boolean readyMove2 = false;
private boolean tablelist = false;
private boolean tablelist2 = false;
private boolean tablelist3 = false;
private boolean tablelist4 = false;
private int moveNum = 0;
private String objectid = null;
private Toolkit toolkit = Toolkit.getDefaultToolkit();
// private Image image = toolkit.getImage("img/cursor_hand.png");
private Image identifyImage = toolkit.getImage("img/identify_cursor.png");
private Cursor c;
private Cursor id;
private Point p;
private newUser addP;
private updateUser updateP;
private newTicket ticket = null;
private QueryParameters query = new QueryParameters();
private DownloadInformation download;
private GraphicsLayer temporary;
JTextField findText = new HintTextField("Search Address");
private Timer timer;
private Timer t;
private Timer subTimer;
private Timer teamTimer;
private Timer flagsTimer;
private parcelSearch parcelsearch = new parcelSearch();
private parcelSearch subSearh = new parcelSearch();
private geocoderSearch geocodeS = new geocoderSearch();
private ticketSearch ticketS = new ticketSearch();
private searchDirectory directoryS = new searchDirectory();
private AddressingForm addressing = new AddressingForm(); //Cool Stuff for each department.
private boolean ticketopen = false;
private tableList list;
private tableList ownerList;
private tableList directorySearch;
private tableList subParcel;
//URL STATIC FINAL PRIVATE
//1.) streets, ranges, points....
//2.) Basemap primary...
//3.) Satellite View...
//4.) Spartan Layer...
//5.) Picture Flags...
private final static String dynamic_url =
"http://gis.lrgvdc911.org/arcgis/rest/services/Dynamic/dynammic_layers_important/MapServer";
private final static String basemap_url =
"http://gis.lrgvdc911.org/arcgis/rest/services/basemap/basemap_new_cache_once/MapServer";
private final static String sat_url =
"http://psap.lrgvdc911.org/arcgis/rest/services/Imagery/MapServer";
private final static String spartan_url =
"http://gis.lrgvdc911.org/arcgis/rest/services/Dynamic/spartan_dynamic_feature/FeatureServer/0";
private final static String flags =
"http://gis.lrgvdc911.org/arcgis/rest/services/identify/cam_final_features/FeatureServer/0";
public esri_map(ImageIcon i)
{
img = i;
findText.setSize(2000, 10);
login = new Login();
googleF = new googleFrame(img);
googleF.basemap.addActionListener(new actionClick());
googleF.closeItem.addActionListener(new actionClick());
googleF.satellite.addActionListener(new actionClick());
setLicense();
}
public void setDefinition()
{
if(login.getRole().equalsIgnoreCase("GIS"))
{
login.setRole("MAPPING");
spartanLayer.setDefinitionExpression("status = '" + login.getRole() + "' and region = '" + login.getRegion() + "' or status = 'HOLD'");
}else{
spartanLayer.setDefinitionExpression("status = '" + login.getRole() + "' or status = 'HOLD'");
}
}
public void setLoginSuccess()
{
Platform.runLater(new Runnable() {
@Override
public void run() {
TrayNotification tray = new TrayNotification();
tray.setMessage("Login was a success");
tray.setTitle("Welcome to Spartan Database");
tray.setNotificationType(NotificationType.SUCCESS);
tray.setAnimationType(AnimationType.POPUP);
tray.showAndDismiss(Duration.seconds(2));
}
});
}
public JComponent createUI() throws Exception {
//Application north search..
JLabel findLabel = new JLabel("Find ");
findLabel.setForeground(Color.WHITE);
findLabel.setFont(new Font(findLabel.getFont().getName(), findLabel
.getFont().getStyle(), 14));
findText.setFont(new Font(findLabel.getFont().getName(), findLabel
.getFont().getStyle(), 14));
findText.setMinimumSize(new Dimension(150, 25));
findText.setMaximumSize(new Dimension(150, 25));
findText.setColumns(10);
JButton findButton = new JButton("Find");
findButton.setFont(new Font(findLabel.getFont().getName(), findLabel
.getFont().getStyle(), 14));
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.decode("#0CA3D2"));
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
topPanel.add(Box.createHorizontalGlue());
// topPanel.add(findLabel);
// topPanel.add(findText);
// topPanel.add(findButton);
//topPanel.add(Box.createHorizontalGlue());
// application content
contentPane = new JPanel(new BorderLayout());
contentPane.add(topPanel, BorderLayout.NORTH);
// map options: topographic map, centered at lat-lon 41.9, 12.5 (Rome), zoom level 12
mapOptions = new MapOptions(MapType.TOPO, 26.3825161, -98.756449, 8);
//Create Arcgis Dynamic Service
TileLayer = new ArcGISTiledMapServiceLayer(
basemap_url);
SatLayer = new ArcGISTiledMapServiceLayer(sat_url);
StreetLayer = new ArcGISDynamicMapServiceLayer(dynamic_url);
final UserCredentials credentials = new UserCredentials();
credentials.setUserAccount("hchapa", "cangri1989");
spartanLayer = new ArcGISFeatureLayer(spartan_url, credentials);
spartanLayer.setOperationMode(QueryMode.ON_DEMAND);
flagsLayer = new ArcGISFeatureLayer(flags, credentials);
flagsLayer.setOperationMode(QueryMode.ON_DEMAND);
//Set Query Definitaion on Spartan Layer..
//Called function....
setDefinition();
// create the map using MapOptions
map = new JMap(mapOptions);
temporary = new GraphicsLayer();
map.addMapOverlay(new MouseOverLay(map));
map.getLayers().clear();
// map.zoomTo(26.3825161, -97.9756449, 40);
map.getLayers().add(TileLayer);
map.getLayers().add(StreetLayer);
map.getLayers().add(spartanLayer);
map.getLayers().add(flagsLayer);
map.getLayers().add(temporary);
contentPane.add(map, BorderLayout.CENTER);
// add marker graphics directly to the map
NavigatorOverlay navigatorOverlay = new NavigatorOverlay();
navigatorOverlay.setLocation(LocationOnMap.TOP_LEFT);
map.addMapOverlay(navigatorOverlay);
map.addMapEventListener(new MapEventListenerAdapter(){
@Override
public void mapExtentChanged(MapEvent arg0)
{
if(login.getRole().equalsIgnoreCase("addressing"))
{
}
}
});
addHitTestOverlay(map, spartanLayer);
addHitTestOverlay2(map, flagsLayer);
// option to use a custom marker image by creating a BufferedImage
return contentPane;
}
public void setLicense()
{
LicenseResult lice = ArcGISRuntime.setClientID("DUrBj4n7d8YXh4GM");
//ArcGISRuntime.License.setLicense("DUrBj4n7d8YXh4GM");
}
public void createWindow(Dimension d) {
window = new JFrame("Spartan Map Application");
p = new Point(window.getX(), window.getY());
// c = toolkit.createCustomCursor(image,p.getPoint(), "test");
id = toolkit.createCustomCursor(identifyImage,window.getLocation(),"Identify");
// window.setCursor(c);
window.setExtendedState(JFrame.MAXIMIZED_BOTH);
window.setIconImage(img.getImage());
dim = d;
window.setSize(dim);
googleF.setSize(dim);
//Setting Menu...
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.getAccessibleContext().setAccessibleDescription("Dealing with Files");
window. setJMenuBar(menuBar);
newItem = new JMenuItem("New Ticket", new ImageIcon("img/document.png"));
newItem.setMnemonic(KeyEvent.VK_P);
newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
newItem.addActionListener(new actionClick());
fileMenu.add(newItem);
closeItem = new JMenuItem("Exit", new ImageIcon("img/close.png"));
closeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
closeItem.addActionListener(new actionClick());
fileMenu.add(closeItem);
mapMenu.setMnemonic(KeyEvent.VK_M);
basemap = new JMenuItem("BaseMap", new ImageIcon("img/map.png"));
basemap.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ActionEvent.CTRL_MASK));
basemap.addActionListener(new actionClick());
satellite = new JMenuItem("Satellite", new ImageIcon("img/satellite.png"));
satellite.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
satellite.addActionListener(new actionClick());
googlem = new JMenuItem("Google Map", new ImageIcon("img/google.png"));
googlem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
googlem.addActionListener(new actionClick());
mapMenu.add(basemap);
mapMenu.add(satellite);
mapMenu.add(googlem);
moveSpartan = new JMenuItem("Move Graphic", new ImageIcon("img/arrow_move2.png"));
moveSpartan.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
moveSpartan.addActionListener(new actionClick());
toolsMenu.add(moveSpartan);
//More tools menu..
identifyFeature = new JMenuItem("Identify", new ImageIcon("img/identify_display.png"));
identifyFeature.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
identifyFeature.addActionListener(new actionClick());
toolsMenu.add(identifyFeature);
profileMenu.setMnemonic(KeyEvent.VK_P);
changeProfile = new JMenuItem("Update Profile", new ImageIcon("img/Add_User_24.png"));
changeProfile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
changeProfile.addActionListener(new actionClick());
profileMenu.add(changeProfile);
if(login.getRights().equals("YES"))
{
newProfile = new JMenuItem("New Profile", new ImageIcon("img/Add_User_24.png"));
newProfile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
newProfile.addActionListener(new actionClick());
profileMenu.add(newProfile);
}
toolsMenu.setMnemonic(KeyEvent.VK_T);
//Adding Menu to the MenuBar..
menuBar.add(fileMenu);
menuBar.add(mapMenu);
menuBar.add(profileMenu);
menuBar.add(toolsMenu);
menuBar.add(new JSeparator());
menuBar.add(findText);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setLayout(new BorderLayout());
window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
super.windowClosing(windowEvent);
try{
map.dispose();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
}
public void setEsriFrame()
{
try{
window.add(createUI());
window.setVisible(true);
parcelsearch.setFeatureLayer(spartanLayer);
timer = new Timer(200, new actionClick());
timer.setRepeats(false);
timer.start();
//Open what department form
if(login.getRole().equalsIgnoreCase("addressing"))
{
count = 0;
this.addressing.setVisible(true);
this.addressing.setMessage("Please wait.... Setting Some Stuff");
this.addressing.runQuery();
this.addressing.addClick(new actionClick());
this.addressing.addTableClick(new table());
this.addressing.addFocusListener(new focusList());
t = new Timer(3000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(download.getFound() && download.getFound2())
{
count++;
if(count == 1)
{
addressing.setRegion(download.setRegionArray());
addressing.setMsag(download.setMsagArray());
count = 0;
}
}
if(addressing.ready())
{
t.stop();
count++;
if(count == 1)
{
proccessBuffer();
}
}
}
});
t.start();
}
}catch(Exception t)
{
t.printStackTrace();
}
}
public void proccessBuffer(){
zoomToCreateBuffer();
}
public void setMap(int i)
{
map.getLayers().clear();
if(layer[i] != layer[layer_loc])
{
layer_loc = i;
if(layer[i] == 1)
{
map.getLayers().add(TileLayer);
map.getLayers().add(StreetLayer);
map.getLayers().add(spartanLayer);
map.getLayers().add(flagsLayer);
map.getLayers().add(temporary);
spartanLayer.requery();
}
else if(layer[i] == 2)
{
map.getLayers().add(SatLayer);
map.getLayers().add(StreetLayer);
map.getLayers().add(spartanLayer);
map.getLayers().add(flagsLayer);
map.getLayers().add(temporary);
spartanLayer.requery();
}
else{
old = map.getExtent().getCenter();
old = (Point) GeometryEngine.project(old, map.getSpatialReference(), wgs84);
//if(map.getResolution())
window.setVisible(false);
googleF.setVisible(true);
googleF.changeWebView(String.valueOf(old.getX()), String.valueOf(old.getY()));
}
}else
{
System.out.println("There are the same");
}
}
public void updateInfomation()
{
moveOn = false;
moveNum = 0;
Graphic up = spartanLayer.getGraphic(getId);
Point p = (Point) GeometryEngine.project(spartanLayer.getGraphic(getId).getGeometry(), map.getSpatialReference(), wgs84);
Map<String, Object> attributes = up.getAttributes();
attributes.put("longy", p.getX());
attributes.put("lat", p.getY());
attributes.put("msag_comm", download.checkMsagContains(spartanLayer.getGraphic(getId).getGeometry()));
attributes.put("exch", download.checkExchContains(spartanLayer.getGraphic(getId).getGeometry()));
attributes.put("esn", download.checkEsnContains(spartanLayer.getGraphic(getId).getGeometry()));
attributes.put("region", download.checkRegionContains(spartanLayer.getGraphic(getId).getGeometry()));
if(!ticketopen)
{
System.out.println("I ran1");
parcelsearch.setObjectId(attributes.get("OBJECTID").toString());
parcelsearch.searchGeometry(spartanLayer.getGraphic(getId).getGeometry());
}
else if(ticket.checkObjectid(objectid))
{
System.out.println("I ran2");
ticket.runGeometry(spartanLayer.getGraphic(getId).getGeometry());
}
spartanLayer.updateGraphic(getId, attributes);
Graphic[] update = {spartanLayer.getGraphic(getId)};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{},update , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
for(int i = 0; i < result.length; i++)
{
//System.out.println("I ran what " + i);
FeatureEditResult []t = result[i];
// System.out.println("T length " + t.length);
for(int y = 0; y < t.length; y++)
{
// System.out.println("I ran something testing this out " + y);
//System.out.println("Global Id " + t[y].getObjectId());
}
}
}
@Override
public void onError(Throwable e) {
// handle the error
}
});
}
public void updateInfomation2()
{
getId = findId();
Graphic[] update = {spartanLayer.getGraphic(getId)};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{},update , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
objectid = null;
for(int i = 0; i < result.length; i++)
{
// System.out.println("I ran what " + i);
FeatureEditResult []t = result[i];
// System.out.println("T length " + t.length);
for(int y = 0; y < t.length; y++)
{
// System.out.println("I ran something testing this out " + y);
// System.out.println("Global Id " + t[y].getObjectId());
}
}
}
@Override
public void onError(Throwable e) {
// handle the error
}
});
}
public void insertNewTicket()
{
//Create new ticket submit to the database...
Point p = (Point)GeometryEngine.project(map.getExtent().getCenter(), map.getSpatialReference(), SpatialReference.create(4326));
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar now = Calendar.getInstance();
// System.out.println("Calendar Month: " + dateFormat.format(now.getTime()));
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("started_ticket", login.getInit());
attributes.put("created_date",dateFormat.format(now.getTime()));
attributes.put("state", "TX");
attributes.put("status", "HOLD");
attributes.put("longy", p.getX());
attributes.put("lat", p.getY());
PictureMarkerSymbol symbol = null;
File f = new File("img/user_location_32.png");
try{
BufferedImage symbolI = ImageIO.read(f);
symbol = new PictureMarkerSymbol(symbolI);
}
catch(Exception t)
{
}
attributes.put("msag_comm", download.checkMsagContains(map.getExtent().getCenter()));
attributes.put("exch", download.checkExchContains(map.getExtent().getCenter()));
attributes.put("esn", download.checkEsnContains(map.getExtent().getCenter()));
attributes.put("region", download.checkRegionContains(map.getExtent().getCenter()));
Graphic insert = new Graphic(map.getExtent().getCenter(), symbol, attributes);
Graphic [] add = {insert};
spartanLayer.applyEdits(add, new Graphic[]{},new Graphic[]{} , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
if(ticket == null || !ticket.isDisplayable())
{
try{
ticket = new newTicket(img, String.valueOf(result[0][0].getObjectId()), spartanLayer);
ticketopen = true;
ticket.packOnce();
ticket.mainT.addActionListener(new actionClick());
ticket.alt1.addActionListener(new actionClick());
ticket.save.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), "Save");
ticket.save.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), "Save");
ticket.save.getActionMap().put("Save", new abClick());
ticket.save.addActionListener(new actionClick());
ticket.userF.addActionListener(new actionClick());
ticket.sub.addActionListener(new actionClick());
ticket.zoom.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK), "Zoom");
ticket.zoom.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK), "Zoom");
ticket.zoom.getActionMap().put("Zoom", new abClick());
ticket.zoom.addActionListener(new actionClick());
ticket.delete.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK), "Delete");
ticket.delete.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK), "Delete");
ticket.delete.getActionMap().put("Delete", new abClick());
ticket.delete.addActionListener(new actionClick());
ticket.next.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), "New");
ticket.next.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), "New");
ticket.next.getActionMap().put("New", new abClick());
ticket.next.addActionListener(new actionClick());
ticket.previous.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), "Prev");
ticket.previous.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), "Prev");
ticket.previous.getActionMap().put("Prev", new abClick());
ticket.previous.addActionListener(new actionClick());
ticket.GraphicsId = ticket.layer.addGraphic(insert);
ticket.position = ticket.list.size() - 1;
ticket.list.get(ticket.position).setPosition(map.getExtent().getCenter());
ticket.list.get(ticket.position).setGeometry(insert.getGeometry());
ticket.list.get(ticket.position).setSymbol(insert.getSymbol());
setUpFocus();
map.getLayers().add(ticket.layer);
ticket.setVisible(true);
ticket.setUpTicket();
ticket.addWindowListener(new WindowAdapter(){
@Override
public void windowClosed(WindowEvent e)
{
super.windowClosed(e);
ticketopen = false;
map.getLayers().remove(ticket.layer);
}
});
ticket.runGeometry(map.getExtent().getCenter());
spartanLayer.refresh();
spartanLayer.requery();
}catch(Exception e)
{
}
}
}
@Override
public void onError(Throwable e) {
// handle the error
}
});
}
public void processTable()
{
//Get Results from teamTimer...
//Add the data to the table...
if(login.getRole().equalsIgnoreCase("addressing"))
{
addressing.setRelatedRest(ticketS.getResults());
addressing.startAddingDataRelated();
//Start adding the symbols in the map..
//set the symbol information before loop starts
SimpleMarkerSymbol marker = new SimpleMarkerSymbol(new Color(116, 209, 234), 10, SimpleMarkerSymbol.Style.SQUARE);
addressing.clearGraphicId();
for(int i = 0; i < addressing.getLengthRelated(); i++)
{
addressing.setIdGraphicRelated(temporary.addGraphic(new Graphic(addressing.getRelatedGeometry(i), marker)));
}
}
}
public void zoomToCreateBuffer()
{
if(login.getRole().equalsIgnoreCase("addressing"))
{
Polygon p = GeometryEngine.buffer(addressing.getGeometry(), map.getSpatialReference(), 500, map.getSpatialReference().getUnit());
temporary.removeAll();
SimpleLineSymbol outline = new SimpleLineSymbol(Color.BLACK, 2, SimpleLineSymbol.Style.SOLID);
SimpleFillSymbol symbol = new SimpleFillSymbol(new Color(160, 32, 240, 50), outline);
addressing.setGraphicId(temporary.addGraphic(new Graphic(p, symbol)));
map.zoomTo(p);
ticketS.queryGeometry(p);
ticketS.setFoundTicket(false);
addressing.destroyAttachments();
addressing.getAttachments();
teamTimer = new Timer(800, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ticketS.getFoundTicket())
{
System.out.println("found gracious data hear....");
System.out.println("Check out my inventory" + ticketS.getResults().featureCount());
processTable();
ticketS.setFoundTicket(false);
parcelsearch.searchGeometry2(addressing.getGeometry());
}
if(parcelsearch.getFoundParcel())
{
teamTimer.stop();
addressing.getParcelModel().setRowCount(0);
addressing.getParcelModel().addRow(new Object[]{parcelsearch.getParcelData().get(0).getFull(),
parcelsearch.getParcelData().get(0).getTax(), parcelsearch.getParcelData().get(0).getProp(),
parcelsearch.getParcelData().get(0).getLegal(), parcelsearch.getParcelData().get(0).getSitus()});
addressing.getSubModel().setRowCount(0);
addressing.searchDirectorySub(parcelsearch.getParcelData().get(0).getLegal());
}
}
});
teamTimer.start();
}
}
public void zoomTOFullExtent()
{
map.zoomTo(map.getFullExtent());
}
public void insertNextTicket()
{
//Create new ticket submit to the database...
//
System.out.println(ticket.position);
System.out.println(ticket.list.size());
Point p = (Point)GeometryEngine.project(map.getExtent().getCenter(), map.getSpatialReference(), SpatialReference.create(4326));
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar now = Calendar.getInstance();
//System.out.println("Calendar Month: " + dateFormat.format(now.getTime()));
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("started_ticket", login.getInit());
attributes.put("created_date",dateFormat.format(now.getTime()));
attributes.put("state", "TX");
attributes.put("status", "HOLD");
attributes.put("msag_comm", download.checkMsagContains(map.getExtent().getCenter()));
attributes.put("exch", download.checkExchContains(map.getExtent().getCenter()));
attributes.put("esn", download.checkEsnContains(map.getExtent().getCenter()));
attributes.put("region", download.checkRegionContains(map.getExtent().getCenter()));
attributes.put("longy", p.getX());
attributes.put("lat", p.getY());
PictureMarkerSymbol symbol = null;
File f = new File("img/user_location_32.png");
try{
BufferedImage symbolI = ImageIO.read(f);
symbol = new PictureMarkerSymbol(symbolI);
}
catch(Exception t)
{
}
Graphic insert = new Graphic(map.getExtent().getCenter(), symbol, attributes);
Graphic [] add = {insert};
System.out.println(insert.getAttributes().toString());
System.out.println("I ran here waht happend.");
spartanLayer.applyEdits(add, new Graphic[]{},new Graphic[]{} , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
try{
//System.out.println("ID is " + result[0][0].getObjectId() + " positino is " + ticket.position);
System.out.println("I ran here as well ");
ticket.setLayer(spartanLayer); //Reset layer with new information...
ticket.setIdText(String.valueOf(result[0][0].getObjectId()), insert);
ticket.refreshForm();
ticket.runGeometry(map.getExtent().getCenter());
// System.out.println("new position " + ticket.position);
}catch(Exception t)
{
}
}
@Override
public void onError(Throwable e) {
// handle the error
}
});
}
public int findId()//This function will loop until find the id matching that object id..
{
int temp = 0;
if(ticket.list.size() > 0)
{
System.out.println("size of the list is " + ticket.list.size());
for(int i = 0; i < spartanLayer.getGraphicIDs().length; i++)
{
temp = spartanLayer.getGraphicIDs()[i];
System.out.println("CURRENT ID CHECKING IS " + temp);
System.out.print("OBJECTID IS " + ticket.list.get(ticket.position).getId());
if(spartanLayer.getGraphic(temp).getAttributeValue("OBJECTID").toString().equalsIgnoreCase(ticket.list.get(ticket.position).getId()))
{
System.out.println("I found something");
return temp;
}
}
}
return 0;
}
public int findId2()
{
int temp = 0;
try{
for(int i = 0; i < spartanLayer.getGraphicIDs().length; i++)
{
temp = spartanLayer.getGraphicIDs()[i];
if(spartanLayer.getGraphic(temp).getAttributeValue("OBJECTID").toString().equalsIgnoreCase(objectid))
return temp;
}
}catch(Exception e)
{
}
return 0;
}
public void changeLocation(Point p)
{
Envelope extent = map.getExtent();
extent.centerAt(p);
map.zoomTo(extent);
updateInfomation();
}
public void deleteRecordN()
{
Graphic up = null;
Map<String, Object> attributes = new HashMap<String, Object>();
if(login.getRole().equalsIgnoreCase("addressing"))
{
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
up = new Graphic(addressing.getGeometry(), null, attributes);
}
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{up}, new Graphic[]{} , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
if(result[1] != null && result[1][0] != null && result[1][0].isSuccess())
{
JOptionPane.showMessageDialog(null, "Success Delete Record ");
addressing.removeArraylist();
addressing.removeRecordTable();
if(addressing.getPosition() > addressing.getPositionLength())
{
addressing.subPosition();
}
addressing.setMessageText();
addressing.moveTable();
addressing.setTablePosition();
}
}
@Override
public void onError(Throwable e) {
// handle the error
JOptionPane.showMessageDialog(null, "Sorry, No more Records To delete");
}
});
}
public void saveRecord()
{
ticket.startProgressBar();
Graphic [] up = ticket.getInfo();
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, up, new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
if(result[2] != null && result[2][0] != null && result[2][0].isSuccess())
{
JOptionPane.showMessageDialog(null, "Saved Record");
ticket.stopProgressBar();
}
}
@Override
public void onError(Throwable e) {
// handle the error
JOptionPane.showMessageDialog(null, e.getMessage());
}
});
}
public void deleteRecord()
{
int temp = findId();
System.out.println(temp);
System.out.println(ticket.list.get(ticket.position).getId());
Graphic up = null;
if(temp != 0)
{
System.out.println(spartanLayer.getCapabilities());
System.out.println("I got id " + temp);
up = spartanLayer.getGraphic(temp);
System.out.println(up.getAttributes().toString());
}else{
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(ticket.list.get(ticket.position).getId()));
up = new Graphic(ticket.list.get(ticket.position).getGeometry(), null, attributes);
}
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{up}, new Graphic[]{} , new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
// do something with the feature edit result object
if(result[1] != null && result[1][0] != null && result[1][0].isSuccess())
{
JOptionPane.showMessageDialog(null, "Success Delete Record " + ticket.list.get(ticket.position).getId());
//update list...
ticket.updateList();
//System.out.println("Lenth of list " + ticket.list.size());
ticket.subTrackPosition();
// System.out.println("New position is " + ticket.position);
//refresh Form..
ticket.removeLayer();
ticket.refreshForm();
// System.out.println("I ran second");
map.panTo(ticket.list.get(ticket.position).getGeometry());
}
}
@Override
public void onError(Throwable e) {
// handle the error
JOptionPane.showMessageDialog(null, "Sorry, No more Records To delete");
}
});
}
private void addHitTestOverlay2(final JMap jMap, final ArcGISFeatureLayer flags) { //For Regular tickets not new...
// create a hit test overlay for the feature layer
final HitTestOverlay hitTestOverlay = new HitTestOverlay(flags);
// add a listener to perform some action when a feature was hit
hitTestOverlay.addHitTestListener(new HitTestListener() {
@Override
public void featureHit(HitTestEvent event) {
if(login.getRole().equalsIgnoreCase("addressing"))
{
flagsLayer.clearSelection();
flagsLayer.setSelectionColor(Color.yellow);
flagsLayer.select((int)hitTestOverlay.getHitFeatures().get(0).getId());
addressing.getPicturesModel().setNumRows(0);
addressing.setTabPane(6);
for(int i = 0; i < hitTestOverlay.getHitFeatures().size(); i++)
{
addressing.getPicturesModel().addRow(new Object[]{hitTestOverlay.getHitFeatures().get(i).getAttributeValue("FilePath")});
}
}
}
});
map.addMapOverlay(hitTestOverlay);
}
private void addHitTestOverlay(final JMap jMap, final ArcGISFeatureLayer spartan) { //For Regular tickets not new...
// create a hit test overlay for the feature layer
final HitTestOverlay hitTestOverlay = new HitTestOverlay(spartan);
// add a listener to perform some action when a feature was hit
hitTestOverlay.addHitTestListener(new HitTestListener() {
@Override
public void featureHit(HitTestEvent event) {
// reset the feature layer to remove previously selected cities
spartan.clearSelection();
if(readyMove)
{
Feature t = hitTestOverlay.getHitFeatures().get(0);
objectid = t.getAttributeValue("OBJECTID").toString();
//System.out.println("Object id is " + objectid);
getId = (int) t.getId();
moveOn = true;
}
else{
if(login.getRole().equalsIgnoreCase("addressing"))
{
Feature t = hitTestOverlay.getHitFeatures().get(0);
System.out.println(map.getSpatialReference().getUnit());
Polygon p = GeometryEngine.buffer(t.getGeometry(), map.getSpatialReference(), 500, map.getSpatialReference().getUnit());
temporary.removeAll();
SimpleLineSymbol outline = new SimpleLineSymbol(Color.BLACK, 3, SimpleLineSymbol.Style.SOLID);
SimpleFillSymbol symbol = new SimpleFillSymbol(new Color(160, 32, 240, 50), outline);
temporary.addGraphic(new Graphic(p, symbol));
map.zoomTo(p);
}
}
}
});
map.addMapOverlay(hitTestOverlay);
}
//Class For Clicking..
public class actionClick implements ActionListener{ //Click Button
@Override
public void actionPerformed(ActionEvent e) {
if(login.getRole().equalsIgnoreCase("addressing"))
{
if(e.getSource() == addressing.getButtonPrev())
{
if(addressing.getPosition() == 0)
{
addressing.endList();
addressing.setTablePosition();
addressing.scrollTable();
addressing.setMessageText();
addressing.updateId();
zoomToCreateBuffer();
}else{
addressing.subPosition();
addressing.setTablePosition();
addressing.scrollTable();
addressing.setMessageText();
addressing.updateId();
zoomToCreateBuffer();
}
return;
}
else if(e.getSource() == addressing.getButtonNext())
{
if(addressing.getPosition() == addressing.getPositionLength())
{
addressing.begList();
addressing.setTablePosition();
addressing.scrollTable();
addressing.setMessageText();
addressing.updateId();
zoomToCreateBuffer();
}
else{
addressing.addPosition();
addressing.setTablePosition();
addressing.scrollTable();
addressing.setMessageText();
addressing.updateId();
zoomToCreateBuffer();
}
return;
}
else if(e.getSource() == addressing.getButtonDel())
{
System.out.println("I ran delete button yay");
deleteRecordN();
return;
}
else if(e.getSource() == addressing.getButtonZoom())
{
zoomToCreateBuffer();
return;
}
else if(e.getSource() == addressing.getButtonAttach())
{
JFileChooser fileChooser = new javax.swing.JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
try
{
final long startTime = System.currentTimeMillis();
ProcessFiles files = new ProcessFiles(fileChooser.getSelectedFile());
dbConnect con = new dbConnect();
int num = con.insertAttachments(addressing.getId(), files);
final long endTime = System.currentTimeMillis();
// Vector newRow = new Vector();
if(num > 0)
addressing.getAttachModel().addRow(new Object[]{con.getFiles().getId(), con.getFiles().getName(), con.getFiles().getType(), con.getFiles().getImage()});
else
JOptionPane.showMessageDialog(null, "Sorry can't upload to big of a file even with compression");
//jTable1.addR
}catch(Exception t)
{
JOptionPane.showMessageDialog(null, t);
}
}
return;
}
else if(e.getSource() == addressing.getButtonSave())
{
String full_address = addressing.getJTextFieldNum().getText();
full_address += addressing.getJComboxPre().getSelectedItem().toString().equalsIgnoreCase("?") ? "" : " " + addressing.getJComboxPre().getSelectedItem().toString();
full_address += addressing.getJTextFieldStreet().getText().equalsIgnoreCase("?") ? "" : " " + addressing.getJTextFieldStreet().getText();
full_address += addressing.getJComboxType().getSelectedItem().toString().equalsIgnoreCase("?") ? "" : " " + addressing.getJComboxType().getSelectedItem().toString();
full_address += addressing.getJComboxPost().getSelectedItem().toString().equalsIgnoreCase("?") ? "" : " " + addressing.getJComboxPost().getSelectedItem().toString();
System.out.println(full_address);
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("dmi_beg", addressing.getJTextFieldDmi().getText());
attributes.put("structure", addressing.getJTextFieldStruct().getText());
attributes.put("dmi_end", addressing.getJTextFieldEnd().getText());
attributes.put("full_address", full_address);
attributes.put("add_num", Double.parseDouble(addressing.getJTextFieldNum().getText()));
attributes.put("prd", addressing.getJComboxPre().getSelectedItem().toString());
attributes.put("rd", addressing.getJTextFieldStreet().getText());
attributes.put("sts", addressing.getJComboxType().getSelectedItem().toString());
attributes.put("pod", addressing.getJComboxPost().getSelectedItem().toString().equalsIgnoreCase("?") ? "" : addressing.getJComboxPost().getSelectedItem().toString());
attributes.put("unit", addressing.getJTextFieldUnit().getText());
attributes.put("msag_comm",addressing.getJComboxMsag().getSelectedItem().toString());
attributes.put("status", addressing.getJComboxStatus().getSelectedItem().toString());
Graphic up = new Graphic(addressing.getGeometry(), null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, new CallbackListener<FeatureEditResult[][]>(){
@Override
public void onCallback(FeatureEditResult[][] result) {
if(result[2][0].isSuccess()){
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Update Record");
}
}
@Override
public void onError(Throwable e) {
// handle the error
}
});
return;
}
}
if(e.getSource() == newItem)
{
if(ticket == null || !ticket.isDisplayable())
{
insertNewTicket();
}
return;
}
else if(e.getSource() == identifyFeature)
{
System.out.println("I ran identify");
window.setCursor(id);
return;
}
else if(e.getSource() == googleF.basemap)
{
window.setVisible(true);
setMap(0);
googleF.setVisible(false);
return;
}
else if(e.getSource() == googleF.satellite)
{
window.setVisible(true);
setMap(1);
googleF.setVisible(false);
return;
}
else if(e.getSource() == closeItem || e.getSource() == googleF.closeItem)
{
map.dispose();
googleF.dispose();
System.exit(1);
return;
}
else if(e.getSource() == basemap)
{
// System.out.println("I ran 1");
setMap(0);
return;
}
else if(e.getSource() == satellite)
{
setMap(1);
return;
}
else if(e.getSource() == googlem)
{
setMap(2);
return;
}
else if(e.getSource() == newProfile)
{
// System.out.println("Array is " + Arrays.toString(download.setRegionArray()));
addP = new newUser(img, download.setRegionArray());
return;
}
else if(e.getSource() == changeProfile)
{
updateP = new updateUser(img, download.setRegionArray(), login);
updateP.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
super.windowClosing(windowEvent);
try{
login = updateP.getNewInfo();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
}
else if(e.getSource() == moveSpartan)
{
readyMove = readyMove ? false : true;
if(readyMove)
window.setCursor(Cursor.HAND_CURSOR);
else
window.setCursor(Cursor.DEFAULT_CURSOR);
if(!readyMove)
{
updateInfomation();
}
//System.out.println("Read equals " + readyMove);
return;
}
else if(e.getSource() == timer)
{
final int THREADS = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
Future<Object> future = executor.submit(new Callable<Object>()
{
public Object call()
{
download = new DownloadInformation();
return null;
}
});
if(future.isDone())
{
System.out.println("FINISH");
}
return;
}
else if(e.getSource() == ticket.sub)
{
ticket.startProgressBar();
directoryS.searchWhat(ticket.list.get(ticket.position).getSub());
subSearh.searchSubdivision(ticket.list.get(ticket.position).getSub());
count = 0;
count2 = 0;
t = new Timer(950, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(count == 10)
{
if(subSearh.getOwnerData().size() > 0)
{
subSearh.setFoundParcel(true);
count = 0;
}
}
else{
count++;
}
if(subSearh.getFoundParcel())
{
System.out.println("FOUnd data");
t.stop();
System.out.println(count);
count = 0;
count++;
if(count == 1)
{
if(tablelist4)
{
subParcel.clearData();
subParcel.addData(subSearh.getOwnerData());
}else{
subParcel = new tableList();
tablelist4 = true;
subParcel.setVisible(true);
subParcel.addWindowListener(new closing());
subParcel.setUpNewColums();
subParcel.addData(subSearh.getOwnerData());
subParcel.customerT.addMouseListener(new table());
count = 0;
subSearh.setFoundParcel(false);
}
}
}
}
});
t.start();
subTimer = new Timer(950, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(directoryS.getFound1() && directoryS.getFound2() && directoryS.getFound3() && directoryS.getFound4())
{
subTimer.stop();
count2++;
if(count2 == 1)
{
if(tablelist3)
{
directorySearch.clearData();
directorySearch.addDirecData(directoryS.getMainData());
}else{
tablelist3 = true;
ticket.startProgressBar();
directorySearch = new tableList();
directorySearch.setTitle("Local Subdivisions");
directorySearch.setVisible(true);
directorySearch.addWindowListener(new closing());
directorySearch.setUpColumns();
directorySearch.addDirecData(directoryS.getMainData());
directorySearch.customerT.addMouseListener(new table());
ticket.stopProgressBar();
}
}
}
}
});
subTimer.start();
return;
}
else if(e.getSource() == ticket.save)
{
saveRecord();
}
else if(e.getSource() == ticket.delete)
{
ticket.startProgressBar();
deleteRecord();
ticket.stopProgressBar();
}
else if(e.getSource() == ticket.userF)
{
ticket.startProgressBar();
parcelsearch.searchPropertyOwner(ticket.list.get(ticket.position).getOfname(), ticket.list.get(ticket.position).getOlname());
count = 0;
t = new Timer(950, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(count == 10)
{
if(parcelsearch.getOwnerData().size() > 0)
{
parcelsearch.setFoundParcel(true);
count = 0;
}
}
else{
count++;
}
if(parcelsearch.getFoundParcel())
{
System.out.println("FOUnd data");
t.stop();
count++;
if(count == 1)
{
if(tablelist2)
{
ownerList.clearData();
ownerList.addData(parcelsearch.getOwnerData());
}else{
tablelist2 = true;
ownerList = new tableList();
ownerList.addWindowListener(new closing());
ownerList.setUpNewColums();
ownerList.addData(parcelsearch.getOwnerData());
ownerList.setVisible(true);
ownerList.customerT.addMouseListener(new table());
count = 0;
ticket.stopProgressBar();
parcelsearch.setFoundParcel(false);
}
}
}
}
});
t.start();
}
else if(e.getSource() == ticket.next)
{
ticket.startProgressBar();
if(ticket.position == ticket.list.size() - 1)
{
System.out.println("I ran once");
insertNextTicket();
ticket.stopProgressBar();
}
else{
//Update the ticket to the next level
System.out.println("I ran once again");
ticket.addPosition();
ticket.removeLayer();
//Refresh information....
ticket.refreshForm();
map.panTo(ticket.list.get(ticket.position).getGeometry());
}
ticket.stopProgressBar();
return;
}
else if(e.getSource() == ticket.previous)
{
//Try to go back in the tickets..
ticket.startProgressBar();
//First Check the current position..
if(ticket.getPosAndSize()[1] > 1 && ticket.getPosAndSize()[0] != 0)//if greater than zero subtract one to the current position.. and refresh form..
{
ticket.subTrackPosition();
ticket.removeLayer();
//Refresh information....
ticket.refreshForm();
//System.out.println("X and Y " + ticket.list.get(ticket.position).getLocation().toString());
map.panTo(ticket.list.get(ticket.position).getGeometry());
}else if(ticket.getPosAndSize()[0] == 0 && ticket.getPosAndSize()[1] > 1)
{
ticket.goToBegining();
ticket.removeLayer();
ticket.refreshForm();
map.panTo(ticket.list.get(ticket.position).getGeometry());
}
ticket.stopProgressBar();
return;
}
else if(e.getSource() == ticket.zoom)
{
map.panTo(ticket.list.get(ticket.position).getGeometry());
map.zoomTo(ticket.list.get(ticket.position).getGeometry());
}
}
}
//Class for shortcut keys listner
private class abClick extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ticket.next)
{
ticket.startProgressBar();
//System.out.println("I ran two");
//Before Insert check that you are the last record on the position..
if(ticket.position == ticket.list.size() - 1)
{
//then insert new ticket();
insertNextTicket();
ticket.stopProgressBar();
}
else{
//Update the ticket to the next level
ticket.addPosition();
ticket.layer.removeAll();
ticket.GraphicsId = ticket.layer.addGraphic(new Graphic(ticket.list.get(ticket.position).getGeometry(), ticket.list.get(ticket.position).getSymbol()));
//Refresh information....
ticket.refreshForm();
//System.out.println("X and Y " + ticket.list.get(ticket.position).getLocation().toString());
map.panTo(ticket.list.get(ticket.position).getGeometry());
ticket.stopProgressBar();
}
return;
}
else if(e.getSource() == ticket.zoom)
{
ticket.startProgressBar();
ticket.setMessage("Zooming in to Ticket");
map.panTo(ticket.list.get(ticket.position).getGeometry());
map.zoomTo(ticket.list.get(ticket.position).getGeometry());
ticket.stopProgressBar();
ticket.setMessage("");
}
else if(e.getSource() == ticket.save)
{
saveRecord();
}
else if(e.getSource() == ticket.delete)
{
ticket.startProgressBar();
deleteRecord();
ticket.stopProgressBar();
}
else if(e.getSource() == ticket.previous)
{
//Try to go back in the tickets..
ticket.startProgressBar();
//First Check the current position..
if(ticket.getPosAndSize()[1] > 1 && ticket.getPosAndSize()[0] != 0)//if greater than zero subtract one to the current position.. and refresh form..
{
ticket.subTrackPosition();
ticket.layer.removeAll();
//insert symbol..
ticket.GraphicsId = ticket.layer.addGraphic(new Graphic(ticket.list.get(ticket.position).getGeometry(), ticket.list.get(ticket.position).getSymbol()));
//Refresh information....
ticket.refreshForm();
//System.out.println("X and Y " + ticket.list.get(ticket.position).getLocation().toString());
map.panTo(ticket.list.get(ticket.position).getGeometry());
}else if(ticket.getPosAndSize()[0] == 0 && ticket.getPosAndSize()[1] > 1)
{
ticket.goToBegining();
ticket.layer.removeAll();
ticket.GraphicsId = ticket.layer.addGraphic(new Graphic(ticket.list.get(ticket.position).getGeometry(), ticket.list.get(ticket.position).getSymbol()));
ticket.refreshForm();
map.panTo(ticket.list.get(ticket.position).getGeometry());
}
ticket.stopProgressBar();
return;
}
}
}
class HintTextField extends JTextField implements FocusListener {
private final String hint;
private boolean showingHint;
public HintTextField(final String hint) {
super(hint);
this.hint = hint;
this.showingHint = true;
super.addFocusListener(this);
}
@Override
public void focusGained(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText("");
showingHint = false;
}
}
@Override
public void focusLost(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText(hint);
showingHint = true;
}
}
@Override
public String getText() {
return showingHint ? "" : super.getText();
}
}
public class MouseOverLay extends MapOverlay{
private JMap map;
private DecimalFormat decimalFormat = new DecimalFormat("##.#######");
public MouseOverLay(JMap map)
{
this.map = map;
}
@Override
public void onMouseMoved(MouseEvent event) {
try{
java.awt.Point p = event.getPoint();
com.esri.core.geometry.Point mapPoint = map.toMapPoint(p.x, p.y);
// mapPoint = (Point) GeometryEngine.project(mapPoint, map.getSpatialReference(), SpatialReference.create(4326));
// System.out.println("Map Coordinates: X = " + decimalFormat.format(mapPoint.getX())
//+ ", Y = " + decimalFormat.format(mapPoint.getY()));
if(moveOn)
{
getId = findId2();
moveNum++;
spartanLayer.updateGraphic(getId, map.toMapPoint(p.x, p.y));
if(ticketopen)
{
ticket.layer.updateGraphic(ticket.GraphicsId, map.toMapPoint(p.x, p.y));
//Update the ObjectData as well...
ticket.list.get(ticket.position).setGeometry(map.toMapPoint(p.x, p.y).copy());
}
if(moveNum == 30)
{
moveNum = 0;
Graphic [] update = {spartanLayer.getGraphic(getId)};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, update, null);
}
}
}finally{
super.onMouseMoved(event);
}
}
}
public void setUpFocus()
{
ticket.fname.addFocusListener(new focusList());
ticket.lname.addFocusListener(new focusList());
ticket.mainT.addFocusListener(new focusList());
ticket.alt1.addFocusListener(new focusList());
ticket.ofname.addFocusListener(new focusList());
ticket.olname.addFocusListener(new focusList());
ticket.subdivision.addFocusListener(new focusList());
ticket.block.addFocusListener(new focusList());
ticket.lotnum.addFocusListener(new focusList());
ticket.taxT.addFocusListener(new focusList());
ticket.propertyT.addFocusListener(new focusList());
ticket.streetT.addFocusListener(new focusList());
ticket.intersectionT.addFocusListener(new focusList());
ticket.description.addFocusListener(new focusList());
ticket.notes.addFocusListener(new focusList());
}
public class focusList implements FocusListener{
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) { //focusLost tickets
if(login.getRole().equalsIgnoreCase("addressing"))
{
int enter = 0;
if(e.getSource() == addressing.getJTextFieldFname())
{
//get information and submit to the server after focusLost...
System.out.println("I ran");
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("cfirst_name", addressing.getJTextFieldFname().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setFname(addressing.getJTextFieldFname().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldLname())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("clast_name", addressing.getJTextFieldLname().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setLname(addressing.getJTextFieldLname().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldMainT())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("telephone_land_line", addressing.getJTextFieldMainT().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setMainT(addressing.getJTextFieldMainT().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldAlt1())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("alt_telephone", addressing.getJTextFieldAlt1().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setAlt1(addressing.getJTextFieldAlt1().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldBlock())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("block_num", addressing.getJTextFieldBlock().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setBlock(addressing.getJTextFieldBlock().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldDescription())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("building_description", addressing.getJTextFieldDescription().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setBuild(addressing.getJTextFieldDescription().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldIntersection())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("intersection", addressing.getJTextFieldIntersection().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setInter(addressing.getJTextFieldIntersection().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldLot())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("lot_num", addressing.getJTextFieldLot().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setLot(addressing.getJTextFieldLot().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldNotes())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("comments", addressing.getJTextFieldNotes().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setNotes(addressing.getJTextFieldNotes().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldOfname())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("pfirst_name", addressing.getJTextFieldOfname().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setOfname(addressing.getJTextFieldOfname().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldOlname())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("plast_name", addressing.getJTextFieldOlname().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setOlname(addressing.getJTextFieldOlname().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldSubdivision())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("subdivision", addressing.getJTextFieldSubdivision().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setSub(addressing.getJTextFieldSubdivision().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldTaxT())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("tax_account_num", addressing.getJTextFieldTaxT().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setTax(addressing.getJTextFieldTaxT().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldProperty())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("property_id", addressing.getJTextFieldProperty().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setProp(addressing.getJTextFieldProperty().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
else if(e.getSource() == addressing.getJTextFieldStreetT())
{
enter = 1;
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("OBJECTID", Integer.parseInt(addressing.getId()));
attributes.put("street", addressing.getJTextFieldStreetT().getText().toUpperCase());
addressing.getData().get(addressing.getPosition()).setStreet(addressing.getJTextFieldStreetT().getText().toUpperCase());
Graphic up = new Graphic(addressing.getGeometry(),null, attributes);
Graphic [] updates = {up};
spartanLayer.applyEdits(new Graphic[]{}, new Graphic[]{}, updates, null);
}
if(enter == 1)
{
return;
}
}
if(ticketopen)
{
if(e.getSource() == ticket.fname)
ticket.list.get(ticket.position).setFname(ticket.fname.getText().toUpperCase());
else if(e.getSource() == ticket.lname)
ticket.list.get(ticket.position).setLname(ticket.lname.getText().toUpperCase());
else if(e.getSource() == ticket.mainT)
{
ticket.list.get(ticket.position).setMainT(ticket.mainT.getText().toUpperCase());
if(ticket.mainT.getText().replace(" ", "").length() > 3)
{
ticketS.searchTelephone(ticket.mainT.getText());
count = 0;
t = new Timer(800, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ticketS.getFoundTicket())
{
t.stop();
count++;
if(count == 1)
{
if(tablelist)
{
list.addNewList(ticketS.getListInfo());
}else
{
tablelist = true;
list = new tableList();
list.setList(ticketS.getListInfo());
list.setVisible(true);
list.setFocusable(true);
ticketS.setFoundTicket(false);
list.customerT.addMouseListener(new table());
list.addWindowListener(new closing());
System.out.println("I ran from maint");
}
}
}
}
});
t.start();
}
}
else if(e.getSource() == ticket.alt1)
{
ticket.list.get(ticket.position).setAlt1(ticket.alt1.getText().toUpperCase());
if( ticket.alt1.getText().replace(" ", "").length() > 3)
{
count = 0;
ticketS.searchTelephone(ticket.alt1.getText());
t = new Timer(800, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ticketS.getFoundTicket())
{
t.stop();
count++;
if(count == 1)
{
if(tablelist)
{
list.addNewList(ticketS.getListInfo());
}else{
tablelist = true;
list = new tableList();
list.setList(ticketS.getListInfo());
list.setVisible(true);
list.setFocusable(true);
list.customerT.addMouseListener(new table());
list.addWindowListener(new closing());
}
}
}
}
});
t.start();
}
}
else if(e.getSource() == ticket.ofname)
ticket.list.get(ticket.position).setOfname(ticket.ofname.getText().toUpperCase());
else if(e.getSource() == ticket.olname)
ticket.list.get(ticket.position).setOlname(ticket.olname.getText().toUpperCase());
else if(e.getSource() == ticket.subdivision)
ticket.list.get(ticket.position).setSub(ticket.subdivision.getText().toUpperCase());
else if(e.getSource() == ticket.block)
ticket.list.get(ticket.position).setBlock(ticket.block.getText());
else if(e.getSource() == ticket.lotnum)
ticket.list.get(ticket.position).setLot(ticket.lotnum.getText());
else if(e.getSource() == ticket.taxT)
{
ticket.startProgressBar();
ticket.list.get(ticket.position).setTax(ticket.taxT.getText().toUpperCase());
ticket.runTaxQuery();
t = new Timer(800, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ticket.list.get(ticket.position).getFound())
{
System.out.println("I ran action performed found geometry");
t.stop();
map.panTo(ticket.list.get(ticket.position).getGeometry());
map.zoomTo(ticket.list.get(ticket.position).getGeometry());
}
}
});
t.start();
}
else if(e.getSource() == ticket.propertyT)
{
ticket.list.get(ticket.position).setProp(ticket.propertyT.getText().toUpperCase());
ticket.runPropQuery();
t = new Timer(800, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ticket.list.get(ticket.position).getFound())
{
t.stop();
map.zoomTo(ticket.list.get(ticket.position).getGeometry());
}
}
});
t.start();
}
else if(e.getSource() == ticket.streetT)
{
ticket.list.get(ticket.position).setStreet(ticket.streetT.getText().toUpperCase());
if(!ticket.intersectionT.getText().trim().equals("") && !ticket.list.get(ticket.position).getFound())
{
System.out.println("I ran starting to geocode");
geocodeS.setMessage("Intersection Search");
geocodeS.search10Stuff(ticket.streetT.getText() + " & " + ticket.intersectionT.getText());
t = new Timer(500, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(geocodeS.getReady())
{
t.stop();
getId = findId();
spartanLayer.updateGraphic(getId, geocodeS.getResult().getLocation());
ticket.layer.updateGraphic(ticket.GraphicsId, geocodeS.getResult().getLocation());
changeLocation(geocodeS.getResult().getLocation());
}
}
});
t.start();
}
}
else if(e.getSource() == ticket.intersectionT)
{
ticket.list.get(ticket.position).setInter(ticket.intersectionT.getText().toUpperCase());
if(!ticket.streetT.getText().trim().equals("") && !ticket.list.get(ticket.position).getFound())
{
System.out.println("I ran starting to geocode");
geocodeS.setMessage("Intersection Search");
geocodeS.search10Stuff(ticket.streetT.getText() + " & " + ticket.intersectionT.getText());
t = new Timer(500, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(geocodeS.getReady())
{
t.stop();
getId = findId();
spartanLayer.updateGraphic(getId, geocodeS.getResult().getLocation());
ticket.layer.updateGraphic(ticket.GraphicsId, geocodeS.getResult().getLocation());
changeLocation(geocodeS.getResult().getLocation());
}
}
});
t.start();
}
}
else if(e.getSource() == ticket.description)
ticket.list.get(ticket.position).setBuild(ticket.description.getText().toUpperCase());
else if(e.getSource() == ticket.notes)
{
ticket.list.get(ticket.position).setNotes(ticket.notes.getText().toUpperCase());
}
}
}
}
//Create a mouse adapter for the tableList...
public class table extends MouseAdapter{ //JTABLE CLICKS
public void mouseClicked(MouseEvent e)
{
if(login.getRole().equalsIgnoreCase("addressing"))
{
if(e.getSource() == addressing.getJtableMain())
{
addressing.setPosition(addressing.getJtableMain().getSelectedRow());
addressing.setMessageText();
addressing.updateId();
zoomToCreateBuffer();
return;
}
else if(e.getSource() == addressing.getJtableRelated())
{
//Diferent process this zooms in to that particular square...
if(e.getClickCount() == 1)
{
map.zoomTo(addressing.getRelatedGeometry(addressing.getTableRelatedRow()));
//Select the currect square...
//clear first then select..
temporary.clearSelection();
temporary.setSelectionColor(Color.yellow);
temporary.select(addressing.getIdGraphicRelated(addressing.getTableRelatedRow()));
return;
}
}
else if(e.getSource() == addressing.getJtableAttachment())
{
if(e.getButton() == java.awt.event.MouseEvent.BUTTON3)
{
dbConnect con = new dbConnect();
if(con.deleteAttachment(addressing.getJtableAttachment().getValueAt(addressing.getJtableAttachment().getSelectedRow(), 0).toString()) > 0)
{
addressing.getAttachModel().removeRow(addressing.getJtableAttachment().getSelectedRow());
JOptionPane.showMessageDialog(null, "Attachment deleted");
}else{
JOptionPane.showMessageDialog(null, "Sorry, couldn't delete your attachment?");
}
return;
}
else if(e.getClickCount() > 1){
try{
ProcessFiles open = new ProcessFiles();
//this.startProgressBar();
if(new File("d:/").exists())
if(!new File("d:/download").exists())
{
new File("d:/download").mkdir();
try{
dbConnect con = new dbConnect();
ProcessFiles data = con.getBlobInfo(addressing.getJtableAttachment().getValueAt(addressing.getJtableAttachment().getSelectedRow(), 0).toString());
//Here is oging to create the file...
if(!new File("d:/download/"+ data.getName()).exists())
{
File f = new File("d:/download/"+ data.getName());
data.writeByteArraysToFile("d:/download/" + data.getName(), data.decodeBase64(data.getBase64(), data.getName()));
data.openFile(f);
}
else{
new File("d:/download/"+data.getName()).delete();
File f = new File("d:/download/"+ data.getName());
data.writeByteArraysToFile("d:/download/" + data.getName(), data.decodeBase64(data.getBase64(), data.getName()));
data.openFile(f);
}
}catch(Exception error)
{
JOptionPane.showMessageDialog(null, error);
}
}
else{
//check if the download file exists in that particular locaiton...
try{
dbConnect con = new dbConnect();
ProcessFiles data = con.getBlobInfo(addressing.getJtableAttachment().getValueAt(addressing.getJtableAttachment().getSelectedRow(), 0).toString());
//Here is oging to create the file...
if(!new File("d:/download/"+ data.getName()).exists())
{
File f = new File("d:/download/"+ data.getName());
data.writeByteArraysToFile("d:/download/" + data.getName(), data.decodeBase64(data.getBase64(), data.getName()));
data.openFile(f);
}
else{
new File("d:/download/"+data.getName()).delete();
File f = new File("d:/download/"+ data.getName());
data.writeByteArraysToFile("d:/download/" + data.getName(), data.decodeBase64(data.getBase64(), data.getName()));
data.openFile(f);
}
}catch(Exception error)
{
JOptionPane.showMessageDialog(null, error);
}
}
else{
//Move to c drive//
}
}catch(Exception t)
{
}
}
return;
}
else if(e.getSource() == addressing.getJtableSubdivision())
{
if(e.getClickCount() > 1)
{
try{
ProcessFiles open = new ProcessFiles();
open.openFile(new File(addressing.getJtableSubdivision().getValueAt(addressing.getJtableSubdivision().getSelectedRow(), 0).toString()));
}catch(Exception t)
{
}
}
}
else if(e.getSource() == addressing.getJtablePictures())
{
try{
ProcessFiles open = new ProcessFiles();
ProcessFiles data = new ProcessFiles();
data.openFile(new File(addressing.getJtablePictures().getValueAt(addressing.getJtablePictures().getSelectedRow(), 0).toString()));
}catch(Exception t)
{
}
}
}
if(tablelist2)
{
if(e.getSource() == ownerList.customerT)
{
if(e.getClickCount() > 1)
{
SimpleLineSymbol outline = new SimpleLineSymbol(Color.BLACK, 3, SimpleLineSymbol.Style.SOLID);
SimpleFillSymbol symbol = new SimpleFillSymbol(new Color(160, 32, 240, 50), outline);
temporary.removeAll();
map.panTo(ownerList.getGeometry2(ownerList.customerT.getSelectedRow()));
map.zoomTo(ownerList.getGeometry2(ownerList.customerT.getSelectedRow()));
temporary.addGraphic(new Graphic(ownerList.getGeometry2(ownerList.customerT.getSelectedRow()),
symbol));
}
}
}
if(tablelist4)
{
if(e.getSource() == subParcel.customerT)
{
if(e.getClickCount() > 1)
{
SimpleLineSymbol outline = new SimpleLineSymbol(Color.BLACK, 3, SimpleLineSymbol.Style.SOLID);
SimpleFillSymbol symbol = new SimpleFillSymbol(new Color(160, 32, 240, 50), outline);
temporary.removeAll();
map.panTo(subParcel.getGeometry2(subParcel.customerT.getSelectedRow()));
map.zoomTo(subParcel.getGeometry2(subParcel.customerT.getSelectedRow()));
temporary.addGraphic(new Graphic(subParcel.getGeometry2(subParcel.customerT.getSelectedRow()),
symbol));
}
}
}
if(tablelist)
{
if(e.getSource() == list.customerT){
if(e.getClickCount() > 1)
{
System.out.println("I ran table ");
System.out.println("SELECTED ROW " + list.customerT.getSelectedRow());
map.panTo(list.getGeometry(list.customerT.getSelectedRow()));
map.zoomTo(list.getGeometry(list.customerT.getSelectedRow()));
}
}
}
if(tablelist3)
{
if(e.getSource() == directorySearch.customerT){
if(e.getClickCount() > 1)
{
System.out.println("I ran table ");
System.out.println("SELECTED ROW " + directorySearch.customerT.getSelectedRow());
try{
ProcessFiles data = new ProcessFiles();
data.openFile(new File(directorySearch.getPath(directorySearch.customerT.getSelectedRow())));
}catch(Exception t)
{
}
}
}
}
}
}
public class closing extends WindowAdapter
{
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
if(e.getSource() == ownerList)
{
tablelist2 = false;
}
else if(e.getSource() == subParcel)
{
tablelist4 = false;
}
else if(e.getSource() == list)
{
tablelist = false;
}
else if(e.getSource() == directorySearch)
{
tablelist3 = false;
}
}
}
}
|
package old.Data20180424;
public class MutiplyStrings {
public static void main(String[] args){
System.out.print(new MutiplyStrings().multiply("91", "9"));
}
public String multiply(String num1, String num2){
if(num1.equals("0") || num2.equals("0"))
return "0";
int[] res = new int[num1.length() + num2.length()];
for(int i = 0; i < num1.length(); i++){
for(int j = 0;j < num2.length(); j++){
res[1 + i + j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
}
}
//从低到高依次进位
int carryIn = 0;
for(int i = res.length - 1; i >= 0; i--){
res[i] += carryIn;
carryIn = res[i] / 10;
res[i] %= 10;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < res.length; i++){
if(i == 0 && res[i] == 0)
continue;
sb.append(res[i]);
}
return sb.toString();
}
}
|
package coordinate;
public class Controller {
public static Move getMove(Coordinate rightHand, Coordinate leftHand) {
Coordinate average = Coordinate.getAverage(rightHand, leftHand);
//Coordinate average = rightHand;
int x = Math.round(average.getX() * 10);
int y = -Math.round(average.getY() * 10);
float z = average.getZ();
int zoomAmount;
int zoomMin = 2, zoomMax = 3;
if (z < zoomMin) {
z -= zoomMin;
z = Math.abs(z);
zoomAmount = -Math.round(z * 5);
} else if (z > zoomMax) {
z -= zoomMax;
z = Math.abs(z);
zoomAmount = Math.round(z * 5);
} else {
zoomAmount = 0;
}
return new Move(x, y, zoomAmount);
//int radius = Math.round((Coordinate.Z_MAX - average.getZ()) * 30);
// return new Circle(
// x, y, radius,
// Coordinate.isWithBound(rightHand, leftHand) ? Color.GREEN : Color.RED);
}
}
|
package by.client.android.railwayapp.ui.page.scoreboard;
import java.util.Map;
import by.client.android.railwayapp.api.ScoreboardStation;
import by.client.android.railwayapp.support.common.MapBuilder;
/**
* Класс конвертер для преобразования типа {@link ScoreboardStation} в название станции
*
* @author ROMAN PANTELEEV
*/
class StationToNameConverter {
private static final Map<ScoreboardStation, String> STATION_STRING_MAP = new MapBuilder<ScoreboardStation, String>()
.put(ScoreboardStation.MINSK, "Минск-Пассажирский")
.put(ScoreboardStation.ORSHA, "Орша-Центральная")
.put(ScoreboardStation.BREST, "Брест-Центральный")
.build();
String convert(ScoreboardStation scoreboardStation) {
return STATION_STRING_MAP.get(scoreboardStation);
}
}
|
/*
Copyright 2006 thor.jini.org Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Created on 16-Dec-2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.jini.projects.thor.configuration;
import net.jini.config.Configuration;
/**
* Provides a way to hook into the Dynamic configuration and be notified when changes occur.
* <code>notify(...)</code> will only be called if <code>getFilter().accept()</code> returns true.
* This allows the creation of notification threads to be done only where the interested party actaully wants
* to know about this particular event.
* @author Calum
*
*/
public interface DynamicConfigurationListener {
/**
* Inform the listener that a change has occured, providing the event indicating the change
* and the new <code>Configuration</code> instance that includes that change
*/
public void notify(Configuration config, ConfigurationChangeEvent evt);
}
|
package RSA算法;
public class sec {
public static void main(String[] args) {
int m=3;
int e=7,d=3,n=20;
double ensec=Math.pow((double) m,(double) e)%n;
System.out.println("ensec="+ensec);
double desec=Math.pow(ensec,(double) d)%n;
System.out.println("desec="+desec);
}
}
|
/* TemporaryExecution.java
Purpose:
Description:
History:
Thu Nov 6 18:38:54 2008, Created by tomyeh
Copyright (C) 2008 Potix Corporation. All Rights Reserved.
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.zkoss.zk.ui.http;
import java.util.Map;
import java.io.Writer;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.sys.ExecutionsCtrl;
/**
* A donut execution that is a temporary execution for creating a page
* or a desktop. It is not a real execution so any update to it are ignored.
*
* @author tomyeh
*/
/*package*/ class TemporaryExecution extends ExecutionImpl {
/** Constructor.
*/
/*package*/ TemporaryExecution(ServletContext ctx, HttpServletRequest request,
HttpServletResponse response, Desktop desktop) {
super(ctx, request, response, desktop, null);
}
public void sendRedirect(String uri) { //getUiEngine not ready yet
try {
((HttpServletResponse)getNativeResponse()).sendRedirect(
uri != null ? uri: "");
setVoided(true);
} catch (IOException ex) {
throw new UiException(ex);
}
}
public void sendRedirect(String uri, String target) {
sendRedirect(uri); //target is ignored (not supported)
}
public void forward(Writer out, String page, Map params, int mode)
throws IOException {
final Execution exec = ExecutionsCtrl.getCurrent();
ExecutionsCtrl.setCurrent(null);
//It is fake one and shall not be re-used by forward
try {
super.forward(out, page, params, mode);
} finally {
ExecutionsCtrl.setCurrent(exec);
}
}
public void include(Writer out, String page, Map params, int mode)
throws IOException {
throw new IllegalStateException("include not allowd in DesktopInit");
}
}
|
package com.darwinsys.testingwithmockito;
public class WorkerBee {
WorkerHelper helper;
void setHelper(WorkerHelper helper) {
this.helper = helper;
}
void process() {
helper.invoke();
}
}
|
package com.example.devansh.inclass09;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
public class Contacts extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseDatabase database;
DatabaseReference myRef;
ArrayList<Contact> contacts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
setTitle("Contacts");
contacts = new ArrayList<Contact>();
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
database = FirebaseDatabase.getInstance();
myRef = database.getReference(user.getUid()).child("Contacts");
findViewById(R.id.btnLogOut).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAuth.signOut();
finish();
}
});
findViewById(R.id.btnCreateNew).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(Contacts.this, "Create New Contact is clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Contacts.this, CreateContact.class);
startActivity(intent);
finish();
}
});
myRef.addChildEventListener(new ChildEventListener() {
String TAG = "test-ChildListener";
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
contacts.add(getContact(dataSnapshot));
generateView();
}
// Can we ignore this method, since user cannot edit contact?
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
/*
String key = dataSnapshot.getKey();
int i = contacts.indexOf(dataSnapshot.getValue());
Log.d(TAG, "index: " + i);
contacts.remove(i);
Log.d(TAG, "size: " + contacts.size());
*/
generateView();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
private Contact getContact(DataSnapshot dataSnapshot){
Contact c = new Contact();
c.dept = "" + dataSnapshot.child("dept").getValue();
c.email = "" + dataSnapshot.child("email").getValue();
c.name = "" + dataSnapshot.child("name").getValue();
c.phone = "" + dataSnapshot.child("phone").getValue();
c.image = Integer.parseInt("" + dataSnapshot.child("image").getValue()); // uhhhh
c.uid = "" + dataSnapshot.getKey();
//Log.d(TAG, "Dept is " + dataSnapshot.child("dept").getValue());
Log.d(TAG, "getContact: ADDED CONTACT" + c);
return c;
}
});
//generateView(); // ---------------------------------------------------------------------------- moved this
}
public void generateView(){
Log.d("test", "Database Receiver : " + myRef.toString());
ListView listView = (ListView)findViewById(R.id.listViewContacts);
ContactsAdapter adapter = new ContactsAdapter(Contacts.this, R.layout.contact_item, contacts);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("test", "Long item click! " + i);
String key = contacts.get(i).uid;
myRef.child(key).removeValue();
contacts.remove(i); // hehe. Doing this instead of onChildRemoved() method
return false;
}
});
}
}
|
import java.awt.Point;
import Entry.Validity;
import Enum.EnumClass.PieceColor;
import Enum.EnumClass.PieceType;
public class Test {
public static void main(String[] args) {
Board board = new Board();
board.setPiece('8', 'a', PieceColor.Black, PieceType.Rook, null, false);
board.setPiece('8', 'c', PieceColor.Black, PieceType.Bishop, null, false);
board.setPiece('8', 'd', PieceColor.Black, PieceType.Queen, null, false);
board.setPiece('8', 'e', PieceColor.Black, PieceType.King, null, false);
board.setPiece('8', 'h', PieceColor.Black, PieceType.Rook, null, false);
board.setPiece('7', 'b', PieceColor.Black, PieceType.Pawn, null, false);
board.setPiece('6', 'e', PieceColor.Black, PieceType.Rook, null, true);
board.setPiece('3', 'c', PieceColor.Black, PieceType.Knight, null, true);
board.setPiece('3', 'd', PieceColor.Black, PieceType.Pawn, null, true);
board.setPiece('3', 'f', PieceColor.Black, PieceType.Knight, null, true);
board.setPiece('2', 'd', PieceColor.White, PieceType.Pawn, null, false);
board.setPiece('2', 'e', PieceColor.White, PieceType.Pawn, null, false);
board.setPiece('1', 'a', PieceColor.White, PieceType.Rook, null, false);
board.setPiece('1', 'e', PieceColor.White, PieceType.King, null, false);
//board.setPiece('1', 'f', PieceColor.White, PieceType.Bishop, null, false);
board.setPiece('1', 'h', PieceColor.White, PieceType.Rook, null, false);
Point from = null;
Point to = null;
Validity validate = null;
//change Black turn
board.setTurn(PieceColor.Black);
//1.black N : true->
from = new Point(2,2); //Point(x,y)
to = new Point(1,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//2.black N : false->Knight can only move in a 2,1 or 1,2 'L' shape
from = new Point(2,2);
to = new Point(1,1);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//change white turn
board.setTurn(PieceColor.White);
//3. false->Not your turn
to = new Point(3,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//4. false->Move puts or keeps your king in check Black:5,2->4,0 king
from = new Point(4,1);
to = new Point(3,2);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//5. the(4,1) take (5,2) so king not check true-> Black:5,2->4,0 king
from = new Point(4,1);
to = new Point(5,2);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//6.Black:3,2->3,0 (king check Black:2,2->3,0)false->Move puts or keeps your king in check
from = new Point(4,0);
to = new Point(3,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//7.king castle :4,0->2,0 false : Black:1,2->2,0
from = new Point(4,0);
to = new Point(2,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//8.king castle :4,0->2,0 false : Black:1,2->2,0
from = new Point(4,0);
to = new Point(6,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//test 90 and 45
//9.
board.setTurn(PieceColor.Black);
from = new Point(2,7);
to = new Point(5,4);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//10.
board.setTurn(PieceColor.Black);
from = new Point(2,7);
to = new Point(0,5);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//11.
board.setTurn(PieceColor.Black);
from = new Point(7,7);
to = new Point(7,0);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//12.
from = new Point(1,6);
to = new Point(1,4);
validate = board.ValidateMove(from, to);
System.out.println(validate.valid+"->"+validate.reason);
//Test for Queen Piece Here:
//13. Test for Queen Move check validation.
from = new Point(3,7);
to = new Point(5,6);
validate = board.ValidateMove(from,to);
System.out.println(validate.valid+"Black_Queen Move->"+validate.reason);
//14. Test for Queen Move check validation. if vertically track has any obstacle, it's non-valid
from = new Point(3,7);
to = new Point(3,1);
validate = board.ValidateMove(from,to);
System.out.println(validate.valid+"Black_Queen Move->"+validate.reason);
//change white turn
board.setTurn(PieceColor.White);
//15. test for Rook Move Validation. if move diagonally, it's not valid.
from = new Point(7,0);
to = new Point(6,1);
validate = board.ValidateMove(from,to);
System.out.println(validate.valid+" White_Rook Move->"+validate.reason);
}
}
|
class Node {
int data;
Node left;
Node right;
Node(int d) {
data = d;
left = null;
right = null;
}
}
public class PrintAllAncessatorNode {
Node root;
//Print all ancessator of a node
public boolean printAncessator(Node node, Node target) {
if(node == null) {
return false;
}
if(node.data == target.data) {
return true;
}
if(printAncessator(node.left, target) || printAncessator(node.right, target)) {
System.out.print(node.data);
return true;
}
return false;
}
//main method
public static void main(String args[]) {
PrintAllAncessatorNode tree = new PrintAllAncessatorNode();
tree.root = new Node(5);
tree.root.left = new Node(6);
tree.root.right = new Node(7);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(3);
tree.root.right.left = new Node(2);
tree.root.right.right = new Node(1);
boolean isAncessator = tree.printAncessator(tree.root, tree.root.right.right);
System.out.print(isAncessator);
}
} |
package com.cpro.rxjavaretrofit.views.adapter;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cpro.rxjavaretrofit.R;
import com.cpro.rxjavaretrofit.entity.LinkLabelListEntity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by lx on 2016/5/27.
*/
public class HomeworkSupervisionLabelsAdapter extends RecyclerView.Adapter {
List<LinkLabelListEntity> list;
List<Integer> alreadyClickLabelList;
public void setList(List<LinkLabelListEntity> list, List<Integer> alreadyClickLabelList){
this.list = list;
this.alreadyClickLabelList = alreadyClickLabelList;
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_homework_supervision_labels, parent, false);
return new LabelsViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final LabelsViewHolder labelsViewHolder = (LabelsViewHolder) holder;
if(alreadyClickLabelList != null && alreadyClickLabelList.size() >0){
for (Integer integer : alreadyClickLabelList) {
if(integer == list.get(position).getLabelId()){
if(list.get(position).getEchoCount() > 0){
labelsViewHolder.tv_label_name.setText(list.get(position).getLabelName() + "(" + list.get(position).getEchoCount() + ")");
labelsViewHolder.echoCount = list.get(position).getEchoCount();
labelsViewHolder.cv_hw_su_label.setBackgroundColor(Color.GRAY);
labelsViewHolder.labelId = list.get(position).getLabelId();
}
}else{
if(list.get(position).getEchoCount() > 0){
labelsViewHolder.tv_label_name.setText(list.get(position).getLabelName() + "(" + list.get(position).getEchoCount() + ")");
labelsViewHolder.echoCount = list.get(position).getEchoCount();
labelsViewHolder.labelId = list.get(position).getLabelId();
}else{
labelsViewHolder.tv_label_name.setText(list.get(position).getLabelName());
labelsViewHolder.echoCount = list.get(position).getEchoCount();
labelsViewHolder.labelId = list.get(position).getLabelId();
}
}
}
}else{
if(list.get(position).getEchoCount() > 0){
labelsViewHolder.tv_label_name.setText(list.get(position).getLabelName() + "(" + list.get(position).getEchoCount() + ")");
labelsViewHolder.echoCount = list.get(position).getEchoCount();
labelsViewHolder.labelId = list.get(position).getLabelId();
}else{
labelsViewHolder.tv_label_name.setText(list.get(position).getLabelName());
labelsViewHolder.echoCount = list.get(position).getEchoCount();
labelsViewHolder.labelId = list.get(position).getLabelId();
}
}
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
public static class LabelsViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.tv_label_name)
public TextView tv_label_name;
@BindView(R.id.cv_hw_su_label)
public CardView cv_hw_su_label;
public int echoCount;
public int labelId;
public LabelsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
|
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
/**
* Created by Shin on 2017-05-26.
*/
public class Schedule implements Loggable {
private MessageLogger logger;
private Date currentDay;
private int dayCounter;
private String[] gamePlan;
private int myTeam;
private Team[] teams;
private Event[] events;
// Singleton Object Initializer
private static Schedule instance;
private Schedule(Team[] teams, int myTeam, Event[] events,String[] gamePlan) {
this.currentDay = new Date();
this.dayCounter = 0;
this.myTeam = myTeam;
this.teams = teams;
this.gamePlan = gamePlan;
this.events = events;
}
public static Schedule getInstance(Team[] teams, int myTeam, Event[] events, String[] gamePlan) {
if(instance == null) {
instance = new Schedule(teams, myTeam, events, gamePlan);
}
return instance;
}
public boolean proceedDay() {
if(this.isGameOver()) return false; // 정해진 날 이상이 되면 종료
this.sendMessage("Date : " + this.getStringDatefromToday(0));
// 해당 날짜에 게임이 예정되어 있다면 게임 진행
if(!this.gamePlan[this.dayCounter].equals("No")) this.doGame();
// 이벤트 발생 (없을 수도 있음)
this.eventOccur();
// if(!this.teams[this.myTeam].isAllPlayerAvailable()) this.teams[this.myTeam].setAllBenchAvailable();
// + 하루
this.dayGoes();
// 1일이면 월급 지급
this.payday();
return true;
}
public boolean isGameOver() {
if(this.dayCounter >= this.gamePlan.length || this.teams[myTeam].getCapital() < 0) {
this.sendMessage("Game over.");
return true;
} else {
return false;
}
}
public void doGame() {
int[] excludes = new int[this.teams.length];
excludes[this.myTeam] = 1;
int chosen = RandomGenerator.getRangedRandomInt(0, this.teams.length - 1);
Team awayTeam = this.teams[chosen == this.myTeam ? (chosen + 1) % this.teams.length : chosen];
Game game = new Game(this.gamePlan[this.dayCounter], this.teams[this.myTeam], awayTeam);
if(this.logger != null) game.setLogger(this.logger);
this.sendMessage("Today, have a game with team " + awayTeam.getName() + " (" + this.gamePlan[this.dayCounter] + " Game)");
this.sendMessage("Press Enter to start the game");
try {
System.in.read();
} catch(Exception e) {;}
game.proceedGame();
}
public void eventOccur() {
int[] chosen = RandomGenerator.chooseMultipleChoice(this.events.length,
(int)RandomGenerator.getRangedRandomInt(0, 3), new int[this.events.length]);
this.sendMessage("===================Events===================");
for(int i : chosen) {
Event event = this.events[i];
Team myTeam = this.teams[this.myTeam];
if(this.logger != null) event.setLogger(this.logger);
if(event.getEffectOnPlayer() == null) { //team event
this.sendMessage("Event occured : " + event.getContent());
event.affect(myTeam, null);
} else { // player event
Player player = myTeam.getPlayers().get(RandomGenerator.getRangedRandomInt(0, myTeam.getPlayers().size() - 1));
this.sendMessage("Event occured : " + player.getName() + event.getContent() +
" (" + player.getName() + " : Healthiness " + event.getEffectOnPlayer().getEffectOnHealthiness() + " / " +
"Psychological " + event.getEffectOnPlayer().getEffectOnPsychological() + ")");
event.affect(myTeam, player);
}
}
this.sendMessage("=============================================");
}
public void dayGoes() {
Calendar c = Calendar.getInstance();
c.setTime(this.currentDay);
c.add(Calendar.DATE, 1);
this.currentDay = c.getTime();
this.dayCounter++;
}
public void payday() {
Calendar c = Calendar.getInstance();
c.setTime(this.currentDay);
if(c.get(Calendar.DAY_OF_MONTH) == 1) {
this.sendMessage("Today is payday. All of staffs and players are paid." + " Balance : $" + String.valueOf(this.teams[myTeam].getCapital()));
Team myTeam = this.teams[this.myTeam];
myTeam.payout(myTeam.getDirector().getSalary());
for(Unit unit : myTeam.getPlayers()) {
myTeam.payout(unit.getSalary());
}
for(Unit unit : myTeam.getStaffs()) {
myTeam.payout(unit.getSalary());
}
}
}
public String getStringDatefromToday(int offset) {
Calendar c = Calendar.getInstance();
c.setTime(this.currentDay);
c.add(Calendar.DATE, offset);
Date t = c.getTime();
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd");
return transFormat.format(t);
}
@Override
public void setLogger(Object o) {
if(o instanceof MessageLogger) {
this.logger = (MessageLogger) o;
}
}
@Override
public void sendMessage(String msg) {
this.logger.addMessage(msg);
}
}
|
/*
* Model loginu, wykonuje pracę związaną z logowaniem i rejestracją
* Ta klasa zawiera implementację czynności jakie użyszkodnik może wykonać
* poprzez uporczywe klikanie przed zalogowaniem się, przy czym
* akcje dotyczące bazy są wykonywane przez LoginRole.
*/
package states;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Vector;
import java.sql.ResultSet;
import utils.StringUtils;
import database.Constants;
import database.LoginRole;
import objects.Account;
public class Login {
Login() {
try {
//pozyskujemy uprawnienia
role = new LoginRole();
}
catch (Exception ex) {
Logger lgr = Logger.getLogger(Login.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
public boolean login(String login, String password) {
try {
String hashedPwd = StringUtils.hash(password);
//zwraca krotki, które mają taki login i hasło (0 albo 1)
ResultSet rs = role.Account_authenticate(login, hashedPwd);
Vector<Account> queryResult = Account.converter.convert(rs);
StateManager.State newState = null;
String accountType = null;
if( queryResult.isEmpty() )
return StateManager.transition(StateManager.State.invalid);
else
accountType = queryResult.get(0).typ_konta;
//jeżeli nie znaleziono krotki to logowanie nie powiodło się,
//wpp aplikacja przechodzi w odpowiedni stan
//(stan invalid to sztuczny stan, który nie powoduje żadnej akcji)
if( accountType.equals(Constants.ROLE.user.toString()) ) {
newState = StateManager.State.user;
} else if( accountType.equals(Constants.ROLE.owner.toString()) ) {
newState = StateManager.State.owner;
} else if( accountType.equals(Constants.ROLE.admin.toString()) ) {
newState = StateManager.State.admin;
} else if( accountType.equals(Constants.ROLE.login.toString()) ) {
newState = StateManager.State.login;
} else {
newState = StateManager.State.invalid;
}
boolean result = StateManager.transition(newState);
if(result == true)
StateManager.setUserId(login);
return result;
}
catch (Exception ex) {
Logger lgr = Logger.getLogger(Login.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
public boolean register(String login, String password, String accountType) {
try {
ResultSet rs = role.Account_exists(login);
Vector<Account> queryResult = Account.converter.convert(rs);
if( queryResult.isEmpty() ) {
String hashedPwd = StringUtils.hash(password);
Account account = new Account(login, hashedPwd, accountType);
return role.Account_insert(account) != 0;
} else
return false;
}
catch (Exception ex) {
Logger lgr = Logger.getLogger(Login.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
private LoginRole role;
} |
package ffm.slc.model.enums;
/**
* The evidence presented to verify one's personal identity; for example: drivers license, passport, birth certificate, etc.
*/
public enum PersonalInformationVerificationType {
BAPTISMAL_OR_CHURCH_CERTIFICATE("Baptismal or church certificate"),
BIRTH_CERTIFICATE("Birth certificate"),
DRIVERS_LICENSE("Drivers license"),
ENTRY_IN_FAMILY_BIBLE("Entry in family Bible"),
HOSPITAL_CERTIFICATE("Hospital certificate"),
IMMIGRATION_DOCUMENT_VISA("Immigration document/visa"),
LIFE_INSURANCE_POLICY("Life insurance policy"),
OTHER("Other"),
OTHER_NON_OFFICIAL_DOCUMENT("Other non-official document"),
OTHER_OFFICIAL_DOCUMENT("Other official document"),
PARENTS_AFFIDAVIT("Parents affidavit"),
PASSPORT("Passport"),
PHYSICIANS_CERTIFICATE("Physicians certificate"),
PREVIOUSLY_VERIFIED_SCHOOL_RECORDS("Previously verified school records"),
STATE_ISSUED_ID("State-issued ID");
private String prettyName;
PersonalInformationVerificationType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
package com.example.demo.filter;
import com.example.demo.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
/**
* AuthFilterRegistrationBean
* FilterRegistrationBean本身不是Filter,它实际上是Filter的工厂。Spring Boot会调用getFilter(),把返回的Filter注册到Servlet容器中。
* 因为我们可以在FilterRegistrationBean中注入需要的资源,然后,在返回的AuthFilter中,这个内部类可以引用外部类的所有字段,自然也包括注入的UserService,
* 整个过程完全基于Spring的IoC容器完成
* 标记了一个@Order(10),因为Spring Boot支持给多个Filter排序,数字小的在前面,所以,多个Filter的顺序是可以固定的
*
* @author ZhangJP
* @date 2021/5/20
*/
@Order(10)
//@Component
@Slf4j
public class AuthFilterRegistrationBean extends FilterRegistrationBean<Filter> {
@Autowired
UserServiceImpl userService;
@Override
public Filter getFilter() {
return new AuthFilter();
}
class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("AuthFilter doFilter...");
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
|
/*
* Copyright 2004-5 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
import java.io.FileInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.FileReader;
import javax.xml.stream.*;
import static javax.xml.stream.XMLStreamConstants.*;
import contact.Contact;
/*
* Use is subject to the license terms.
*/
/**
*
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class Main {
public static void main(String[] args) throws Exception {
String nameToLookFor = args[0];
JAXBContext jaxbContext = JAXBContext.newInstance("contact");
Unmarshaller um = jaxbContext.createUnmarshaller();
// set up a parser
XMLInputFactory xmlif = XMLInputFactory.newInstance();
XMLStreamReader xmlr =
xmlif.createXMLStreamReader(new FileReader("contact.xml"));
// move to the root element and check its name.
xmlr.nextTag();
xmlr.require(START_ELEMENT, null, "addressBook");
xmlr.nextTag(); // move to the first <contact> element.
while (xmlr.getEventType() == START_ELEMENT) {
// unmarshall one <contact> element into a JAXB Contact object
xmlr.require(START_ELEMENT, null, "contact");
Contact contact = (Contact) um.unmarshal(xmlr);
if( contact.getName().equals(nameToLookFor)) {
// we found what we wanted to find. show it and quit now.
System.out.println("the e-mail address is "+contact.getEmail());
return;
}
if (xmlr.getEventType() == CHARACTERS) {
xmlr.next(); // skip the whitespace between <contact>s.
}
}
System.out.println("Unable to find "+nameToLookFor);
}
}
|
public class prism extends rectangle{
public prism(double width, double length, double height) {
super(width, length, height);
}
@Override
public double area() {
return (2*width * length) + (2*length* height) + (2*height*width) ;
}
@Override
public double volume() {
return width * length* height;
}
public String toString() {
return "Prism : "+"height : " + height + " width : "+ width + " length : " + length
+ "\n"+ "perimeter of base : "+ pC() + " volume : " + volume() +"\n"+ " area : "+ area();
}
}
|
package behavioral.mediator;
import java.util.Random;
/**
* @author Renat Kaitmazov
*/
public final class Producer implements Runnable {
/*--------------------------------------------------------*/
/* Static variables
/*--------------------------------------------------------*/
private static final Random RANDOM = new Random(System.currentTimeMillis());
public static final int UPPER_BOUND = 1_000;
private static int ID_COUNTER = 1;
/*--------------------------------------------------------*/
/* Instance variables
/*--------------------------------------------------------*/
private final Mediator mediator;
private final int id;
/*--------------------------------------------------------*/
/* Constructors
/*--------------------------------------------------------*/
public Producer(Mediator mediator) {
this.mediator = mediator;
id = ID_COUNTER++;
}
/*--------------------------------------------------------*/
/* Runnable implementation
/*--------------------------------------------------------*/
@Override
public final void run() {
for (int i = 0; i < id; ++i) {
final int message = RANDOM.nextInt(UPPER_BOUND);
System.out.printf("Producer ID %d: produced %d\n", id, message);
mediator.storeMessage(message);
}
}
}
|
package com.vincent.algorithm.basic.array;
/**
* leetcode 121
* 121. 买卖股票的最佳时机
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
*
* 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
*
* 注意:你不能在买入股票前卖出股票。
*
*
*
* 示例 1:
*
* 输入: [7,1,5,3,6,4]
* 输出: 5
* 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
* 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
* 示例 2:
*
* 输入: [7,6,4,3,1]
* 输出: 0
* 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
*/
public class BestTimeToBuyAndSellStock {
/**
解题讲解:力扣官方
题意:
就是只能进行一次股票的买入和卖出。能够获得的最大利润是多少
都要先买菜能卖
解题思路:
1.要想利益最大化,肯定是低点买入,高点卖出
2.一次循环过程中,找到最小的值,并基于此对其进行卖出计算,有一个变量存储最大的差值即可
*/
public int maxProfit(int[] prices) {
int minValue = Integer.MAX_VALUE;//这里一定是最大值,如果设为0,那很可能数组中,本身就没有0的元素,那最小值始终是0,而不是数组的最小值
int maxProfit = 0;
for(int i=0;i<prices.length;i++) {
minValue = Math.min(minValue,prices[i]);
int todaySaleProfit = prices[i] - minValue;
maxProfit = Math.max(maxProfit,todaySaleProfit);
}
return maxProfit;
}
}
|
package com.mystore.base;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
import com.mystore.actiondriver.Action;
import com.mystore.utility.ExtentManager;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseClass {
public static Properties prop;
//public static WebDriver driver;
public static ThreadLocal<RemoteWebDriver> driver=new ThreadLocal<>();
@BeforeSuite(groups = {"Smoke","Sanity","Regression"})
public void beforeSuite()
{
ExtentManager.setExtent();
DOMConfigurator.configure("log4j.xml");
}
public static WebDriver getDriver()
{
return driver.get();
}
@BeforeMethod(groups = {"Smoke","Sanity","Regression"})
public void readConfig() throws IOException
{
prop=new Properties();
FileInputStream fs=new FileInputStream(System.getProperty("user.dir")+"/Configuration/Config.properties");
prop.load(fs);
}
public void launchApplication(String browserName) throws IOException
{
//readConfig();
//String browserName=prop.getProperty("browser");
if(browserName.equalsIgnoreCase("Chrome"))
{
WebDriverManager.chromedriver().setup();
//driver=new ChromeDriver();
driver.set(new ChromeDriver());
}
else if(browserName.equalsIgnoreCase("FireFox"))
{
WebDriverManager.firefoxdriver().setup();
//driver=new FirefoxDriver();
driver.set(new FirefoxDriver());
}
else if(browserName.equalsIgnoreCase("Safari"))
{
//driver=new SafariDriver();
driver.set(new SafariDriver());
}
getDriver().manage().window().maximize();
Action.implicitWait(getDriver(),10);
Action.pageLoadTimeOut(getDriver(), 40);
getDriver().get(prop.getProperty("url"));
}
@AfterSuite
public void afterSuite()
{
ExtentManager.endReport();
}
}
|
package com.app.aston.adapter;
/**
* Created by vincent on 28/06/2016.
*/
public class AstonTwitter {
private TwitterApi twitterApi = new TwitterApi();
public void send(String message) {
twitterApi.tweet(message);
}
}
|
package phonebook;
import java.util.Scanner;
public class Application {
// main is the method that will run first in app
public static void makeSelection() {
String newLine = System.getProperty("line.separator");
System.out.println("Menu" + newLine + "1. Add New Record" + newLine + "2. Update Record");
System.out.println("3. Delete Record" + newLine + "4. Search By FirstName" + newLine + "5. Search By LastName");
System.out.println("6. Search By First and Last Name" + newLine + "7. Search By PhoneNumber" + newLine
+ "8. Search By City");
System.out.println("9. Search by State" + newLine + "10. Show All Records" + newLine + "11. Exit" + newLine);
System.out.println("Enter Selection: " + newLine);
}
private static Person[] expandArray(Person[] phoneBook) {
Person[] target = new Person[phoneBook.length + 1];
for (int i = 0; i < phoneBook.length; i++) {
target[i] = phoneBook[i];
}
return target;
}
private static Person[] expandNewArray(Person[] phoneBook) {
Person[] target = new Person[phoneBook.length + 1];
for (int i = 0; i < phoneBook.length; i++) {
target[i] = phoneBook[i];
}
return target;
}
private static Person setAll(String name, String last, String phone, String street, String city, String state,
String zip) {
Person p = new Person(name, last, phone);
Address a = new Address();
a.setStreet(street);
a.setCity(city);
a.setState(state);
a.setZip(zip);
p.setAddress(a);
return p;
}
public static void main(String[] args) {// This will
// line separator
String newLine = System.getProperty("line.separator");
// Person p = new Person();
Address a = new Address();
Person[] phoneBook = new Person[0];
boolean hasEnded = false;
makeSelection();
while (!hasEnded) {
Scanner scanner = new Scanner(System.in);
String selection = scanner.nextLine();
switch (selection) {
case "1":
// code block
System.out.println("Please enter enter record in the following format: " + newLine
+ "Without spaces after commas" + newLine
+ "firstName,lastName,phoneNumber(000)-000-0000,street,city,state,zip" + newLine + "Enter:");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
String[] s = selection.split(",");
phoneBook = expandArray(phoneBook);
phoneBook[phoneBook.length - 1] = setAll(s[0], s[1], s[2], s[3], s[4], s[5], s[6]);
makeSelection();
System.out.println("Record Added!");
System.out.println("Enter Another Selection: ");
break;
case "2":
System.out.println("Enter Phone Number Associated With Person Being Updated: ");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
for (int i = 0; i < phoneBook.length; i++) {
if (selection.equalsIgnoreCase(phoneBook[i].getPhoneNumber())) {
System.out.println("Record Found");
System.out.println(phoneBook[i]);
System.out.println("Please update record in the following format: " + newLine
+ "firstName, lastName, phoneNumber(000-000-0000), street, city, state, zip" + newLine
+ "Enter:");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
s = selection.split(",");
phoneBook[i] = setAll(s[0], s[1], s[2], s[3], s[4], s[5], s[6]);
System.out.println(phoneBook[i]);
System.out.println("Record Updated! ");
System.out.println("Make Another Selection: ");
} else {
System.out.println("Record Not Found Try A Different Menu Item: ");
}
}
break;
case "3":
System.out.println("Enter Phone Number Associated With Person Being Deleted: ");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
for (int i = 0; i < phoneBook.length; i++) {
if (selection.equalsIgnoreCase(phoneBook[i].getPhoneNumber())) {
System.out.println("Record Found");
System.out.println(phoneBook[i]);
System.out.println("Are you sure you want to delete person " + newLine
+ "Enter 1 for yes and 2 for no" + newLine + "Enter:");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
Person recordFound = phoneBook[i];
Person[] updatedBook = new Person[phoneBook.length - 1];
if (selection.equals("1")) {
for (int i1 = 0; i1 < phoneBook.length; i1++) {
if (!phoneBook[i1].getPhoneNumber().equals(recordFound.getPhoneNumber())) {
// updatedBook =
// expandNewArray(updatedBook);
updatedBook[i1] = phoneBook[i1];
}
}
phoneBook = updatedBook;
} else {
System.out.println("No record was deleted: ");
System.out.println("Make Another Selection: ");
break;
}
System.out.println(phoneBook.length);
System.out.println("Record Deleted! ");
System.out.println("Make Another Selection: ");
} else {
System.out.println("Record Not Found Try A Different Menu Item: ");
}
}
break;
case "4":
System.out.println("Enter First Name: ");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
for (int i = 0; i < phoneBook.length; i++) {
if (selection.equalsIgnoreCase(phoneBook[i].getFirstName())) {
System.out.println("Record Found!");
System.out.println(phoneBook[i]);
System.out.println("Enter Selection: ");
} else if (phoneBook.length - 1 == i && !selection.equalsIgnoreCase(phoneBook[i].getFirstName())) {
System.out.println("Retry Or Enter A Different Selection: ");
}
}
break;
case "5":
System.out.println("Enter Last Name: ");
scanner = new Scanner(System.in);
selection = scanner.nextLine();
for (int i = 0; i < phoneBook.length; i++) {
if (selection.equalsIgnoreCase(phoneBook[i].getLastName())) {
System.out.println("Record Found!");
System.out.println(phoneBook[i]);
System.out.println("Enter Selection: ");
} else if (phoneBook.length - 1 == i && !selection.equalsIgnoreCase(phoneBook[i].getLastName())) {
System.out.println("Retry Or Enter A Different Selection: ");
}
}
break;
case "10":
for (int i = 0; i < phoneBook.length; i++) {
System.out.println(phoneBook[i]);
}
System.out.println("Showing All Records: ");
System.out.println("Enter Another Selection: ");
break;
case "11":
System.out.println("Thank you, Good Bye!");
hasEnded = true;
// code block
break;
default:
// code block
}
}
}
}
|
package com.git.cloud.resmgt.common.service.impl;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.common.model.IsActiveEnum;
import com.git.cloud.common.support.PaginationParam;
import com.git.cloud.resmgt.common.dao.IRmDatacenterDAO;
import com.git.cloud.resmgt.common.model.po.RmDatacenterPo;
import com.git.cloud.resmgt.common.service.IRmDatacenterService;
import com.git.cloud.sys.model.po.SysUserPo;
import com.git.support.util.PwdUtil;
import com.google.common.collect.Maps;
/**
* @ClassName:RmDatacenterServiceImpl
* @Description:数据中心信息
* @author mijia
* @date 2014-12-17 下午1:43:25
*
*
*/
public class RmDatacenterServiceImpl implements IRmDatacenterService {
private IRmDatacenterDAO rmDatacenterDAO;
@Override
public RmDatacenterPo getDataCenterById(String dcId)
throws RollbackableBizException {
return rmDatacenterDAO.getDataCenterById(dcId);
}
@Override
public List<RmDatacenterPo> getDataCenters()
throws RollbackableBizException {
return rmDatacenterDAO.getDataCenters();
}
@Override
public Object getDevicePagination(PaginationParam paginationParam) {
return rmDatacenterDAO.pageQuery("findRmDatacenterTotal", "findRmDatacenterPage", paginationParam);
}
@Override
public void saveRmDatacenter(RmDatacenterPo rmDatacenterPo) throws RollbackableBizException {
SysUserPo sysUserPo=(SysUserPo) SecurityUtils.getSubject().getPrincipal();
String user=sysUserPo.getFirstName()+sysUserPo.getLastName();
String id = com.git.cloud.foundation.util.UUIDGenerator.getUUID();
rmDatacenterPo.setCreateDateTime(new Date());
rmDatacenterPo.setCreateUser(user);
rmDatacenterPo.setId(id);
rmDatacenterPo.setIsActive(IsActiveEnum.YES.getValue());
rmDatacenterDAO.saveRmDatacenter(rmDatacenterPo);
}
@Override
public void updateRmDatacenter(RmDatacenterPo rmDatacenterPo) throws RollbackableBizException {
SysUserPo sysUserPo=(SysUserPo) SecurityUtils.getSubject().getPrincipal();
String user=sysUserPo.getFirstName()+sysUserPo.getLastName();
rmDatacenterPo.setUpdateDateTime(new Date());
rmDatacenterPo.setUpdateUser(user);
rmDatacenterDAO.updateRmDatacenter(rmDatacenterPo);
}
@Override
public Map<String, String> selectPoolByDatacenterId(String dataCenterId) throws RollbackableBizException {
String count=(String) rmDatacenterDAO.selectPoolByDatacenterId(dataCenterId);
RmDatacenterPo rmDatacenterPo=rmDatacenterDAO.getDataCenterById(dataCenterId);
String datacenterName=rmDatacenterPo.getDatacenterCname();
Map<String, String> map = Maps.newHashMap();
map.put("count", count);
map.put("datacenterName", datacenterName);
return map;
}
@Override
public void deleteDatacenter(String[] split) throws RollbackableBizException {
rmDatacenterDAO.deleteDatacenter(split);
}
@Override
public RmDatacenterPo selectQueueIdenfortrim(String queueIden) throws RollbackableBizException {
return rmDatacenterDAO.selectQueueIdenfortrim(queueIden);
}
@Override
public RmDatacenterPo selectDCenamefortrim(String ename) throws RollbackableBizException {
return rmDatacenterDAO.selectDCenamefortrim(ename);
}
public void setRmDatacenterDAO(IRmDatacenterDAO rmDatacenterDAO) {
this.rmDatacenterDAO = rmDatacenterDAO;
}
@Override
public List<RmDatacenterPo> getDataCenterAccessData() throws RollbackableBizException {
List<RmDatacenterPo> poList = rmDatacenterDAO.getDataCenterAccessData();
for(RmDatacenterPo po : poList){
po.setPassword(PwdUtil.decryption(po.getPassword()));
}
return poList;
}
@Override
public String getDiskList() throws Exception{
// String openstackIp = "172.21.31.10";
// String token = OpenstackServiceFactory.getTokenServiceInstance(openstackIp).getToken();
// String targetProjectId = OpenstackServiceFactory.getIdentityServiceInstance(openstackIp, token).getManageProject();
// String volumeList = OpenstackServiceFactory.getVolumeServiceInstance(openstackIp, token).getVolumeList(token, targetProjectId);
return null;
}
@Override
public String getDiskDetailed(String volumeId) throws Exception {
// String openstackIp = "172.21.31.10";
// String token = OpenstackServiceFactory.getTokenServiceInstance(openstackIp).getToken();
// String targetProjectId = OpenstackServiceFactory.getIdentityServiceInstance(openstackIp, token).getManageProject();
// String volumeDetail = OpenstackServiceFactory.getVolumeServiceInstance(openstackIp, token).getVolumeDetail(token, targetProjectId, volumeId);
return null;
}
}
|
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* @author liaohong
* @date 2018/7/9 11:23
*/
public class SocketServer {
public void server() {
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10000);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("服务端已启动,等待客户端连接..");
Socket socket = serverSocket.accept();//侦听并接受到此套接字的连接,返回一个Socket对象
System.out.println("建立连接");
String line;
BufferedReader client = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
BufferedReader server = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("客户端" + ":" + client.readLine());
System.out.print("服务器:");
line = server.readLine();
writer.write(line + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SocketServer socketServer = new SocketServer();
socketServer.server();
}
}
|
package com.example.administrator.competition.entity;
public class CommonConfig {
public static String recordAndLiveKey = "recordAndLiveKey";
public static String guessGradeKey = "guessGradeKey";
public static int recordValue = 10000;
public static int LiveValue = 10001;
public static int primaryValue = 10002;
public static int middleValue = 10003;
public static int highValue = 10004;
public static int oneToOneValue = 10005;
}
|
package com.gagetalk.gagetalkcustomer.fragment;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.gagetalk.gagetalkcommon.api.Function;
import com.gagetalk.gagetalkcommon.constant.ConstValue;
import com.gagetalk.gagetalkcommon.constant.ReqUrl;
import com.gagetalk.gagetalkcommon.network.Network;
import com.gagetalk.gagetalkcommon.util.MyLog;
import com.gagetalk.gagetalkcustomer.R;
import com.gagetalk.gagetalkcustomer.activities.ChatActivity;
import com.gagetalk.gagetalkcustomer.adapter.ChatRoomAdapter;
import com.gagetalk.gagetalkcustomer.api.CustomerFunction;
import com.gagetalk.gagetalkcustomer.api.CustomerNetwork;
import com.gagetalk.gagetalkcustomer.data.ChatRoomData;
import com.gagetalk.gagetalkcustomer.data.DayData;
import com.gagetalk.gagetalkcustomer.database.AccessDB;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
/**
* Created by hyochan on 3/28/15.
*/
public class MsgFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private static final String TAG = "MsgFragment";
private Activity activity;
private Context context;
private SwipeRefreshLayout swipeRefreshLayout;
private ArrayList<ChatRoomData> arrayChatRoom;
private ListView listChatOn;
private ChatRoomAdapter chatRoomAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.msg_fragment, container, false);
activity = getActivity();
context = getActivity().getApplicationContext();
// register receiver for view more click in ProductListAdapter
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeRefreshLayout.setOnRefreshListener(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConstValue.LOGIN_FILTER);
intentFilter.addAction(ConstValue.SERVER_ALIVE_RECEIVER);
intentFilter.addAction(ConstValue.CHAT_MY_RECEIVER);
intentFilter.addAction(ConstValue.CHAT_PEERS_RECEIVER);
activity.registerReceiver(msgFragReceiver, intentFilter);
listChatOn = (ListView) view.findViewById(R.id.list_chat_on);
return view;
}
@Override
public void onResume() {
super.onResume();
// send broadcast to MainFragment to change the fragment if not logged in
if(!CustomerFunction.getInstance(context).isCusLocallyLoggedIn()){
Intent intent = new Intent().setAction(ConstValue.MOVE_TO_MSG_FRAG_FILTER);
intent.putExtra("fragment", ConstValue.HOME_FRAGMENT);
context.sendBroadcast(intent);
}
// selectChatRoom();
reqServerCustomerChatRoom();
}
@Override
public void onDestroyView() {
getActivity().unregisterReceiver(msgFragReceiver);
super.onDestroyView();
}
private void selectChatRoom(){
MyLog.i(TAG, "selectChatRoom onResume");
// 1. setup data from local database first time
arrayChatRoom = AccessDB.getInstance(context).selectChatRoom();
// 2. setup adapter
chatRoomAdapter = new ChatRoomAdapter(context, R.id.txt_name_peer, arrayChatRoom);
// 3. bind adapter
listChatOn.setAdapter(chatRoomAdapter);
listChatOn.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// set chatroom msg and chat msg read
Intent intent = new Intent(context, ChatActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("mar_id", chatRoomAdapter.getItem(position).getMarId());
intent.putExtra("mar_name", chatRoomAdapter.getItem(position).getMarName());
startActivity(intent);
// activity.finish();
activity.overridePendingTransition(R.anim.right_to_left_in, R.anim.right_to_left_out);
}
});
}
@Override
public void onRefresh() {
reqServerCustomerChatRoom();
}
private BroadcastReceiver msgFragReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "action : " + action);
if (action.equals(ConstValue.LOGIN_FILTER)) {
reqServerCustomerChatRoom();
/*selectChatRoom();*/
/* when logged in =>
1. select the data in server
2. insert the data existing in server
*/
}
else if(action.equals(ConstValue.SERVER_ALIVE_RECEIVER)){
MyLog.d(TAG, "SERVER ALIVE RECEIVER !!!!");
reqServerCustomerChatRoom();
}
else if(action.equals(ConstValue.CHAT_PEERS_RECEIVER)){
MyLog.d(TAG, "ChatBR PEER MSG RECEIVED!!!!!!!!!!!!!!!!!!");
String idPeer = intent.getStringExtra("id_peer");
String namePeer = intent.getStringExtra("name_peer");
String msgPeer = intent.getStringExtra("msg_peer");
int type = intent.getIntExtra("type", 0);
String path = intent.getStringExtra("path");
String datePeer = intent.getStringExtra("date_peer");
DayData dayData = new DayData(
Integer.parseInt(datePeer.substring(0,4)),
Integer.parseInt(datePeer.substring(5,7)),
Integer.parseInt(datePeer.substring(8,10)),
Integer.parseInt(datePeer.substring(11,13)),
Integer.parseInt(datePeer.substring(14,16)),
Integer.parseInt(datePeer.substring(17,19)));
ChatRoomData chatRoomData = new ChatRoomData(idPeer, namePeer,
CustomerFunction.getInstance(context).getCusID(), null, msgPeer,
type, path, dayData.getChatDate(), 0, idPeer);
AccessDB.getInstance(context).updateChatRoom(chatRoomData);
selectChatRoom();
}
else if(action.equals(ConstValue.CHAT_MY_RECEIVER)){
MyLog.d(TAG, "ChatBR MY MSG RECEIVED!!!!!!!!!!!!!!!!!!");
String room = intent.getStringExtra("room");
String idMy = intent.getStringExtra("id_my");
String nameMy = intent.getStringExtra("name_my");
String msgMy = intent.getStringExtra("msg_my");
int type = intent.getIntExtra("type", 0);
String path = intent.getStringExtra("path");
String dateMy = intent.getStringExtra("date_my");
MyLog.d(TAG, "dateMy : " + dateMy);
DayData dayData = new DayData(
Integer.parseInt(dateMy.substring(0,4)),
Integer.parseInt(dateMy.substring(5,7)),
Integer.parseInt(dateMy.substring(8,10)),
Integer.parseInt(dateMy.substring(11,13)),
Integer.parseInt(dateMy.substring(14,16)),
Integer.parseInt(dateMy.substring(17,19)));
MyLog.d(TAG, "year : " + dayData.getYear() + ", month : " + dayData.getMonth() + ", day : " + dayData.getDay() + ", " +
"hour : " + dayData.getHour() + ", min : " + dayData.getMin() + ", sec : " + dayData.getSecond());
ChatRoomData chatRoomData = new ChatRoomData(room, null,
idMy, nameMy, msgMy,
type, path, dayData.getChatDate(), 0, idMy);
AccessDB.getInstance(context).updateChatRoom(chatRoomData);
selectChatRoom();
}
}
};
private void reqServerCustomerChatRoom(){
String url = ReqUrl.CustomerRoomTask + ReqUrl.SELECT;
Network.getInstance(context).reqPost(activity, url, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
try {
int resultCode = response.getInt("resultCode");
switch (resultCode){
case ConstValue.RESPONSE_NOT_LOGGED_IN:
// this will not happen because it is done after login (received from the broadcast login filter)
break;
case ConstValue.RESPONSE_NO_DATA:
AccessDB.getInstance(context).deleteAllChatRoom();
break;
case ConstValue.RESPONSE_SUCCESS:
JSONArray chatJSONArray = response.getJSONArray("chatroom");
/*MyLog.i(TAG, "chatJSONArray : " + chatJSONArray.toString());*/
for(int i = 0; i<chatJSONArray.length(); i++){
JSONObject chatJSONObject = chatJSONArray.getJSONObject(i);
String dateStr = chatJSONObject.getString("send_date");
MyLog.d(TAG, "dateStr : " + dateStr);
DayData dayData = new DayData(
Integer.parseInt(dateStr.substring(0, 4)),
Integer.parseInt(dateStr.substring(5, 7)),
Integer.parseInt(dateStr.substring(8, 10)),
Integer.parseInt(dateStr.substring(11, 13)),
Integer.parseInt(dateStr.substring(14, 16)),
Integer.parseInt(dateStr.substring(17, 19)));
MyLog.d(TAG, "dateData.getChatDate() : " + dayData.getChatDate());
ChatRoomData chatRoomData = new ChatRoomData(
chatJSONObject.getString("mar_id"),
chatJSONObject.getString("mar_name"),
chatJSONObject.getString("cus_id"),
chatJSONObject.getString("cus_name"),
chatJSONObject.getString("message"),
chatJSONObject.getInt("type"),
chatJSONObject.getString("path"),
dayData.getChatDate(),
chatJSONObject.getInt("read_msg"),
chatJSONObject.getString("sender")
);
/*MyLog.d(TAG, "ChatRoomData - "
+ "\n mar_id : " + chatRoomData.getMarId()
+ "\n mar_name : " + chatRoomData.getMarName()
+ "\n cus_id : " + chatRoomData.getCusId()
+ "\n cus_name : " + chatRoomData.getCusName()
+ "\n message : " + chatRoomData.getMessage()
+ "\n type : " + chatRoomData.getType()
+ "\n path : " + chatRoomData.getPath()
+ "\n send_date : " + chatRoomData.getSendDate()
+ "\n read_msg : " + chatRoomData.getReadMsg()
+ "\n sender : " + chatRoomData.getSender()
);*/
AccessDB.getInstance(context).insertChatRoom(chatRoomData);
}
break;
}
selectChatRoom();
swipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
Function.getInstance(context).logErrorParsingJson(e);
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Network.getInstance(context).toastErrorMsg(activity);
swipeRefreshLayout.setRefreshing(false);
}
});
}
} |
package io.mosip.tf.t5.cryptograph.model;
import lombok.Data;
@Data
public class EventModel {
private String publisher;
private String topic;
private String publishedOn;
private Event event;
}
|
package net.leloubil.mcpwn.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import lombok.AllArgsConstructor;
import net.leloubil.mcpwn.R;
import net.leloubil.mcpwn.UserAdapter;
import net.leloubil.mcpwn.mcapi.UserData;
import java.util.function.Consumer;
@SuppressWarnings("NullableProblems")
@AllArgsConstructor
public class UserDisplayFragment extends Fragment {
private Consumer<View> onFabCLick;
private Consumer<UserData> userData;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
long start = System.currentTimeMillis();
final View vieww = inflater.inflate(R.layout.fragment_user_display, container, false);
RecyclerView view = vieww.findViewById(R.id.recyclerview_users);
view.setLayoutManager(new LinearLayoutManager(getContext()));
view.setAdapter(new UserAdapter(userData));
vieww.findViewById(R.id.floatingActionButton).setOnClickListener(this::onActionClick);
long end = System.currentTimeMillis();
Log.d("Time limiterdsdf ", "ddd: display took " + (end - start) + "ms");
return vieww;
}
private void onActionClick(View fab) {
onFabCLick.accept(fab);
}
}
|
package com.lesports.albatross.entity;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* 通用解析列表
* Created by zhouchenbin on 16/6/1.
*/
public class HttpRespNorlistEntity<T> extends HttpRespResultEntity {
@SerializedName("data")
@Expose
private List<T> data = new ArrayList<>();
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
} |
package com.nitnelave.CreeperHeal.block;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
/**
* Represents the second part of a double chest, the first one being a
* CreeperChest.
*
* @author nitnelave
*
*/
public class NeighborChest
{
/*
* The chest itself.
*/
private final BlockState chest;
/*
* Whether it is the right part of the double chest or the left one.
*/
private final boolean right;
/**
* Constructor.
*
* @param chest
* The block where the chest is.
* @param right
* Whether the block is the right part of the double chest.
*/
public NeighborChest(Block chest, boolean right)
{
this(chest.getState(), right);
}
/**
* Constructor.
*
* @param chest
* The blockState representing the chest.
* @param right
* Whether the block is the right part of the double chest.
*/
public NeighborChest(BlockState chest, boolean right)
{
this.chest = chest;
this.right = right;
}
/**
* Get whether the block is the right part of the double chest.
*
* @return Whether the block is the right part of the double chest.
*/
public boolean isRight()
{
return right;
}
/**
* Get the blockState representing the chest.
*
* @return The blockState representing the chest.
*/
public BlockState getChest()
{
return chest;
}
/**
* Gets the block where the chest is.
*
* @return The block.
*/
public Block getBlock()
{
return chest.getBlock();
}
public void update(boolean b)
{
chest.update(true);
chest.getBlock().setType(chest.getType());
}
}
|
package me.willwei.meeting.film.common.persistence.dao;
import me.willwei.meeting.film.common.persistence.model.CatDictT;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 类型信息表 Mapper 接口
* </p>
*
* @author leiming
* @since 2019-08-01
*/
public interface CatDictTMapper extends BaseMapper<CatDictT> {
}
|
package com.zxelec.cache.service;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.zxelec.cache.bean.Employee;
import com.zxelec.cache.mapper.EmployeeMapper;
@Service
public class EmpService {
private Logger logger = LogManager.getLogger(EmpService.class);
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 将方法的运行结果进行缓存
* cacheNames/value:指定缓存名字
* key:缓存数据的key,可以用它来指定,,默认是使用方法的参数
* keygenerator:key的生成器,可以自己指定key的生成器组件id
* kye/keygenerator:二选一
* cachemanager:指定缓存管理器:或者cacheeResolver指定获取解析器
* condition:指定符合条件的情况下进行缓存
* unless:否定缓存:当unless指定的条件为true,方法的返回值就不会被缓存,可以获取到结果进行判断
* sync:是否进行异步模式
*
* 原理
* 1、自定配置类cacheautoconfiguration
* 2、缓存的配置类
* org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
* org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
* org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
* org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
* org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
* org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
* org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
* @param id
* @return
*/
@Cacheable(cacheNames = "emp",key = "#id")
public Employee queryEmpById(Integer id) {
logger.info("查询@Cacheable数据:"+id);
return employeeMapper.getEmployeeById(id);
}
/**
* @CachePut :调用方法同时更新缓存
* @return
*/
@CachePut(cacheNames = "emp",key = "#id")
public Employee getEmpId(Integer id) {
logger.info("查询@CachePut数据:"+id);
return employeeMapper.getEmployeeById(id);
}
/**
* 删除数据
* @cacheEvict:清除缓存
* value 存储地址
* key:指定要清除的数据
* allEntries 清除全部数据
* beforeInvocatio = false 缓存的清除是否在方法之前执行
* 默认代表是在方法之后执行
* @param id
*/
@CacheEvict(value = "emp",
/* key = "#id" , */
allEntries = true )
public void delEmpId(Integer id) {
// employeeMapper.delEmp(id);
logger.info("删除@@CacheEvict数据:"+id);
}
public Employee getRedisId(Integer id) {
Employee emp = employeeMapper.getEmployeeById(id);
String json = JSONObject.toJSONString(emp);
logger.info("数据存储到redis:"+id);
stringRedisTemplate.opsForValue().set("id_"+id, json);
return emp;
}
}
|
package sop.vo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import sop.persistence.beans.PurchaseOrder;
import sop.persistence.beans.PurchaseOrderCharge;
import sop.persistence.beans.PurchaseOrderItem;
import sop.persistence.beans.PurchaseOrderLc;
import sop.persistence.beans.PurchaseOrderSbk;
import sop.persistence.beans.SaleOrderCharge;
import sop.persistence.beans.SaleOrderItem;
import sop.persistence.beans.SaleOrderLc;
import sop.persistence.beans.SaleOrderSbk;
/**
* @Author: LCF
* @Date: 2020/1/9 11:49
* @Package: sop.vo
*/
public class PurchaseOrderDetailsVo extends PurchaseOrder {
private static final long serialVersionUID = -7730194593419089855L;
private Map<String, PurchaseOrderItem> purchaseOrderItems;
private boolean haveLc = false;
private PurchaseOrderLc purchaseOrderLc;
private Map<String, PurchaseOrderLc> purchaseOrderLcs;
private boolean haveCharge = false;
private PurchaseOrderCharge purchaseOrderCharge;
private Map<String, PurchaseOrderCharge> purchaseOrderCharges;
private boolean haveSbk = false;
private PurchaseOrderSbk purchaseOrderSbk;
private Map<String, PurchaseOrderSbk> purchaseOrderSbks;
public PurchaseOrderDetailsVo() {
}
public PurchaseOrderDetailsVo(PurchaseOrder purchaseOrder) {
if (purchaseOrder != null) {
setPoArtArtNo(purchaseOrder.getPoArtArtNo());
setPoArtEanNo(purchaseOrder.getPoArtEanNo());
setPoArtGeneral(purchaseOrder.getPoArtGeneral());
setPoArtGrnPoint(purchaseOrder.getPoArtGrnPoint());
setPoArtLang(purchaseOrder.getPoArtLang());
setPoArtOther(purchaseOrder.getPoArtOther());
setPoArtResy(purchaseOrder.getPoArtResy());
setPoCnf(purchaseOrder.getPoCnf());
setPoCnfPort(purchaseOrder.getPoCnfPort());
setPoContReq(purchaseOrder.getPoContReq());
setPoCtnPkgDesc(purchaseOrder.getPoCtnPkgDesc());
setPoCurr(purchaseOrder.getPoCurr());
setPoDate(purchaseOrder.getPoDate());
setPoDelDetails(purchaseOrder.getPoDelDetails());
setPoDepDate(purchaseOrder.getPoDepDate());
setPoDepPaid(purchaseOrder.getPoDepPaid());
setPoDepRatio(purchaseOrder.getPoDepRatio());
setPoDest(purchaseOrder.getPoDest());
setPoDtlArtNo(purchaseOrder.getPoDtlArtNo());
setPoDtlEanNo(purchaseOrder.getPoDtlEanNo());
setPoDtlGeneral(purchaseOrder.getPoDtlGeneral());
setPoDtlGrnPoint(purchaseOrder.getPoDtlGrnPoint());
setPoDtlLang(purchaseOrder.getPoDtlLang());
setPoDtlOther(purchaseOrder.getPoDtlOther());
setPoDtlResy(purchaseOrder.getPoDtlResy());
setPoEtdDate(purchaseOrder.getPoEtdDate());
setPoFob(purchaseOrder.getPoFob());
setPoFobPort(purchaseOrder.getPoFobPort());
setPoIartInsSh(purchaseOrder.getPoIartInsSh());
setPoIartLabel(purchaseOrder.getPoIartLabel());
setPoIartOther(purchaseOrder.getPoIartOther());
setPoIdtlInsSh(purchaseOrder.getPoIdtlInsSh());
setPoIdtlLabel(purchaseOrder.getPoIdtlLabel());
setPoIdtlOther(purchaseOrder.getPoIdtlOther());
setPoIpkgInsSh(purchaseOrder.getPoIpkgInsSh());
setPoIpkgLabel(purchaseOrder.getPoIpkgLabel());
setPoIpkgOther(purchaseOrder.getPoIpkgOther());
setPoLshpDate(purchaseOrder.getPoLshpDate());
setPoNo(purchaseOrder.getPoNo());
setPoOdtl(purchaseOrder.getPoOdtl());
setPoOrdAmtWord(purchaseOrder.getPoOrdAmtWord());
setPoOrdTotAmt(purchaseOrder.getPoOrdTotAmt());
setPoOrdTotChg(purchaseOrder.getPoOrdTotChg());
setPoOrdTotNet(purchaseOrder.getPoOrdTotNet());
setPoPkgArtNo(purchaseOrder.getPoPkgArtNo());
setPoPkgEanNo(purchaseOrder.getPoPkgEanNo());
setPoPkgGeneral(purchaseOrder.getPoPkgGeneral());
setPoPkgGrnPoint(purchaseOrder.getPoPkgGrnPoint());
setPoPkgLang(purchaseOrder.getPoPkgLang());
setPoPkgOther(purchaseOrder.getPoPkgOther());
setPoPkgResy(purchaseOrder.getPoPkgResy());
setPoPtermDays(purchaseOrder.getPoPtermDays());
setPoRouting(purchaseOrder.getPoRouting());
setPoSoNoRef(purchaseOrder.getPoSoNoRef());
setPoSpMainMark(purchaseOrder.getPoSpMainMark());
setPoSpSideMark(purchaseOrder.getPoSpSideMark());
setPoSuCode(purchaseOrder.getPoSuCode());
setPoSuPterm(purchaseOrder.getPoSuPterm());
setPoPterm(purchaseOrder.getPoPterm());
setCoCode(purchaseOrder.getCoCode());
setCrtDate(purchaseOrder.getCrtDate());
setCrtUsr(purchaseOrder.getCrtUsr());
setModDate(purchaseOrder.getModDate());
setModUsr(purchaseOrder.getModUsr());
}
}
public PurchaseOrderDetailsVo(SaleOrderDetailsVo saleOrder) {
setPoNo(saleOrder.getSoNo());
setPoCnf(saleOrder.getSoCnf());
setPoCnfPort(saleOrder.getSoCnfPort());
setPoContReq(saleOrder.getSoContReq());
setPoCurr(saleOrder.getSoCurr());
setPoDelDetails(saleOrder.getSoDelDetails());
setPoDepDate(saleOrder.getSoDepDate());
setPoDepPaid(saleOrder.getSoDepPaid());
setPoDepRatio(saleOrder.getSoDepRatio());
setPoDest(saleOrder.getSoDest());
setPoEtdDate(saleOrder.getSoEtd());
setPoFob(saleOrder.getSoFob());
setPoFobPort(saleOrder.getSoFobPort());
setPoLshpDate(saleOrder.getSoLshpDate());
setPoSoNoRef(saleOrder.getSoNo());
setPoRouting(saleOrder.getSoRouting());
if (saleOrder.getSaleOrderItems() != null && saleOrder.getSaleOrderItems().size() > 0) {
setPurchaseOrderItems(saleOrderItemsToPurchaseOrderItems(saleOrder.getSaleOrderItems()));
}
if (saleOrder.getSaleOrderLcs() != null && saleOrder.getSaleOrderLcs().size() > 0) {
setPurchaseOrderLcs(saleOrderLcsToPurchaseOrderLcs(saleOrder.getSaleOrderLcs()));
}
if (saleOrder.getSaleOrderCharges() != null && saleOrder.getSaleOrderCharges().size() > 0) {
setPurchaseOrderCharges(saleOrderChargesToPurchaseOrderCharges(saleOrder.getSaleOrderCharges()));
}
if (saleOrder.getSaleOrderSbks() != null && saleOrder.getSaleOrderSbks().size() > 0) {
setPurchaseOrderSbks(saleOrderSbksToPurchaseOrderSbks(saleOrder.getSaleOrderSbks()));
}
}
private Map<String, PurchaseOrderSbk> saleOrderSbksToPurchaseOrderSbks(
Map<String, SaleOrderSbk> saleOrderSbks) {
Map<String, PurchaseOrderSbk> getPurchaseOrderSbks = new HashMap<String, PurchaseOrderSbk>();
Iterator iter = saleOrderSbks.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next().toString();
SaleOrderSbk saleOrderSbk = saleOrderSbks.get(key);
PurchaseOrderSbk getPurchaseOrderSbk = new PurchaseOrderSbk(saleOrderSbk);
getPurchaseOrderSbks.put(key, getPurchaseOrderSbk);
}
return getPurchaseOrderSbks;
}
private Map<String, PurchaseOrderCharge> saleOrderChargesToPurchaseOrderCharges(
Map<String, SaleOrderCharge> saleOrderCharges) {
Map<String, PurchaseOrderCharge> getPurchaseOrderCharges = new HashMap<String, PurchaseOrderCharge>();
Iterator iter = saleOrderCharges.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next().toString();
SaleOrderCharge saleOrderCharge = saleOrderCharges.get(key);
PurchaseOrderCharge getPurchaseOrderCharge = new PurchaseOrderCharge(saleOrderCharge);
getPurchaseOrderCharges.put(key, getPurchaseOrderCharge);
}
return getPurchaseOrderCharges;
}
private Map<String, PurchaseOrderLc> saleOrderLcsToPurchaseOrderLcs(
Map<String, SaleOrderLc> saleOrderLcs) {
Map<String, PurchaseOrderLc> getPurchaseOrderLcs = new HashMap<String, PurchaseOrderLc>();
Iterator iter = saleOrderLcs.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next().toString();
SaleOrderLc saleOrderLc = saleOrderLcs.get(key);
PurchaseOrderLc getPurchaseOrderLc = new PurchaseOrderLc(saleOrderLc);
getPurchaseOrderLcs.put(key, getPurchaseOrderLc);
}
return getPurchaseOrderLcs;
}
private Map<String, PurchaseOrderItem> saleOrderItemsToPurchaseOrderItems(
Map<String, SaleOrderItem> saleOrderItems) {
Map<String, PurchaseOrderItem> getPurchaseOrderItems = new HashMap<String, PurchaseOrderItem>();
Iterator iter = saleOrderItems.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next().toString();
SaleOrderItem saleOrderItem = saleOrderItems.get(key);
PurchaseOrderItem getPurchaseOrderItem = new PurchaseOrderItem(saleOrderItem);
getPurchaseOrderItems.put(key, getPurchaseOrderItem);
}
return getPurchaseOrderItems;
}
public Map<String, PurchaseOrderItem> getPurchaseOrderItems() {
return purchaseOrderItems;
}
public void setPurchaseOrderItems(Map<String, PurchaseOrderItem> purchaseOrderItems) {
this.purchaseOrderItems = purchaseOrderItems;
}
public boolean isHaveLc() {
return haveLc;
}
public void setHaveLc(boolean haveLc) {
this.haveLc = haveLc;
}
public PurchaseOrderLc getPurchaseOrderLc() {
return purchaseOrderLc;
}
public void setPurchaseOrderLc(PurchaseOrderLc purchaseOrderLc) {
this.purchaseOrderLc = purchaseOrderLc;
}
public boolean isHaveCharge() {
return haveCharge;
}
public void setHaveCharge(boolean haveCharge) {
this.haveCharge = haveCharge;
}
public PurchaseOrderCharge getPurchaseOrderCharge() {
return purchaseOrderCharge;
}
public void setPurchaseOrderCharge(PurchaseOrderCharge purchaseOrderCharge) {
this.purchaseOrderCharge = purchaseOrderCharge;
}
public boolean isHaveSbk() {
return haveSbk;
}
public void setHaveSbk(boolean haveSbk) {
this.haveSbk = haveSbk;
}
public PurchaseOrderSbk getPurchaseOrderSbk() {
return purchaseOrderSbk;
}
public void setPurchaseOrderSbk(PurchaseOrderSbk purchaseOrderSbk) {
this.purchaseOrderSbk = purchaseOrderSbk;
}
public Map<String, PurchaseOrderLc> getPurchaseOrderLcs() {
return purchaseOrderLcs;
}
public void setPurchaseOrderLcs(Map<String, PurchaseOrderLc> purchaseOrderLcs) {
this.purchaseOrderLcs = purchaseOrderLcs;
}
public Map<String, PurchaseOrderCharge> getPurchaseOrderCharges() {
return purchaseOrderCharges;
}
public void setPurchaseOrderCharges(
Map<String, PurchaseOrderCharge> purchaseOrderCharges) {
this.purchaseOrderCharges = purchaseOrderCharges;
}
public Map<String, PurchaseOrderSbk> getPurchaseOrderSbks() {
return purchaseOrderSbks;
}
public void setPurchaseOrderSbks(Map<String, PurchaseOrderSbk> purchaseOrderSbks) {
this.purchaseOrderSbks = purchaseOrderSbks;
}
}
|
package ru.otus.sua.L08.atm.staff;
public interface AdvancedAtmMachine {
void reset();
}
|
import Controller.GameController;
/**
* @author Bitmonk
*/
public class GameMain {
public static void main(String[] args) {
GameController ticTacToe = new GameController();
ticTacToe.start();
}
}
|
package com.example.kyle.myapplication.Screens;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kyle.myapplication.Database.Abstract.Abstract_Table;
import com.example.kyle.myapplication.Database.DBOperation;
import com.example.kyle.myapplication.Database.DatabaseManager;
import com.example.kyle.myapplication.Database.Incident.Tbl_Incident;
import com.example.kyle.myapplication.Database.Incident.Tbl_Incident_Manager;
import com.example.kyle.myapplication.Database.IncidentLink.Tbl_IncidentLink;
import com.example.kyle.myapplication.Database.IncidentLink.Tbl_IncidentLink_Manager;
import com.example.kyle.myapplication.Database.Personnel.Tbl_Personnel;
import com.example.kyle.myapplication.Database.Personnel.Tbl_Personnel_Manager;
import com.example.kyle.myapplication.Database.Role.Tbl_Role;
import com.example.kyle.myapplication.Database.Role.Tbl_Role_Manager;
import com.example.kyle.myapplication.Database.SubmittedForms.Tbl_SubmittedForms;
import com.example.kyle.myapplication.Database.SubmittedForms.Tbl_SubmittedForms_Manager;
import com.example.kyle.myapplication.Database.Templates.Tbl_Templates;
import com.example.kyle.myapplication.Database.Templates.Tbl_Templates_Manager;
import com.example.kyle.myapplication.Helpers.FTPManager;
import com.example.kyle.myapplication.Helpers.LoggedInUser;
import com.example.kyle.myapplication.Helpers.OpenScreens;
import com.example.kyle.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class Login extends AppCompatActivity
{
Button btnLogin, btnRegister;
EditText txtEmail, txtPassword;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.btnRegister);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtPassword = (EditText) findViewById(R.id.txtPassword);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
btnLogin.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
login();
}
});
btnRegister.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
OpenScreens.OpenCreatePersonnelScreen(null, true);
}
});
performDevTests();
}
private void performDevTests()
{
Thread thread = new Thread()
{
@Override
public void run()
{
try
{
synchronized (this)
{
testDatabase();
testUploadDownload();
}
}
catch (Exception ex)
{
}
}
};
thread.start();
}
private void testUploadDownload()
{
//UploadDownloadFile(Context context, boolean isUpload, boolean isTemplate, String filePathAndName)
//download the template and put it into the specified path
FTPManager.UploadDownloadFile(this, FTPManager.FTPMode.DOWNLOAD, "data/data/com.example.kyle.myapplication/Incident Commander - Template1.docx", "Incident Commander - Template1.docx");
}
private void testDatabase()
{
String op = Tbl_Personnel_Manager.current.GetFullCreateScript() +
Tbl_Role_Manager.current.GetFullCreateScript() +
Tbl_Incident_Manager.current.GetFullCreateScript() +
Tbl_IncidentLink_Manager.current.GetFullCreateScript() +
Tbl_Templates_Manager.current.GetFullCreateScript() +
Tbl_SubmittedForms_Manager.current.GetFullCreateScript();
DBOperation operation = new DBOperation(Abstract_Table.SQLMode.CREATETTABLES, op, "ICS database successfully created", "Unable to create ICS database");
DatabaseManager.CreateDatabase(this, operation);
//personnel
Tbl_Personnel person1 = new Tbl_Personnel("Kyle", "Wertz", "Wertz.8@wright.edu", "Password1", "111-111-1111", "Developer", true);
person1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Personnel person2 = new Tbl_Personnel("Brandon", "Bradley", "Bradley.85@wright.edu", "Password2", "222-222-2222", "Developer", true);
person2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Personnel person3 = new Tbl_Personnel("Naif", "Alqahtani", "Alqahtani.31@wright.edu", "Password3", "333-333-3333", "Developer", true);
person3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Personnel person4 = new Tbl_Personnel("Justin", "Lagenbach", "Lagenbach.2@wright.edu", "Password4", "444-444-4444", "Developer", true);
person4.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Personnel_Manager.current.RecordOperation(person1);
Tbl_Personnel_Manager.current.RecordOperation(person2);
Tbl_Personnel_Manager.current.RecordOperation(person3);
Tbl_Personnel_Manager.current.RecordOperation(person4);
//roles
//examples taken from https://upload.wikimedia.org/wikipedia/commons/3/3e/ICS_Structure.PNG
Tbl_Role role1 = new Tbl_Role("Incident Commander");
role1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Role role2 = new Tbl_Role("Public Information Officer");
role2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Role role3 = new Tbl_Role("Liaison Officer");
role3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Role role4 = new Tbl_Role("Safety Officer");
role4.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Role_Manager.current.RecordOperation(role1);
Tbl_Role_Manager.current.RecordOperation(role2);
Tbl_Role_Manager.current.RecordOperation(role3);
Tbl_Role_Manager.current.RecordOperation(role4);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//templates
Tbl_Templates template1 = new Tbl_Templates(1, "Template 1", "Incident Commander - Template1.docx");
template1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template1);
Tbl_Templates template2 = new Tbl_Templates(2, "Template 2", "Public Information Officer - Template2.docx");
template2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template2);
Tbl_Templates template3 = new Tbl_Templates(3, "Template 3", "Liaison Officer - Template3.docx");
template3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template3);
Tbl_Templates template4 = new Tbl_Templates(4, "Template 4", "Safety Officer - Template4.docx");
template4.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template4);
Tbl_Templates template5 = new Tbl_Templates(1, "Template 5", "Public Information Officer - Template5.docx");
template5.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template5);
Tbl_Templates template6 = new Tbl_Templates(2, "Template 6", "Incident Commander - Template6.docx");
template6.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template6);
Tbl_Templates template7 = new Tbl_Templates(3, "Template 7", "Public Information Officer - Template7.docx");
template7.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template7);
Tbl_Templates template8 = new Tbl_Templates(4, "Template 8", "Liaison Officer - Template8.docx");
template8.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template8);
Tbl_Templates template9 = new Tbl_Templates(1, "Template 9", "Safety Officer - Template9.docx");
template9.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template9);
Tbl_Templates template10 = new Tbl_Templates(2, "Template 10", "Public Information Officer - Template10.docx");
template10.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template10);
Tbl_Templates template11 = new Tbl_Templates(3, "Template 11", "Incident Commander - Template11.docx");
template11.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template11);
Tbl_Templates template12 = new Tbl_Templates(4, "Template 12", "Public Information Officer - Template12.docx");
template12.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template12);
Tbl_Templates template13 = new Tbl_Templates(1, "Template 13", "Liaison Officer - Template13.docx");
template13.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template13);
Tbl_Templates template14 = new Tbl_Templates(2, "Template 14", "Safety Officer - Template14.docx");
template14.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template14);
Tbl_Templates template15 = new Tbl_Templates(3, "Template 15", "Public Information Officer - Template15.docx");
template15.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template15);
Tbl_Templates template16 = new Tbl_Templates(4, "Template 16", "Incident Commander - Template16.docx");
template16.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Templates_Manager.current.RecordOperation(template16);
//incidents
List<Tbl_IncidentLink> dummyLinks = new ArrayList<Tbl_IncidentLink>();
Tbl_IncidentLink incidentLink1 = new Tbl_IncidentLink(1, 1, 1, 1);
incidentLink1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_IncidentLink incidentLink2 = new Tbl_IncidentLink(1, 2, 2, 2);
incidentLink2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_IncidentLink incidentLink3 = new Tbl_IncidentLink(1, 3, 3, 3);
incidentLink3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_IncidentLink incidentLink4 = new Tbl_IncidentLink(1, 4, 4, 4);
incidentLink4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyLinks.add(incidentLink1);
dummyLinks.add(incidentLink2);
dummyLinks.add(incidentLink3);
dummyLinks.add(incidentLink4);
List<Tbl_SubmittedForms> dummyForms = new ArrayList<Tbl_SubmittedForms>();
Tbl_SubmittedForms forms1 = new Tbl_SubmittedForms(1, 1, 1, "data/data/com.example.kyle.myapplication/1.docx", "1.docx", "1st form", "09-11-2001 08:47:00");
forms1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_SubmittedForms forms2 = new Tbl_SubmittedForms(1, 2, 2, "data/data/com.example.kyle.myapplication/2.docx", "2.docx", "2nd form", "09-11-2001 09:46:00");
forms2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_SubmittedForms forms3 = new Tbl_SubmittedForms(1, 3, 3, "data/data/com.example.kyle.myapplication/3.docx", "3.docx", "3rd form", "09-11-2001 10:46:00");
forms3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_SubmittedForms forms4 = new Tbl_SubmittedForms(1, 4, 4, "data/data/com.example.kyle.myapplication/4.docx", "4.docx", "4th form", "09-11-2001 11:46:00");
forms4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyForms.add(forms1);
dummyForms.add(forms2);
dummyForms.add(forms3);
dummyForms.add(forms4);
Tbl_Incident incident1 = new Tbl_Incident("09-11-2001 08:46:00", "", "Attack on the first tower", "180 Greenwich St", "New York NY 10007", "40.711667", "-74.0125", dummyLinks, dummyForms);
incident1.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Incident_Manager.current.RecordOperation(incident1);
dummyLinks = new ArrayList<Tbl_IncidentLink>();
incidentLink1 = new Tbl_IncidentLink(2, 2, 3, 1);
incidentLink1.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink2 = new Tbl_IncidentLink(2, 1, 4, 2);
incidentLink2.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink3 = new Tbl_IncidentLink(2, 3, 2, 3);
incidentLink3.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink4 = new Tbl_IncidentLink(2, 4, 1, 4);
incidentLink4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyLinks.add(incidentLink1);
dummyLinks.add(incidentLink2);
dummyLinks.add(incidentLink3);
dummyLinks.add(incidentLink4);
dummyForms = new ArrayList<Tbl_SubmittedForms>();
forms1 = new Tbl_SubmittedForms(3, 4, 5, "data/data/com.example.kyle.myapplication/1.docx", "1.docx", "1st form", "09-11-2001 09:04:00");
forms1.sqlMode = Abstract_Table.SQLMode.INSERT;
forms2 = new Tbl_SubmittedForms(3, 3, 6, "data/data/com.example.kyle.myapplication/2.docx", "2.docx", "2nd form", "09-11-2001 10:03:00");
forms2.sqlMode = Abstract_Table.SQLMode.INSERT;
forms3 = new Tbl_SubmittedForms(3, 2, 7, "data/data/com.example.kyle.myapplication/3.docx", "3.docx", "3rd form", "09-11-2001 11:03:00");
forms3.sqlMode = Abstract_Table.SQLMode.INSERT;
forms4 = new Tbl_SubmittedForms(3, 1, 8, "data/data/com.example.kyle.myapplication/4.docx", "4.docx", "4th form", "09-11-2001 12:03:00");
forms4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyForms.add(forms1);
dummyForms.add(forms2);
dummyForms.add(forms3);
dummyForms.add(forms4);
Tbl_Incident incident2 = new Tbl_Incident("09-11-2001 09:03:00", "", "Attack on the second tower", "180 Greenwich St", "New York NY 10007", "40.711667", "-74.0125", dummyLinks, dummyForms);
incident2.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Incident_Manager.current.RecordOperation(incident2);
dummyLinks = new ArrayList<Tbl_IncidentLink>();
incidentLink1 = new Tbl_IncidentLink(3, 4, 1, 1);
incidentLink1.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink2 = new Tbl_IncidentLink(3, 2, 4, 2);
incidentLink2.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink3 = new Tbl_IncidentLink(3, 3, 3, 3);
incidentLink3.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink4 = new Tbl_IncidentLink(3, 1, 2, 4);
incidentLink4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyLinks.add(incidentLink1);
dummyLinks.add(incidentLink2);
dummyLinks.add(incidentLink3);
dummyLinks.add(incidentLink4);
dummyForms = new ArrayList<Tbl_SubmittedForms>();
forms1 = new Tbl_SubmittedForms(4, 4, 9, "data/data/com.example.kyle.myapplication/1.docx", "1.docx", "1st form", "02-23-2016 14:26:01");
forms1.sqlMode = Abstract_Table.SQLMode.INSERT;
forms2 = new Tbl_SubmittedForms(4, 1, 10, "data/data/com.example.kyle.myapplication/2.docx", "2.docx", "2nd form", "02-23-2016 15:25:01");
forms2.sqlMode = Abstract_Table.SQLMode.INSERT;
forms3 = new Tbl_SubmittedForms(4, 3, 11, "data/data/com.example.kyle.myapplication/3.docx", "3.docx", "3rd form", "02-23-2016 16:25:01");
forms3.sqlMode = Abstract_Table.SQLMode.INSERT;
forms4 = new Tbl_SubmittedForms(4, 2, 12, "data/data/com.example.kyle.myapplication/4.docx", "4.docx", "4th form", "02-23-2016 17:25:01");
forms4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyForms.add(forms1);
dummyForms.add(forms2);
dummyForms.add(forms3);
dummyForms.add(forms4);
Tbl_Incident incident3 = new Tbl_Incident("02-23-2016 14:25:01", "", "Fire at Wright State", "3640 Colonel Glenn Hwy", "Fairborn, OH 45342", "39.7815", "-84.0635983", dummyLinks, dummyForms);
incident3.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Incident_Manager.current.RecordOperation(incident3);
dummyLinks = new ArrayList<Tbl_IncidentLink>();
incidentLink1 = new Tbl_IncidentLink(4, 3, 4, 1);
incidentLink1.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink2 = new Tbl_IncidentLink(4, 4, 1, 2);
incidentLink2.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink3 = new Tbl_IncidentLink(4, 2, 2, 3);
incidentLink3.sqlMode = Abstract_Table.SQLMode.INSERT;
incidentLink4 = new Tbl_IncidentLink(4, 1, 3, 4);
incidentLink4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyLinks.add(incidentLink1);
dummyLinks.add(incidentLink2);
dummyLinks.add(incidentLink3);
dummyLinks.add(incidentLink4);
dummyForms = new ArrayList<Tbl_SubmittedForms>();
forms1 = new Tbl_SubmittedForms(4, 4, 13, "data/data/com.example.kyle.myapplication/1.docx", "1.docx", "1st form", "02-25-2016 19:06:45");
forms1.sqlMode = Abstract_Table.SQLMode.INSERT;
forms2 = new Tbl_SubmittedForms(4, 2, 14, "data/data/com.example.kyle.myapplication/2.docx", "2.docx", "2nd form", "02-25-2016 20:05:45");
forms2.sqlMode = Abstract_Table.SQLMode.INSERT;
forms3 = new Tbl_SubmittedForms(4, 1, 15, "data/data/com.example.kyle.myapplication/3.docx", "3.docx", "3rd form", "02-25-2016 21:05:45");
forms3.sqlMode = Abstract_Table.SQLMode.INSERT;
forms4 = new Tbl_SubmittedForms(4, 3, 16, "data/data/com.example.kyle.myapplication/4.docx", "4.docx", "4th form", "02-25-2016 22:05:45");
forms4.sqlMode = Abstract_Table.SQLMode.INSERT;
dummyForms.add(forms1);
dummyForms.add(forms2);
dummyForms.add(forms3);
dummyForms.add(forms4);
Tbl_Incident incident4 = new Tbl_Incident("02-25-2016 19:05:45", "", "Burglary at Wright State", "3640 Colonel Glenn Hwy", "Fairborn, OH 45342", "39.7815", "-84.0635983", dummyLinks, dummyForms);
incident4.sqlMode = Abstract_Table.SQLMode.INSERT;
Tbl_Incident_Manager.current.RecordOperation(incident4);
}
private void login()
{
Tbl_Personnel searchCriteria = new Tbl_Personnel();
searchCriteria.email = txtEmail.getText().toString();
searchCriteria.password = txtPassword.getText().toString();
// for dev purposes we will leave this empty
if (searchCriteria.email.isEmpty())
{
Toast.makeText(this, "E-mail address is required.", Toast.LENGTH_LONG).show();
}
else if (searchCriteria.password.isEmpty())
{
Toast.makeText(this, "Password is required.", Toast.LENGTH_LONG).show();
}
else
{
List<Tbl_Personnel> resultList = Tbl_Personnel_Manager.current.Select(searchCriteria);
//defaulted to true so you don't have to enter your username and password every time
//boolean isValid = true && resultList.size() > 0; //resultList.size() == 1;
boolean isValid = resultList.size() == 1;
if (isValid)
{
LoggedInUser.User = resultList.get(0);
OpenScreens.OpenMainScreen();
}
else
{
Toast.makeText(this, "Invalid E-mail address or password.", Toast.LENGTH_LONG).show();
}
}
}
}
|
/**
*
*/
package com.atlassian.tutorial.myweb.jira;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Bongjin Kwon
*
*/
@Controller
public class JiraRestProxyController {
//private HttpHost jiraHost = new HttpHost("localhost", 2990, "http");
private HttpHost jiraHost = new HttpHost("hhivaas_app01", 2990, "http");
private ObjectMapper om = new ObjectMapper();
@RequestMapping(value = {"/"}, method=RequestMethod.GET)
public String home() {
return "page.home";
}
@RequestMapping("/jira/rest/api/2/issue")
@ResponseBody
public String create(@RequestParam("pkey") String pkey, @RequestParam("summary") String summary, @RequestParam("desc") String desc, @RequestParam("itype") String itype ) throws Exception {
Issue issue = new Issue(pkey, summary, desc, itype);
String json = om.writeValueAsString(issue);
System.out.println(json);
HttpUriRequest httpreq = RequestBuilder.post()
.setUri(new URI(jiraHost.toURI() +"/jira/rest/api/2/issue"))
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setEntity(new StringEntity(json, "UTF-8")) // set json request body.
.build();
return callAPI(httpreq);
}
@RequestMapping("/jira/rest/api/2/search")
@ResponseBody
public String search(@RequestParam("jql") String jql ) throws Exception {
HttpUriRequest httpget = RequestBuilder.get()
.setUri(new URI(jiraHost.toURI() +"/jira/rest/api/2/search"))
.addParameter("jql", jql)
.build();
return callAPI(httpget);
}
private String callAPI(HttpUriRequest request) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(jiraHost.getHostName(), jiraHost.getPort()),
new UsernamePasswordCredentials("admin", "admin"));
AuthCache authCache = new BasicAuthCache();
authCache.put(jiraHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpClient httpclient = HttpClientBuilder.create().build();
System.out.println("Executing request " + request.getRequestLine());
HttpResponse response = httpclient.execute(request, context);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
String resJson = EntityUtils.toString(response.getEntity());
System.out.println(resJson);
return resJson;
}
}
|
package jire.event;
import static jire.Environment.environment;
import java.lang.reflect.Method;
public abstract class AbstractEventManager implements EventManager {
private final EventRegistry registry;
public AbstractEventManager(EventRegistry registry) {
this.registry = registry;
}
public AbstractEventManager() {
this(new EventRegistry());
}
protected final EventRegistry getRegistry() {
return registry;
}
@Override
@SuppressWarnings("unchecked")
public final void registerListener(EventListener listener) {
for (Method method : listener.getClass().getMethods()) {
if (method.isAnnotationPresent(EventHandler.class)
&& method.getParameterTypes().length == 1
&& Event.class
.isAssignableFrom(method.getParameterTypes()[0])) {
EventHandler eventHandler = method
.getAnnotation(EventHandler.class);
/*
* Unchecked cast suppressed because it is better to throw an
* exception, as it clearly signals something is wrong with the
* specified event handler.
*/
getRegistry().register(
(Class<? extends Event>) method.getParameterTypes()[0],
eventHandler.priority(),
eventHandler.ignoreCancelled(), method, listener);
}
}
environment.getEventManager().dispatchEvent(
new EventListenerRegisteredEvent(this, listener));
}
} |
package VotingInterface;
import Voting.VoteDBHandler;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Candidates extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Candidates frame = new Candidates(0);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Candidates(int id) {
final OpeningScreen os = new OpeningScreen();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final int ID = id;
JButton rdbtnNewRadioButton = new JButton("Squirtle");
rdbtnNewRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Yes, please", "No, thanks"};
int n = JOptionPane.showOptionDialog(contentPane,
"Are you sure?",
"A Follow-up Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
VoteDBHandler squirtle = new VoteDBHandler();
squirtle.saveVotes("squirtle", ID);
JOptionPane.showMessageDialog(contentPane, "Thank you For Voting!");
dispose();
os.setVisible(true);
} else if (n == JOptionPane.NO_OPTION) {
Candidates c = new Candidates(ID);
c.setVisible(true);
}
}
});
rdbtnNewRadioButton.setBounds(249, 79, 109, 23);
contentPane.add(rdbtnNewRadioButton);
JButton rdbtnNewRadioButton_1 = new JButton("Charmander");
rdbtnNewRadioButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Yes, please", "No, thanks"};
int n = JOptionPane.showOptionDialog(contentPane,
"Are you sure?",
"A Follow-up Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
VoteDBHandler squirtle = new VoteDBHandler();
squirtle.saveVotes("charmander", ID);
JOptionPane.showMessageDialog(contentPane, "Thank you For Voting!");
dispose();
os.setVisible(true);
} else if (n == JOptionPane.NO_OPTION) {
Candidates c = new Candidates(ID);
c.setVisible(true);
}
}
});
rdbtnNewRadioButton_1.setBounds(249, 114, 109, 23);
contentPane.add(rdbtnNewRadioButton_1);
JButton rdbtnNewRadioButton_2 = new JButton("Bulbasaur");
rdbtnNewRadioButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Yes, please", "No, thanks"};
int n = JOptionPane.showOptionDialog(contentPane,
"Are you sure?",
"A Follow-up Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
VoteDBHandler squirtle = new VoteDBHandler();
squirtle.saveVotes("bulbasaur", ID);
JOptionPane.showMessageDialog(contentPane, "Thank you For Voting!");
dispose();
os.setVisible(true);
} else if (n == JOptionPane.NO_OPTION) {
Candidates c = new Candidates(ID);
c.setVisible(true);
}
}
});
rdbtnNewRadioButton_2.setBounds(249, 149, 109, 23);
contentPane.add(rdbtnNewRadioButton_2);
JButton rdbtnNewRadioButton_3 = new JButton("Pikachu");
rdbtnNewRadioButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Yes, please", "No, thanks"};
int n = JOptionPane.showOptionDialog(contentPane,
"Are you sure?",
"A Follow-up Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
VoteDBHandler squirtle = new VoteDBHandler();
squirtle.saveVotes("pikachu", ID);
JOptionPane.showMessageDialog(contentPane, "Thank you For Voting!");
dispose();
os.setVisible(true);
} else if (n == JOptionPane.NO_OPTION) {
Candidates c = new Candidates(ID);
c.setVisible(true);
}
}
});
rdbtnNewRadioButton_3.setBounds(249, 184, 109, 23);
contentPane.add(rdbtnNewRadioButton_3);
JLabel lblDemocraticParty = new JLabel("Democratic Party");
lblDemocraticParty.setBounds(114, 81, 123, 16);
contentPane.add(lblDemocraticParty);
JLabel lblRepublicanParty = new JLabel("Republican Party");
lblRepublicanParty.setBounds(113, 116, 109, 16);
contentPane.add(lblRepublicanParty);
JLabel lblGreenParty = new JLabel("Green Party");
lblGreenParty.setBounds(114, 151, 108, 16);
contentPane.add(lblGreenParty);
JLabel lblLibertarianParty = new JLabel("Libertarian Party");
lblLibertarianParty.setBounds(114, 186, 108, 16);
contentPane.add(lblLibertarianParty);
JLabel lblSelectTheCandidate = new JLabel("Select the candidate you wish to vote for. ");
lblSelectTheCandidate.setBounds(128, 31, 230, 25);
contentPane.add(lblSelectTheCandidate);
JLabel lblYouWillHave = new JLabel("You will have a chance to change your decision");
lblYouWillHave.setBounds(114, 54, 230, 14);
contentPane.add(lblYouWillHave);
JLabel lblCandidateSelection = new JLabel("Candidate Selection");
lblCandidateSelection.setBounds(182, 11, 95, 14);
contentPane.add(lblCandidateSelection);
}
}
|
package ru.mikhaylov.controller;
import org.springframework.web.bind.annotation.*;
import ru.mikhaylov.model.User;
import ru.mikhaylov.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@Controller
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(value = "users/{page}", method = RequestMethod.GET)
public String showAllUsers( @PathVariable("page") int page, Model model){
model.addAttribute("user", new User());
model.addAttribute("listUsers", userService.listUsers(page-1));
return "users";
}
@RequestMapping(value = "SearchId/", method = RequestMethod.POST)
public String SearchId(@RequestParam("id") int id, Model model){
model.addAttribute("user", userService.getUserById(id));
return "SearchId";
}
@RequestMapping(value = "SearchName/", method = RequestMethod.POST)
public String SearchName(@RequestParam("name") String name, Model model){
if(this.userService.getUsersByName(name)!=null)
model.addAttribute("usersByName",userService.getUsersByName(name));
return "SearchName";
}
@RequestMapping("/remove/{id}")
public String removeUser(@PathVariable("id") int id){
userService.removeUser(id);
return "redirect:/users/1";
}
@RequestMapping("edit/{id}")
public String editUser(@PathVariable("id") int id, Model model){
model.addAttribute("user", userService.getUserById(id));
model.addAttribute("listUsers", userService.listUsers(1));
return "users";
}
@RequestMapping(value = "/users/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user){
this.userService.addUser(user);
return "redirect:/users/1";
}
}
|
package Loader;
import UI.Controller.DeviceController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class Loader extends Application {
public static boolean SHUTDOWN_ACTIVE = false;
@Override
public void start(Stage stage) throws Exception{
Thread.setDefaultUncaughtExceptionHandler(Loader::showErr);
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("root.fxml"));
Scene scene = new Scene(root, 1280, 720);
stage.setScene(scene);
stage.show();
}
@Override
public void stop(){
SHUTDOWN_ACTIVE = true;
System.out.println("Starting Shut Down");
try {
if(DeviceController.currentReader != null){
DeviceController.currentReader.closePort();
}
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Shut Down...");
}
private static void showErr(Thread t, Throwable e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error!");
alert.setHeaderText("Error Handler");
alert.setContentText(e.getMessage());
alert.showAndWait();
System.exit(-1);
}
public static void main(String[] args) {
launch();
}
} |
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sandy.user.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.sandy.infrastructure.jdbc.support.StatementParameter;
import com.sandy.infrastructure.util.PagingArraryList;
import com.sandy.infrastructure.util.PagingList;
import com.sandy.user.domain.Account;
/**
* account data access object
*
* @author Sandy
* @since 1.0.0 11th 10 2018
*/
@Repository("accountDao")
public class AccountDao extends AbstractDao<Account, Long> {
@Override
protected void initDao() throws Exception {
super.initDao();
this.tableName = "SYSTEM_USER";
}
@Override
public PagingList<Account> queryPageForList(Map<String, Object> criteria, Integer page, Integer pageSize) {
Long id = (Long) criteria.get("id");
StringBuilder sql = new StringBuilder("SELECT * FROM ").append(tableName);
StringBuilder sqlCount = new StringBuilder("SELECT COUNT(ID) FROM ").append(tableName);
StatementParameter param = new StatementParameter();
if(null != id) {
sql.append(" WHERE ID=? ");
param.setLong(id);
}
Integer total = queryForInt(sqlCount.toString(), param);
sql.append(" LIMIT ?,? ");
param.setInt((page -1) * pageSize );
param.setInt(pageSize);
List<Account> list = queryForList(sql.toString(), param, abstractModelClass);
PagingArraryList<Account> pageList = new PagingArraryList<Account>();
pageList.setPage(page);
pageList.setData(list);
pageList.setTotal(total);
return pageList;
}
/**
* query by mobile
* @param mobile
* @return system user
*/
public Account queryByMobile(String mobile) {
StringBuilder sql = new StringBuilder(" SELECT * FROM ").append(tableName).append(" WHERE MOBILE=?");
Object [] args = {mobile};
return queryForObject(sql.toString(), args, Account.class);
}
/**
* query by email
* @param email
* @return
*/
public Account queryByEmail(String email) {
StringBuilder sql = new StringBuilder(" SELECT * FROM ").append(tableName).append(" WHERE EMAIL=?");
Object [] args = {email};
return queryForObject(sql.toString(), args, Account.class);
}
/**
* query by user name
* @param userName
* @return
*/
public Account queryByUserName(String userName) {
StringBuilder sql = new StringBuilder(" SELECT * FROM ").append(tableName).append(" WHERE USER_NAME=?");
Object [] args = {userName};
return queryForObject(sql.toString(), args, Account.class);
}
}
|
package com.metoo.module.app.socket.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpSocketServer {
public static void main(String[] args) {
DatagramSocket ds = null;
DatagramPacket dp = null;
try {
// 1, 开放端口
ds = new DatagramSocket(1025);
// 2, 接收数据包
byte[] buf = new byte[1024];
dp = new DatagramPacket(buf, 0,buf.length);
try {
ds.receive(dp);
System.out.println(new String(dp.getData(), 0, dp.getLength()));
System.out.println(dp.getData().toString());
ds.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.wuyuan.android.activity;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kaixin.android.R;
import com.wuyuan.android.result.ConcurrentJobResult;
import com.wuyuan.android.utils.ActivityForResultUtil;
import com.wuyuan.android.utils.GetAddressUtil;
import com.wuyuan.android.utils.HttpPostParam;
import com.wuyuan.android.utils.SyncHttp;
public class WorkPubActivity extends Activity{
private Button mBack;
private EditText mTitle;
private EditText mSalary;
private EditText mLimitPerson;
private EditText mWorkTime;
private EditText mWorkPath;
private EditText mContractMan;
private EditText mContractPhone;
private EditText mContent;
private Button mSubmitBtn;
private String title;
private String Salary;
private String LimitPerson;
private String WorkTime;
private String WorkPath;
private String ContractMan;
private String ContractPhone;
private String Content;
private String LimitTime;
private String Imagepath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.work_pub);
findViewById();
setListener();
}
private void init() {
Imagepath = "/storage/emulated/0/Download/NASAEarth-01.jpg";
title = mTitle.getText().toString();
Salary = mSalary.getText().toString();
LimitPerson = mLimitPerson.getText().toString();
WorkTime = mWorkTime.getText().toString();
WorkPath = mWorkPath.getText().toString();
ContractMan = mContractMan.getText().toString();
ContractPhone = mContractPhone.getText().toString();
Content = mContent.getText().toString();
System.out.println(title+Salary);
}
private void findViewById() {
mBack = (Button) findViewById(R.id.work_pub_back);
mTitle = (EditText)findViewById(R.id.work_pub_title);
mSalary = (EditText)findViewById(R.id.work_pub_money);
mLimitPerson =(EditText)findViewById(R.id.work_pub_num);
mWorkTime =(EditText)findViewById(R.id.work_pub_worktime);
mWorkPath =(EditText)findViewById(R.id.work_pub_workpath);
mContractMan =(EditText)findViewById(R.id.work_pub_linkman);
mContractPhone =(EditText)findViewById(R.id.work_pub_phone);
mContent =(EditText)findViewById(R.id.work_pub_content);
mSubmitBtn =(Button)findViewById(R.id.work_pub_submit);
}
private void setListener() {
mBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 关闭当前界面
finish();
}
});
mSubmitBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
new PostWorkThread().start();
/*if(title.equals("")){
Toast.makeText(getApplicationContext(), "请输入标题", Toast.LENGTH_SHORT).show();
}else{
new PostWorkThread().start();
Toast.makeText(getApplicationContext(), "发表成功", Toast.LENGTH_SHORT).show();
}*/
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
class PostWorkThread extends Thread{
public void run(){
init();
System.out.println("count---------------->"+new ConcurrentJobResult().getCount());
DateFormat df1 = DateFormat.getDateInstance();
LimitTime = df1.format(new Date()).toString();
// Intent intent = getIntent();
// Bundle bundle = intent.getExtras();
// count = bundle.getInt("count") ;
ActivityForResultUtil.MYSQLCOUNTNUM = ActivityForResultUtil.MYSQLCOUNTNUM + 1;
Log.i("work--------------->ActivityForResultUtil.MYSQLCOUNTNUM", ActivityForResultUtil.MYSQLCOUNTNUM+"");
List <HttpPostParam> params = new ArrayList <HttpPostParam>();
params.add(new HttpPostParam("title", title));
params.add(new HttpPostParam("image", Imagepath));
params.add(new HttpPostParam("current_job_id",ActivityForResultUtil.MYSQLCOUNTNUM+""));
params.add(new HttpPostParam("Salary",Salary));
params.add(new HttpPostParam("limit_time",LimitTime));
params.add(new HttpPostParam("person_limit",LimitPerson));
params.add(new HttpPostParam("work_time",WorkTime));
params.add(new HttpPostParam("place",WorkPath));
params.add(new HttpPostParam("phone",ContractPhone));
params.add(new HttpPostParam("content",Content));
params.add(new HttpPostParam("contract_person",ContractMan));
SyncHttp http = new SyncHttp();
try
{
String rst = http.post(GetAddressUtil.WORK_PUBLIC, params);
System.out.println("result--------------->"+rst);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.beike.dao.film;
import java.util.List;
import com.beike.dao.GenericDao;
import com.beike.entity.film.Cinema;
import com.beike.entity.film.CinemaInfo;
import com.beike.entity.film.FilmShow;
import com.beike.page.Pager;
public interface CinemaDao extends GenericDao<Cinema, Long> {
/**
* 查询影院区域Id
* @param cityId
* @return
*/
public List<Long> queryCinemaAreaIdsByCity(Long cityId);
/**
* 查询影院详情
* @param cinemaId 影院ID
* @return
*/
public CinemaInfo queryCinemaDetail(Long cinemaId);
/**
* 按区域查询影院总数
* @param cityId
* @param areaId
* @param pager
* @return
*/
public int queryCinemaCount(Long cityId, Long areaId);
/**
* 查询影院正在上映的影片总数
* @param pager
* @param cinemaId
* @return
*/
public int queryShowFilmCountByCinema(Long cinemaId);
/**
* 按区域查询影院列表
* @param pager
* @param cityId
* @param areaId
* @return
*/
public List<CinemaInfo> queryCinema(Pager pager, Long cityId, Long areaId);
/**
* 按区域所有影院列表
* @param pager
* @param cityId
* @param areaId
* @return
*/
public List<CinemaInfo> queryCinema(Long cityId, Long areaId);
/**
* 查询影院下某影片的放映计划
* @param cinemaId
* @param filmId
* @return
*/
public List<FilmShow> queryFilmShowPlainByCinema(Long cinemaId,Long filmId);
public Long queryQianpinCinemaByWpId(Long cinemaId);
/**
* 查询一个影院是否是千品网影院
* @param cinemaId
* @return
*/
public boolean queryIsQianpinCinema(Long cinemaId);
}
|
package rafaxplayer.cheftools.Globalclasses.models;
public class Stock_Product {
private int ID;
private int stockId;
private int productoId;
private int cantidad;
private int formatoid;
private int categoriaid;
public Stock_Product() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getStockId() {
return stockId;
}
public void setStockId(int stockId) {
this.stockId = stockId;
}
public int getProductoId() {
return productoId;
}
public void setProductoId(int productoId) {
this.productoId = productoId;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public int getFormatoid() {
return formatoid;
}
public void setFormatoid(int formatoid) {
this.formatoid = formatoid;
}
public int getCategoriaid() {
return categoriaid;
}
public void setCategoriaid(int categoriaid) {
this.categoriaid = categoriaid;
}
}
|
package objects.transportsystem.transportsystems.vehicle.vehicles;
import objects.people.Person;
import objects.product.Product;
import objects.transportsystem.transportsystems.vehicle.Vehicle;
import org.apache.catalina.User;
import service.utility.OpsID;
import service.utility.UserInteractions;
import visualInterfaces.Constants;
import java.util.ArrayList;
public class Ambulance extends Vehicle {
/////////////////////////////////////////////////////ATTRIB/////////////////////////////////////////////////////////
private ArrayList<String> equipment;
private ArrayList<String> personal;
/////////////////////////////////////////////////////CONSTR/////////////////////////////////////////////////////////
public Ambulance(String transportId, String transportName, String status, int gasTank, String make, String model, ArrayList<String> equipment, ArrayList<String> personal) {
super(transportId, transportName, status, gasTank, make, model);
this.equipment = equipment;
this.personal = personal;
}
public Ambulance(ArrayList<String> equipment, ArrayList<String> personal) {
this.equipment = equipment;
this.personal = personal;
}
public Ambulance() {
}
/////////////////////////////////////////////////////METHOD/////////////////////////////////////////////////////////
public ArrayList<String> gatherInfo() {
return super.gatherInfo();
}
public ArrayList<ArrayList<String>> gatherListedInfo() {
ArrayList<ArrayList<String>> s = super.gatherListedInfo();
s.add(personal);
s.add(equipment);
return s;
}
public void modifyMe(ArrayList<String> atribMod) {
if (atribMod.contains("Equipamiento")|| atribMod.contains("*")) {
System.out.printf("Esta es la lista de equipamiento de la ambulancia");
this.setEquipment(UserInteractions.formIDList(this.equipment, "PR",Constants.equipmentLimitAMB));
for(String p : this.getEquipment()){
Product prod = (Product) OpsID.decodeID(p);
prod.setAreaId(this.getId());
}
}
if (atribMod.contains("Personal")|| atribMod.contains("*")) {
System.out.printf("Esta es la lista de personal de la ambulancia");
this.setPersonal(UserInteractions.formIDList(this.personal, "PEE", Constants.personellLimitAMB));
}
}
/////////////////////////////////////////////////////AUTOGEN////////////////////////////////////////////////////////
public ArrayList<String> getPersonal() {
return personal;
}
public void setPersonal(ArrayList<String> personal) {
this.personal = personal;
}
public ArrayList<String> getEquipment() {
return equipment;
}
public void setEquipment(ArrayList<String> equipment) {
this.equipment = equipment;
}
}
|
/*
* Copyright 2015 The RPC Project
*
* The RPC Project 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 io.flood.rpc.network;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.channel.ChannelHandlerContext;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
public abstract class MessageDispatcher<R> {
private final ExecutorService excutors = java.util.concurrent.Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat(
"message dispatcher proccess %d").build());
private final List<MessageEventListener> evnts=new ArrayList<MessageEventListener>();
public final void dispatchMessageEvent(final ChannelHandlerContext ctx, final NetPackage message) {
if(NetPackage.SYS_EVENT_POINT>message.command()){
broadcastEvent(ctx,message);
return;
}
excutors.execute(new Runnable() {
public void run() {
onMessage(ctx, message);
}
});
}
public void addMessageEventListener(MessageEventListener messageEventListener){
evnts.add(messageEventListener);
}
private void broadcastEvent(ChannelHandlerContext context,NetPackage message){
for (MessageEventListener evt:evnts) {
evt.onEvent(context,message);
}
}
public abstract void onMessage(ChannelHandlerContext ctx, NetPackage message);
}
|
package org.apache.cassandra.db.transaction;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ROTCohort {
private static Logger logger = LoggerFactory.getLogger(ROTCohort.class);
public static ConcurrentHashMap<Long, ROT_Timestamp> map = new ConcurrentHashMap<>();
public static void addTV(long id, long[] tv) {
if(map.contains(id)) {
ROT_Timestamp idts = map.get(id);
idts.tv = tv;
idts.cv.signal();
} else {
ROT_Timestamp new_idts = new ROT_Timestamp();
ROT_Timestamp idts = map.putIfAbsent(id, new_idts);
if(idts == null)
idts = new_idts;
idts.tv = tv;
idts.cv.signal();
}
}
public static long[] getTV(long id) throws InterruptedException, TimeoutException {
if(map.contains(id)) {
ROT_Timestamp idts = map.get(id);
idts.cv.await();
map.remove(id);
return idts.tv;
} else {
ROT_Timestamp new_idts = new ROT_Timestamp();
ROT_Timestamp idts = map.putIfAbsent(id, new_idts);
if(idts == null)
idts = new_idts;
boolean success = idts.cv.await(2, TimeUnit.SECONDS);
if(!success)
throw new TimeoutException("Cohort timed out waiting for coordinator for transaction " + id);
map.remove(id);
return idts.tv;
}
}
}
|
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws FileNotFoundException {
File f = new File("D:/Task text.txt");
Scanner sc=new Scanner(System.in);
sc=new Scanner(f);
String s[]=new String[1000000] ;
int i=0; int k=0; int d=0;
String s1; String s2="";
for(i=0; sc.hasNext(); i++ ){
s[i]=sc.nextLine();
if (!s[i].equals("")){
k++;
}
s2=s[i]+s2;
}
for (int j=1; j<s2.length(); j++){
char c=s2.charAt(j);
if (c==' ') {
d++;
}
}
if (d>0) {d--;
}
String [] words = s2.split(" ");
d=d-(words.length);
/*s1 = s2.replace(" "," ");
s1 = s2.replace(" "," ");
s1 = s2.replace(" "," ");*/
int l=s2.length()-d;
System.out.println("Symbols:"+l);
System.out.println("Words:"+words.length);
System.out.println("Lines:" + k);
sc.close();
}
}
|
package com.anger.service.userservice.exception;
/**
* Custom {@link RuntimeException} that handles 409 Conflict HTTP error codes.
*/
public class ConflictException extends RuntimeException {
public ConflictException() {
super("HTTP 409 Conflict");
}
public ConflictException(String message) {
super(message);
}
}
|
package com.example.paindairy.worker;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.example.paindairy.Dashboard;
import com.example.paindairy.R;
import com.example.paindairy.entity.PainRecord;
import com.example.paindairy.viewmodel.PainRecordViewModel;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.Gson;
import java.util.Date;
import java.util.Map;
/**
* Woker class
*/
public class PushPainRecordToFirebaseWorker extends Worker {
public PushPainRecordToFirebaseWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
storeDataToFirebase();
return Result.success();
}
/**
* Send data to server
*/
private void storeDataToFirebase() {
if (FirebaseAuth.getInstance().getCurrentUser() == null)
return;
Gson gson = new Gson();
String json = getApplicationContext().getSharedPreferences("sharedPreferencesDashboard", Context.MODE_PRIVATE).getString("painRecord", "");
PainRecord painRecord = gson.fromJson(json, PainRecord.class);
FirebaseDatabase.getInstance().getReference("PainRecords")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(String.valueOf(painRecord.uid))
.setValue(painRecord).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i("Info", "Inserted record to database at: " + new Date().toString());
displayNotification("Inserted", new Date().toString() );
}
else {
displayNotification("Data Insert Failed: ", new Date().toString() );
Log.i("Info", "Insertion failed");
}
}
});
}
/**
* Send Notification once data is inserted
* @param task
* @param desc
*/
private void displayNotification(String task, String desc) {
NotificationManager manger = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("painDairy", "PainDairy",NotificationManager.IMPORTANCE_DEFAULT );
manger.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "painDairy")
.setContentTitle(task)
.setContentText(desc)
.setSmallIcon(R.drawable.ic_health);
manger.notify(1, builder.build());
}
}
|
/**
* ${Project_Name}
* Created by ${USER}
* ${MONTH} ${YEAR}
*
* Software Development for Mobile Devices
* Metropolitan State University of Denver
* <p/>
*
*/
|
package servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import connection.LoginManager;
public class clerklogin extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
HttpSession session=request.getSession();
session.setAttribute("username",username);
String password = request.getParameter("password");
String login="";
login = LoginManager.ClerkLogin(username,password);
if(login!="fail")
{
session.setAttribute("clerkname",username);
session.setAttribute("clerkid",login);
response.sendRedirect("clerkhome.jsp?m1=success");
}
else{
response.sendRedirect("clerkLogin.jsp?s=fail");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.