text
stringlengths
10
2.72M
package org.spider.core; /** * @author liuxin * @version Id: SpiderHandler.java, v 0.1 2018/7/26 下午9:45 */ public interface SpiderHandler<T, D> { /** 需要开发者自己去实现的 **/ /** * @param htmlDefinition 当前url页面文档 * 返回将要持久化的实体类 * @return */ T doCrawl(HtmlDefinition<D> htmlDefinition,WillRequests willRequests); }
import java.io.*; import java.util.*; public class ReadMeGenerator { private static class Item implements Comparable { String name; String path; String original_path; String extension; Item(String path) { int slash_index = path.lastIndexOf("/"); int dot_index = path.lastIndexOf("."); this.name = path.substring(slash_index + 1, dot_index); this.extension = path.substring(dot_index + 1); this.original_path = path; this.path = path.replace("../", ""); } public String getName() { return name; } public String getPath() { return " [(" + this.extension + ")](./" + this.path + ")"; } public String getOriginalPath() { return " [(" + this.extension + ")](./" + this.original_path + ")"; } public String toString() { return getName() + getPath(); } public String toOriginalString() { return getName() + getOriginalPath(); } public int compareTo(Object o) { Item other = (Item) o; if (this.name.equals(other.name)) { return this.extension.compareTo(other.extension); } return this.name.compareTo(other.name); } } private static TreeMap<String, ArrayList<Item>> files_group_by_tags_map; // tag - Item of file private static TreeMap<String, ArrayList<String>> files_group_by_sources_map; // file name - url private static TreeMap<Integer, ArrayList<Item>> statisticURL; // count - url private static ArrayList<String> tags; private static String[] getFolderPaths() { String[] folder_paths = {"../Java/", "../C/", "../C++/", "../Python/"}; return folder_paths; } private static String getFilePath() { return "../README.md"; } private static ArrayList<String> getTags() throws Exception { tags = new ArrayList<>(); Scanner scanner = new Scanner(new File("tags.env")); while (scanner.hasNextLine()) { String tag = scanner.nextLine(); tags.add(tag); } ; scanner.close(); return tags; } private static String[] getHeader() { String[] header = { "# Problems-Solving", "My implementation of useful data structures, algorithms, as well as my solutions to" + " programming puzzles.", }; return header; } private static ArrayList<String> getStatistic() { // TODO: separated by difficulty (easy/medium/hard) TreeMap<String, Integer> source_count = new TreeMap<>(); int problems_number = 0; for (Map.Entry<String, ArrayList<String>> entry : files_group_by_sources_map.entrySet()) { HashSet<String> urls = new HashSet<>(); for (String url : entry.getValue()) { urls.add(url); } source_count.put(entry.getKey(), urls.size()); problems_number += urls.size(); } ArrayList<String> info = new ArrayList<>(); // list { info.add("```java"); info.add("Number of problems : " + problems_number); for (Map.Entry<String, Integer> entry : source_count.entrySet()) { info.add("- " + entry.getKey() + " : " + entry.getValue()); } info.add("```"); } // pie-chart { info.add("```mermaid"); info.add("pie"); info.add("\ttitle Category by sources"); for (Map.Entry<String, Integer> entry : source_count.entrySet()) { info.add("\t\"" + entry.getKey() + "\" : " + entry.getValue()); } info.add("```"); } return info; } private static ArrayList<String> getBody() { // body ArrayList<String> body = new ArrayList<>(); for (Map.Entry<String, ArrayList<Item>> entry : files_group_by_tags_map.entrySet()) { TreeMap<String, String> line_map = new TreeMap<>(); ArrayList<Item> items = entry.getValue(); Collections.sort(items); for (Item item : items) { if (line_map.containsKey(item.getName())) { line_map.put(item.getName(), line_map.get(item.getName()) + item.getPath()); } else { line_map.put(item.getName(), item.getPath()); } } // block header body.add("### " + entry.getKey() + " (" + line_map.size() + ")"); // block body String prefix = entry.getKey().equals("#todo") ? "- [ ] " : "- [x] "; for (Map.Entry<String, String> line_entry : line_map.entrySet()) { body.add(prefix + line_entry.getKey() + line_entry.getValue()); } } return body; } private static String getSource(String protocol, String url) { int url_idx = url.indexOf(protocol); int next_slash_idx = url.indexOf("/", url_idx + protocol.length()); return url.substring(url_idx + protocol.length(), next_slash_idx); } private static void init() throws Exception { // init statisticURL = new TreeMap<>(); files_group_by_tags_map = new TreeMap<>(); for (String tag : getTags()) { files_group_by_tags_map.put(tag, new ArrayList<>()); } files_group_by_sources_map = new TreeMap<>(); } private static void analyticFile(File fileEntry) throws Exception { int number_url = 0; Scanner scanner = new Scanner(fileEntry); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] words = line.split(" "); for (String word : words) { // by tags { if (files_group_by_tags_map.containsKey(word)) { files_group_by_tags_map.get(word).add(new Item(fileEntry.getPath())); } } // by sources { String source = ""; if (word.contains("http://")) { number_url++; source = getSource("http://", word); } else if (word.contains("https://")) { number_url++; source = getSource("https://", word); } if (!source.isEmpty()) { if (source.startsWith("www.")) { source = source.substring(4); } if (files_group_by_sources_map.containsKey(source)) { files_group_by_sources_map.get(source).add(word); } else { ArrayList<String> url = new ArrayList<>(); url.add(word); files_group_by_sources_map.put(source, url); } } } } } scanner.close(); // internal statistic if (statisticURL.containsKey(number_url)) { statisticURL.get(number_url).add(new Item(fileEntry.getPath())); } else { ArrayList<Item> url_list = new ArrayList<>(); url_list.add(new Item(fileEntry.getPath())); statisticURL.put(number_url, url_list); } } private static void internalAnalytics() throws Exception { FileWriter writer = new FileWriter("internal_analytics.md"); // 1/statistic by URL count String header = "# Statistic by URL count"; writer.write(header + System.lineSeparator()); for (Map.Entry<Integer, ArrayList<Item>> entry : statisticURL.entrySet()) { ArrayList<Item> urls = entry.getValue(); writer.write( "## URL count " + entry.getKey() + " (" + urls.size() + ") :" + System.lineSeparator()); Collections.sort(urls); for (Item url : urls) { writer.write("- " + url.toOriginalString() + System.lineSeparator()); } } writer.close(); } private static void analytics() throws Exception { for (String folder_path : getFolderPaths()) { final File folder = new File(folder_path); for (final File fileEntry : folder.listFiles()) { analyticFile(fileEntry); } } internalAnalytics(); } private static void flushToReadMe() throws Exception { FileWriter writer = new FileWriter(getFilePath()); // header for (String line : getHeader()) { writer.write(line + System.lineSeparator()); } // statistic for (String line : getStatistic()) { writer.write(line + System.lineSeparator()); } // body for (String line : getBody()) { writer.write(line + System.lineSeparator()); } writer.close(); } private static void generateReadMe() throws Exception { init(); analytics(); flushToReadMe(); } public static void main(String[] args) throws Exception { generateReadMe(); } }
package com.baiwang.custom.common.model; import java.util.List; public class FpdataModel { public String getInvoiceCode() { return InvoiceCode; } public void setInvoiceCode(String invoiceCode) { InvoiceCode = invoiceCode; } public String getRepeatMark() { return repeatMark; } public void setRepeatMark(String repeatMark) { this.repeatMark = repeatMark; } public String getInvoiceNumber() { return InvoiceNumber; } public void setInvoiceNumber(String invoiceNumber) { InvoiceNumber = invoiceNumber; } public String getInvoiceType() { return InvoiceType; } public void setInvoiceType(String invoiceType) { InvoiceType = invoiceType; } public String getBillingDate() { return BillingDate; } public void setBillingDate(String billingDate) { BillingDate = billingDate; } public String getBillingStatus() { return BillingStatus; } public void setBillingStatus(String billingStatus) { BillingStatus = billingStatus; } public String getCheckCode() { return CheckCode; } public void setCheckCode(String checkCode) { CheckCode = checkCode; } public String getSecureCode() { return SecureCode; } public void setSecureCode(String secureCode) { SecureCode = secureCode; } public String getMachineCode() { return MachineCode; } public void setMachineCode(String machineCode) { MachineCode = machineCode; } public String getTotalAmount() { return TotalAmount; } public void setTotalAmount(String totalAmount) { TotalAmount = totalAmount; } public String getTotalTax() { return TotalTax; } public void setTotalTax(String totalTax) { TotalTax = totalTax; } public String getAmountTax() { return AmountTax; } public void setAmountTax(String amountTax) { AmountTax = amountTax; } public String getPurchaserName() { return PurchaserName; } public void setPurchaserName(String purchaserName) { PurchaserName = purchaserName; } public String getPurchaserTaxNo() { return PurchaserTaxNo; } public void setPurchaserTaxNo(String purchaserTaxNo) { PurchaserTaxNo = purchaserTaxNo; } public String getPurchaserAddressPhone() { return PurchaserAddressPhone; } public void setPurchaserAddressPhone(String purchaserAddressPhone) { PurchaserAddressPhone = purchaserAddressPhone; } public String getPurchaserBank() { return PurchaserBank; } public void setPurchaserBank(String purchaserBank) { PurchaserBank = purchaserBank; } public String getSalesTaxNo() { return SalesTaxNo; } public void setSalesTaxNo(String salesTaxNo) { SalesTaxNo = salesTaxNo; } public String getSalesName() { return SalesName; } public void setSalesName(String salesName) { SalesName = salesName; } public String getSalesAddressPhone() { return SalesAddressPhone; } public void setSalesAddressPhone(String salesAddressPhone) { SalesAddressPhone = salesAddressPhone; } public String getSalesBank() { return SalesBank; } public void setSalesBank(String salesBank) { SalesBank = salesBank; } public String getSKR() { return SKR; } public void setSKR(String sKR) { SKR = sKR; } public String getFKR() { return FKR; } public void setFKR(String fKR) { FKR = fKR; } public String getKPR() { return KPR; } public void setKPR(String kPR) { KPR = kPR; } public String getRemark() { return Remark; } public void setRemark(String remark) { Remark = remark; } public String getCheckStatus() { return CheckStatus; } public void setCheckStatus(String checkStatus) { CheckStatus = checkStatus; } public String getCheckTime() { return CheckTime; } public void setCheckTime(String checkTime) { CheckTime = checkTime; } public List<FpmxlistModel> getMXENTRYS() { return MXENTRYS; } public void setMXENTRYS(List<FpmxlistModel> mXENTRYS) { MXENTRYS = mXENTRYS; } private String InvoiceCode; private String repeatMark; private String InvoiceNumber; private String InvoiceType; private String BillingDate; private String BillingStatus; private String CheckCode; private String SecureCode; private String MachineCode; private String TotalAmount; private String TotalTax; private String AmountTax; private String PurchaserName; private String PurchaserTaxNo; private String PurchaserAddressPhone; private String PurchaserBank; private String SalesTaxNo; private String SalesName; private String SalesAddressPhone; private String SalesBank; private String SKR; private String FKR; private String KPR; private String Remark; private String CheckStatus; private String CheckTime; private List<FpmxlistModel> MXENTRYS; }
package org.os.dbkernel.fdb.fdbtracemerger; import java.time.ZoneId; import java.util.Arrays; import java.util.Iterator; public abstract class AbstractParameters { protected abstract class AbstractParser { protected final Iterator<String> argsIter; protected AbstractParser(final Iterator<String> iter) { this.argsIter = iter; } private final void parse() { while (argsIter.hasNext()) { final String arg = argsIter.next(); if (arg.startsWith("-")) { consumeSwitch(arg.substring(1)); } else { consumeArg(arg); } } } abstract void consumeSwitch(final String sw); abstract void consumeArg(final String arg); protected String checkNext(final Object oldV, final String argName) { if (oldV != null) { throw new IllegalArgumentException("Duplicated switch " + argName); } if (! argsIter.hasNext()) { throw new IllegalArgumentException("No value of the " + argName + " switch"); } return argsIter.next(); } protected int checkNext(final int oldV, final String argName) { if (oldV > 0) { throw new IllegalArgumentException("Duplicated switch " + argName); } if (! argsIter.hasNext()) { throw new IllegalArgumentException("No value of the " + argName + " switch"); } final int newV = Integer.valueOf(argsIter.next()); if (newV <= 0) { throw new IllegalArgumentException("Invalid value of " + argName + " switch: " + newV); } return newV; } } public final void parseArgs(final String[] args) { parse(Arrays.asList(args).iterator()); } public final void parse(final Iterator<String> iter) { init(); getParser(iter).parse(); fillOther(); } abstract AbstractParser getParser(final Iterator<String> iter); abstract void init(); void fillOther() {} }
package kiki.AccountCal.Beta; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import kiki.AccountCal.Beta.TableAdapter.TableCell; import kiki.AccountCal.Beta.TableAdapter.TableRow; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** *KikiAccount *个人记账器 *内建SQLite数据库 * */ public class KikiAccountCalActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); paramsIni(); setListeners(); // setAdapter(); setDbAdapter(); } //Menu菜单 @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0,0,0,"统计"); menu.add(0,1,1,"设置"); menu.add(0,2,2,"退出"); menu.add(0,3,3,"关于"); return super.onCreateOptionsMenu(menu); } @SuppressLint({ "ParserError", "ParserError" }) @Override public boolean onOptionsItemSelected(MenuItem item) { //取得自定义对话框 LayoutInflater factory=LayoutInflater.from(KikiAccountCalActivity.this); final View aboutDialog=factory.inflate(R.layout.aboutdialog, null); // TODO Auto-generated method stub switch(item.getItemId()){ case 0: Intent intent=new Intent(); intent.setClass(KikiAccountCalActivity.this, Statistic.class); startActivity(intent); break; //统计表 case 1:break; //设置 case 2:KikiAccountCalActivity.this.finish(); break; //退出 case 3: Uri webpage=Uri.parse("http://evocrab.blog.163.com"); Intent mapIntent=new Intent(Intent.ACTION_VIEW,webpage); startActivity(mapIntent); break; /* Builder dialog=new AlertDialog.Builder(KikiAccountCalActivity.this) .setTitle("关于KikiAccount") //.setMessage("版本 1.0") //信息 //.setIcon() //图标 .setView(aboutDialog) ; dialog.show(); break; //关于 */ default:break; } return super.onOptionsItemSelected(item); } private Button IncomeCal; //新增收入按钮 private Button PaymentCal; //新增支出按钮 private double incomeSta; //收入合计 private double paymentSta; //支出合计 private TextView caculate; //统计项 private ListView itemList; //详细列表 //参数初始化 private void paramsIni(){ incomeSta=0; paymentSta=0; caculate=(TextView)findViewById(R.id.statistic); itemList=(ListView)findViewById(R.id.itemListView); String tmlStr="总收入:"+"总支出:"; caculate.setText(tmlStr); itemList.setAdapter(null); } //按钮监听 private void setListeners() { IncomeCal = (Button) findViewById(R.id.income); PaymentCal = (Button) findViewById(R.id.payment); IncomeCal.setOnClickListener(goIncome); PaymentCal.setOnClickListener(goPayment); } //新增收入按钮 private Button.OnClickListener goIncome = new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(KikiAccountCalActivity.this, IncomeCal.class); startActivity(intent); //KikiAccountCalActivity.this.finish(); } }; //新增支出按钮 private Button.OnClickListener goPayment = new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(KikiAccountCalActivity.this, PaymentCal.class); startActivity(intent); //KikiAccountCalActivity.this.finish(); } }; // ListDataBase private KikiDB DbAssistant; private Cursor mDbCursor; private void setDbAdapter() { DbAssistant = new KikiDB(this); DbAssistant.open(); fillData(); String tmlStr="总收入:"+incomeSta+"元"+" "+"总支出"+paymentSta+"元"; caculate.setText(tmlStr); } private void fillData() { //锁定只查询本月 Calendar timeZoneBegin=Calendar.getInstance(); timeZoneBegin.set(timeZoneBegin.get(Calendar.YEAR), timeZoneBegin.get(Calendar.MONTH), 1,0,0,0); Calendar timeZoneEnd=Calendar.getInstance(); timeZoneEnd.set(timeZoneEnd.get(Calendar.YEAR), timeZoneEnd.get(Calendar.MONTH)+1,1,0,0,0); // mDbCursor = DbAssistant.getAll(); //执行查询 mDbCursor=DbAssistant.getSomething(timeZoneBegin.getTime().getTime(), timeZoneEnd.getTime().getTime()); int rowCount=mDbCursor.getCount(); //行数 int colCount=mDbCursor.getColumnCount(); //列数 int viewCount=colCount-2; //要显示的列数 // 新表格 ArrayList<TableRow> table = new ArrayList<TableRow>(); int width=this.getWindowManager().getDefaultDisplay().getWidth()/(viewCount); //设定标题栏的默认宽度 //表格数据 for(int i=0;i<rowCount;i++){ //循环行 mDbCursor.moveToPosition(i); TableCell[] cells=new TableCell[viewCount]; int colView=0; int rowColor=0; //设定行的颜色 boolean inorout=true; for(int j=0;j<colCount;j++){ //循环列 switch(j){ case 0:break; //序列号抛弃 case 1: //关于日期显示 Date recDate=new Date(); recDate.setTime(Long.parseLong(mDbCursor.getString(j))); SimpleDateFormat dateFormat=new SimpleDateFormat("dd号HH点mm分"); String tmldate=dateFormat.format(recDate); // System.out.println(tmldate); cells[colView++]=new TableCell( tmldate, width, LayoutParams.FILL_PARENT, TableCell.STRING ); break; case 2: //类型进行行颜色判断 if(mDbCursor.getString(j).compareTo("income")>0){ rowColor=1; inorout=false; }else{ inorout=true; } break; case 4: //获取数额 if(inorout){ incomeSta+=Double.parseDouble(mDbCursor.getString(j)); }else{ paymentSta+=Double.parseDouble(mDbCursor.getString(j)); } default: cells[colView++]=new TableCell( mDbCursor.getString(j), //设置每个cells内容 width, LayoutParams.FILL_PARENT, TableCell.STRING ); break; } } table.add(new TableRow(cells,rowColor)); } //添加表格到view并绑定tableListView进行显示 TableAdapter tableAdapter=new TableAdapter(this,table); itemList.setAdapter(tableAdapter); } }
package team.groupproject.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.paypal.api.payments.Links; import com.paypal.api.payments.Payment; import com.paypal.base.rest.PayPalRESTException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.view.RedirectView; import team.groupproject.dto.OrderDto; import team.groupproject.model.MessageResponse; import team.groupproject.service.PaypalService; @RestController @RequestMapping("/api/paypal") @CrossOrigin public class PayPalController { @Autowired PaypalService service; public static final String SUCCESS_URL = "/pay/success"; public static final String CANCEL_URL = "/pay/cancel"; @PostMapping("/pay") public ResponseEntity<?> createPayment(@RequestBody OrderDto orderDto) { try { Payment payment = service.createPayment(orderDto.getPrice(), orderDto.getCurrency(), orderDto.getMethod(), orderDto.getIntent(), orderDto.getDescription(), "http://localhost:8080/api/paypal" + CANCEL_URL, "http://localhost:8080/api/paypal" + SUCCESS_URL); for (Links link : payment.getLinks()) { if (link.getRel().equals("approval_url")) { System.out.println(link.getHref()); return ResponseEntity.ok(new MessageResponse(link.getHref())); } } } catch (PayPalRESTException e) { e.printStackTrace(); } return ResponseEntity.ok(new MessageResponse("cancel.html")); } //pay pal sends these @GetMapping(value = CANCEL_URL) public RedirectView cancelPay() { return new RedirectView("http://127.0.0.1:5500/cancel.html"); } @GetMapping(value = SUCCESS_URL) public RedirectView successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) { try { Payment payment = service.executePayment(paymentId, payerId); if (payment.getState().equals("approved")) { return new RedirectView("http://localhost:3000/paypalsuccess"); } } catch (PayPalRESTException e) { System.out.println(e.getMessage()); } return new RedirectView("http://127.0.0.1:5500/dashboard.html"); } }
package io.nuls.consensus.constant; import java.math.BigInteger; /** * 共识模块常量类 * * @author tag * 2018/11/6 */ public interface ConsensusConstant { /** * DB config */ String DB_CONFIG_NAME = "db_config.properties"; String DB_DATA_PATH = "rocksdb.datapath"; String DB_DATA_DEFAULT_PATH = "rocksdb.datapath"; /** * Consensus module related table name/共识模块相关表名 */ String DB_NAME_AGENT = "agent"; String DB_NAME_APPEND_DEPOSIT = "append_agent_deposit"; String DB_NAME_REDUCE_DEPOSIT = "reduce_agent_deposit"; String DB_NAME_DEPOSIT = "deposit"; String DB_NAME_PUNISH = "punish"; String DB_NAME_CONFIG = "config"; String DB_NAME_STAKING_LIMIT = "staking_limit"; String DB_NAME_AWARD_SETTLE_RECORD = "award_settle_record"; String DB_NAME_RANDOM_SEEDS = "random_seed"; String DB_NAME_PUB_KEY = "pubKey"; String DB_NAME_AGENT_DEPOSIT_NONCE = "agent_deposit_nonce"; String DB_NAME_VIRTUAL_AGENT_CHANGE = "virtual_agent_change"; byte[] EMPTY_SEED = new byte[32]; /** * boot path */ String BOOT_PATH = "io.nuls,network.nerve"; /** * context path */ String CONTEXT_PATH = "io.nuls.pocbft"; /** * rpc file path */ String RPC_PATH = "network.nerve.pocbft.rpc"; /** * system params */ String SYS_FILE_ENCODING = "file.encoding"; /** * Load the block header of the last specified number of rounds during initialization * 初始化时加载最近指定轮数的惩罚信息 */ int INIT_PUNISH_OF_ROUND_COUNT = 2100; /** * 系统启动时缓存指定轮次的区块头 * Buffer a specified number of blocks at system startup */ int INIT_BLOCK_HEADER_COUNT = 2100; /** * 同一个出块地址1000轮内存在3轮发出两个相同高度,但不同hash的block,节点将会被红牌惩罚 */ byte REDPUNISH_BIFURCATION = 3; /** * 信誉值的最小值,小于等于该值会给红牌处罚 */ double RED_PUNISH_CREDIT_VAL = -1D; /** * 共识锁定时间 */ long CONSENSUS_LOCK_TIME = -1; /** * Map初始值 */ int INIT_CAPACITY_2 = 2; int INIT_CAPACITY_4 = 4; int INIT_CAPACITY_8 = 8; int INIT_CAPACITY_16 = 16; int INIT_CAPACITY_32 = 32; int INIT_CAPACITY_64 = 64; /** * 接口版本号 */ String RPC_VERSION = "1.0"; /** * 接口调用失败重试次数 */ int RPC_CALL_TRY_COUNT = 5; byte VALUE_OF_ONE_HUNDRED = 100; String SEPARATOR = "_"; String SEED_NODE_SEPARATOR = ","; /** * 解锁交易允许的最大时间差(S) */ long UNLOCK_TIME_DIFFERENCE_LIMIT = 600; byte VOTE_STAGE_ONE = 1; byte VOTE_STAGE_TWO = 2; /** * index */ long INIT_ROUND_INDEX = 2; String DATE_FORMAT = "yyyyMMdd"; String DEFALT_KEY = "NERVE_PRICE"; int ONE_DAY_SECONDS = 24 * 60 * 60; int ONE_DAY_MILLISECONDS = ONE_DAY_SECONDS * 1000; int HALF_DAY_MILLISECONDS = 12 * 60 * 60 * 1000; /** * 共识网络节点 正常出块最低比例常量60% */ int POC_NETWORK_NODE_PERCENT = 50; short POC_CONNECT_MAX_FAIL_TIMES = 100; String STACKING_CONFIG_FILE = "staking-asset"; }
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.common.utils.excel; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.thinkgem.jeesite.common.utils.Reflections; import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField; import com.thinkgem.jeesite.modules.sys.utils.DictUtils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion) * * @author ThinkGem * @version 2013-04-21 */ public class ExportExcel { private static Logger log = LoggerFactory.getLogger(ExportExcel.class); /** * 工作薄对象 */ private SXSSFWorkbook wb; /** * 工作表对象 */ private Sheet sheet; /** * 样式列表 */ private Map<String, CellStyle> styles; /** * 当前行号 */ private int rownum; /** * 注解列表(Object[]{ ExcelField, Field/Method }) */ List<Object[]> annotationList = Lists.newArrayList(); public List<Object[]> getAnnotationList() { return annotationList; } public void setAnnotationList(List<Object[]> annotationList) { this.annotationList = annotationList; } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param cls * 实体对象,通过annotation.ExportField获取标题 */ public ExportExcel(String title, Class<?> cls) { this(title, cls, 1); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param cls * 实体对象,通过annotation.ExportField获取标题 * @Param properties * 用户所选择的需要导出的列 */ public ExportExcel(String title, Class<?> cls,String[] properties) { this(title, cls, 1,properties); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param cls * 实体对象,通过annotation.ExportField获取标题 * @param type * 导出类型(1:导出数据;2:导出模板) */ public ExportExcel(String title, Class<?> cls, int type, String[] properties) { // Get annotation field Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { ExcelField ef = f.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == type)) { //如果f包含在properties中,则添加到annotationList中 for (String property :properties) { if (f.getName().equalsIgnoreCase(property)){ annotationList.add(new Object[] { ef, f }); } } } } // Get annotation method Method[] ms = cls.getDeclaredMethods(); for (Method m : ms) { ExcelField ef = m.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == type)) { for (String property :properties) { if (m.getName().equalsIgnoreCase(property)){ annotationList.add(new Object[] { ef, m }); } } } } // Field sorting Collections.sort(annotationList, new Comparator<Object[]>() { @Override public int compare(Object[] o1, Object[] o2) { return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort())); }; }); // Initialize List<String> headerList = Lists.newArrayList(); for (Object[] os : annotationList) { String t = ((ExcelField) os[0]).title(); // 如果是导出,则去掉注释 if (type == 1) { String[] ss = StringUtils.split(t, "**", 2); if (ss.length == 2) { t = ss[0]; } } headerList.add(t); } initialize(title, headerList); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param cls * 实体对象,通过annotation.ExportField获取标题 * @param type * 导出类型(1:导出数据;2:导出模板) * @param groups * 导入分组 */ public ExportExcel(String title, Class<?> cls, int type, int... groups) { // Get annotation field Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { ExcelField ef = f.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == type)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, f }); break; } } } } else { annotationList.add(new Object[] { ef, f }); } } } // Get annotation method Method[] ms = cls.getDeclaredMethods(); for (Method m : ms) { ExcelField ef = m.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == type)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, m }); break; } } } } else { annotationList.add(new Object[] { ef, m }); } } } // Field sorting Collections.sort(annotationList, new Comparator<Object[]>() { @Override public int compare(Object[] o1, Object[] o2) { return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort())); }; }); // Initialize List<String> headerList = Lists.newArrayList(); for (Object[] os : annotationList) { String t = ((ExcelField) os[0]).title(); // 如果是导出,则去掉注释 if (type == 1) { String[] ss = StringUtils.split(t, "**", 2); if (ss.length == 2) { t = ss[0]; } } headerList.add(t); } initialize(title, headerList); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param headers * 表头数组 */ public ExportExcel(String title, String[] headers) { initialize(title, Lists.newArrayList(headers)); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param jsonheaders * json表头 */ public ExportExcel(String title, String jsonheaders,int headlevel,int colsize) { initialize(title, jsonheaders,headlevel,colsize); } int createMulHeader(String jsontext,int excelrow,int excelcolumn,int headlevel) { int cellCountSum = 0; JSONArray jarr=JSONArray.fromObject(jsontext); JSONObject jobj=null; int rowcount = 0; int colnum=0; int cellCount=0; Row headerRow=sheet.getRow(excelrow-1); for(int i=0;i<jarr.size();i++)//遍历子集 { jobj=JSONObject.fromObject(jarr.get(i)); if(jobj.containsKey("subnode")) { rowcount=0; cellCount=createMulHeader(jobj.get("subnode").toString(),excelrow+1,excelcolumn,headlevel); } else { rowcount = headlevel-excelrow+1; cellCount=1; } System.out.println(excelcolumn+":"+headerRow+":"+excelrow+":"+rownum); Cell cell =headerRow.createCell(excelcolumn-1); cell.setCellValue(jobj.get("nodename").toString()); if((excelrow+rowcount-1-(excelrow-1))>0||(excelcolumn+cellCount-2-(excelcolumn-1))>0) { sheet.addMergedRegion(new CellRangeAddress(excelrow-1, excelrow+rowcount-1, excelcolumn-1,excelcolumn+cellCount-2)); } System.out.println(jobj.get("nodename")+":"+(excelrow-1)+":"+(excelrow+rowcount-1)+":"+(excelcolumn-1)+":"+(excelcolumn+cellCount-2)); sheet.autoSizeColumn(colnum); cellCountSum+=cellCount; excelcolumn+=cellCount; } return cellCountSum; } /** * 初始化函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param headerList * 表头列表 */ private void initialize(String title, String jsontext,int headlevel,int colsize) { wb = new SXSSFWorkbook(500); sheet = wb.createSheet("Export"); styles = createStyles(wb); if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), colsize-1)); } int nowrowunm=rownum; for(int i=0;i<headlevel;i++) { System.out.println("create row "+i); sheet.createRow(rownum++); } createMulHeader(jsontext,nowrowunm+1,1,headlevel); for (int i = 0; i < colsize; i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth > 4000 ? 4000 : colWidth); } log.debug("Initialize success11."); } /** * 构造函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param headerList * 表头列表 */ public ExportExcel(String title, List<String> headerList) { initialize(title, headerList); } /** * 初始化函数 * * @param title * 表格标题,传“空值”,表示无标题 * @param headerList * 表头列表 */ private void initialize(String title, List<String> headerList) { wb = new SXSSFWorkbook(500); sheet = wb.createSheet("Export"); styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1)); } if (headerList == null) { throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length == 2) { cell.setCellValue(ss[0]); Comment comment = sheet.createDrawingPatriarch().createCellComment( new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); } else { cell.setCellValue(headerList.get(i)); } sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth > 4000 ? 4000 : colWidth); } log.debug("Initialize success11."); } /** * 创建表格样式 * * @param wb * 工作薄对象 * @return 样式列表 */ private Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); CellStyle style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); Font titleFont = wb.createFont(); titleFont.setFontName("Arial"); titleFont.setFontHeightInPoints((short) 16); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(titleFont); styles.put("title", style); style = wb.createCellStyle(); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); Font dataFont = wb.createFont(); dataFont.setFontName("Arial"); dataFont.setFontHeightInPoints((short) 10); style.setFont(dataFont); styles.put("data", style); style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); style.setAlignment(CellStyle.ALIGN_LEFT); styles.put("data1", style); style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); style.setAlignment(CellStyle.ALIGN_CENTER); styles.put("data2", style); style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); style.setAlignment(CellStyle.ALIGN_RIGHT); styles.put("data3", style); style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); // style.setWrapText(true); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); Font headerFont = wb.createFont(); headerFont.setFontName("Arial"); headerFont.setFontHeightInPoints((short) 10); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerFont.setColor(IndexedColors.WHITE.getIndex()); style.setFont(headerFont); styles.put("header", style); return styles; } /** * 添加一行 * * @return 行对象 */ public Row addRow() { return sheet.createRow(rownum++); } /** * 添加一个单元格 * * @param row * 添加的行 * @param column * 添加列号 * @param val * 添加值 * @return 单元格对象 */ public Cell addCell(Row row, int column, Object val) { return this.addCell(row, column, val, 0, Class.class); } /** * 添加一个单元格 * * @param row * 添加的行 * @param column * 添加列号 * @param val * 添加值 * @param align * 对齐方式(1:靠左;2:居中;3:靠右) * @return 单元格对象 */ public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) { Cell cell = row.createCell(column); String cellvalue = ""; CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : "")); DataFormat format = wb.createDataFormat(); CellStyle style1 = styles.get("data" + (align >= 1 && align <= 3 ? align : "")); style1.setDataFormat(format.getFormat("yyyy-MM-dd")); try { if (val == null) { cell.setCellValue(""); } else if (val instanceof String) { cellvalue = val.toString(); /*if(StringUtils.isNoneBlank(cellvalue)) { cellvalue=cellvalue.trim(); if(cellvalue.length()>50) cellvalue=cellvalue.substring(0, 50); }*/ cell.setCellValue(cellvalue); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); } else if (val instanceof Long) { cell.setCellValue((Long) val); } else if (val instanceof Double) { cell.setCellValue((Double) val); } else if (val instanceof Float) { cell.setCellValue(val.toString()); } else if (val instanceof Number) { cell.setCellValue(((Number) val).doubleValue()); } else if (val instanceof Date) { cell.setCellValue((Date) val); cell.setCellStyle(style1); } else { if (fieldType != Class.class) { cellvalue = (String) fieldType.getMethod("setValue", Object.class).invoke(null, val); /* if(StringUtils.isNoneBlank(cellvalue)) { cellvalue=cellvalue.trim(); if(cellvalue.length()>50) cellvalue=cellvalue.substring(0, 50); }*/ cell.setCellValue(cellvalue); } else { cellvalue = (String) Class .forName( this.getClass() .getName() .replaceAll(this.getClass().getSimpleName(), "fieldtype." + val.getClass().getSimpleName() + "Type")) .getMethod("setValue", Object.class).invoke(null, val); /* if(StringUtils.isNoneBlank(cellvalue)) { cellvalue=cellvalue.trim(); if(cellvalue.length()>50) cellvalue=cellvalue.substring(0, 50); }*/ cell.setCellValue(cellvalue); } } } catch (Exception ex) { log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString()); cell.setCellValue(val.toString()); if (val instanceof Date) { cell.setCellStyle(style1); } else { cell.setCellStyle(style); } } return cell; } /** * 添加数据(通过annotation.ExportField添加数据) * * @return list 数据列表 */ public <E> ExportExcel setDataList(List<E> list) { for (E e : list) { int colunm = 0; Row row = addRow(); StringBuilder sb = new StringBuilder(); for (Object[] os : annotationList) { ExcelField ef = (ExcelField) os[0]; Object val = null; // Get entity value try { if (StringUtils.isNotBlank(ef.value())) { val = Reflections.invokeGetter(e, ef.value()); } else { if (os[1] instanceof Field) { val = Reflections.invokeGetter(e, ((Field) os[1]).getName()); } else if (os[1] instanceof Method) { val = Reflections.invokeMethod(e, ((Method) os[1]).getName(), new Class[] {}, new Object[] {}); } } // If is dict, get dict label if (StringUtils.isNotBlank(ef.dictType())) { val = DictUtils.getDictLabel(val == null ? "" : val.toString(), ef.dictType(), ""); } } catch (Exception ex) { // Failure to ignore log.info(ex.toString()); val = ""; } // log.debug(val.toString()+":error:"); this.addCell(row, colunm++, val, ef.align(), ef.fieldType()); sb.append(val + ", "); } // log.debug("Write success: [" + row.getRowNum() + "] " + sb.toString()); } return this; } /** * 添加数据 * dataList=[{column_5=测试, column_6=测试1, column_1=S20153131236, column_2=2, column_3=测试, column_4=测试, column_0=于梦佳}, {column_5=测试2, column_6=测试2, column_1=S20153131240, column_2=2, column_3=测试2, column_4=测试2, column_0=周田田}] * 该方法只针对于自动生成的表有用,数据格式如上 * @return ExportExcel 数据列表 */ public ExportExcel setDataList(List<HashMap<String,String>> list,int columnSize) { for (HashMap<String,String> map : list) { int colunm = 0; Row row = addRow(); StringBuilder sb = new StringBuilder(); for(int i = 0;i<columnSize;i++){ this.addCell(row, colunm++, map.get("column_"+i), 2, null); sb.append(map.get("column_"+i)+", "); } } return this; } /** * 添加数据 * dataList=[{column_5=测试, column_6=测试1, column_1=S20153131236, column_2=2, column_3=测试, column_4=测试, column_0=于梦佳}, {column_5=测试2, column_6=测试2, column_1=S20153131240, column_2=2, column_3=测试2, column_4=测试2, column_0=周田田}] * 该方法只针对于自动生成的表有用,数据格式如上 * @return ExportExcel 数据列表 */ public ExportExcel setDataList(List<HashMap<String,Object>> list,String[] colheader,Boolean ismer,Boolean[] colmer,int[] rowspan) { if(!ismer)//不需要合并单元格 { for (HashMap<String, Object> map : list) { int colunm = 0; Row row = addRow(); for(int i = 0;i<colheader.length;i++) { this.addCell(row, colunm++, map.get(colheader[i]), 2, null); } } } if(ismer)//需要合并单元格 { int frow=rownum,lrow=0; int rowindex=rownum; int rownumt=0; for(int i=0;i<list.size();i++) addRow(); for (HashMap<String, Object> map : list) { int colunm = 0; Row row=this.getSheet().getRow(rowindex++);//获得当前列 for(int i = 0;i<colheader.length;i++)//列 { if(colmer[i])//该列合并 { if(rowspan[rownumt]>0) { lrow=frow+rowspan[rownumt]-1; this.sheet.addMergedRegion(new CellRangeAddress(frow,lrow,colunm,colunm)); System.out.println(rownumt+":"+frow+":"+lrow+":"+colunm+":"+map.get(colheader[i])); try { this.addCell(row, colunm, map.get(colheader[i]), 2, null); }catch(Exception ex){} } colunm++; } else//非合并列 this.addCell(row, colunm++, map.get(colheader[i]), 2, null); } frow++; rownumt++; } } return this; } /** * 添加数据 * dataList=[{column_5=测试, column_6=测试1, column_1=S20153131236, column_2=2, column_3=测试, column_4=测试, column_0=于梦佳}, {column_5=测试2, column_6=测试2, column_1=S20153131240, column_2=2, column_3=测试2, column_4=测试2, column_0=周田田}] * 该方法只针对于自动生成的表有用,数据格式如上 * @return ExportExcel 数据列表 */ /** * 输出数据流 * * @param os * 输出数据流 */ public ExportExcel write(OutputStream os) throws IOException { wb.write(os); return this; } /** * 输出到客户端 * * @param fileName * 输出文件名 */ public ExportExcel write(HttpServletResponse response, String fileName) throws IOException { response.reset(); response.setContentType("application/octet-stream; charset=utf-8"); //response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName)); response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "ISO-8859-1")); write(response.getOutputStream()); return this; } /** * 输出到文件 * * @param fileName * 输出文件名 */ public ExportExcel writeFile(String name) throws FileNotFoundException, IOException { FileOutputStream os = new FileOutputStream(name); this.write(os); return this; } /** * 清理临时文件 */ public ExportExcel dispose() { wb.dispose(); return this; } public Sheet getSheet() { return sheet; } // /** // * 导出测试 // */ // public static void main(String[] args) throws Throwable { // // List<String> headerList = Lists.newArrayList(); // for (int i = 1; i <= 10; i++) { // headerList.add("表头"+i); // } // // List<String> dataRowList = Lists.newArrayList(); // for (int i = 1; i <= headerList.size(); i++) { // dataRowList.add("数据"+i); // } // // List<List<String>> dataList = Lists.newArrayList(); // for (int i = 1; i <=1000000; i++) { // dataList.add(dataRowList); // } // // ExportExcel ee = new ExportExcel("表格标题", headerList); // // for (int i = 0; i < dataList.size(); i++) { // Row row = ee.addRow(); // for (int j = 0; j < dataList.get(i).size(); j++) { // ee.addCell(row, j, dataList.get(i).get(j)); // } // } // // ee.writeFile("target/export.xlsx"); // // ee.dispose(); // // log.debug("Export success."); // // } /** * 添加数据 * dataList=[{column_5=测试, column_6=测试1, column_1=S20153131236, column_2=2, column_3=测试, column_4=测试, column_0=于梦佳}, {column_5=测试2, column_6=测试2, column_1=S20153131240, column_2=2, column_3=测试2, column_4=测试2, column_0=周田田}] * 该方法只针对于自动生成的表有用,数据格式如上 * @return ExportExcel 数据列表 */ public ExportExcel setDataList(List<HashMap<String,Object>> list,String[] colheader,Boolean ismer,Boolean[] colmer,int[][] rowspan) { if(!ismer)//不需要合并单元格 { for (HashMap<String, Object> map : list) { int colunm = 0; Row row = addRow(); for(int i = 0;i<colheader.length;i++) { this.addCell(row, colunm++, map.get(colheader[i]), 2, null); } } } if(ismer)//需要合并单元格 { int frow=rownum,lrow=0; int rowindex=rownum; int rownumt=0; for(int i=0;i<list.size();i++){ addRow(); } for (HashMap<String, Object> map : list){ int colunm = 0; Row row=this.getSheet().getRow(rowindex++);//获得当前列 for(int i = 0;i<colheader.length;i++){//列 if(colmer[i]){//该列合并 if(rowspan[i][rownumt]>0){ lrow=frow+rowspan[i][rownumt]-1; this.sheet.addMergedRegion(new CellRangeAddress(frow,lrow,colunm,colunm)); System.out.println(rownumt+":"+frow+":"+lrow+":"+colunm+":"+map.get(colheader[i])); try { this.addCell(row, colunm, map.get(colheader[i]), 2, null); }catch(Exception ex){} } colunm++; }else//非合并列 this.addCell(row, colunm++, map.get(colheader[i]), 2, null); } frow++; rownumt++; } } return this; } }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.sl.usermodel.Sheet; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Workbook; import org.openqa.selenium.By; public class Excel4Read { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File("F:\\INPUTSHEET.xls"); FileInputStream inputStream = new FileInputStream(file); Workbook Workbook = null; Workbook = new HSSFWorkbook(inputStream); org.apache.poi.ss.usermodel.Sheet sht = Workbook.getSheetAt(0); System.out.println(Workbook.getSheetAt(0).getSheetName()); int rowCount = sht.getLastRowNum()-sht.getFirstRowNum(); System.out.println(rowCount); /*String text = sht.getRow(1).getCell(1).getStringCellValue(); String text2 = sht.getRow(1).getCell(0).getStringCellValue(); System.out.println(text); System.out.println(text2);*/ /*String baseurl = sht.getRow(1).getCell(0).getStringCellValue(); System.out.println(baseurl);*/ /*String Passangers = sht.getRow(1).getCell(3).getStringCellValue(); System.out.println(Passangers);*/ String DepartingFrom = sht.getRow(1).getCell(4).getStringCellValue(); //driver.findElement(By.name("fromPort")).sendKeys(DepartingFrom); System.out.println(DepartingFrom); int rowcount = sht.getLastRowNum()-sht.getFirstRowNum(); Iterator<Row> colcount = sht.rowIterator(); System.out.println(colcount); for(int i=0; i<=rowcount; i++) { Row row = sht.getRow(i); String baseurl = row.getCell(i).getStringCellValue(); System.out.println(baseurl); for(int j=1; j<=10; j++) { String UN = row.getCell(i).getStringCellValue(); String PW = row.getCell(i).getStringCellValue(); System.out.println(UN); System.out.println(PW); } } /*int Passangers = (int) sht.getRow(1).getCell(3).getNumericCellValue(); //driver.findElement(By.name("passCount")).getText(); System.out.println(Passangers); /*for(int i=1;i<=rowCount;i++) { Row row = sht.getRow(i); String UN = row.getCell(0).getStringCellValue(); String PW = row.getCell(1).getStringCellValue(); System.out.println(UN); System.out.println(PW); Cell cell = row.createCell(2); cell.setCellValue(UN+" "+PW); Cell cell2 = row.createCell(3); cell2.setCellValue(UN+" "+PW); } /*inputStream.close(); //Create an object of FileOutputStream class to create write data in excel file FileOutputStream outputStream = new FileOutputStream("F:\\Outputsheet.xls"); //write data in the excel file Workbook.write(outputStream); //Close output stream outputStream.close();*/ } }
package com.cheese.radio; import java.util.List; public class JsonEntity { }
package com.esum.framework.jdbc; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import junit.framework.TestCase; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.log4j.PropertyConfigurator; import com.esum.framework.common.util.SysUtil; import com.esum.framework.core.config.Configurator; import com.esum.framework.jdbc.datasource.DataSourceManager; import com.esum.framework.jdbc.datasource.JdbcDataSource; import com.esum.framework.jdbc.support.JdbcUtils; import com.esum.framework.jdbc.support.SQLConstants; public class JdbcDataSourceTest extends TestCase { public void setUp() throws Exception { System.setProperty("xtrus.home", "d:/test/xtrus-4.4.1"); Configurator.init(Configurator.DEFAULT_DB_PROPERTIES_ID, SysUtil.replacePropertyToValue("${xtrus.home}/conf/db.properties")); PropertyConfigurator.configure(System.getProperty("xtrus.home")+"/conf/log.properties"); } public void testGetDataSource() throws Exception { JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource(); assertNotNull(jds); assertNotNull(jds.getDataSource()); assertEquals(SQLConstants.DB_NAME_SYBASE, JdbcUtils.commonDatabaseName(jds.getConnection())); } public void testGetConnection() throws Exception { JdbcDataSource jds = DataSourceManager.getInstance().createDefaultDataSource(); Connection conn = jds.getConnection(); assertNotNull(conn); DataSource ds = jds.getDataSource(); if(ds instanceof BasicDataSource) { } JdbcUtils.closeQuietly(conn); } public void testLoadMultipleDataSource() throws Exception { Configurator.init("test.config", SysUtil.replacePropertyToValue("${xtrus.home}/conf/db.properties")); class DSThread extends Thread { public void run() { Connection conn = null; try { JdbcDataSource jds = DataSourceManager.getInstance().createDataSourceById("test.config"); conn = jds.getConnection(); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { } } } } for(int i=0;i<5;i++) { DSThread t = new DSThread(); t.start(); } Thread.sleep(5*1000); } }
package com.tweetapp.entities; import java.util.List; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Document(collection = "users") @Data @AllArgsConstructor @NoArgsConstructor //@IdClass(UsersEntityId.class) public class UsersEntity { @Id private ObjectId objectId; private String loginId; private String firstName; private String lastName; private String emailId; private String password; private String contactNumber; private Boolean loggedIn; private List<String> roles; }
//accept book publisher all details calculate and ditels import java.util.*; class book_publishar { public static void main(String args[]) { double rate=0.0; double dis=0.0,pay=0.0,vat=0.0,net=0.0; boolean flag=true; String pname=""; Scanner x=new Scanner(System.in); System.out.print("Enter mrp of given book:-"); double mrp=x.nextDouble(); if(mrp>0){ System.out.print("Enter Publisher name as BPB.TMH.VEENUS:-"); pname=x.nextLine(); pname=x.nextLine(); if(pname.equalsIgnoreCase("BPB")) rate=30.0; else if(pname.equalsIgnoreCase("TMH")) rate=20.0; else if(pname.equalsIgnoreCase("VEENUS")) rate=25.0; else { flag=false; System.out.println("Invalied publisher name found Plz enter agan:"); } } else{ flag=false; System.out.print("Invaled Mrp found Plz enter agan"); } if(flag) { dis=mrp*rate/100; pay=mrp-dis; vat=pay*12/100; net=pay+vat; System.out.println("***************Bill*********************"); System.out.println("Publisher name as TMH,BPB,VEENUS:- "+pname); System.out.println("Publisher M.R.P IN RS:- "+mrp); System.out.println("Dicount slab in persentege:- "+rate+"%"); System.out.println("Dicount amount in Rs:- "+dis); System.out.println("=========================================="); System.out.println("Payble Amount in Rs:- "+pay); System.out.println("12% Vat in Rs:- "+vat); System.out.println("=========================================="); System.out.println("Net Bill amount in Rs:- "+net); System.out.println("*******************************************"); } }//close of main }//close of class
package com.design.pattern.visitor; /** * @Author: 98050 * @Time: 2019-01-21 22:12 * @Feature: */ public class Test { public static void main(String[] args) { ComputerPart computer = new Computer(); computer.accept(new ComputerPartVisitorImpl()); } }
package com.xianzaishi.wms.tmscore.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.xianzaishi.wms.tmscore.manage.itf.IPickDetailManage; import com.xianzaishi.wms.tmscore.service.itf.IPickDetailService; import com.xianzaishi.wms.tmscore.vo.PickDetailQueryVO; import com.xianzaishi.wms.tmscore.vo.PickDetailVO; public class PickDetailServiceImpl implements IPickDetailService { @Autowired private IPickDetailManage pickDetailManage = null; public IPickDetailManage getPickDetailManage() { return pickDetailManage; } public void setPickDetailManage(IPickDetailManage pickDetailManage) { this.pickDetailManage = pickDetailManage; } public Boolean addPickDetailVO(PickDetailVO pickDetailVO) { pickDetailManage.addPickDetailVO(pickDetailVO); return true; } public List<PickDetailVO> queryPickDetailVOList( PickDetailQueryVO pickDetailQueryVO) { return pickDetailManage.queryPickDetailVOList(pickDetailQueryVO); } public PickDetailVO getPickDetailVOByID(Long id) { return (PickDetailVO) pickDetailManage.getPickDetailVOByID(id); } public Boolean modifyPickDetailVO(PickDetailVO pickDetailVO) { return pickDetailManage.modifyPickDetailVO(pickDetailVO); } public Boolean deletePickDetailVOByID(Long id) { return pickDetailManage.deletePickDetailVOByID(id); } public List<PickDetailVO> getPickDetailVOByPickID(Long id) { return pickDetailManage.getPickDetailVOByOutgoingID(id); } public Boolean batchAddPickDetailVO(List<PickDetailVO> pickDetailVOs) { return pickDetailManage.batchAddPickDetailVO(pickDetailVOs); } public Boolean batchModifyPickDetailVO(List<PickDetailVO> pickDetailVOs) { return pickDetailManage.batchModifyPickDetailVO(pickDetailVOs); } public Boolean batchDeletePickDetailVO(List<PickDetailVO> pickDetailVOs) { return pickDetailManage.batchDeletePickDetailVO(pickDetailVOs); } public Boolean batchDeletePickDetailVOByID(List<Long> storyDetailIDs) { return pickDetailManage.batchDeletePickDetailVOByID(storyDetailIDs); } }
package com.hello.suripu.service.pairing.sense; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.hello.suripu.core.db.DeviceDAO; import com.hello.suripu.core.models.DeviceAccountPair; import com.hello.suripu.core.swap.Intent; import com.hello.suripu.core.swap.Result; import com.hello.suripu.core.swap.Swapper; import com.hello.suripu.service.pairing.PairState; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SensePairStateEvaluatorTest { private SensePairStateEvaluator evaluator; private DeviceDAO deviceDAO; private Swapper swapper; @Before public void setUp() { this.deviceDAO = mock(DeviceDAO.class); this.swapper = mock(Swapper.class); this.evaluator = new SensePairStateEvaluator(deviceDAO, swapper); } @Test public void testNotPaired() { final SensePairingRequest request = SensePairingRequest.create(99L, "abc"); final ImmutableList<DeviceAccountPair> empty = ImmutableList.copyOf(new ArrayList<DeviceAccountPair>()); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(empty); Assert.assertEquals(PairState.NOT_PAIRED, evaluator.getSensePairingState(request)); } @Test public void testPairedSameAccount() { final SensePairingRequest request = SensePairingRequest.create(99L, "abc"); final DeviceAccountPair pair = new DeviceAccountPair( request.accountId(), 0L, request.senseId(), DateTime.now(DateTimeZone.UTC) ); final ImmutableList<DeviceAccountPair> senses = ImmutableList.copyOf(Lists.newArrayList(pair)); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(senses); assertEquals(PairState.PAIRED_WITH_CURRENT_ACCOUNT, evaluator.getSensePairingState(request)); } @Test public void testUserIsPairedToDifferentSense() { final SensePairingRequest request = SensePairingRequest.create(99L, "abc"); final DeviceAccountPair pair = new DeviceAccountPair( request.accountId(), 0L, "different_sense", DateTime.now(DateTimeZone.UTC) ); final ImmutableList<DeviceAccountPair> senses = ImmutableList.copyOf(Lists.newArrayList(pair)); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(senses); assertEquals(PairState.PAIRING_VIOLATION, evaluator.getSensePairingState(request)); } @Test public void testUserIsPairedToMulitpleSense() { final SensePairingRequest request = SensePairingRequest.create(99L, "abc"); final DeviceAccountPair pair = new DeviceAccountPair( request.accountId(), 0L, "different_sense", DateTime.now(DateTimeZone.UTC) ); final ImmutableList<DeviceAccountPair> senses = ImmutableList.copyOf(Lists.newArrayList(pair, pair)); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(senses); assertEquals(PairState.PAIRING_VIOLATION, evaluator.getSensePairingState(request)); } @Test public void testUserHasNoSwap() { final SensePairingRequest request = SensePairingRequest.create(99L, "abc"); when(swapper.query(request.senseId())).thenReturn(Optional.<Intent>absent()); final DeviceAccountPair pair = new DeviceAccountPair( request.accountId(), 0L, "different_sense", DateTime.now(DateTimeZone.UTC) ); final ImmutableList<DeviceAccountPair> senses = ImmutableList.copyOf(Lists.newArrayList(pair, pair)); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(senses); assertEquals(PairState.PAIRING_VIOLATION, evaluator.getSensePairingState(request)); } @Test public void testUserHasSwap() { // TODO: this is a useless test for now final SensePairingRequest request = SensePairingRequest.create(99L, "abc", true); final Intent intent = Intent.create(request.senseId(), "old", request.accountId()); when(swapper.query(request.senseId())).thenReturn(Optional.of(intent)); when(swapper.swap(intent)).thenReturn(Result.success()); final DeviceAccountPair pair = new DeviceAccountPair( request.accountId(), 0L, "different_sense", DateTime.now(DateTimeZone.UTC) ); final ImmutableList<DeviceAccountPair> senses = ImmutableList.copyOf(Lists.newArrayList(pair, pair)); when(deviceDAO.getSensesForAccountId(request.accountId())).thenReturn(senses); when(deviceDAO.registerSense(request.accountId(), request.senseId())).thenReturn(1L); assertEquals(PairState.PAIRED_WITH_CURRENT_ACCOUNT, evaluator.getSensePairingStateAndMaybeSwap(request)); } }
package com.simpletime.service; import org.springframework.stereotype.Service; import com.simpletime.base.service.BaseServiceImpl; import com.simpletime.pojo.Admin; @Service public class AdminService extends BaseServiceImpl<Admin> { }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.support; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.jmx.MBeanServerNotFoundException; import org.springframework.lang.Nullable; /** * {@link FactoryBean} that obtains a {@link javax.management.MBeanServer} reference * through the standard JMX 1.2 {@link javax.management.MBeanServerFactory} * API. * * <p>Exposes the {@code MBeanServer} for bean references. * * <p>By default, {@code MBeanServerFactoryBean} will always create * a new {@code MBeanServer} even if one is already running. To have * the {@code MBeanServerFactoryBean} attempt to locate a running * {@code MBeanServer} first, set the value of the * "locateExistingServerIfPossible" property to "true". * * @author Rob Harrop * @author Juergen Hoeller * @since 1.2 * @see #setLocateExistingServerIfPossible * @see #locateMBeanServer * @see javax.management.MBeanServer * @see javax.management.MBeanServerFactory#findMBeanServer * @see javax.management.MBeanServerFactory#createMBeanServer * @see javax.management.MBeanServerFactory#newMBeanServer * @see MBeanServerConnectionFactoryBean * @see ConnectorServerFactoryBean */ public class MBeanServerFactoryBean implements FactoryBean<MBeanServer>, InitializingBean, DisposableBean { protected final Log logger = LogFactory.getLog(getClass()); private boolean locateExistingServerIfPossible = false; @Nullable private String agentId; @Nullable private String defaultDomain; private boolean registerWithFactory = true; @Nullable private MBeanServer server; private boolean newlyRegistered = false; /** * Set whether the {@code MBeanServerFactoryBean} should attempt * to locate a running {@code MBeanServer} before creating one. * <p>Default is {@code false}. */ public void setLocateExistingServerIfPossible(boolean locateExistingServerIfPossible) { this.locateExistingServerIfPossible = locateExistingServerIfPossible; } /** * Set the agent id of the {@code MBeanServer} to locate. * <p>Default is none. If specified, this will result in an * automatic attempt being made to locate the attendant MBeanServer, * and (importantly) if said MBeanServer cannot be located no * attempt will be made to create a new MBeanServer (and an * MBeanServerNotFoundException will be thrown at resolution time). * <p>Specifying the empty String indicates the platform MBeanServer. * @see javax.management.MBeanServerFactory#findMBeanServer(String) */ public void setAgentId(String agentId) { this.agentId = agentId; } /** * Set the default domain to be used by the {@code MBeanServer}, * to be passed to {@code MBeanServerFactory.createMBeanServer()} * or {@code MBeanServerFactory.findMBeanServer()}. * <p>Default is none. * @see javax.management.MBeanServerFactory#createMBeanServer(String) * @see javax.management.MBeanServerFactory#findMBeanServer(String) */ public void setDefaultDomain(String defaultDomain) { this.defaultDomain = defaultDomain; } /** * Set whether to register the {@code MBeanServer} with the * {@code MBeanServerFactory}, making it available through * {@code MBeanServerFactory.findMBeanServer()}. * <p>Default is {@code true}. * @see javax.management.MBeanServerFactory#createMBeanServer * @see javax.management.MBeanServerFactory#findMBeanServer */ public void setRegisterWithFactory(boolean registerWithFactory) { this.registerWithFactory = registerWithFactory; } /** * Creates the {@code MBeanServer} instance. */ @Override public void afterPropertiesSet() throws MBeanServerNotFoundException { // Try to locate existing MBeanServer, if desired. if (this.locateExistingServerIfPossible || this.agentId != null) { try { this.server = locateMBeanServer(this.agentId); } catch (MBeanServerNotFoundException ex) { // If agentId was specified, we were only supposed to locate that // specific MBeanServer; so let's bail if we can't find it. if (this.agentId != null) { throw ex; } logger.debug("No existing MBeanServer found - creating new one"); } } // Create a new MBeanServer and register it, if desired. if (this.server == null) { this.server = createMBeanServer(this.defaultDomain, this.registerWithFactory); this.newlyRegistered = this.registerWithFactory; } } /** * Attempt to locate an existing {@code MBeanServer}. * Called if {@code locateExistingServerIfPossible} is set to {@code true}. * <p>The default implementation attempts to find an {@code MBeanServer} using * a standard lookup. Subclasses may override to add additional location logic. * @param agentId the agent identifier of the MBeanServer to retrieve. * If this parameter is {@code null}, all registered MBeanServers are * considered. * @return the {@code MBeanServer} if found * @throws org.springframework.jmx.MBeanServerNotFoundException * if no {@code MBeanServer} could be found * @see #setLocateExistingServerIfPossible * @see JmxUtils#locateMBeanServer(String) * @see javax.management.MBeanServerFactory#findMBeanServer(String) */ protected MBeanServer locateMBeanServer(@Nullable String agentId) throws MBeanServerNotFoundException { return JmxUtils.locateMBeanServer(agentId); } /** * Create a new {@code MBeanServer} instance and register it with the * {@code MBeanServerFactory}, if desired. * @param defaultDomain the default domain, or {@code null} if none * @param registerWithFactory whether to register the {@code MBeanServer} * with the {@code MBeanServerFactory} * @see javax.management.MBeanServerFactory#createMBeanServer * @see javax.management.MBeanServerFactory#newMBeanServer */ protected MBeanServer createMBeanServer(@Nullable String defaultDomain, boolean registerWithFactory) { if (registerWithFactory) { return MBeanServerFactory.createMBeanServer(defaultDomain); } else { return MBeanServerFactory.newMBeanServer(defaultDomain); } } @Override @Nullable public MBeanServer getObject() { return this.server; } @Override public Class<? extends MBeanServer> getObjectType() { return (this.server != null ? this.server.getClass() : MBeanServer.class); } @Override public boolean isSingleton() { return true; } /** * Unregisters the {@code MBeanServer} instance, if necessary. */ @Override public void destroy() { if (this.newlyRegistered) { MBeanServerFactory.releaseMBeanServer(this.server); } } }
package com.mediafire.sdk.response_models.folder; import com.mediafire.sdk.response_models.ApiResponse; import com.mediafire.sdk.response_models.data_models.FolderContentsModel; public class FolderGetContentsResponse extends ApiResponse { public FolderContentsModel folder_content; public FolderContentsModel getFolderContents() { return folder_content; } }
package com.karya.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.karya.bean.ItemdtBean; import com.karya.bean.PuOrderTrendBean; import com.karya.bean.PurchaseAnalyticsBean; import com.karya.bean.SupplierWiseAnalyticsBean; import com.karya.model.Itemdt001MB; import com.karya.model.PuOrderTrend001MB; import com.karya.model.PurchaseAnalytics001MB; import com.karya.model.SupplierWiseAnalytics001MB; import com.karya.service.IBuyAnalyticsService; import com.karya.service.IItemdtService; @Controller @RequestMapping(value="BuyAnalyticsDetails") public class BuyAnalyticsController extends BaseController{ @Resource(name="buyanalyticsService") private IBuyAnalyticsService buyanalyticsService; @Resource(name="ItemdtService") private IItemdtService ItemdtService; private @Value("${Item.Status}") String[] statuslist; private @Value("${Putree.type}") String[] purchasetree; private @Value("${PuBase.type}") String[] purchasebase; private @Value("${valqty.choose}") String[] valorqty; private @Value("${range.type}") String[] rangetype; @RequestMapping(value = "/deletepuanalytics", method = RequestMethod.GET) public ModelAndView deletepuanalytics(@ModelAttribute("command") PurchaseAnalyticsBean purchaseanalyticsBean, BindingResult result) { buyanalyticsService.deletepuanalytics(purchaseanalyticsBean.getPuansId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("PuTreeList", purchasetree); model.put("PuBasedList", purchasebase); model.put("PuvalqtyList", valorqty); model.put("PurangeList", rangetype); model.put("puanalyticsList", preparepuanalyticsListofBean(buyanalyticsService.listpuanalytics())); return new ModelAndView("redirect:/BuyAnalyticsDetails/puanalytics?mode=Delete"); } @RequestMapping(value = "/savepuanalytics", method = RequestMethod.POST) public ModelAndView savepuanalytics(@ModelAttribute("command") @Valid PurchaseAnalyticsBean purchaseanalyticsBean, BindingResult result) { PurchaseAnalytics001MB purchaseanalytics001MB=preparepuanalyticsModel(purchaseanalyticsBean); Map<String, Object> model = new HashMap<String, Object>(); model.put("PuTreeList", purchasetree); model.put("PuBasedList", purchasebase); model.put("PuvalqtyList", valorqty); model.put("PurangeList", rangetype); model.put("puanalyticsList", preparepuanalyticsListofBean(buyanalyticsService.listpuanalytics())); if(result.hasErrors()){ return new ModelAndView("puanalytics", model); } buyanalyticsService.addpuanalytics(purchaseanalytics001MB); if(purchaseanalyticsBean.getPuansId()==0){ return new ModelAndView("redirect:/BuyAnalyticsDetails/puanalytics?mode=New"); }else { return new ModelAndView("redirect:/BuyAnalyticsDetails/puanalytics?mode=Old"); } } @RequestMapping(value = "/editpuanalytics", method = RequestMethod.GET) public ModelAndView editpuanalytics(@ModelAttribute("command") PurchaseAnalyticsBean purchaseanalyticsBean, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("puanalyticsEdit", preparepuanalyticsEditBean(buyanalyticsService.getpuanalytics(purchaseanalyticsBean.getPuansId()))); model.put("PuTreeList", purchasetree); model.put("PuBasedList", purchasebase); model.put("PuvalqtyList", valorqty); model.put("PurangeList", rangetype); model.put("puanalyticsList", preparepuanalyticsListofBean(buyanalyticsService.listpuanalytics())); return new ModelAndView("puanalytics", model); } @RequestMapping(value = "/puanalytics", method = RequestMethod.GET) public ModelAndView puanalytics(@ModelAttribute("command") PurchaseAnalyticsBean purchaseanalyticsBean, BindingResult result,String mode) { Map<String, Object> model = new HashMap<String, Object>(); if(mode != null) { if(mode.equals("New")) { model.put("msg", submitSuccess); } else if(mode.equals("Old")) { model.put("msg", updateSuccess); } else if(mode.equals("Delete")) { model.put("msg", deleteSuccess); } } model.put("PuTreeList", purchasetree); model.put("PuBasedList", purchasebase); model.put("PuvalqtyList", valorqty); model.put("PurangeList", rangetype); model.put("puanalyticsList", preparepuanalyticsListofBean(buyanalyticsService.listpuanalytics())); return new ModelAndView("puanalytics", model); } @RequestMapping(value = "/swsanalytics", method = RequestMethod.GET) public ModelAndView swsanalytics(@ModelAttribute("command") SupplierWiseAnalyticsBean swsanalyticsBean, BindingResult result,String mode) { Map<String, Object> model = new HashMap<String, Object>(); if(mode != null) { if(mode.equals("New")) { model.put("msg", submitSuccess); } else if(mode.equals("Old")) { model.put("msg", updateSuccess); } else if(mode.equals("Delete")) { model.put("msg", deleteSuccess); } } model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("swsanalyticsList", prepareswsanalytivsListofBean(buyanalyticsService.listswsanalytics())); return new ModelAndView("swsanalytics", model); } @RequestMapping(value = "/deleteswsanalytics", method = RequestMethod.GET) public ModelAndView deleteswsanalytics(@ModelAttribute("command") SupplierWiseAnalyticsBean swsanalyticsBean, BindingResult result) { buyanalyticsService.deleteswsanalytics(swsanalyticsBean.getSwsId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("swsanalyticsList", prepareswsanalytivsListofBean(buyanalyticsService.listswsanalytics())); return new ModelAndView("redirect:/BuyAnalyticsDetails/swsanalytics?mode=Delete"); } @RequestMapping(value = "/saveswsanalytics", method = RequestMethod.POST) public ModelAndView saveswsanalytics(@ModelAttribute("command") @Valid SupplierWiseAnalyticsBean swsanalyticsBean, BindingResult result) { SupplierWiseAnalytics001MB supplierwiseanalytics001MB=prepareswsanalyticsModel(swsanalyticsBean); Map<String, Object> model = new HashMap<String, Object>(); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("swsanalyticsList", prepareswsanalytivsListofBean(buyanalyticsService.listswsanalytics())); if(result.hasErrors()){ return new ModelAndView("swsanalytics", model); } buyanalyticsService.addswsanalytics(supplierwiseanalytics001MB); if(swsanalyticsBean.getSwsId()==0){ return new ModelAndView("redirect:/BuyAnalyticsDetails/swsanalytics?mode=New"); }else { return new ModelAndView("redirect:/BuyAnalyticsDetails/swsanalytics?mode=Old"); } } @RequestMapping(value = "/editswsanalytics", method = RequestMethod.GET) public ModelAndView editswsanalytics(@ModelAttribute("command") SupplierWiseAnalyticsBean swsanalyticsBean, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("swsanalyticsEdit", prepareswsanalyticsEditBean(buyanalyticsService.getswsanalytics(swsanalyticsBean.getSwsId()))); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("swsanalyticsList", prepareswsanalytivsListofBean(buyanalyticsService.listswsanalytics())); return new ModelAndView("swsanalytics", model); } @RequestMapping(value = "/puordtrend", method = RequestMethod.GET) public ModelAndView puordtrend(@ModelAttribute("command") PuOrderTrendBean puordertrendBean, BindingResult result,String mode) { Map<String, Object> model = new HashMap<String, Object>(); if(mode != null) { if(mode.equals("New")) { model.put("msg", submitSuccess); } else if(mode.equals("Old")) { model.put("msg", updateSuccess); } else if(mode.equals("Delete")) { model.put("msg", deleteSuccess); } } model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("PuTreeList", purchasetree); model.put("PurangeList", rangetype); model.put("puordtrendList", preparepuordertrendListofBean(buyanalyticsService.listpuordtrend())); return new ModelAndView("puordtrend", model); } @RequestMapping(value = "/deletepuordtrend", method = RequestMethod.GET) public ModelAndView deletepuordtrend(@ModelAttribute("command") PuOrderTrendBean puordertrendBean, BindingResult result) { buyanalyticsService.deletepuordtrend(puordertrendBean.getPtrId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("PuTreeList", purchasetree); model.put("PurangeList", rangetype); model.put("puordtrendList", preparepuordertrendListofBean(buyanalyticsService.listpuordtrend())); return new ModelAndView("redirect:/BuyAnalyticsDetails/puordtrend?mode=Delete"); } @RequestMapping(value = "/savepuordtrend", method = RequestMethod.POST) public ModelAndView savepuordtrend(@ModelAttribute("command") @Valid PuOrderTrendBean puordertrendBean, BindingResult result) { PuOrderTrend001MB puordertrend001MB=preparepuordertrendModel(puordertrendBean); Map<String, Object> model = new HashMap<String, Object>(); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("PuTreeList", purchasetree); model.put("PurangeList", rangetype); model.put("puordtrendList", preparepuordertrendListofBean(buyanalyticsService.listpuordtrend())); if(result.hasErrors()){ return new ModelAndView("puordtrend", model); } buyanalyticsService.addpuordtrend(puordertrend001MB); if(puordertrendBean.getPtrId()==0){ return new ModelAndView("redirect:/BuyAnalyticsDetails/puordtrend?mode=New"); }else { return new ModelAndView("redirect:/BuyAnalyticsDetails/puordtrend?mode=Old"); } } @RequestMapping(value = "/editpuordtrend", method = RequestMethod.GET) public ModelAndView editpuordtrend(@ModelAttribute("command") PuOrderTrendBean puordertrendBean, BindingResult result) { Map<String, Object> model = new HashMap<String, Object>(); model.put("puordertrendEdit", preparepuordertrendEditBean(buyanalyticsService.getpuordtrend(puordertrendBean.getPtrId()))); model.put("itemlist", prepareListofBean(ItemdtService.listallItems())); model.put("PuTreeList", purchasetree); model.put("PurangeList", rangetype); model.put("puordtrendList", preparepuordertrendListofBean(buyanalyticsService.listpuordtrend())); return new ModelAndView("puordtrend", model); } private List<ItemdtBean> prepareListofBean(List<Itemdt001MB> itemdts){ List<ItemdtBean> beans = null; if(itemdts != null && !itemdts.isEmpty()){ beans=new ArrayList<ItemdtBean>(); ItemdtBean bean=null; for(Itemdt001MB itemdt : itemdts ){ bean=new ItemdtBean(); bean.setItemId(itemdt.getItemId()); bean.setItemCode(itemdt.getItemCode()); bean.setQuantity(itemdt.getQuantity()); bean.setRate(itemdt.getRate()); bean.setAmount(itemdt.getAmount()); beans.add(bean); } } return beans; } private List<PurchaseAnalyticsBean> preparepuanalyticsListofBean(List<PurchaseAnalytics001MB> purchaseanalytics001MB){ List<PurchaseAnalyticsBean> beans = null; if(purchaseanalytics001MB != null && !purchaseanalytics001MB.isEmpty()){ beans = new ArrayList<PurchaseAnalyticsBean>(); PurchaseAnalyticsBean bean = null; for(PurchaseAnalytics001MB puanalytics : purchaseanalytics001MB){ bean = new PurchaseAnalyticsBean(); bean.setPuansId(puanalytics.getPuansId()); bean.setAnRange(puanalytics.getAnRange()); bean.setBasedOn(puanalytics.getBasedOn()); bean.setCompany(puanalytics.getCompany()); bean.setFromDate(puanalytics.getFromDate()); bean.setToDate(puanalytics.getToDate()); bean.setTreeType(puanalytics.getTreeType()); bean.setValueorqty(puanalytics.getValueorqty()); beans.add(bean); } } return beans; } private PurchaseAnalytics001MB preparepuanalyticsModel(PurchaseAnalyticsBean purchaseanalyticsBean){ PurchaseAnalytics001MB purchaseanalytics001MB = new PurchaseAnalytics001MB(); if(purchaseanalyticsBean.getPuansId()!= 0){ purchaseanalytics001MB.setPuansId(purchaseanalyticsBean.getPuansId()); } purchaseanalytics001MB.setAnRange(purchaseanalyticsBean.getAnRange()); purchaseanalytics001MB.setBasedOn(purchaseanalyticsBean.getBasedOn()); purchaseanalytics001MB.setCompany(purchaseanalyticsBean.getCompany()); purchaseanalytics001MB.setFromDate(purchaseanalyticsBean.getFromDate()); purchaseanalytics001MB.setToDate(purchaseanalyticsBean.getToDate()); purchaseanalytics001MB.setTreeType(purchaseanalyticsBean.getTreeType()); purchaseanalytics001MB.setValueorqty(purchaseanalyticsBean.getValueorqty()); return purchaseanalytics001MB; } private PurchaseAnalyticsBean preparepuanalyticsEditBean(PurchaseAnalytics001MB purchaseanalytics001MB){ PurchaseAnalyticsBean bean = new PurchaseAnalyticsBean(); bean.setPuansId(purchaseanalytics001MB.getPuansId()); bean.setAnRange(purchaseanalytics001MB.getAnRange()); bean.setBasedOn(purchaseanalytics001MB.getBasedOn()); bean.setCompany(purchaseanalytics001MB.getCompany()); bean.setFromDate(purchaseanalytics001MB.getFromDate()); bean.setToDate(purchaseanalytics001MB.getToDate()); bean.setTreeType(purchaseanalytics001MB.getTreeType()); bean.setValueorqty(purchaseanalytics001MB.getValueorqty()); return bean; } private List<SupplierWiseAnalyticsBean> prepareswsanalytivsListofBean(List<SupplierWiseAnalytics001MB> supplierwiseanalytics001MB){ List<SupplierWiseAnalyticsBean> beans = null; if(supplierwiseanalytics001MB != null && !supplierwiseanalytics001MB.isEmpty()){ beans = new ArrayList<SupplierWiseAnalyticsBean>(); SupplierWiseAnalyticsBean bean = null; for(SupplierWiseAnalytics001MB sws : supplierwiseanalytics001MB){ bean = new SupplierWiseAnalyticsBean(); bean.setSwsId(sws.getSwsId()); bean.setConsAmt(sws.getConsAmt()); bean.setConsQty(sws.getConsQty()); bean.setDelAmt(sws.getDelAmt()); bean.setDelQty(sws.getDelQty()); bean.setDescription(sws.getDescription()); bean.setItemCode(sws.getItemCode()); bean.setSwsUOM(sws.getSwsUOM()); bean.setTotalAmt(sws.getTotalAmt()); bean.setTotalQty(sws.getTotalQty()); beans.add(bean); } } return beans; } private SupplierWiseAnalytics001MB prepareswsanalyticsModel(SupplierWiseAnalyticsBean swsanalyticsBean){ SupplierWiseAnalytics001MB supplierwiseanalytics001MB = new SupplierWiseAnalytics001MB(); if(swsanalyticsBean.getSwsId()!= 0){ supplierwiseanalytics001MB.setSwsId(swsanalyticsBean.getSwsId()); } supplierwiseanalytics001MB.setConsAmt(swsanalyticsBean.getConsAmt()); supplierwiseanalytics001MB.setConsQty(swsanalyticsBean.getConsQty()); supplierwiseanalytics001MB.setDelAmt(swsanalyticsBean.getDelAmt()); supplierwiseanalytics001MB.setDelQty(swsanalyticsBean.getDelQty()); supplierwiseanalytics001MB.setDescription(swsanalyticsBean.getDescription()); supplierwiseanalytics001MB.setItemCode(swsanalyticsBean.getItemCode()); supplierwiseanalytics001MB.setSwsUOM(swsanalyticsBean.getSwsUOM()); supplierwiseanalytics001MB.setTotalAmt(swsanalyticsBean.getTotalAmt()); supplierwiseanalytics001MB.setTotalQty(swsanalyticsBean.getTotalQty()); return supplierwiseanalytics001MB; } private SupplierWiseAnalyticsBean prepareswsanalyticsEditBean(SupplierWiseAnalytics001MB supplierwiseanalytics001MB){ SupplierWiseAnalyticsBean bean = new SupplierWiseAnalyticsBean(); bean.setSwsId(supplierwiseanalytics001MB.getSwsId()); bean.setConsAmt(supplierwiseanalytics001MB.getConsAmt()); bean.setConsQty(supplierwiseanalytics001MB.getConsQty()); bean.setDelAmt(supplierwiseanalytics001MB.getDelAmt()); bean.setDelQty(supplierwiseanalytics001MB.getDelQty()); bean.setDescription(supplierwiseanalytics001MB.getDescription()); bean.setItemCode(supplierwiseanalytics001MB.getItemCode()); bean.setSwsUOM(supplierwiseanalytics001MB.getSwsUOM()); bean.setTotalAmt(supplierwiseanalytics001MB.getTotalAmt()); bean.setTotalQty(supplierwiseanalytics001MB.getTotalQty()); return bean; } private List<PuOrderTrendBean> preparepuordertrendListofBean(List<PuOrderTrend001MB> puordertrend001MB){ List<PuOrderTrendBean> beans = null; if(puordertrend001MB != null && !puordertrend001MB.isEmpty()){ beans = new ArrayList<PuOrderTrendBean>(); PuOrderTrendBean bean = null; for(PuOrderTrend001MB puordtr : puordertrend001MB){ bean = new PuOrderTrendBean(); bean.setPtrId(puordtr.getPtrId()); bean.setAprAmt(puordtr.getAprAmt()); bean.setAprQty(puordtr.getAprQty()); bean.setAugAmt(puordtr.getAugAmt()); bean.setAugQty(puordtr.getAugQty()); bean.setBasedOn(puordtr.getBasedOn()); bean.setCompany(puordtr.getCompany()); bean.setDecAmt(puordtr.getDecAmt()); bean.setDecQty(puordtr.getDecQty()); bean.setFebAmt(puordtr.getFebAmt()); bean.setFebQty(puordtr.getFebQty()); bean.setFiscalYear(puordtr.getFiscalYear()); bean.setItemCode(puordtr.getItemCode()); bean.setJanAmt(puordtr.getJanAmt()); bean.setJanQty(puordtr.getJanQty()); bean.setMarAmt(puordtr.getMarAmt()); bean.setMarQty(puordtr.getMarQty()); bean.setMayAmt(puordtr.getMayAmt()); bean.setMayQty(puordtr.getMayQty()); bean.setJulAmt(puordtr.getJulAmt()); bean.setJulQty(puordtr.getJulQty()); bean.setJunAmt(puordtr.getJunAmt()); bean.setJunQty(puordtr.getJunQty()); bean.setSepAmt(puordtr.getSepAmt()); bean.setSepQty(puordtr.getSepQty()); bean.setOctAmt(puordtr.getOctAmt()); bean.setOctQty(puordtr.getOctQty()); bean.setNovAmt(puordtr.getNovAmt()); bean.setNovQty(puordtr.getNovQty()); bean.setTotalAmt(puordtr.getTotalAmt()); bean.setTotalQty(puordtr.getTotalQty()); bean.setPeriod(puordtr.getPeriod()); bean.setPeriod(puordtr.getPeriod()); beans.add(bean); } } return beans; } private PuOrderTrend001MB preparepuordertrendModel(PuOrderTrendBean puordertrendBean){ PuOrderTrend001MB puordertrend001MB = new PuOrderTrend001MB(); if(puordertrendBean.getPtrId()!= 0){ puordertrend001MB.setPtrId(puordertrendBean.getPtrId()); } puordertrend001MB.setAprAmt(puordertrendBean.getAprAmt()); puordertrend001MB.setAprQty(puordertrendBean.getAprQty()); puordertrend001MB.setAugAmt(puordertrendBean.getAugAmt()); puordertrend001MB.setAugQty(puordertrendBean.getAugQty()); puordertrend001MB.setBasedOn(puordertrendBean.getBasedOn()); puordertrend001MB.setCompany(puordertrendBean.getCompany()); puordertrend001MB.setDecAmt(puordertrendBean.getDecAmt()); puordertrend001MB.setDecQty(puordertrendBean.getDecQty()); puordertrend001MB.setFebAmt(puordertrendBean.getFebAmt()); puordertrend001MB.setFebQty(puordertrendBean.getFebQty()); puordertrend001MB.setFiscalYear(puordertrendBean.getFiscalYear()); puordertrend001MB.setItemCode(puordertrendBean.getItemCode()); puordertrend001MB.setJanAmt(puordertrendBean.getJanAmt()); puordertrend001MB.setJanQty(puordertrendBean.getJanQty()); puordertrend001MB.setJulAmt(puordertrendBean.getJulAmt()); puordertrend001MB.setJunAmt(puordertrendBean.getJunAmt()); puordertrend001MB.setJunQty(puordertrendBean.getJunQty()); puordertrend001MB.setNovAmt(puordertrendBean.getNovAmt()); puordertrend001MB.setNovQty(puordertrendBean.getNovQty()); puordertrend001MB.setMarAmt(puordertrendBean.getMarAmt()); puordertrend001MB.setMarQty(puordertrendBean.getMarQty()); puordertrend001MB.setMayAmt(puordertrendBean.getMayAmt()); puordertrend001MB.setMayQty(puordertrendBean.getMayQty()); puordertrend001MB.setOctAmt(puordertrendBean.getOctAmt()); puordertrend001MB.setOctQty(puordertrendBean.getOctQty()); puordertrend001MB.setTotalAmt(puordertrendBean.getTotalAmt()); puordertrend001MB.setTotalQty(puordertrendBean.getTotalQty()); puordertrend001MB.setSepAmt(puordertrendBean.getSepAmt()); puordertrend001MB.setSepQty(puordertrendBean.getSepQty()); puordertrend001MB.setPeriod(puordertrendBean.getPeriod()); return puordertrend001MB; } private PuOrderTrendBean preparepuordertrendEditBean(PuOrderTrend001MB puordertrend001MB){ PuOrderTrendBean bean = new PuOrderTrendBean(); bean.setPtrId(puordertrend001MB.getPtrId()); bean.setPeriod(puordertrend001MB.getPeriod()); bean.setAprAmt(puordertrend001MB.getAprAmt()); bean.setAprQty(puordertrend001MB.getAprQty()); bean.setAugAmt(puordertrend001MB.getAugAmt()); bean.setItemCode(puordertrend001MB.getItemCode()); bean.setAugQty(puordertrend001MB.getAugQty()); bean.setBasedOn(puordertrend001MB.getBasedOn()); bean.setCompany(puordertrend001MB.getCompany()); bean.setDecAmt(puordertrend001MB.getDecAmt()); bean.setDecQty(puordertrend001MB.getDecQty()); bean.setFebAmt(puordertrend001MB.getFebAmt()); bean.setFebQty(puordertrend001MB.getFebQty()); bean.setFiscalYear(puordertrend001MB.getFiscalYear()); bean.setMarAmt(puordertrend001MB.getMarAmt()); bean.setMarQty(puordertrend001MB.getMarQty()); bean.setMayAmt(puordertrend001MB.getMayAmt()); bean.setMayQty(puordertrend001MB.getMayQty()); bean.setNovAmt(puordertrend001MB.getNovAmt()); bean.setNovQty(puordertrend001MB.getNovQty()); bean.setOctAmt(puordertrend001MB.getOctAmt()); bean.setOctQty(puordertrend001MB.getOctQty()); bean.setJanAmt(puordertrend001MB.getJanAmt()); bean.setJanQty(puordertrend001MB.getJanQty()); bean.setJulAmt(puordertrend001MB.getJulAmt()); bean.setJulQty(puordertrend001MB.getJulQty()); bean.setJunAmt(puordertrend001MB.getJunAmt()); bean.setJunQty(puordertrend001MB.getJunQty()); bean.setTotalAmt(puordertrend001MB.getTotalAmt()); bean.setTotalQty(puordertrend001MB.getTotalQty()); bean.setSepAmt(puordertrend001MB.getSepAmt()); bean.setSepQty(puordertrend001MB.getSepQty()); return bean; } }
package psoft.backend.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import psoft.backend.model.Disciplina; import java.io.Serializable; import java.util.List; @Repository public interface DisciplinaDAO<T, ID extends Serializable> extends JpaRepository<Disciplina, Long> { List<Disciplina> saveAll(Iterable disciplinaList); List<Disciplina> findAll(); Disciplina findById(long id); }
package com.UBQPageObjectLib; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import com.UBQGenericLib.WebDriverCommonLib; /** * @author Praneeth * */ public class PriceMaster extends WebDriverCommonLib { WebDriver driver; // ----------------------Constructor----------------------// public PriceMaster(WebDriver driver) { this.driver = driver; } // ----------------------UI Elements----------------------// // ---Entertexttosearch---// @FindBy(how = How.XPATH, using = "//input[@id='searchTxt']") private WebElement TextSearch; // ---Select SBU---// @FindBy(how = How.XPATH, using = "//select[@id='SBU']") private WebElement SBU; // ---Select customcode---// @FindBy(how = How.XPATH, using = "//input[@id='prod_custom_code']") private WebElement customcode; // ---Select prodcustomcode---// @FindBy(how = How.XPATH, using = "//input[@id='prod_code']") private WebElement prodcustomcode; // ---Select productName---// @FindBy(how = How.XPATH, using = "//input[@id='prod_name']") private WebElement productName; // ---Select Pcs---// @FindBy(how = How.XPATH, using = "//input[@id='prod_cbb_size']") private WebElement Pcs; // ---Select SearchBtn---// @FindBy(how = How.XPATH, using = "//input[@id='searchBtn']") private WebElement SearchBtn; // --- ProdType---// @FindBy(how = How.XPATH, using = "//input[@id='pr_context_type']") private WebElement ProdType; // --- MRP---// @FindBy(how = How.XPATH, using = "//input[@id='pr_mrp_pkt__disp__']") private WebElement MRP; // --- DTRRate---// @FindBy(how = How.XPATH, using = "//input[@id='pr_dtr_rate__disp__']") private WebElement DTRRate; // --- DTRRateTax---// @FindBy(how = How.XPATH, using = "//input[@id='pr_dtr_rate_tax__disp__']") private WebElement DTRRateTax; // --- DLRRate---// @FindBy(how = How.XPATH, using = "//input[@id='pr_dlr_rate__disp__']") private WebElement DLRRate; // --- MRP---// @FindBy(how = How.XPATH, using = "//input[@id='pr_dlr_rate_tax__disp__']") private WebElement DLRRateTax; // --- PopupProductSelect---// @FindBy(how = How.XPATH, using = "//input[@id='prod_code']") private WebElement PopupProductSelect; // --- PopupOktn---// @FindBy(how = How.XPATH, using = "//input[@id='ok']") private WebElement PopupOktn; // ----------------------Basic functions----------------------// // --------For enterTextSearch-----------// public void EnterTexttoSearch(String search) { entervalue(search, TextSearch); } // --------For getTextSearch-----------// public String getEnteredsearchedText() { return getvalue(TextSearch); } // ---For Select SBU---// public void selectSBU(String sbu) { selectvalue(sbu, SBU); } // ---For getSBU---// public String getBeatSBU() { return getselectDrpdwnValue(SBU); } // --------For enter custom code-----------// public void Entercustomcode(String ccode) { entervalue(ccode, customcode); } // --------For get custom code-----------// public String getEnteredcustomcode() { return getvalue(customcode); } // --------For enter custom code-----------// public void Enterprodcustomcode(String pcode) { entervalue(pcode, prodcustomcode); } // --------For get custom code-----------// public String getEnteredprodcustomcode() { return getvalue(prodcustomcode); } // --------For enter productName-----------// public void EnterproductName(String pname) { entervalue(pname, productName); } // --------For get productName-----------// public String getEnteredproductName() { return getvalue(productName); } // --------For enter productName-----------// public void EnterPcs(String pcs) { entervalue(pcs, Pcs); } // --------For get productName-----------// public String getEnteredPcs() { return getvalue(Pcs); } // ---For SearchBtn---// public void clickSearchBtn() { buttonClick(SearchBtn); } // --------For getProdType-----------// public String getProdType() { return getvalue(ProdType); } // --------For getMRP-----------// public String getMRP() { return getvalue(MRP); } // --------For getDTRRatee-----------// public String getDTRRate() { return getvalue(DTRRate); } // --------For getDTRRateTax-----------// public String getDTRRateTax() { return getvalue(DTRRateTax); } // --------For getDTRRateTax-----------// public String getDLRRate() { return getvalue(DLRRate); } // --------For getDTRRateTax-----------// public String getDLRRateTax() { return getvalue(DLRRateTax); } // ---For SearchBtn---// public void clickonPopupProductSelect() { buttonClick(PopupProductSelect); } // ---For SearchBtn---// public void clickonPopupOktn() { buttonClick(PopupOktn); } // ---For getNumOfProductRows---// public int getNumOfMainProductRows() { List<WebElement> size = driver.findElements(By.xpath("//table[@id='sm_dyna_table']/tbody/tr")); return size.size(); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet; import org.junit.jupiter.api.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link FlashMap} tests. * * @author Rossen Stoyanchev */ public class FlashMapTests { @Test public void isExpired() throws InterruptedException { assertThat(new FlashMap().isExpired()).isFalse(); FlashMap flashMap = new FlashMap(); flashMap.startExpirationPeriod(0); Thread.sleep(100); assertThat(flashMap.isExpired()).isTrue(); } @Test public void notExpired() throws InterruptedException { FlashMap flashMap = new FlashMap(); flashMap.startExpirationPeriod(10); Thread.sleep(100); assertThat(flashMap.isExpired()).isFalse(); } @Test public void compareTo() { FlashMap flashMap1 = new FlashMap(); FlashMap flashMap2 = new FlashMap(); assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); flashMap1.setTargetRequestPath("/path1"); assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(-1); assertThat(flashMap2.compareTo(flashMap1)).isEqualTo(1); flashMap2.setTargetRequestPath("/path2"); assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); flashMap1.addTargetRequestParam("id", "1"); assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(-1); assertThat(flashMap2.compareTo(flashMap1)).isEqualTo(1); flashMap2.addTargetRequestParam("id", "2"); assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); } @Test public void addTargetRequestParamNullValue() { FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParam("text", "abc"); flashMap.addTargetRequestParam("empty", " "); flashMap.addTargetRequestParam("null", null); assertThat(flashMap.getTargetRequestParams()).hasSize(1); assertThat(flashMap.getTargetRequestParams().getFirst("text")).isEqualTo("abc"); } @Test public void addTargetRequestParamsNullValue() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("key", "abc"); params.add("key", " "); params.add("key", null); FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParams(params); assertThat(flashMap.getTargetRequestParams()).hasSize(1); assertThat(flashMap.getTargetRequestParams().get("key")).hasSize(1); assertThat(flashMap.getTargetRequestParams().getFirst("key")).isEqualTo("abc"); } @Test public void addTargetRequestParamNullKey() { FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParam(" ", "abc"); flashMap.addTargetRequestParam(null, "abc"); assertThat(flashMap.getTargetRequestParams().isEmpty()).isTrue(); } @Test public void addTargetRequestParamsNullKey() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add(" ", "abc"); params.add(null, " "); FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParams(params); assertThat(flashMap.getTargetRequestParams().isEmpty()).isTrue(); } }
package cn.homeron.homerfast.biz.controller; import cn.homeron.homerfast.biz.bean.CatBean; import cn.homeron.homerfast.biz.service.CatService; import cn.homeron.homerfast.common.controller.BaseController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/cat") public class CatController extends BaseController<CatService, CatBean> { }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.matsci.client; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.utils.OperatingSystem; import org.ow2.proactive.scheduler.ext.common.util.IOTools; import org.ow2.proactive.scheduler.ext.matsci.common.DummyJVMProcess; import org.ow2.proactive.scheduler.ext.matsci.common.JVMSpawnHelper; import org.ow2.proactive.scheduler.ext.matsci.common.ProcessInitializer; import org.ow2.proactive.scheduler.ext.matsci.common.ProcessListener; import java.io.*; import java.util.Map; /** * DataspaceHelper * * @author The ProActive Team */ public class DataspaceHelper implements ProcessInitializer, ProcessListener { static DataspaceHelper instance = null; /** * Node name where this task is being executed */ protected static String nodeName = "MatSciDataSpaceHelper"; protected PrintStream outDebug; protected File nodeTmpDir; protected JVMSpawnHelper helper; protected long semtimeout = 2; protected int retries = 30; protected boolean debug; protected String inbasename; protected String outbasename; protected int deployID; protected Node node; protected Process process; protected Integer childPid; protected static OperatingSystem os = OperatingSystem.getOperatingSystem(); protected AODataspaceRegistry registry; private DataspaceHelper(String oldregistryurl, String inbasename, String outbasename, boolean debug) throws Throwable { this.debug = debug; this.inbasename = inbasename; this.outbasename = outbasename; // system temp dir String tmpPath = System.getProperty("java.io.tmpdir"); // log file writer used for debugging File tmpDirFile = new File(tmpPath); nodeTmpDir = new File(tmpDirFile, nodeName); if (!nodeTmpDir.exists()) { nodeTmpDir.mkdirs(); } File logFile = new File(tmpPath, "" + this.getClass().getSimpleName() + ".log"); if (!logFile.exists()) { logFile.createNewFile(); } outDebug = new PrintStream(new BufferedOutputStream(new FileOutputStream(logFile, true))); if (oldregistryurl != null) { registry = (AODataspaceRegistry) PAActiveObject.lookupActive(AODataspaceRegistry.class.getName(), oldregistryurl); node = PAActiveObject.getActiveObjectNode(registry); childPid = registry.getPID(); } if (registry == null) { try { helper = new JVMSpawnHelper(debug, outDebug, nodeTmpDir, nodeName, semtimeout, retries); process = helper.startProcess(nodeName, this, this); IOTools.LoggingThread lt1; if (debug) { lt1 = new IOTools.LoggingThread(process, "[DS]", System.out, System.err, outDebug); } else { lt1 = new IOTools.LoggingThread(process); } Thread t1 = new Thread(lt1, "OUT DS"); t1.setDaemon(true); t1.start(); helper.waitForRegistration(process); deploy(); helper.unsubscribeJMXRuntimeEvent(); } catch (Throwable e) { outDebug.flush(); outDebug.close(); throw e; } } } /** * Tells if this DataspaceHelper object is properly connected to a running AODataspaceRegistry active object * @return */ public static boolean isConnected() { if (instance == null) { return false; } if (instance.registry == null) { return false; } try { instance.registry.getPID(); return true; } catch (Exception e) { return false; } } /** * Initialize this DataspaceHelper * @param url if url is provided, it tries to reconnect to an existing running AODataspaceRegistry, if not it will spawn a new JVM to store a new AODataspaceRegistry active object * @param inbasename Input Space Base Name which will be prepended to any created DataSpace * @param outbasename Output Space Base Name which will be prepended to any created DataSpace * @param debug debug mode will print a lot of debugging information to standard output * @throws Throwable */ public static void init(String url, String inbasename, String outbasename, boolean debug) throws Throwable { if (instance == null) { instance = new DataspaceHelper(url, inbasename, outbasename, debug); } } public static DataspaceHelper getInstance() throws Throwable { if (instance == null) { throw new IllegalStateException(); } return instance; } /** * Returns the URL of the remote AODataspaceRegistry active object * @return */ public String getUrl() { if (instance == null) { throw new IllegalStateException(); } return PAActiveObject.getUrl(registry); } /** * Asks the remote AODataspaceRegistry to create a DataSpace on the given path. If a dataspace already exists for this path, it will reuse it. * @param path path to create a new dataspace * @return */ public Pair<String, String> createDataSpace(String path) { Pair<String, String> answer = registry.createDataSpace(path); answer = PAFuture.getFutureValue(answer); return answer; } /** * Shuts down the spawned JVM and remote AODataspaceRegistry */ public void shutdown() { if (debug) { System.out.println("[" + new java.util.Date() + " " + this.getClass().getSimpleName() + "] Shutting down handler"); outDebug.println("[" + new java.util.Date() + " " + this.getClass().getSimpleName() + "] Shutting down handler"); } try { node.killAllActiveObjects(); } catch (NodeException e) { } catch (IOException e) { } if (process != null) { process.destroy(); } else if (os.equals(OperatingSystem.windows)) { if (debug) { System.out.println("Killing process " + childPid); outDebug.println("Killing process " + childPid); } try { Runtime.getRuntime().exec("taskkill /PID " + childPid + " /T"); Runtime.getRuntime().exec("tskill " + childPid); } catch (IOException e) { e.printStackTrace(); } } else { if (debug) { System.out.println("Killing process " + childPid); outDebug.println("Killing process " + childPid); } try { Runtime.getRuntime().exec("kill -9 " + childPid); } catch (IOException e) { e.printStackTrace(); } } outDebug.close(); } private void deploy() throws NodeException, ActiveObjectCreationException { ProActiveException ex = null; if (debug) { System.out.println("[" + new java.util.Date() + " " + this.getClass().getSimpleName() + "] Deploying Worker"); outDebug.println("[" + new java.util.Date() + " " + this.getClass().getSimpleName() + "] Deploying Worker"); } registry = (AODataspaceRegistry) PAActiveObject.newActive(AODataspaceRegistry.class.getName(), new Object[] { inbasename, outbasename, nodeName, debug }, node); } public void initProcess(DummyJVMProcess jvmprocess, Map<String, String> env) throws Throwable { // do nothing } public void setNode(Node node) { this.node = node; } public void setDeployID(Integer deployID) { this.deployID = deployID; } public Integer getDeployID() { return deployID; } }
package com.org.annotation; import java.lang.annotation.*; /** * 记录日志 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) @Documented @Inherited public @interface Log { public enum LOG_TYPE{ADD,UPDATE,DEL,SELECT,ATHOR}; /**内容*/ String desc(); /**类型 curd*/ LOG_TYPE type() default LOG_TYPE.ADD; }
package com.xwolf.eop.system.entity; import lombok.Data; @Data public class UserRole { private Integer rid; private String ucode; private String rcode; }
package com.darwinsys.gcmclient; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.TextView; import android.widget.Toast; import com.darwinsys.gcmclient.R; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; /** A simple(?) demonstration of GCM messaging; in this demo the app only * receives a message from GCM, which is originated by the "GCMMockServer" project. * @author Ian Darwin with help from Google documentation */ public class GcmMainActivity extends Activity { static final String TAG = "com.darwinsys.gcmdemo"; private static final String TAG_CONFORMANCE = "RegulatoryCompliance"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** The Sender Id is the Project ID number from the Google Developer's Console */ private static final String GCM_SENDER_ID = "117558675814"; public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; /** A Context to be used in inner classes */ private Context context; /** The log textview */ private TextView logTv; /** In real life this would be in the Application singleton class */ private Executor threadPool = Executors.newFixedThreadPool(1); /** the GCM instance */ private GoogleCloudMessaging gcm; /** The registration Id we get back from GCM the first time we register */ private String registrationId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "MainActivity.onCreate()"); setContentView(R.layout.activity_main); logTv = (TextView) findViewById(R.id.logView); context = getApplicationContext(); logTv.setText("Start\n"); // GCM stuff if (checkForGcm()) { logTv.append("Passed checkforGCM\n"); gcm = GoogleCloudMessaging.getInstance(this); registrationId = getRegistrationId(this); if (registrationId.isEmpty()) { threadPool.execute(new Runnable() { public void run() { final String regn = registerWithGcm(); Log.d(TAG, "New Registration = " + regn); setMessageOnUiThread(regn + "\n"); } }); } else { final String mesg = "Previous Registration = " + registrationId; Log.d(TAG, mesg); logTv.append(mesg + "\n"); } } else { logTv.append("Failed checkforGCM"); } } void setMessageOnUiThread(final String mesg) { runOnUiThread(new Runnable() { public void run() { logTv.append(mesg); } }); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "MainActivity.onResume()"); checkForGcm(); } boolean checkForGcm() { int ret = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (ConnectionResult.SUCCESS == ret) { Log.d(TAG, "MainActivity.checkForGcm(): SUCCESS"); return true; } else { Log.d(TAG, "MainActivity.checkForGcm(): FAILURE"); if (GooglePlayServicesUtil.isUserRecoverableError(ret)) { GooglePlayServicesUtil.getErrorDialog(ret, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Toast.makeText(this, "Google Message Not Supported on this device; you will not get update notifications!!", Toast.LENGTH_LONG).show(); Log.d(TAG_CONFORMANCE, "User accepted to run the app without update notifications!"); } return false; } } /** * Gets the current registration ID for application on GCM service. * <p> * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing registration ID. * @author Adapted from the Google Cloud Messaging example */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getSharedPreferences(GcmMainActivity.class.getSimpleName(), Context.MODE_PRIVATE); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must remove the registration ID // since the existing regID is not guaranteed to work with the new app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * Get the app version, which comes ultimately from the AndroidManifest * (you don't have to keep your own "version number" in the app too!). * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { // This is a "CANTHAPPEN", so why is it a checked exception? final String mesg = "CANTHAPPEN: could not get my own package name!?!?: " + e; Log.wtf(TAG, mesg); throw new RuntimeException(mesg); } } /** * Register this app, the first time on this device, with Google Cloud Messaging Service * @return The registration ID * @author Adapted from the Google Cloud Messaging example */ private String registerWithGcm() { String mesg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } registrationId = gcm.register(GCM_SENDER_ID); mesg = "Device registered! My registration =" + registrationId; // You should send the registration ID to your server over HTTP, // so it can use GCM/HTTP or CCS to send messages to your app. // The request to your server should be authenticated if your app // is using accounts. sendRegistrationIdToMyServer(); // For this demo: we don't need to send it because the device // will send upstream messages to a server that echo back the // message using the 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, registrationId); } catch (IOException ex) { mesg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. Toast.makeText(context, mesg, Toast.LENGTH_LONG).show(); throw new RuntimeException(mesg); } return mesg; } private void sendRegistrationIdToMyServer() { // TODO Auto-generated method stub } /** * You need to save the long RegistrationId string someplace; this version * stores the registration ID and app versionCode in the application's * {@code SharedPreferences}. * @param context application's context. * @param regId registration ID * @author Adapted from the Google Cloud Messaging example */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getSharedPreferences(GcmMainActivity.class.getSimpleName(), Context.MODE_PRIVATE); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package org.kuali.ole.select.lookup; import org.kuali.ole.docstore.discovery.service.QueryServiceImpl; import org.kuali.ole.select.businessobject.OlePurchaseOrderItem; import org.kuali.ole.select.document.OLEInvoicePurchaseOrderSearch; import org.kuali.ole.select.document.OlePurchaseOrderDocument; import org.kuali.ole.sys.OLEConstants; import org.kuali.ole.sys.OLEKeyConstants; import org.kuali.ole.sys.context.SpringContext; import org.kuali.rice.krad.lookup.LookupableImpl; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.web.form.LookupForm; import java.util.*; /** * This is the Lookupable Impl class for the PurchaseOrder Documents */ public class OLEInvoicePurchaseOrderSearchLookupableImpl extends LookupableImpl { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OLEInvoicePurchaseOrderSearchLookupableImpl.class); private static transient BusinessObjectService businessObjectService; protected BusinessObjectService getBusinessObjectService() { if (businessObjectService == null) { businessObjectService = SpringContext.getBean(BusinessObjectService.class); } return businessObjectService; } /** * Overrided to customize the Purchase Order Document Search * * @param form * @param searchCriteria * @param bounded * @return */ @Override public Collection<?> performSearch(LookupForm form, Map<String, String> searchCriteria, boolean bounded) { LOG.debug("Inside performSearch()"); BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class); List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = new ArrayList<OlePurchaseOrderDocument>(); Map<String, String> stringMap = new HashMap<>(); Map invoicePurchaseOrderSearchMap = new HashMap(); List<OLEInvoicePurchaseOrderSearch> finalOLEInvoicePurchaseOrderSearchList = new ArrayList<OLEInvoicePurchaseOrderSearch>(); OLEInvoicePurchaseOrderSearch oleInvoicePurchaseOrderSearch = null; if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.TITLE) && (searchCriteria.get(OLEConstants.InvoiceDocument.TITLE)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.TITLE); } else { stringMap.put(OLEConstants.InvoiceDocument.TITLE, searchCriteria.get(OLEConstants.InvoiceDocument.TITLE)); searchCriteria.remove(OLEConstants.InvoiceDocument.TITLE); } if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.AUTHOR) && (searchCriteria.get(OLEConstants.InvoiceDocument.AUTHOR)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.AUTHOR); } else { stringMap.put(OLEConstants.InvoiceDocument.AUTHOR, searchCriteria.get(OLEConstants.InvoiceDocument.AUTHOR)); searchCriteria.remove(OLEConstants.InvoiceDocument.AUTHOR); } if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.ISBN) && (searchCriteria.get(OLEConstants.InvoiceDocument.ISBN)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.ISBN); } else { stringMap.put(OLEConstants.InvoiceDocument.ISBN, searchCriteria.get(OLEConstants.InvoiceDocument.ISBN)); searchCriteria.remove(OLEConstants.InvoiceDocument.ISBN); } if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.VENDOR_NAME) && (searchCriteria.get(OLEConstants.InvoiceDocument.VENDOR_NAME)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.VENDOR_NAME); } if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.INVOICE_DOCUMENT_NUMBER) && (searchCriteria.get(OLEConstants.InvoiceDocument.INVOICE_DOCUMENT_NUMBER)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.INVOICE_DOCUMENT_NUMBER); } if (searchCriteria.containsKey(OLEConstants.InvoiceDocument.INVOICE_PURAP_DOCUMENT_IDENTIFIER) && (searchCriteria.get(OLEConstants.InvoiceDocument.INVOICE_PURAP_DOCUMENT_IDENTIFIER)).isEmpty()) { searchCriteria.remove(OLEConstants.InvoiceDocument.INVOICE_PURAP_DOCUMENT_IDENTIFIER); } if ((searchCriteria.containsKey(OLEConstants.InvoiceDocument.VENDOR_HEADER_IDENTIFIER) && !searchCriteria.get(OLEConstants.InvoiceDocument.VENDOR_HEADER_IDENTIFIER).isEmpty()) && (searchCriteria.containsKey(OLEConstants.InvoiceDocument.VENDOR_DETAIL_IDENTIFIER) && !searchCriteria.get(OLEConstants.InvoiceDocument.VENDOR_DETAIL_IDENTIFIER).isEmpty())) { List<HashMap<String, Object>> documentList1 = null; if (((String) stringMap.get(OLEConstants.InvoiceDocument.TITLE)) != null || ((String) stringMap.get(OLEConstants.InvoiceDocument.AUTHOR)) != null || ((String) stringMap.get(OLEConstants.InvoiceDocument.ISBN)) != null) { // if(documentList.size()>0){ // HashMap<String, Object> itemvalues = documentList.get(0); StringBuffer query = new StringBuffer(""); if (((String) stringMap.get(OLEConstants.InvoiceDocument.TITLE)) != null) { String title = (String) stringMap.get(OLEConstants.InvoiceDocument.TITLE); query.append("((Title_search:" + title.toLowerCase() + ")OR(Title_search:" + title.toLowerCase() + "*)) AND "); } if (((String) stringMap.get(OLEConstants.InvoiceDocument.AUTHOR)) != null) { String author = (String) stringMap.get(OLEConstants.InvoiceDocument.AUTHOR); query.append("((Author_search:" + author.toLowerCase() + ")OR(Author_search:" + author.toLowerCase() + "*)) AND "); } if (((String) stringMap.get(OLEConstants.InvoiceDocument.ISBN)) != null) { String isbn = (String) stringMap.get(OLEConstants.InvoiceDocument.ISBN); query.append("(ISBN_search:" + isbn + ") AND"); } query = new StringBuffer(query.substring(0, query.lastIndexOf("AND"))); documentList1 = QueryServiceImpl.getInstance().retriveResults(query.toString()); List idList = new ArrayList(); for (int i = 0; i < documentList1.size(); i++) { Map<String, String> queryResult = (Map) documentList1.get(i); idList.add(queryResult.get("id")); Map vendorItemIdentifier = new HashMap(); vendorItemIdentifier.put("itemTitleId", queryResult.get("id")); // boolean retrieveFromPO = false; List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, vendorItemIdentifier); String purchaseOrderNumber = olePurchaseOrderItems.get(0).getDocumentNumber(); searchCriteria.put("documentNumber", purchaseOrderNumber); List totalSearchResults = (List) businessObjectService.findMatching(OlePurchaseOrderDocument.class, searchCriteria); //totalSearchResults.add(olePurchaseOrderDocumentList); if (totalSearchResults != null && totalSearchResults.size() > 0) olePurchaseOrderDocumentList.addAll(totalSearchResults); } /*Returns Search result */ if (olePurchaseOrderDocumentList != null && olePurchaseOrderDocumentList.size() > 0) { for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) { if (olePurchaseOrderDocument.getApplicationDocumentStatus().equalsIgnoreCase("OPEN")) { oleInvoicePurchaseOrderSearch = new OLEInvoicePurchaseOrderSearch(); oleInvoicePurchaseOrderSearch.setDocumentNumber(olePurchaseOrderDocument.getDocumentNumber()); oleInvoicePurchaseOrderSearch.setPostingYear(olePurchaseOrderDocument.getPostingYear()); oleInvoicePurchaseOrderSearch.setPurapDocumentIdentifier(olePurchaseOrderDocument.getPurapDocumentIdentifier().toString()); oleInvoicePurchaseOrderSearch.setAmount(olePurchaseOrderDocument.getTotalDollarAmount()); OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) olePurchaseOrderDocument.getItems().get(0); String bibId = olePurchaseOrderItem.getItemTitleId(); HashMap bibDetails = new HashMap(); List<HashMap<String, Object>> documentList = QueryServiceImpl.getInstance().retriveResults("(DocType:bibliographic) AND (id:" + bibId + ")"); if (documentList.size() > 0) { HashMap<String, Object> itemvalues = documentList.get(0); if (itemvalues.get("Title_display") != null) oleInvoicePurchaseOrderSearch.setTitle((String) ((ArrayList) itemvalues.get("Title_display")).get(0)); if (itemvalues.get("Author_display") != null) oleInvoicePurchaseOrderSearch.setAuthor((String) ((ArrayList) itemvalues.get("Author_display")).get(0)); if (itemvalues.get("ISBN_display") != null) oleInvoicePurchaseOrderSearch.setIsbn((String) ((ArrayList) itemvalues.get("ISBN_display")).get(0)); } finalOLEInvoicePurchaseOrderSearchList.add(oleInvoicePurchaseOrderSearch); } } } } else if (searchCriteria != null) { olePurchaseOrderDocumentList = (List) businessObjectService.findMatching(OlePurchaseOrderDocument.class, searchCriteria); /*Returns Search result */ if (olePurchaseOrderDocumentList != null && olePurchaseOrderDocumentList.size() > 0) { for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) { if (olePurchaseOrderDocument.getApplicationDocumentStatus().equalsIgnoreCase("OPEN")) { oleInvoicePurchaseOrderSearch = new OLEInvoicePurchaseOrderSearch(); oleInvoicePurchaseOrderSearch.setDocumentNumber(olePurchaseOrderDocument.getDocumentNumber()); oleInvoicePurchaseOrderSearch.setPostingYear(olePurchaseOrderDocument.getPostingYear()); oleInvoicePurchaseOrderSearch.setPurapDocumentIdentifier(olePurchaseOrderDocument.getPurapDocumentIdentifier().toString()); oleInvoicePurchaseOrderSearch.setAmount(olePurchaseOrderDocument.getTotalDollarAmount()); OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) olePurchaseOrderDocument.getItems().get(0); String bibId = olePurchaseOrderItem.getItemTitleId(); HashMap bibDetails = new HashMap(); List<HashMap<String, Object>> documentList = QueryServiceImpl.getInstance().retriveResults("(DocType:bibliographic) AND (id:" + bibId + ")"); if (documentList.size() > 0) { HashMap<String, Object> itemvalues = documentList.get(0); if (itemvalues.get("Title_display") != null) oleInvoicePurchaseOrderSearch.setTitle((String) ((ArrayList) itemvalues.get("Title_display")).get(0)); if (itemvalues.get("Author_display") != null) oleInvoicePurchaseOrderSearch.setAuthor((String) ((ArrayList) itemvalues.get("Author_display")).get(0)); if (itemvalues.get("ISBN_display") != null) oleInvoicePurchaseOrderSearch.setIsbn((String) ((ArrayList) itemvalues.get("ISBN_display")).get(0)); } finalOLEInvoicePurchaseOrderSearchList.add(oleInvoicePurchaseOrderSearch); } } } } } else { GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEKeyConstants.ERROR_NO_VENDOR, new String[]{}); } return finalOLEInvoicePurchaseOrderSearchList; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.handler; import java.io.IOException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.lang.Nullable; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; /** * Wrap a {@link org.springframework.web.socket.WebSocketSession WebSocketSession} * to guarantee only one thread can send messages at a time. * * <p>If a send is slow, subsequent attempts to send more messages from other threads * will not be able to acquire the flush lock and messages will be buffered instead. * At that time, the specified buffer-size limit and send-time limit will be checked * and the session will be closed if the limits are exceeded. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 4.0.3 */ public class ConcurrentWebSocketSessionDecorator extends WebSocketSessionDecorator { private static final Log logger = LogFactory.getLog(ConcurrentWebSocketSessionDecorator.class); private final int sendTimeLimit; private final int bufferSizeLimit; private final OverflowStrategy overflowStrategy; @Nullable private Consumer<WebSocketMessage<?>> preSendCallback; private final Queue<WebSocketMessage<?>> buffer = new LinkedBlockingQueue<>(); private final AtomicInteger bufferSize = new AtomicInteger(); private volatile long sendStartTime; private volatile boolean limitExceeded; private volatile boolean closeInProgress; private final Lock flushLock = new ReentrantLock(); private final Lock closeLock = new ReentrantLock(); /** * Basic constructor. * @param delegate the {@code WebSocketSession} to delegate to * @param sendTimeLimit the send-time limit (milliseconds) * @param bufferSizeLimit the buffer-size limit (number of bytes) */ public ConcurrentWebSocketSessionDecorator(WebSocketSession delegate, int sendTimeLimit, int bufferSizeLimit) { this(delegate, sendTimeLimit, bufferSizeLimit, OverflowStrategy.TERMINATE); } /** * Constructor that also specifies the overflow strategy to use. * @param delegate the {@code WebSocketSession} to delegate to * @param sendTimeLimit the send-time limit (milliseconds) * @param bufferSizeLimit the buffer-size limit (number of bytes) * @param overflowStrategy the overflow strategy to use; by default the * session is terminated. * @since 5.1 */ public ConcurrentWebSocketSessionDecorator( WebSocketSession delegate, int sendTimeLimit, int bufferSizeLimit, OverflowStrategy overflowStrategy) { super(delegate); this.sendTimeLimit = sendTimeLimit; this.bufferSizeLimit = bufferSizeLimit; this.overflowStrategy = overflowStrategy; } /** * Return the configured send-time limit (milliseconds). * @since 4.3.13 */ public int getSendTimeLimit() { return this.sendTimeLimit; } /** * Return the configured buffer-size limit (number of bytes). * @since 4.3.13 */ public int getBufferSizeLimit() { return this.bufferSizeLimit; } /** * Return the current buffer size (number of bytes). */ public int getBufferSize() { return this.bufferSize.get(); } /** * Return the time (milliseconds) since the current send started, * or 0 if no send is currently in progress. */ public long getTimeSinceSendStarted() { long start = this.sendStartTime; return (start > 0 ? (System.currentTimeMillis() - start) : 0); } /** * Set a callback invoked after a message is added to the send buffer. * @param callback the callback to invoke * @since 5.3 */ public void setMessageCallback(Consumer<WebSocketMessage<?>> callback) { this.preSendCallback = callback; } @Override public void sendMessage(WebSocketMessage<?> message) throws IOException { if (shouldNotSend()) { return; } this.buffer.add(message); this.bufferSize.addAndGet(message.getPayloadLength()); if (this.preSendCallback != null) { this.preSendCallback.accept(message); } do { if (!tryFlushMessageBuffer()) { if (logger.isTraceEnabled()) { logger.trace(String.format("Another send already in progress: " + "session id '%s':, \"in-progress\" send time %d (ms), buffer size %d bytes", getId(), getTimeSinceSendStarted(), getBufferSize())); } checkSessionLimits(); break; } } while (!this.buffer.isEmpty() && !shouldNotSend()); } private boolean shouldNotSend() { return (this.limitExceeded || this.closeInProgress); } private boolean tryFlushMessageBuffer() throws IOException { if (this.flushLock.tryLock()) { try { while (true) { WebSocketMessage<?> message = this.buffer.poll(); if (message == null || shouldNotSend()) { break; } this.bufferSize.addAndGet(-message.getPayloadLength()); this.sendStartTime = System.currentTimeMillis(); getDelegate().sendMessage(message); this.sendStartTime = 0; } } finally { this.sendStartTime = 0; this.flushLock.unlock(); } return true; } return false; } private void checkSessionLimits() { if (!shouldNotSend() && this.closeLock.tryLock()) { try { if (getTimeSinceSendStarted() > getSendTimeLimit()) { String format = "Send time %d (ms) for session '%s' exceeded the allowed limit %d"; String reason = String.format(format, getTimeSinceSendStarted(), getId(), getSendTimeLimit()); limitExceeded(reason); } else if (getBufferSize() > getBufferSizeLimit()) { switch (this.overflowStrategy) { case TERMINATE -> { String format = "Buffer size %d bytes for session '%s' exceeds the allowed limit %d"; String reason = String.format(format, getBufferSize(), getId(), getBufferSizeLimit()); limitExceeded(reason); } case DROP -> { int i = 0; while (getBufferSize() > getBufferSizeLimit()) { WebSocketMessage<?> message = this.buffer.poll(); if (message == null) { break; } this.bufferSize.addAndGet(-message.getPayloadLength()); i++; } if (logger.isDebugEnabled()) { logger.debug("Dropped " + i + " messages, buffer size: " + getBufferSize()); } } default -> // Should never happen.. throw new IllegalStateException("Unexpected OverflowStrategy: " + this.overflowStrategy); } } } finally { this.closeLock.unlock(); } } } private void limitExceeded(String reason) { this.limitExceeded = true; throw new SessionLimitExceededException(reason, CloseStatus.SESSION_NOT_RELIABLE); } @Override public void close(CloseStatus status) throws IOException { this.closeLock.lock(); try { if (this.closeInProgress) { return; } if (!CloseStatus.SESSION_NOT_RELIABLE.equals(status)) { try { checkSessionLimits(); } catch (SessionLimitExceededException ex) { // Ignore } if (this.limitExceeded) { if (logger.isDebugEnabled()) { logger.debug("Changing close status " + status + " to SESSION_NOT_RELIABLE."); } status = CloseStatus.SESSION_NOT_RELIABLE; } } this.closeInProgress = true; super.close(status); } finally { this.closeLock.unlock(); } } @Override public String toString() { return getDelegate().toString(); } /** * Enum for options of what to do when the buffer fills up. * @since 5.1 */ public enum OverflowStrategy { /** * Throw {@link SessionLimitExceededException} that will result * in the session being terminated. */ TERMINATE, /** * Drop the oldest messages from the buffer. */ DROP } }
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.gatein.wcm.subsystem; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.List; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.staxmapper.XMLElementReader; /** * @author <a href="mailto:ppalaga@redhat.com">Peter Palaga</a> * */ public class GateInWcmExtension implements org.jboss.as.controller.Extension { private static final Logger log = Logger.getLogger(GateInWcmExtension.class); private static final int MANAGEMENT_API_MAJOR_VERSION = 1; private static final int MANAGEMENT_API_MINOR_VERSION = 2; private static final String RESOURCE_NAME = GateInWcmExtension.class.getPackage().getName() + ".LocalDescriptions"; public static final String SUBSYSTEM_NAME = "gateinwcm"; static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME); for (String kp : keyPrefix) { prefix.append('.').append(kp); } return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, GateInWcmExtension.class.getClassLoader(), true, false); } /* * (non-Javadoc) * * @see org.jboss.as.controller.Extension#initialize(org.jboss.as.controller.ExtensionContext) */ @Override public void initialize(ExtensionContext context) { log.info("org.gatein.wcm.cmis.JcrServiceFactoryActivator.initialize(ExtensionContext)"); final SubsystemRegistration registration = context.registerSubsystem(SUBSYSTEM_NAME, MANAGEMENT_API_MAJOR_VERSION, MANAGEMENT_API_MINOR_VERSION); registration.registerSubsystemModel(GateInWcmRootResource.INSTANCE); } /* * (non-Javadoc) * * @see org.jboss.as.controller.Extension#initializeParsers(org.jboss.as.controller.parsing.ExtensionParsingContext) */ @Override public void initializeParsers(ExtensionParsingContext context) { for (Namespace namespace : Namespace.values()) { XMLElementReader<List<ModelNode>> reader = namespace.getXMLReader(); if (reader != null) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, namespace.getUri(), reader); } } } }
package com.qx.wechat.comm.sdk.request.query; import com.qx.wechat.comm.sdk.request.msg.PassiveMsgType; public class RobotNameQuery extends BasicQuery{ private static final long serialVersionUID = 1723864340095385011L; private String robot_wxid; public RobotNameQuery() { super.setType(PassiveMsgType.ROBOT_NAME_MSG.getValue()); } public String getRobot_wxid() { return robot_wxid; } public RobotNameQuery setRobot_wxid(String robot_wxid) { this.robot_wxid = robot_wxid; return this; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.interceptor; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.CachingConfigurer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.testfixture.cache.CacheTestUtils; import org.springframework.lang.Nullable; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.springframework.context.testfixture.cache.CacheTestUtils.assertCacheHit; import static org.springframework.context.testfixture.cache.CacheTestUtils.assertCacheMiss; /** * Provides various {@link CacheResolver} customisations scenario * * @author Stephane Nicoll * @since 4.1 */ class CacheResolverCustomizationTests { private ConfigurableApplicationContext context; private CacheManager cacheManager; private CacheManager anotherCacheManager; private SimpleService simpleService; @BeforeEach void setup() { this.context = new AnnotationConfigApplicationContext(Config.class); this.cacheManager = context.getBean("cacheManager", CacheManager.class); this.anotherCacheManager = context.getBean("anotherCacheManager", CacheManager.class); this.simpleService = context.getBean(SimpleService.class); } @AfterEach void tearDown() { this.context.close(); } @Test void noCustomization() { Cache cache = this.cacheManager.getCache("default"); Object key = new Object(); assertCacheMiss(key, cache); Object value = this.simpleService.getSimple(key); assertCacheHit(key, value, cache); } @Test void customCacheResolver() { Cache cache = this.cacheManager.getCache("primary"); Object key = new Object(); assertCacheMiss(key, cache); Object value = this.simpleService.getWithCustomCacheResolver(key); assertCacheHit(key, value, cache); } @Test void customCacheManager() { Cache cache = this.anotherCacheManager.getCache("default"); Object key = new Object(); assertCacheMiss(key, cache); Object value = this.simpleService.getWithCustomCacheManager(key); assertCacheHit(key, value, cache); } @Test void runtimeResolution() { Cache defaultCache = this.cacheManager.getCache("default"); Cache primaryCache = this.cacheManager.getCache("primary"); Object key = new Object(); assertCacheMiss(key, defaultCache, primaryCache); Object value = this.simpleService.getWithRuntimeCacheResolution(key, "default"); assertCacheHit(key, value, defaultCache); assertCacheMiss(key, primaryCache); Object key2 = new Object(); assertCacheMiss(key2, defaultCache, primaryCache); Object value2 = this.simpleService.getWithRuntimeCacheResolution(key2, "primary"); assertCacheHit(key2, value2, primaryCache); assertCacheMiss(key2, defaultCache); } @Test void namedResolution() { Cache cache = this.cacheManager.getCache("secondary"); Object key = new Object(); assertCacheMiss(key, cache); Object value = this.simpleService.getWithNamedCacheResolution(key); assertCacheHit(key, value, cache); } @Test void noCacheResolved() { Method method = ReflectionUtils.findMethod(SimpleService.class, "noCacheResolved", Object.class); assertThatIllegalStateException().isThrownBy(() -> this.simpleService.noCacheResolved(new Object())) .withMessageContaining(method.toString()); } @Test void unknownCacheResolver() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> this.simpleService.unknownCacheResolver(new Object())) .satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("unknownCacheResolver")); } @Configuration @EnableCaching static class Config implements CachingConfigurer { @Override @Bean public CacheManager cacheManager() { return CacheTestUtils.createSimpleCacheManager("default", "primary", "secondary"); } @Bean public CacheManager anotherCacheManager() { return CacheTestUtils.createSimpleCacheManager("default", "primary", "secondary"); } @Bean public CacheResolver primaryCacheResolver() { return new NamedCacheResolver(cacheManager(), "primary"); } @Bean public CacheResolver secondaryCacheResolver() { return new NamedCacheResolver(cacheManager(), "primary"); } @Bean public CacheResolver runtimeCacheResolver() { return new RuntimeCacheResolver(cacheManager()); } @Bean public CacheResolver namedCacheResolver() { NamedCacheResolver resolver = new NamedCacheResolver(); resolver.setCacheManager(cacheManager()); resolver.setCacheNames(Collections.singleton("secondary")); return resolver; } @Bean public CacheResolver nullCacheResolver() { return new NullCacheResolver(cacheManager()); } @Bean public SimpleService simpleService() { return new SimpleService(); } } @CacheConfig(cacheNames = "default") static class SimpleService { private final AtomicLong counter = new AtomicLong(); @Cacheable public Object getSimple(Object key) { return this.counter.getAndIncrement(); } @Cacheable(cacheResolver = "primaryCacheResolver") public Object getWithCustomCacheResolver(Object key) { return this.counter.getAndIncrement(); } @Cacheable(cacheManager = "anotherCacheManager") public Object getWithCustomCacheManager(Object key) { return this.counter.getAndIncrement(); } @Cacheable(cacheResolver = "runtimeCacheResolver", key = "#p0") public Object getWithRuntimeCacheResolution(Object key, String cacheName) { return this.counter.getAndIncrement(); } @Cacheable(cacheResolver = "namedCacheResolver") public Object getWithNamedCacheResolution(Object key) { return this.counter.getAndIncrement(); } @Cacheable(cacheResolver = "nullCacheResolver") // No cache resolved for the operation public Object noCacheResolved(Object key) { return this.counter.getAndIncrement(); } @Cacheable(cacheResolver = "unknownCacheResolver") // No such bean defined public Object unknownCacheResolver(Object key) { return this.counter.getAndIncrement(); } } /** * Example of {@link CacheResolver} that resolve the caches at * runtime (i.e. based on method invocation parameters). * <p>Expects the second argument to hold the name of the cache to use */ private static class RuntimeCacheResolver extends AbstractCacheResolver { private RuntimeCacheResolver(CacheManager cacheManager) { super(cacheManager); } @Override @Nullable protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) { String cacheName = (String) context.getArgs()[1]; return Collections.singleton(cacheName); } } private static class NullCacheResolver extends AbstractCacheResolver { private NullCacheResolver(CacheManager cacheManager) { super(cacheManager); } @Override @Nullable protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) { return null; } } }
package com.reactnative.googlecast.types; import androidx.annotation.Nullable; import com.google.android.gms.cast.MediaStatus; public class RNGCPlayerState { public static int fromJson(final @Nullable String value) { switch (value) { case "buffering": return MediaStatus.PLAYER_STATE_BUFFERING; case "idle": return MediaStatus.PLAYER_STATE_IDLE; case "paused": return MediaStatus.PLAYER_STATE_PAUSED; case "playing": return MediaStatus.PLAYER_STATE_PLAYING; case "loading": default: return MediaStatus.PLAYER_STATE_UNKNOWN; } } public static @Nullable String toJson(final int value) { switch (value) { case MediaStatus.PLAYER_STATE_BUFFERING: return "buffering"; case MediaStatus.PLAYER_STATE_IDLE: return "idle"; case MediaStatus.PLAYER_STATE_PAUSED: return "paused"; case MediaStatus.PLAYER_STATE_PLAYING: return "playing"; default: return null; } } }
package com.example.u5_pastragram1; public class SignUpActivity { }
package indi.jcl.magicblog.interceptor; import org.springframework.util.StringUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Created by Magic Long on 2016/9/22. */ public class PermissionInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); String requestType = request.getHeader("X-Requested-With"); if (session.getAttribute("session") == null) { if (!StringUtils.isEmpty(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) { response.setStatus(911); response.setHeader("sessionstatus", "timeout"); response.addHeader("loginPath", "login.html"); } response.sendRedirect(request.getContextPath() + "/login.html"); return false; } else { return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex); } }
package com.example.peti.wateringsystem; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.arch.persistence.room.TypeConverters; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; @Database(entities = {Measurement.class}, version = 1, exportSchema = false) @TypeConverters({Converters.class}) public abstract class MeasurementRoomDatabase extends RoomDatabase { public abstract MeasurementDAO measurementDao(); private static volatile MeasurementRoomDatabase INSTANCE; private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){ @Override public void onOpen (@NonNull SupportSQLiteDatabase db){ super.onOpen(db); } }; static MeasurementRoomDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (MeasurementRoomDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), MeasurementRoomDatabase.class, "word_database") .addCallback(sRoomDatabaseCallback) .allowMainThreadQueries() .build(); } } } return INSTANCE; } }
package assign5; public class Customer { private String custNo; private String custName; private String category; public Customer(String custNo, String custName, String category) throws InvalidInputException { if (( custNo.startsWith("c")||custNo.startsWith("C") )&&custName.length()>=4 &&(category.equals("Platinum")||category.equals("Gold")||category.equals("Silver"))) { this.custNo = custNo; this.custName = custName; this.category = category; } else { throw new InvalidInputException("Enter Valid Detais"); } } public String getCustNo() { return custNo; } public void setCustNo(String custNo) { this.custNo = custNo; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
package com.javaguru.studentservice.student; import com.javaguru.studentservice.student.domain.StudentEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface StudentRepository extends JpaRepository<StudentEntity, String> { }
package br.com.zolp.estudozolp.types; /** * Enumerator responsável por identificar os tipos de processo a que o log se refere. * * @author stp * @version 0.0.1-SNAPSHOT * */ public enum TipoProcesso { HTTP(1, "HTTP"), JMS(2, "JMS"), ARQUIVO(-1, "ARQUIVO"); private int tipoInt; private String tipoStr; TipoProcesso(final int i, final String s) { this.tipoInt = i; this.tipoStr = s; } public int toInt() { return this.tipoInt; } public String toString() { return this.tipoStr; } }
package cn.happy.spring0930.dao; import cn.happy.spring0930.entity.User; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; /** * Created by LY on 2017/9/30. */ @Component @Repository @Service public interface IUserDao { public void save(User u); }
package com.beike.dao.card; import com.beike.common.entity.card.Card; import com.beike.common.exception.StaleObjectStateException; import com.beike.dao.GenericDao; /** * @author yurenli * 卡密记录Dao * 2011-12-16 10:38:02 */ public interface CardDao extends GenericDao<Card, Long>{ /** * 根据主键查询 * @param cardNo * @return */ public Card findById(Long id); /** * 根据卡号查询 * @param cardNo * @return */ public Card findByCardNo(String cardNo,String cardPwd); /** * 根据卡号,卡密信息更新 * @param cardNo * @param cardPwd * @param userId * @param version */ public void updateBycardNoorcardPwd(String cardNo,String cardPwd,Long userId,Long version) throws StaleObjectStateException; /** * 数据插入 * @param card * @return */ public Long insertCard(Card card); /** * 数据更新 * @param card * @return */ public void updateCard(Card card)throws StaleObjectStateException; }
package core.event.game.damage; import core.server.game.Damage; public class TargetEquipmentCheckDamageEvent extends AbstractDamageEvent { public TargetEquipmentCheckDamageEvent(Damage damage) { super(damage); } }
package com.example.hemil.papa_johns.AbstractFactory; public class ItalianSausageMarinara_Pasta implements Pasta { int quantity; public ItalianSausageMarinara_Pasta(int quantity){ this.quantity = quantity; } public String getName(){ return "Italian Sausage Marinara"; } public double getCost() { return 10.00*quantity; } }
package demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Source; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.MessageChannel; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @EnableBinding(Source.class) @RestController public class PaymentSource { @Autowired private MessageChannel output; @RequestMapping(path = "/api/payments", method = RequestMethod.POST) public void locations(@RequestBody String paymentInfo) { this.output.send(MessageBuilder.withPayload(paymentInfo).build()); } }
package com; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * Created by Administrator on 2017/07/15. */ public class Mainh00 extends Application { @Override public void start(Stage stage) { stage.setTitle("HTML"); stage.setWidth(500); stage.setHeight(500); Scene scene = new Scene(new Group()); VBox root = new VBox(); Hyperlink link = new Hyperlink("Moreyoung"); root.getChildren().addAll(link); scene.setRoot(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
package com.redsun.platf.dao.base; import com.redsun.platf.entity.tag.Attachment; import com.redsun.platf.util.sideutil.PagedResult; import com.redsun.platf.util.search.MorePropertyFilter; import org.hibernate.criterion.Criterion; import java.io.Serializable; import java.util.List; import java.util.Map; /** * 封装Page的DAO泛型接口. * * 可在Service层直接使用, 也可以扩展泛型DAO子类使用 * * 参考Spring2.5自带的Petlinc例子, 使用HibernateTemplate,取消使用Hibernate原生API. * * @param <T> DAO操作的对象类型 * @param <PK> 主键类型 * * @author 1.1 * 增加extends idao ,將有關page的操作全整到次處 * * */ public interface IPagedDao<T, PK extends Serializable> extends IAbstractBaseDao<T, PK> { /** * 分页获取全部对象. */ public abstract PagedResult<T> getAll(final PagedResult<T> page); /** * 按HQL分页查询. * * @param page 分页参数. 注意不支持其中的orderBy参数. * @param hql hql语句. * @param values 数量可变的查询参数,按顺序绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ public abstract PagedResult<T> findPage(final PagedResult<T> page, final String hql, final Object... values); /** * 按HQL分页查询. * * @param page 分页参数. 注意不支持其中的orderBy参数. * @param hql hql语句. * @param values 命名参数,按名称绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ public abstract PagedResult<T> findPage(final PagedResult<T> page, final String hql, final Map<String, ?> values); /** * 按Criteria分页查询. * * @param page 分页参数. * @param criterions 数量可变的Criterion. * * @return 分页查询结果.附带结果列表及所有查询输入参数. */ public abstract PagedResult<T> findPage(final PagedResult<T> page, final Criterion... criterions); /** * 按属性过滤条件列表分页查找对象. */ public abstract PagedResult<T> findPage(final PagedResult<T> page, final List<MorePropertyFilter> filters); }
package br.com.porquesim.eventmanager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class EventManager { private Map<Class<? extends Event>, List<EventConfiguration>> targets = new LinkedHashMap<Class<? extends Event>, List<EventConfiguration>>(); private Map<String, List<EventListener>> map = new LinkedHashMap<String, List<EventListener>>(); private List<Object> sources = new ArrayList<Object>(); private static EventManager INSTANCE = new EventManager(); public static EventManager get() { return INSTANCE; } private EventManager() { } public void registerListener(Object caller) { Method[] methods = caller.getClass().getDeclaredMethods(); for(Method m : methods) { System.out.println(m.getName() + " => " + m.isAnnotationPresent(ListenTo.class)); if(m.isAnnotationPresent(ListenTo.class)) { ListenTo listener = m.getAnnotation(ListenTo.class); Class<? extends Event> evtClass = listener.event(); EventConfiguration config = new EventConfiguration(caller, m); if(targets.get(evtClass) == null) { targets.put(evtClass, new LinkedList<EventConfiguration>()); } targets.get(evtClass).add(config); } } } public void registerListener(String event, EventListener listener) { if(map.get(event) == null) { map.put(event, new LinkedList<EventListener>()); } map.get(event).add(listener); } public void fire(Event evt) { List<EventConfiguration> currentTargets = targets.get(evt.getClass()); if(currentTargets != null) { try { for(int i = 0; i < currentTargets.size(); i++) { EventConfiguration config = currentTargets.get(i); config.getMethod().invoke(config.getListener(), evt); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } public void fire(String evt) { List<EventListener> currentTargets = map.get(evt); if(currentTargets != null) { for(int i = 0; i < currentTargets.size(); i++) { EventListener listener = currentTargets.get(i); listener.on(evt); } } } }
package com.mahang.weather.view.card; import android.content.Context; import android.support.v7.widget.CardView; import android.util.AttributeSet; public class WeatherCardSuggestionView extends CardView { public WeatherCardSuggestionView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public WeatherCardSuggestionView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onFinishInflate() { // TODO Auto-generated method stub super.onFinishInflate(); } }
package com.pisen.ott.launcher.localplayer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ThumbnailUtils; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.pisen.ott.launcher.R; import com.pisen.ott.launcher.localplayer.AlbumData; /** * 一级浏览适配器 * * @author yangyp * @version 1.0, 2015年1月20日 上午11:10:56 */ public class ImageLocalPalyerPagerAdapter extends LocalPalyerPagerAdapter { public ImageLocalPalyerPagerAdapter(Context context) { super(context); } @Override public View newView(Context context, AlbumData item, ViewGroup parent) { FileBrowserIconView f = new FileBrowserIconView(context); f.setIconBound(context.getResources().getDimensionPixelSize(R.dimen.local_player_image_width) , context.getResources().getDimensionPixelSize(R.dimen.local_player_image_height)); return f; } @Override public void bindView(final View view, Context context, final AlbumData item) { FileBrowserIconView iconView = (FileBrowserIconView) view; iconView.setIconText(item.title, item.count); if (!TextUtils.isEmpty(item.thumbnailUrl)) { Bitmap bitmap = BitmapFactory.decodeFile(item.thumbnailUrl); if (bitmap != null) { iconView.setIconImageBitmap(bitmap); } else { // 无缩略图,设置默认图片 iconView.setIconImageBitmapRes(R.drawable.local_image); } } else { iconView.setIconImageBitmapRes(R.drawable.local_image); setThum(iconView.findViewById(R.id.imgIcon), item); } } /** * 异步获得第一张缩略图 * @param v * @param item */ public static void setThum(final View v, final AlbumData item){ if (v instanceof ImageView) { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { Bitmap b = (Bitmap) msg.obj; if (b != null) { ((ImageView)v).setImageBitmap(b); }else{ // 无缩略图,设置默认图片 ((ImageView)v).setImageResource(R.drawable.local_image); } } } }; if (!TextUtils.isEmpty(item.path)) { (new Thread() { @Override public void run() { Message m = new Message(); m.what = 1; m.obj = getImageThumbnail(item.path, 300, 300); handler.sendMessage(m); } }).start(); }else{ // 无缩略图,设置默认图片 ((ImageView)v).setImageResource(R.drawable.local_image); } } } /** 获取图片文件的缩略图 */ public static Bitmap getImageThumbnail(String imagePath, int width, int height) { Bitmap bitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = true; // 获取这个图片的宽和高,注意此处的bitmap为null bitmap = BitmapFactory.decodeFile(imagePath, options); options.inJustDecodeBounds = false; // 设为 false // 计算缩放比 int h = options.outHeight; int w = options.outWidth; int beWidth = w / width; int beHeight = h / height; int be = 1; if (beWidth < beHeight) { be = beWidth; } else { be = beHeight; } if (be <= 0) { be = 1; } options.inSampleSize = be; // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false bitmap = BitmapFactory.decodeFile(imagePath, options); // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象 bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT); return bitmap; } }
package com.K.HJ; import java.util.HashMap; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/board") public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Autowired SqlSession session; @RequestMapping("/select") public String select() { logger.info("Welcome home! The client locale is " + 1 + "."); List<HashMap<String, Object>> resultList = session.selectList("test.select"); logger.info("Count : {}", resultList.size()); return "home"; } }
/* * Copyright (c) 2005-2009 Citrix Systems, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation, with the additional linking exception as * follows: * * Linking this library statically or dynamically with other modules is * making a combined work based on this library. Thus, the terms and * conditions of the GNU General Public License cover the whole combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend this exception to your version of * the library, but you are not obligated to do so. If you do not wish to do * so, delete this exception statement from your version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.citrix.xenserver.console; import java.net.Socket; import java.net.URL; import java.util.logging.Logger; import java.util.logging.Level; import javax.swing.SwingUtilities; public class Main { public static void main(String[] args) throws Throwable { new Main(args, new Initialize(), new Initialize()); } private static final Logger logger = Logger.getLogger(Main.class.getName()); public final VNCCanvas canvas_ = new VNCCanvas(); public VNCStream stream_; private boolean usessl; private String path; private String auth; private int port; private ConnectionListener _listener; private ConsoleListener _console; public boolean firstTime = true; public Main(String[] args, ConnectionListener listener, ConsoleListener console) { if ("true".equals(args[2])) { usessl = true; } else { usessl = false; port = Integer.parseInt(args[3]); } path = args[0]; auth = args[1]; stream_ = new VNCStream(canvas_, listener, console); canvas_.setStream(stream_); canvas_.setConsoleListener(console); _listener = listener; _console = console; } public void connect() { try { if (usessl) { stream_.disconnect(); URL uri = new URL(path); String uuid = auth; RawHTTP http = new RawHTTP("CONNECT", uri.getHost(), 443, uri .getPath().concat("?").concat(uri.getQuery()), uuid, "https".equals(uri.getProtocol()), _listener, _console); http.connect(); stream_.connect(http, new char[0]); } else { stream_.disconnect(); String password = auth; int n = password.length(); char[] c = new char[n]; password.getChars(0, n, c, 0); stream_.connectSocket(new Socket(path, port), c); } } catch (final Throwable t) { if (_listener != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { _listener.ConnectionFailed(t.getMessage()); } }); } } } }
/* * 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 modelo; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author USUARIO */ @Entity @Table(name = "equipo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Equipo.findAll", query = "SELECT e FROM Equipo e") , @NamedQuery(name = "Equipo.findByIdEquipo", query = "SELECT e FROM Equipo e WHERE e.idEquipo = :idEquipo") , @NamedQuery(name = "Equipo.findByIntegral", query = "SELECT e FROM Equipo e WHERE e.integral = :integral") , @NamedQuery(name = "Equipo.findByAsociado", query = "SELECT e FROM Equipo e WHERE e.asociado = :asociado")}) public class Equipo implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "idEquipo") private Integer idEquipo; @Size(max = 45) @Column(name = "integral") private String integral; @Size(max = 45) @Column(name = "asociado") private String asociado; public Equipo() { } public Equipo(Integer idEquipo) { this.idEquipo = idEquipo; } public Integer getIdEquipo() { return idEquipo; } public void setIdEquipo(Integer idEquipo) { this.idEquipo = idEquipo; } public String getIntegral() { return integral; } public void setIntegral(String integral) { this.integral = integral; } public String getAsociado() { return asociado; } public void setAsociado(String asociado) { this.asociado = asociado; } @Override public int hashCode() { int hash = 0; hash += (idEquipo != null ? idEquipo.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Equipo)) { return false; } Equipo other = (Equipo) object; if ((this.idEquipo == null && other.idEquipo != null) || (this.idEquipo != null && !this.idEquipo.equals(other.idEquipo))) { return false; } return true; } @Override public String toString() { return "modelo.Equipo[ idEquipo=" + idEquipo + " ]"; } }
package ffm.slc.model.resources; /** * The person's Social Security number or a state-approved alternative identification number. */ public class StaffId extends StringResource{}
package model_checker; public class TreeNode { boolean isAtomicProperty; String atomicProperty; String operator; TreeNode left; TreeNode right; public TreeNode(boolean isAtomicProperty, String atomicProperty, String operator){ this.isAtomicProperty = isAtomicProperty; this.atomicProperty = atomicProperty; this.operator = operator; } }
package com.cleanup.todocTB.repositories; import android.arch.lifecycle.LiveData; import com.cleanup.todocTB.database.dao.ProjectDao; import com.cleanup.todocTB.model.Project; import java.util.List; public class ProjectDataRepository { private ProjectDao mProjectDao; public ProjectDataRepository(ProjectDao pProjectDao) { mProjectDao = pProjectDao; } public LiveData<List<Project>> getProjects() { return mProjectDao.getProjects(); } }
/* * */ package global.coda.hospitalmanagement.config; import org.glassfish.jersey.server.ResourceConfig; import global.coda.hospitalmanagement.service.DoctorService; import global.coda.hospitalmanagement.service.PatientService; /** * @author VC * */ public class JerseyConfig extends ResourceConfig { /** * Instantiates a new jersey config. */ public JerseyConfig() { register(DoctorService.class); register(PatientService.class); } }
package com.lesports.albatross.activity; import android.content.Intent; import android.media.MediaScannerConnection; import android.os.Bundle; import android.os.Environment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.lesports.albatross.Constants; import com.lesports.albatross.R; import com.lesports.albatross.adapter.community.PhotoPagerAdapter; import com.lesports.albatross.custom.FixedViewPager; import com.lesports.albatross.utils.FileUtil; import com.lesports.albatross.utils.FrescoUtil; import com.lesports.albatross.utils.Utils; import java.io.File; import java.util.ArrayList; import static me.nereo.multi_image_selector.MultiImageSelector.EXTRA_RESULT; /** * 图片预览页 * Created by jiangjianxiong on 16/6/8. */ public class PhotoActivity extends BaseActivity implements View.OnClickListener { private FixedViewPager mPhotoViewPager; private PhotoPagerAdapter adapter; private TextView tv_index;//当前位置 private TextView tv_count;//总数 private ImageView iv_save; private ArrayList<String> mList; private int currentPosition = 0;//当前位置 private boolean isLocal = Boolean.FALSE;//默认false为普通预览,true为可取消选择的本地图片(来自:发动态-图片预览) @Override public void resourcesInit(Bundle savedInstanceState) { mList = getIntent().getStringArrayListExtra("data"); currentPosition = getIntent().getIntExtra("position", 0); isLocal = getIntent().getBooleanExtra("isLocal", false); if (!isLocal) { setHeaderVisiable(false); } } @Override public int viewBindLayout() { return R.layout.activity_photo; } @Override public void viewBindId() { mPhotoViewPager = (FixedViewPager) findViewById(R.id.viewpager); tv_index = (TextView) findViewById(R.id.tv_index); tv_count = (TextView) findViewById(R.id.tv_count); if (!isLocal) { iv_save = (ImageView) findViewById(R.id.iv_save); iv_save.setVisibility(View.VISIBLE); } } @Override public void viewInit(LayoutInflater inflater) { if (isLocal) { setRightImg(R.drawable.ic_del_selector); } adapter = new PhotoPagerAdapter(PhotoActivity.this, isLocal); mPhotoViewPager.setAdapter(adapter); adapter.updateDatas(mList); mPhotoViewPager.setCurrentItem(currentPosition); tv_count.setText(String.valueOf(mList.size())); updateTitle(); } @Override public void viewBindListener() { mPhotoViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { currentPosition = position; updateTitle(); } @Override public void onPageScrollStateChanged(int state) { } }); if (!isLocal) { iv_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!Utils.isFastClick(PhotoActivity.this)) { savePhoto(); } } }); } } /** * 更新序号 */ private void updateTitle() { tv_index.setText(String.valueOf(currentPosition + 1)); } /** * 保存到手机 */ private void savePhoto() { String folder = Environment.getExternalStorageDirectory().getPath() + Constants.FOLDER_NAME; if (!FileUtil.isFolderExist(folder)) { FileUtil.makeDirs(folder); } File toFile = new File(folder, System.currentTimeMillis() + ".jpg"); File file = FrescoUtil.getCachedImageOnDisk(mList.get(currentPosition));//首先检查本地是否存在图片的缓存文件 if (null != file) { FileUtil.savePhoto(file, toFile);//直接保存 } else { FrescoUtil.saveBitmap(PhotoActivity.this, mList.get(currentPosition), toFile); } MediaScannerConnection.scanFile(this, new String[]{toFile.toString()}, null, null); } /** * 删除单张 */ @Override protected void handleHeaderEventRight() { mList.remove(currentPosition);//remove if (!mList.isEmpty()) { //update viewpager adapter = new PhotoPagerAdapter(PhotoActivity.this, isLocal); mPhotoViewPager.setAdapter(adapter); adapter.updateDatas(mList); // 更新index if (currentPosition == mList.size()) { currentPosition--; } mPhotoViewPager.setCurrentItem(currentPosition); updateTitle(); tv_count.setText(String.valueOf(mList.size())); } else {//返回 handleHeaderEventLeft(); } } /** * 返回 */ @Override protected void handleHeaderEventLeft() { exit(); } public void exit() { Intent data = new Intent(); data.putStringArrayListExtra(EXTRA_RESULT, mList); setResult(RESULT_OK, data); finish(); } }
/* * 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 fiuba.algo3.tests; import fiuba.algo3.modelo.Persona; import org.junit.Assert; import org.junit.Test; /** * * @author brahvic */ public class PersonaTests { @Test public void test01PersonaIgualdadConMismoNombre(){ Persona per = new Persona("Braian"); Assert.assertTrue(per.equals(new Persona("Braian"))); } @Test public void test02PersonaFallaIgualdadNombreDistinto(){ Persona per = new Persona("Braian"); Assert.assertFalse(per.equals(new Persona("Hernan"))); } @Test public void test03PersonaAgregaEvento(){ Persona per = new Persona("Braian"); per.agregarEvento("miEvento", 2016, 6, 15, 2); Assert.assertTrue(per.estaOcupado(2016, 6, 15, 2)); } @Test public void test04PersonaNoTieneEvento(){ Persona per = new Persona("Braian"); Assert.assertFalse(per.estaOcupado(2016, 6, 15, 2)); } }
package com.Day15; public class WelcomeMessage { public static void main(String[] args) { System.out.println("Welcome to HashMap program..."); } }
package com.wdl.webapp.filter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; /** * @author bin * */ public class SystemFilter implements Filter { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response =(HttpServletResponse) servletResponse; String basePath = request.getContextPath(); request.setAttribute("basePath", basePath); // XSS漏洞 filterChain.doFilter(new RequestWrapper(request), response); //禁用缓存 2016年7月19日14:28:09 @Defferson.Cheng response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); } public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() { } }
package amery.jdk.lambda; public class SubDefaultFunClass implements DefaultFunInterface { public static void main(String[] args) { // 实例化一个子类对象,改子类对象可以直接调用父接口中的默认方法 count SubDefaultFunClass sub = new SubDefaultFunClass(); sub.count(); } }
package String类; /** *将一个字符串指定部分反转 。比如 “ab cdef cdefg”反转为 ”ab fedc fedc g” */ public class 面试题2 { public static void main(String[] args) { System.out.println(getReverse1("hhudench", 3, 7)); System.out.println(getReverse2("hhudench", 3, 7)); System.out.println(getReverse2("hhudench", 3, 7)); } //该方法将String转为char型数组,在循环颠倒 public static String getReverse1(String s,int start, int end){ char[] s_chars = s.toCharArray(); char temp = ' '; for (int x = start-1,y=end-1;x<y;x++,y--) { temp = s_chars[x]; s_chars[x] = s_chars[y]; s_chars[y] = temp; } return new String(s_chars); } //使用Strin拼接,效率低 public static String getReverse3(String s,int start, int end){ String s1 = s.substring(0,start-1); for (int i = end-1;i>=start-1;i++){ s1 += s.charAt(i); } s1 += s.substring(end,s.length()); return s1; } //使用Stringbuilder进行优化 public static String getReverse2(String s,int start, int end){ StringBuilder sb = new StringBuilder(); char[] s_chars = s.toCharArray(); sb.append(s.substring(0,start-1)); for (int i=end-1; i >=start-1; i--) { sb.append(s_chars[i]); } sb.append(s.substring(end,s.length())); return sb.toString(); } }
package poo; import javax.swing.*; import java.awt.Event; import javax.swing.Timer; import java. awt .Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; public class Prueba_temporizador2 { public static void main(String[] args) { Reloj mireloj=new Reloj(); mireloj.enMarcha(3000, true); JOptionPane.showMessageDialog(null, "Pulse para cancelar"); } } class Reloj{ public void enMarcha(int intervalo, final boolean sonido){ class DameLahora2 implements ActionListener{// clase interna con modificador de acceso private public void actionPerformed(ActionEvent evento){ Date ahora=new Date(); System.out.println("Muestra la hora cada 3 segundos " + ahora); if(sonido){ Toolkit.getDefaultToolkit().beep(); } } } ActionListener oyente=new DameLahora2(); Timer mitemporizador=new Timer(intervalo, oyente); mitemporizador.start(); } }
package com.mygdx.game.components; import com.artemis.Component; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; /** * Created by EvilEntity on 23/02/2017. */ public class Renderable extends Component { public static final int SHAPE_RECT = 0; public static final int SHAPE_CIRCLE = 1; public int shape; public ShapeRenderer.ShapeType renderType = ShapeRenderer.ShapeType.Filled; }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ContentCategoryService.java * @Package com.taotao.service * @Description: TODO(用一句话描述该文件做什么) * @author: axin * @date: 2018年12月20日 下午10:14:05 * @version V1.0 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ package com.taotao.service; import java.util.List; import com.taotao.common.pojo.TaotaoResult; import com.taotao.common.pojo.TreeNode; /** * @Description: 内容分类服务 * @ClassName: ContentCategoryService * @author: Axin * @date: 2018年12月20日 下午10:14:05 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ public interface ContentCategoryService { List<TreeNode> getCategoryList(Long parentId); TaotaoResult insertContentCategory(Long parentId, String name); /** * @Description: 删除内容分类根据id * @Title: deleteContentCategoryById * @param: @param id * @param: @return * @return: TaotaoResult * @throws */ void deleteContentCategoryById(Long id); /** * @Description: 修改分类名称 * @Title: updateContentCategoryNameById * @param: id * @return: void * @throws */ void updateContentCategoryNameById(Long id,String name); }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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 com.gbase.streamql.hive; import org.apache.hadoop.hive.ql.HiveDriverRunHook; import org.apache.hadoop.hive.ql.HiveDriverRunHookContext; public class StreamQLDriverRunHook implements HiveDriverRunHook{ private Utility util = new Utility(); //@Override public void preDriverRun(HiveDriverRunHookContext hookContext) throws Exception { Conf.Init(); String cmd = hookContext.getCommand(); StreamQLParser parser = new StreamQLParser(cmd); parser.parse(); util.Logger("STEP INTO PRE DRIVER RUN"); util.Logger("CMD TYPE:" + parser.getCmdType()); StreamJob job = null; if (parser.getTransformSql() != null) { if(parser.getStreamJobName() != null && !parser.getStreamJobName().equals("")) job = new StreamJob(parser.getStreamJobName()); StreamQLBuilder builder = new StreamQLBuilder(parser, job); Logger("change " + hookContext.getCommand() + " \n"); realRun(cmd,parser,job,builder); Logger("to " + hookContext.getCommand() + "\n"); } } //@Override public void postDriverRun(HiveDriverRunHookContext hookContext) throws Exception { // do nothing } private void realRun(String cmd, StreamQLParser parser, StreamJob job, StreamQLBuilder builder) throws Exception { boolean isContinueHandle = false; String myCmd = ""; switch(parser.getCmdType()) { case CREATE_STREAMJOB: { if( job.isExists()) { throw new Exception("Create stream job error! Stream job name \"" + parser.getStreamJobName() + "\" exists!"); } isContinueHandle = true; break; } case SHOW_STREAMJOBS: { //TODO //check status again isContinueHandle = true; break; } case START_STREAMJOB: { if(!job.isExists()) throw new Exception("Start stream job failed! Stream job \"" + parser.getStreamJobName() + "\" does not exist!"); if(job.isStopped()) { job.start(); isContinueHandle = true; } else { throw new Exception("Execute error! target stream job is running!"); } break; } case STOP_STREAMJOB: { if(!job.isExists()) throw new Exception("Stop stream job failed! Stream job \"" + parser.getStreamJobName() + "\" does not exist!"); if(job.isRunning()) { job.stop(); isContinueHandle = true; } else { //do nothing } break; } case DROP_STREAMJOB: { if(!job.isExists()) throw new Exception("Drop stream job failed! Stream job \"" + parser.getStreamJobName() + "\" does not exist!"); if(job.isStopped()) { isContinueHandle = true; } else { throw new Exception("Execute error! Unable to delete the running job!"); } break; } case CREATE_STREAM: case SHOW_STREAMS: case DROP_STREAM: case INSERT_STREAM: case EXPLAIN_PLAN: isContinueHandle = true; break; case UNMATCHED: break; default: break; } if(isContinueHandle) { myCmd = builder.getSql(); util.setCmd(cmd, myCmd); } } private void Logger(String output) { if(Conf.SYS_IS_DEBUG) System.out.print(output); } }
package com.pwq.utils; import org.apache.commons.lang3.time.DateFormatUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 时间工具类 */ public class DateUtils { public static final String PATTERN_YEAR = "yyyy"; public static final String PATTERN1 = "yyyy-MM-dd"; public static final String PATTERN2 = "yyyyMMdd"; public static final String PATTERN3 = "yyyyMMddhhmmss"; public static final String PATTERN4 = "MM/dd/yyyy hh:mm:ss"; public static final String PATTERN5 = "yyyyMM"; public static final String PATTERN6 = "yyyy-MM"; public static final String PATTERN7 = "yyyy-MM-dd hh:mm:ss"; /** * 获取当前月份 * @return */ public static String getCurrentMonth2() { SimpleDateFormat format = new SimpleDateFormat(PATTERN6); System.out.println("执行到我了没"); return format.format(new Date()); } /** * 获取当前月份 * @return */ public static String getCurrentMonth() { SimpleDateFormat format = new SimpleDateFormat(PATTERN5); return format.format(new Date()); } /** * 获取当前日期 * @return */ public static String getCurrentDate() { SimpleDateFormat format = new SimpleDateFormat(PATTERN1); return format.format(new Date()); } /** * 获取当前日期 * @return */ public static String getCurrentDate1() { SimpleDateFormat format = new SimpleDateFormat(PATTERN2); System.out.println("haha"); return format.format(new Date()); } /** * 获取当前年 * @return */ public static String getCurrentYear() { SimpleDateFormat format = new SimpleDateFormat(PATTERN_YEAR); return format.format(new Date()); } /**e * 获取当前日期 * @return */ public static String getCurrentDate2() { SimpleDateFormat format = new SimpleDateFormat(PATTERN2); return format.format(new Date()); } /** * 获取制定毫秒数之前的日期 * * @param timeDiff * @return */ public static String getDesignatedDate(long timeDiff) { SimpleDateFormat format = new SimpleDateFormat(PATTERN1); long nowTime = System.currentTimeMillis(); long designTime = nowTime - timeDiff; return format.format(designTime); } /** * * 获取前几天的日期 */ public static String getPrefixDate(String count) { Calendar cal = Calendar.getInstance(); int day = 0 - Integer.parseInt(count); cal.add(Calendar.DATE, day); // int amount 代表天数 Date datNew = cal.getTime(); SimpleDateFormat format = new SimpleDateFormat(PATTERN1); return format.format(datNew); } /** * * 获取前几天的日期 */ public static String getPrefixDate2(String count) { Calendar cal = Calendar.getInstance(); int day = 0 - Integer.parseInt(count); cal.add(Calendar.DATE, day); // int amount 代表天数 Date datNew = cal.getTime(); SimpleDateFormat format = new SimpleDateFormat(PATTERN2); return format.format(datNew); } /** * 日期转换成字符串 * @param date * @return */ public static String dateToString(Date date, String pattern) { SimpleDateFormat format = new SimpleDateFormat(pattern); return format.format(date); } /** * 字符串转换日期 * @param str * @return */ public static Date stringToDate(String str, String pattern) { SimpleDateFormat format = new SimpleDateFormat(pattern); if (!str.equals("") && str != null) { try { return format.parse(str); } catch (ParseException e) { e.printStackTrace(); } } return null; } /** * @param sBegin * @param sEnd */ // java中怎样计算两个时间如:“21:57”和“08:20”相差的分钟数、小时数 java计算两个时间差小时 分钟 秒 . public void timeSubtract(String sBegin, String sEnd) { SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date begin = null; Date end = null; try { begin = dfs.parse(sBegin); end = dfs.parse(sEnd); } catch (ParseException e) { e.printStackTrace(); } long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒 long day1 = between / (24 * 3600); long hour1 = between % (24 * 3600) / 3600; long minute1 = between % 3600 / 60; long second1 = between % 60; System.out.println("" + day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒"); } /** * 生成时间随机数 * @return */ public static String getRandTimeByDate() { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN3); return sdf.format(new Date()); } /** * @Description:获取当前添加时间 * @param @param minute * @param @return * @throws */ public static Date getNowAddTime(int minute) { Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.MINUTE, minute); return nowTime.getTime(); } /** * 短日期格式转换为长日期格式 * @param shortDate * @return */ public static String getCustomDateByShortDate(String shortDate) { String result = shortDate; try { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN2); SimpleDateFormat csdf = new SimpleDateFormat(PATTERN1); result = csdf.format(sdf.parse(shortDate)); } catch (Exception ex) { // 忽略 } return result; } /** * 短年月日格式转换为长年月格式 * @param shortDate * @return */ public static String getCustomYearMonth(String shortDate) { System.out.println("haha"); String result = shortDate; try { if (shortDate.length() == 6) { result = String.format("%s-%s", result.substring(0, 4), result.substring(4, 6)); } } catch (Exception ex) { // 忽略 } return result; } /** * 获取当前年月 * * @return */ public static String getCustomYearMont(String format) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(new Date()); } /** * 获取与当前年月差别的月份 * * @return */ public static String getDiffMonth(String format, int i) { if(StringUtils.isBlank(format)){ return ""; } String formatTemp = format.replace("-", "").replace(".", ""); String startMonth = getCustomYearMont(formatTemp); if(formatTemp.equalsIgnoreCase("MMYYYY")){ startMonth = startMonth.substring(2,6)+startMonth.substring(0,2); } else if(formatTemp.equalsIgnoreCase("YYYYMM")){ } else{ return ""; } startMonth += "01"; try{ Date dStart = new SimpleDateFormat("yyyyMMdd").parse(startMonth); Calendar dd = Calendar.getInstance(); dd.setTime(dStart); dd.add(Calendar.MONTH, i); startMonth = new SimpleDateFormat(format).format(dd.getTime()); }catch (Exception e){} return startMonth; } /** * 获取与当前年月差别的日期 * * @return */ public static String getDiffDay(String format, int i) { String startMonth = getCustomYearMont(format); startMonth = startMonth.replace("-", ""); try{ Date dStart = new SimpleDateFormat("yyyyMMdd").parse(startMonth); Calendar dd = Calendar.getInstance(); dd.setTime(dStart); dd.add(Calendar.MONTH, i); startMonth = new SimpleDateFormat(format).format(dd.getTime()); } catch (Exception ex) { } return startMonth; } /** * 指定月第一天 * @return */ public static String getFirstDay(Calendar c, String format) { c.set(Calendar.DAY_OF_MONTH, 1); return DateFormatUtils.format(c, format); } /** * 指定月第一天 * @return */ public static String getFirstDay(Date d, String format) { Calendar c = Calendar.getInstance(); c.setTime(d); c.set(Calendar.DAY_OF_MONTH, 1); return DateFormatUtils.format(c, format); } /** * 指定月最后一天 * @return */ public static String getLastDay(Calendar c, String format) { c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); return DateFormatUtils.format(c, format); } /** * 指定月最后一天 * @return */ public static String getLastDay(Date d, String format) { Calendar c = Calendar.getInstance(); c.setTime(d); c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); return DateFormatUtils.format(c, format); } /** * 指定月第一天 * @return */ public static String getFirstDay(String format, int i) { String month = getDiffMonth( "yyyyMM", i); if(month.length() != 6){ return ""; } String firstDay = month + "01"; try{ Date dStart = new SimpleDateFormat("yyyyMMdd").parse(firstDay); firstDay = new SimpleDateFormat(format).format(dStart.getTime()); } catch (Exception ex) {} return firstDay; } /** * 指定月最后一天 * @return */ public static String getLastDay(String format, int i) { String month = getDiffMonth( "yyyyMM", i+1); if(month.length() != 6){ return ""; } String firstDay = month + "01"; String lastDay = ""; try{ Date dStart = new SimpleDateFormat("yyyyMMdd").parse(firstDay); Calendar dd = Calendar.getInstance(); dd.setTime(dStart); dd.add(Calendar.DAY_OF_MONTH, -1); lastDay = new SimpleDateFormat(format).format(dd.getTime()); }catch (Exception ex) {} return lastDay; } /** * @Author: WenqiangPu * @Description: 通过月初时间字符串得到月末时间 * @param month * @return: * @Date: 11:37 2017/10/16 */ public static String getLastDay(String month){ String firstDay = month + "01"; String lastDay = ""; try{ Date dStart = new SimpleDateFormat("yyyyMMdd").parse(firstDay); Calendar dd = Calendar.getInstance(); dd.setTime(dStart); lastDay = dd.getActualMaximum(Calendar.DAY_OF_MONTH)+""; return month+lastDay; }catch (Exception ex) {} return lastDay; } /** * 获取和现在月比较的月份 * @return */ public static String getCompareDate(String date) { try{ if(date.compareTo(getCurrentDate()) > 0 && date.length() >= 6){//将10改成6 兼容yyyy-mm wenqiangpu改 date = String.valueOf(Integer.parseInt(date.substring(0, 4))-1) + date.substring(4, date.length()); } } catch (Exception ex){ } return date; } /** * yyyyMMddHHmmss转化成yyyy-MM-dd HH:mm:ss * @return */ public static String convertYearDateTime(String dateValidDate) { try{ Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateValidDate); dateValidDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); } catch (Exception ex){ } return dateValidDate; } }
class Solution { int[][] fourSides=new int[][]{{1,0},{0,1},{-1,0},{0,-1}}; public int islandPerimeter(int[][] grid) { int perimeter=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]==1){ perimeter+=connectedArea(grid,i,j); } } } return perimeter; } public int connectedArea(int[][] grid, int row, int col){ int sides=0; for(int[] dir:fourSides){ int newRow=row+dir[0]; int newCol=col+dir[1]; if(newRow<0 || newRow>=grid.length ||newCol<0 || newCol>=grid[0].length || grid[newRow][newCol]!=1){ sides++; } } return sides; } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.pipeline.stop; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.yahoo.cubed.settings.CLISettings; /** * Manage pipeline stop. */ public class PipelineStopperManager { private static final String SCRIPT_NAME = "stopPipeline.sh"; private static final String SCRIPT_PATH = CLISettings.PIPELINE_SCRIPTS_PATH; private ExecutorService executorService; /** * Create thread to stop pipeline. */ public PipelineStopperManager() { // create a thread to run the script this.executorService = Executors.newSingleThreadExecutor(); } /** * Create pipeline stopper. */ public static PipelineStopper createStopper(String pipelineName, String pipelineOwner) { PipelineStopper stopper = new PipelineStopper(); stopper.setScriptFileDir(SCRIPT_PATH); stopper.setScriptFileName(SCRIPT_NAME); stopper.setPipelineName(pipelineName); stopper.setPipelineOwner(pipelineOwner); return stopper; } /** * Stop a pipeline. */ public Future<PipelineStopper.Status> stopPipeline(String pipelineName, String pipelineOwner) throws java.lang.InterruptedException { return this.executorService.submit(createStopper(pipelineName, pipelineOwner)); } }
package de.varylab.discreteconformal.plugin; import static de.varylab.discreteconformal.plugin.InterpolationMethod.Incircle; import static de.varylab.discreteconformal.plugin.TargetGeometry.Hyperbolic; import static java.awt.BasicStroke.CAP_SQUARE; import static java.awt.BasicStroke.JOIN_ROUND; import static java.lang.Double.isNaN; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import de.jreality.plugin.job.AbstractJob; import de.jreality.plugin.job.Job; import de.jreality.plugin.job.JobQueuePlugin; import de.jreality.ui.ColorChooseJButton; import de.jreality.ui.ColorChooseJButton.ColorChangedEvent; import de.jreality.ui.ColorChooseJButton.ColorChangedListener; import de.jreality.ui.LayoutFactory; import de.jtem.halfedge.Edge; import de.jtem.halfedge.Face; import de.jtem.halfedge.HalfEdgeDataStructure; import de.jtem.halfedge.Vertex; import de.jtem.halfedge.util.HalfEdgeUtils; import de.jtem.halfedgetools.adapter.AdapterSet; import de.jtem.halfedgetools.adapter.type.generic.TexturePosition3d; import de.jtem.halfedgetools.plugin.HalfedgeInterface; import de.jtem.halfedgetools.plugin.HalfedgeLayer; import de.jtem.halfedgetools.plugin.HalfedgeListener; import de.jtem.halfedgetools.plugin.texturespace.TextureSpacePlugin; import de.jtem.halfedgetools.util.GeometryUtility; import de.jtem.java2d.SceneComponent; import de.jtem.java2dx.Line2DDouble; import de.jtem.jrworkspace.plugin.Controller; import de.jtem.jrworkspace.plugin.Plugin; import de.jtem.jrworkspace.plugin.sidecontainer.widget.ShrinkPanel; import de.varylab.discreteconformal.adapter.HyperbolicModel; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.adapter.CoTexturePositionAdapter; import de.varylab.discreteconformal.uniformization.FundamentalPolygon; import de.varylab.discreteconformal.uniformization.VisualizationUtility; public class UniformizationDomainPlugin extends Plugin implements TextureSpacePlugin, ColorChangedListener, ActionListener, ChangeListener, HalfedgeListener { private HalfedgeInterface hif = null; private JobQueuePlugin jobQueue = null; // active data section private CoHDS surface = null; private FundamentalPolygon Pcut = null, Pminimal = null, Pcanonical = null, Popposite = null, Pkeen = null; private boolean uniformizationUpdateRequested = false; private ShrinkPanel options = new ShrinkPanel("Uniformization"); private JCheckBox fundamentalChecker = new JCheckBox("Fundamental Domain", true), triangulationChecker = new JCheckBox("Triangulation", true), polygonChecker = new JCheckBox("Polygon", true), axesChecker = new JCheckBox("Axes", true), drawAllAxes = new JCheckBox("Draw all Axes", false), dashedAxes = new JCheckBox("Dashed Axes", true), boundaryChecker = new JCheckBox("Boundary", false), faceCirclesChecker = new JCheckBox("Face Circles"), vertexCirclesWhiteChecker = new JCheckBox("White Vertex Circles"), vertexCirclesBlackChecker = new JCheckBox("Black Vertex Circles"); private ColorChooseJButton fundamentalColorButton = new ColorChooseJButton(new Color(0, 102, 204), true), triangulationColorButton = new ColorChooseJButton(new Color(102, 102, 102), true), polygonColorButton = new ColorChooseJButton(new Color(204, 102, 0), true), boundaryColorButton = new ColorChooseJButton(new Color(204, 102, 0), true), axesColorButton = new ColorChooseJButton(new Color(0, 153, 204), true); private SceneComponent scene = new SceneComponent(), boundaryComponent = new SceneComponent(), fundamentalDomainComponent = new SceneComponent(), axesComponent = new SceneComponent(), polygonComponent = new SceneComponent(), boundaryEdgesComponent = new SceneComponent(), triangulationComponent = new SceneComponent(), faceCirclesComponent = new SceneComponent(), vertexCirclesWhiteComponent = new SceneComponent(), vertexCirclesBlackComponent = new SceneComponent(); private Shape unitCircleShape = new Ellipse2D.Double(-1,-1,2,2); private SpinnerNumberModel coverMaxDistanceModel = new SpinnerNumberModel(0.8, 0.0, 100.0, 0.01), coverElementsModel = new SpinnerNumberModel(1, 0, 1000, 1); private JSpinner coverMaxDistanceSpinner = new JSpinner(coverMaxDistanceModel), coverElementsSpinner = new JSpinner(coverElementsModel); private JComboBox<DomainPolygon> domainCombo = new JComboBox<>(DomainPolygon.values()); private JComboBox<HyperbolicModel> modelCombo = new JComboBox<>(HyperbolicModel.values()); private JComboBox<InterpolationMethod> interpolationCombo = new JComboBox<>(InterpolationMethod.values()); private JComboBox<TargetGeometry> geometryCombo = new JComboBox<>(TargetGeometry.values()); public UniformizationDomainPlugin() { scene.addChild(fundamentalDomainComponent); scene.addChild(triangulationComponent); triangulationComponent.setFilled(false); scene.addChild(boundaryEdgesComponent); boundaryEdgesComponent.setFilled(false); boundaryEdgesComponent.setStroke(new BasicStroke(2)); scene.addChild(axesComponent); axesComponent.setFilled(false); axesComponent.setStroke(new BasicStroke(2, CAP_SQUARE, JOIN_ROUND, 1, new float[] {5, 7}, 1)); scene.addChild(polygonComponent); polygonComponent.setFilled(false); polygonComponent.setStroke(new BasicStroke(2)); scene.addChild(boundaryComponent); boundaryComponent.setOutlinePaint(Color.BLACK); boundaryComponent.setFilled(false); boundaryComponent.setStroke(new BasicStroke(2)); boundaryComponent.setVisible(false); fundamentalDomainComponent.setFilled(true); fundamentalDomainComponent.setOutlined(false); faceCirclesComponent.setOutlinePaint(Color.DARK_GRAY); faceCirclesComponent.setFilled(false); scene.addChild(faceCirclesComponent); vertexCirclesWhiteComponent.setFilled(false); scene.addChild(vertexCirclesWhiteComponent); vertexCirclesBlackComponent.setFilled(false); scene.addChild(vertexCirclesBlackComponent); GridBagConstraints lc = LayoutFactory.createLeftConstraint(); GridBagConstraints rc = LayoutFactory.createRightConstraint(); options.setLayout(new GridBagLayout()); options.add(triangulationChecker, lc); options.add(triangulationColorButton, rc); options.add(fundamentalChecker, lc); options.add(fundamentalColorButton, rc); options.add(polygonChecker, lc); options.add(polygonColorButton, rc); options.add(axesChecker, lc); options.add(axesColorButton, rc); options.add(drawAllAxes, lc); options.add(dashedAxes, rc); options.add(boundaryChecker, lc); options.add(boundaryColorButton, rc); options.add(faceCirclesChecker, rc); options.add(vertexCirclesWhiteChecker, rc); options.add(vertexCirclesBlackChecker, rc); options.add(new JSeparator(JSeparator.HORIZONTAL), rc); options.add(new JLabel("Geometry"), lc); options.add(geometryCombo, rc); options.add(new JLabel("Domain"), lc); options.add(domainCombo, rc); options.add(new JLabel("Cover Elements"), lc); options.add(coverElementsSpinner, rc); options.add(new JLabel("Cover Distance"), lc); options.add(coverMaxDistanceSpinner, rc); options.add(new JLabel("Hyperbolic Model"), lc); options.add(modelCombo, rc); options.add(new JLabel("Interpolation"), lc); options.add(interpolationCombo, rc); interpolationCombo.setSelectedItem(Incircle); interpolationCombo.addActionListener(this); modelCombo.addActionListener(this); triangulationChecker.addActionListener(this); triangulationColorButton.addColorChangedListener(this); polygonChecker.addActionListener(this); polygonColorButton.addColorChangedListener(this); axesChecker.addActionListener(this); axesColorButton.addColorChangedListener(this); drawAllAxes.addActionListener(this); dashedAxes.addActionListener(this); boundaryChecker.addActionListener(this); boundaryColorButton.addColorChangedListener(this); fundamentalChecker.addActionListener(this); fundamentalColorButton.addColorChangedListener(this); faceCirclesChecker.addActionListener(this); vertexCirclesWhiteChecker.addActionListener(this); vertexCirclesBlackChecker.addActionListener(this); domainCombo.addActionListener(this); coverElementsSpinner.addChangeListener(this); coverMaxDistanceSpinner.addChangeListener(this); geometryCombo.addActionListener(this); updateStates(); } private void updateStates() { triangulationComponent.setVisible(triangulationChecker.isSelected()); triangulationComponent.setOutlinePaint(triangulationColorButton.getColor()); polygonComponent.setVisible(polygonChecker.isSelected()); polygonComponent.setOutlinePaint(polygonColorButton.getColor()); axesComponent.setVisible(axesChecker.isSelected()); axesComponent.setOutlinePaint(axesColorButton.getColor()); boundaryEdgesComponent.setVisible(boundaryChecker.isSelected()); boundaryEdgesComponent.setOutlinePaint(boundaryColorButton.getColor()); fundamentalDomainComponent.setVisible(fundamentalChecker.isSelected()); faceCirclesComponent.setVisible(faceCirclesChecker.isSelected()); vertexCirclesWhiteComponent.setVisible(vertexCirclesWhiteChecker.isSelected()); vertexCirclesBlackComponent.setVisible(vertexCirclesBlackChecker.isSelected()); Color fc = fundamentalColorButton.getColor(); Color fcAlpha = new Color(fc.getRed(), fc.getGreen(), fc.getBlue(), 51); fundamentalDomainComponent.setPaint(fcAlpha); vertexCirclesWhiteComponent.setOutlinePaint(fc); vertexCirclesBlackComponent.setOutlinePaint(fc); if (dashedAxes.isSelected()) { axesComponent.setStroke(new BasicStroke(2, CAP_SQUARE, JOIN_ROUND, 1, new float[] {5, 7}, 1)); } else { axesComponent.setStroke(new BasicStroke(2)); } scene.fireAppearanceChange(); } @Override public void actionPerformed(ActionEvent e) { updateStates(); if (faceCirclesChecker == e.getSource()) { updateFaceCircles(hif.get(), hif.getAdapters()); } if (vertexCirclesWhiteChecker == e.getSource()) { updateVertexCircles(hif.get(), hif.getAdapters(), true); } if (vertexCirclesBlackChecker == e.getSource()) { updateVertexCircles(hif.get(), hif.getAdapters(), false); } if (domainCombo == e.getSource()) { updateUniformization(); } if (geometryCombo == e.getSource()) { if (getSelectedGeometry() == TargetGeometry.Euclidean) { setHyperbolicModel(HyperbolicModel.Klein); } updateGeometry(true); } if (modelCombo == e.getSource()) { updateGeometry(true); } if (interpolationCombo == e.getSource()) { updateGeometry(true); } if (drawAllAxes == e.getSource()) { updateGeometry(true); } } @Override public void stateChanged(ChangeEvent e) { if (coverElementsSpinner == e.getSource()) { updateUniformization(); } if (coverMaxDistanceSpinner == e.getSource()) { updateUniformization(); } } private void updateGeometry(boolean updateUniformization) { updateAdapters(); uniformizationUpdateRequested = updateUniformization; hif.updateNoUndo(); } public void updateAdapters() { CoTexturePositionAdapter texturePositionAdapter = hif.getAdapters().query(CoTexturePositionAdapter.class); texturePositionAdapter.setInterpolationMethod(getSelectedInterpolation()); texturePositionAdapter.setModel(getSelectedHyperbolicModel()); } public InterpolationMethod getSelectedInterpolation() { return (InterpolationMethod)interpolationCombo.getSelectedItem(); } public HyperbolicModel getSelectedHyperbolicModel() { return (HyperbolicModel)modelCombo.getSelectedItem(); } public void setHyperbolicModel(HyperbolicModel model) { try { modelCombo.removeActionListener(this); modelCombo.setSelectedItem(model); } finally { modelCombo.addActionListener(this); } updateAdapters(); } public void setGeometry(TargetGeometry geometry) { try { geometryCombo.removeActionListener(this); geometryCombo.setSelectedItem(geometry); } finally { geometryCombo.addActionListener(this); } updateAdapters(); } public TargetGeometry getSelectedGeometry() { return (TargetGeometry)geometryCombo.getSelectedItem(); } public DomainPolygon getSelectedPoygonType() { return (DomainPolygon)domainCombo.getSelectedItem(); } @Override public void colorChanged(ColorChangedEvent cce) { updateStates(); } public void updateUniformization() { if (surface != null) { Job j = new AbstractJob() { @Override public String getJobName() { return "Uniformization Visualization"; } @Override protected void executeJob() throws Exception { createUniformization(surface, Pcut, Pminimal, Pcanonical, Popposite, Pkeen); } }; jobQueue.queueJob(j); } } public void createUniformization( CoHDS surface, FundamentalPolygon Pcut, FundamentalPolygon Pminimal, FundamentalPolygon Pcanonical, FundamentalPolygon Popposite, FundamentalPolygon Pkeen ) { this.surface = surface; this.Pcut = Pcut; this.Pminimal = Pminimal; this.Pcanonical = Pcanonical; this.Popposite = Popposite; this.Pkeen = Pkeen; HyperbolicModel model = getSelectedHyperbolicModel(); TargetGeometry geometry = getSelectedGeometry(); int maxElements = coverElementsModel.getNumber().intValue(); double maxDistance = coverMaxDistanceModel.getNumber().doubleValue(); boolean allAxes = drawAllAxes.isSelected(); DomainPolygon p = (DomainPolygon) domainCombo.getSelectedItem(); FundamentalPolygon P = null; switch (p) { case Minimal: P = Pminimal; break; case Canonical: P = Pcanonical; break; case Opposite: P = Popposite; break; case Keen: P = Pkeen; break; default: P = Pcut; break; } Path2D axesPath = new Path2D.Float(); Path2D polyPath = new Path2D.Float(); Path2D triangulationPath = new Path2D.Float(); Path2D boundaryPath = new Path2D.Float(); Path2D fundamentalDomainPath = new Path2D.Float(); P.normalizeEdgeList(); VisualizationUtility.createUniversalCover( P, model, maxElements, maxDistance, true, true, allAxes, null, null, axesPath, polyPath, fundamentalDomainPath ); VisualizationUtility.createTriangulation( surface, P, model, maxElements, maxDistance, triangulationPath, boundaryPath ); triangulationComponent.setShape(triangulationPath); boundaryEdgesComponent.setShape(boundaryPath); axesComponent.setShape(axesPath); polygonComponent.setShape(polyPath); fundamentalDomainComponent.setShape(fundamentalDomainPath); boundaryComponent.setVisible(geometry == Hyperbolic); if (geometry == TargetGeometry.Automatic) { geometry = TargetGeometry.calculateTargetGeometry(surface); } switch (geometry) { case Euclidean: axesComponent.setShape(null); axesComponent.setVisible(false); break; default: break; } switch (model) { case Halfplane: Rectangle2D bbox = polyPath.getBounds2D(); bbox = bbox.createUnion(axesPath.getBounds2D()); Shape realLineShape = new Line2DDouble(1.2*bbox.getMinX(), 0, 1.2*bbox.getMaxX(), 0); boundaryComponent.setShape(realLineShape); break; default: boundaryComponent.setShape(unitCircleShape); break; } scene.fireAppearanceChange(); } private < V extends Vertex<V, E, F>, E extends Edge<V, E, F>, F extends Face<V, E, F>, HDS extends HalfEdgeDataStructure<V, E, F> > void updateFaceCircles(HDS surface, AdapterSet a) { if (!faceCirclesChecker.isSelected()) { faceCirclesComponent.setShape(null); return; } Path2D circles = new Path2D.Double(); for (F f : surface.getFaces()) { double[] p1 = a.getD(TexturePosition3d.class, f.getBoundaryEdge().getTargetVertex()); double[] p2 = a.getD(TexturePosition3d.class, f.getBoundaryEdge().getNextEdge().getTargetVertex()); double[] p3 = a.getD(TexturePosition3d.class, f.getBoundaryEdge().getPreviousEdge().getTargetVertex()); double[] c = GeometryUtility.circumCircle(p1, p2, p3); Ellipse2D e = new Ellipse2D.Double(c[0] - c[3], c[1] - c[3], 2*c[3], 2*c[3]); circles.append(e, false); } faceCirclesComponent.setShape(circles); } private < V extends Vertex<V, E, F>, E extends Edge<V, E, F>, F extends Face<V, E, F>, HDS extends HalfEdgeDataStructure<V, E, F> > void updateVertexCircles(HDS surface, AdapterSet a, boolean white) { if (white) { if (!vertexCirclesWhiteChecker.isSelected()) { vertexCirclesWhiteComponent.setShape(null); return; } } else { if (!vertexCirclesBlackChecker.isSelected()) { vertexCirclesBlackComponent.setShape(null); return; } } Path2D circles = new Path2D.Double(); Set<V> lattice = getSublatticeVertices(surface, white); for (V v : lattice) { V v1 = v.getIncomingEdge().getStartVertex(); V v2 = v.getIncomingEdge().getNextEdge().getTargetVertex(); V v3 = v.getIncomingEdge().getOppositeEdge().getPreviousEdge().getStartVertex(); double[] p1 = a.getD(TexturePosition3d.class, v1); double[] p2 = a.getD(TexturePosition3d.class, v2); double[] p3 = a.getD(TexturePosition3d.class, v3); double[] c = GeometryUtility.circumCircle(p1, p2, p3); if (isNaN(c[0]) || isNaN(c[1]) || isNaN(c[2]) || isNaN(c[3])) continue; Ellipse2D e = new Ellipse2D.Double(c[0] - c[3], c[1] - c[3], 2*c[3], 2*c[3]); circles.append(e, false); } if (white) { vertexCirclesWhiteComponent.setShape(circles); } else { vertexCirclesBlackComponent.setShape(circles); } } private < V extends Vertex<V, E, F>, E extends Edge<V, E, F>, F extends Face<V, E, F>, HDS extends HalfEdgeDataStructure<V, E, F> > Set<V> getSublatticeVertices(HDS surface, boolean white) { Set<V> result = new HashSet<>(); Set<V> visited = new HashSet<>(); if (surface.numVertices() == 0) return visited; TreeSet<V> visitQueue = new TreeSet<>(); visitQueue.add(surface.getVertex(0)); while (!visitQueue.isEmpty()) { V v = visitQueue.pollFirst(); visited.add(v); if (white) result.add(v); for (E e : HalfEdgeUtils.incomingEdges(v)) { V vv = e.getStartVertex(); if (!white) result.add(vv); for (E ee : HalfEdgeUtils.incomingEdges(vv)) { V vvv = ee.getStartVertex(); if (!visited.contains(vvv)) { visitQueue.add(vvv); } } } } return result; } public void reset() { surface = null; Pcut = null; Pminimal = null; Pcanonical = null; Popposite = null; boundaryComponent.setVisible(false); triangulationComponent.setShape(null); axesComponent.setShape(null); polygonComponent.setShape(null); fundamentalDomainComponent.setShape(null); faceCirclesComponent.setShape(null); scene.fireAppearanceChange(); } @Override public SceneComponent getSceneComponent() { return scene; } @Override public ShrinkPanel getOptionPanel() { return options; } @Override public boolean getRenderOnTop() { return true; } @Override public void dataChanged(HalfedgeLayer layer) { if (uniformizationUpdateRequested) { updateUniformization(); uniformizationUpdateRequested = false; } else { reset(); } updateFaceCircles(layer.get(), layer.getEffectiveAdapters()); updateVertexCircles(hif.get(), hif.getAdapters(), true); updateVertexCircles(hif.get(), hif.getAdapters(), false); } @Override public void adaptersChanged(HalfedgeLayer layer) { } @Override public void activeLayerChanged(HalfedgeLayer old, HalfedgeLayer active) { } @Override public void layerCreated(HalfedgeLayer layer) { } @Override public void layerRemoved(HalfedgeLayer layer) { } @Override public void storeStates(Controller c) throws Exception { super.storeStates(c); } @Override public void restoreStates(Controller c) throws Exception { super.restoreStates(c); } @Override public void install(Controller c) throws Exception { super.install(c); hif = c.getPlugin(HalfedgeInterface.class); hif.addHalfedgeListener(this); jobQueue = c.getPlugin(JobQueuePlugin.class); } public int getMaxCoverElements() { return coverElementsModel.getNumber().intValue(); } public double getMaxCoverDistance() { return coverMaxDistanceModel.getNumber().doubleValue(); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.converter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.util.Assert; /** * A {@link MessageConverter} that delegates to a list of registered converters * to be invoked until one of them returns a non-null result. * * <p>As of 4.2.1, this composite converter implements {@link SmartMessageConverter} * in order to support the delegation of conversion hints. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 4.0 */ public class CompositeMessageConverter implements SmartMessageConverter { private final List<MessageConverter> converters; /** * Create an instance with the given converters. */ public CompositeMessageConverter(Collection<MessageConverter> converters) { Assert.notEmpty(converters, "Converters must not be empty"); this.converters = new ArrayList<>(converters); } @Override @Nullable public Object fromMessage(Message<?> message, Class<?> targetClass) { for (MessageConverter converter : getConverters()) { Object result = converter.fromMessage(message, targetClass); if (result != null) { return result; } } return null; } @Override @Nullable public Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { for (MessageConverter converter : getConverters()) { Object result = (converter instanceof SmartMessageConverter smartMessageConverter ? smartMessageConverter.fromMessage(message, targetClass, conversionHint) : converter.fromMessage(message, targetClass)); if (result != null) { return result; } } return null; } @Override @Nullable public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers) { for (MessageConverter converter : getConverters()) { Message<?> result = converter.toMessage(payload, headers); if (result != null) { return result; } } return null; } @Override @Nullable public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) { for (MessageConverter converter : getConverters()) { Message<?> result = (converter instanceof SmartMessageConverter smartMessageConverter ? smartMessageConverter.toMessage(payload, headers, conversionHint) : converter.toMessage(payload, headers)); if (result != null) { return result; } } return null; } /** * Return the underlying list of delegate converters. */ public List<MessageConverter> getConverters() { return this.converters; } @Override public String toString() { return "CompositeMessageConverter[converters=" + getConverters() + "]"; } }
package com.gsccs.sme.plat.auth.service; import java.util.List; import com.gsccs.sme.plat.auth.model.AreaT; /** */ public interface AreaService { List<AreaT> getByParId(Integer parentid); List<AreaT> findAreaList(String ids); /** * 分页查询 */ public List<AreaT> find(AreaT area, String order, int currPage, int pageSize); public int count(AreaT area); public String getAreaStr(Integer id); }
package com.bignerdranch.android.photogallery; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface ApiEndpointInterface { @GET("services/rest/?method=flickr.photos.getRecent&extras=url_s&format=json&nojsoncallback=1") Call<GalleryApiResponse> getGalleryItems(@Query("api_key") String apikey, @Query("page") int page); // toegevoegd voor challenge p.428 @GET("services/rest/?method=flickr.photos.search&extras=url_s&format=json&nojsoncallback=1") Call<GalleryApiResponse> getSearchItems(@Query("api_key") String apikey, @Query("text") String text); }
package com.alibaba.druid.bvt.sql.mysql.alterTable; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; import com.alibaba.druid.sql.parser.Token; import junit.framework.TestCase; import org.junit.Assert; public class MySqlAlterTableTest51_table_options extends TestCase { public void test_0_options_no_comma_no_eq() { String sql = "alter table test001\n" + "auto_increment 1\n" + "avg_row_length 1\n" + "default character set utf8\n" + "checksum 0\n" + "default collate utf8_unicode_ci\n" + "comment 'hehe'\n" + "compression 'LZ4'\n" + "connection 'conn'\n" + "index directory 'path'\n" + "delay_key_write 1\n" + "encryption 'N'\n" + "engine innodb\n" + "insert_method no\n" + "key_block_size 32\n" + "max_rows 999\n" + "min_rows 1\n" + "pack_keys default\n" + "password 'psw'\n" + "row_format dynamic\n" + "stats_auto_recalc default\n" + "stats_persistent default\n" + "stats_sample_pages 10\n" + "tablespace `tbs_name` storage memory\n" + "union (tb1,tb2,tb3)\n" + "auto_increment 1"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); Assert.assertEquals("ALTER TABLE test001\n" + "\tAUTO_INCREMENT = 1 AVG_ROW_LENGTH = 1 CHARACTER SET = utf8 CHECKSUM = 0 COLLATE = utf8_unicode_ci COMMENT = 'hehe' COMPRESSION = 'LZ4' CONNECTION = 'conn' COLLATE = 'path' DELAY_KEY_WRITE = 1 ENCRYPTION = 'N' ENGINE = innodb INSERT_METHOD = no KEY_BLOCK_SIZE = 32 MAX_ROWS = 999 MIN_ROWS = 1 PACK_KEYS = DEFAULT PASSWORD = 'psw' ROW_FORMAT = dynamic STATS_AUTO_RECALC = DEFAULT STATS_PERSISTENT = DEFAULT STATS_SAMPLE_PAGES = 10 TABLESPACE = `tbs_name` STORAGE memory UNION = (tb1, tb2, tb3) AUTO_INCREMENT = 1", SQLUtils.toMySqlString(stmt)); } public void test_0_options_comma_eq() { String sql = "alter table test001\n" + "auto_increment = 2,\n" + "avg_row_length = 2,\n" + "character set = utf8,\n" + "checksum = 1,\n" + "collate = utf8_unicode_ci,\n" + "comment = 'hehe',\n" + "compression = 'NONE',\n" + "connection = 'conn',\n" + "data directory = 'path',\n" + "delay_key_write = 0,\n" + "encryption = 'Y',\n" + "engine = innodb,\n" + "insert_method = first,\n" + "key_block_size = 64,\n" + "max_rows = 999,\n" + "min_rows = 1,\n" + "pack_keys = 0,\n" + "password = 'psw',\n" + "row_format = fixed,\n" + "stats_auto_recalc = 1,\n" + "stats_persistent = 0,\n" + "stats_sample_pages = 2,\n" + "tablespace `tbs_name`\n" + "union = (tb1,tb2,tb3);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); Assert.assertEquals("ALTER TABLE test001\n" + "\tAUTO_INCREMENT = 2 AVG_ROW_LENGTH = 2 CHARACTER SET = utf8 CHECKSUM = 1 COLLATE = utf8_unicode_ci COMMENT = 'hehe' COMPRESSION = 'NONE' CONNECTION = 'conn' COLLATE = 'path' DELAY_KEY_WRITE = 0 ENCRYPTION = 'Y' ENGINE = innodb INSERT_METHOD = first KEY_BLOCK_SIZE = 64 MAX_ROWS = 999 MIN_ROWS = 1 PACK_KEYS = 0 PASSWORD = 'psw' ROW_FORMAT = fixed STATS_AUTO_RECALC = 1 STATS_PERSISTENT = 0 STATS_SAMPLE_PAGES = 2 TABLESPACE = `tbs_name` UNION = (tb1, tb2, tb3);", SQLUtils.toMySqlString(stmt)); } }
package com.bnade.wow.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; /** * Created by liufeng0103@163.com on 2017/7/25. */ @RunWith(SpringRunner.class) @SpringBootTest public class PetServiceTest { @Autowired private PetService petService; @Test public void testFindById() throws Exception { System.out.println(petService.findById(39)); } }
package com.esum.framework.security.pki.keystore.info; import java.io.IOException; import java.sql.SQLException; public abstract class KeyStoreInfo { protected String mKeyStoreFile = null; protected String mKeyStorePassword = null; protected String mKeyStoreFileType = null; protected String mTrustStoreFile = null; protected String mTrustStorePassword = null; KeyStoreInfo() throws IOException, SQLException { init(); } abstract void init() throws IOException, SQLException; public String getKeyStoreFile() { return mKeyStoreFile; } protected void setKeyStoreFile(String keyStoreFile) { mKeyStoreFile = keyStoreFile; } public String getKeyStorePassword() { return mKeyStorePassword; } protected void setKeyStorePassword(String keyStorePassword) { mKeyStorePassword = keyStorePassword; } public String getKeyStoreFileType() { return mKeyStoreFileType; } /** * KeyStore Type: JKS, PKCS12 */ protected void setKeyStoreFileType(String keyStoreFileType) { mKeyStoreFileType = keyStoreFileType; } public String getTrustStoreFile() { return mTrustStoreFile; } protected void setTrustStoreFile(String trustStoreFile) { mTrustStoreFile = trustStoreFile; } public String getTrustStorePassword() { return mTrustStorePassword; } protected void setTrustStorePassword(String trustStorePassword) { mTrustStorePassword = trustStorePassword; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("KeyStore File Path: " + mKeyStoreFile + "\n"); sb.append("KeyStore File Password: " + mKeyStorePassword + "\n"); sb.append("KeyStore File Type: " + mKeyStoreFileType + "\n"); sb.append("TrustSTore File Path: " + mTrustStoreFile + "\n"); sb.append("TrustSTore File Password: " + mTrustStorePassword); return sb.toString(); } }
package com.stk123.task.quartz.job; import com.stk123.util.ServiceUtils; public class XueqiuUser { public String name; public String id; @Override public String toString() { return ServiceUtils.wrapLink(this.name, "http://xueqiu.com/"+this.id); } }
package com.BasicJava; public class IfCodition { public static void main(String[] args) { int StudentMarks =80; if(StudentMarks<100) { System.out.println("student got good score"); } } }
package dev.fujioka.eltonleite.presentation.dto.user; import java.time.LocalDate; public class UserRequestTO { private String username; private String password; private LocalDate dateBirth; public UserRequestTO() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public LocalDate getDateBirth() { return dateBirth; } public void setDateBirth(LocalDate dateBirth) { this.dateBirth = dateBirth; } @Override public String toString() { return String.format("UserRequest [username=%s, password=%s, dateBirth=%s]", username, password, dateBirth); } }
package com.company; public class Node { // reference to the next node in the list Node next; // data in the node (object because we want to store anything) Object data; /** * first constructor for creating node without second reference * @param data data associated with node */ public Node(Object data) { this.data = data; this.next = null; } /** * second constructor for creating full node in one go * @param data data associated with node * @param next reference to next node */ public Node(Object data, Node next) { this.data = data; this.next = next; } public void setData(Object data) { this.data = data; } public Object getData() { return data; } public void setNext(Node next) { this.next = next; } public Node getNext() { return next; } }
package jp.ac.kyushu_u.csce.modeltool.dictionary.dict.handler; import java.util.List; import jp.ac.kyushu_u.csce.modeltool.dictionary.constant.DictionaryConstants; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.DictionaryView; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.Entry; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.TableTab; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.handlers.HandlerUtil; /** * 見出し語のコピーを行うハンドラクラス * * @author KBK yoshimura */ public class CopyHandler extends AbstractHandler implements IHandler { /** * execute * @see org.eclipse.core.commands.IHandler#execute(ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage(); // 辞書ビューの取得(開いていない場合処理なし) DictionaryView view = (DictionaryView)page.findView(DictionaryConstants.PART_ID_DICTIONARY); if (view == null) { return null; } // アクティブなタブの取得(アクティブなタブがない場合は処理なし) TableTab tab = view.getActiveTableTab(false); if (tab == null) { return null; } // 選択されたテーブルの行を取得(行が選択されていない場合処理なし) // Entry selectEntry = tab.getSelection(); // if (selectEntry == null) { // return null; // } List<Entry> selectEntries = tab.getSelections(); // 見出し語のコピー String model = tab.getDictionary().getDictionaryClass().model; // tab.copyEntry(view, selectEntry, model); tab.copyEntries(view, selectEntries, model); return null; } }
package com.designpattern.dp5prototypepattern.deepcopy; import java.io.Serializable; public class Rectangle implements Serializable { public float l = 100; public float w = 100; public void big(){ l *= 2; w *= 2; } public void small(){ l /= 2; w /= 2; } }
package springboot.health; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Health.Builder; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class AppHealth implements HealthIndicator { private int freeDiskSpace = 1000; @Override public Health health() { Builder healthBuilder = new Builder(); if (freeDiskSpace > 500) { healthBuilder.up(); } else { healthBuilder.down(new Exception("Out of disk space!")); } return healthBuilder.build(); } }
package nathan.banking; import java.util.ArrayList; import java.util.HashMap; public class Customer extends User { /** * */ private static final long serialVersionUID = -6742085101022354619L; public static Customer createNew(String username, String password, HashMap<String, String> personalInfo) { User u = new Customer(); u.username = username; u.password = password; u.personalInfo = new HashMap<String, String>(); u.personalInfo.putAll(personalInfo); u.connectedAccounts = new ArrayList<Account>(); DataIO.users.put(username, u); return (Customer)u; } @Override public boolean canViewUserData() { return false; } @Override public boolean canSetUserData() { return false; } @Override public boolean canApproveAccounts() { return false; } @Override public boolean isAdmin() { return false; } }
package com.example.kuno.optionmenubyxml; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /* \res\menu - 메뉴를 정의하는 xml파일 - 가장 상위에 <menu>태그를 가지고 있습니다. - 각각의 메뉴아이템은 <item>태그로 정의해 줍니다. - 메뉴를 정의한 xml파일 onCreateOptionsMenu()메소드 안에서 인플레이터 객체를 사용해서 메뉴정보를 생성합니다. */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { //return super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //return super.onOptionsItemSelected(item); switch (item.getItemId()){ case R.id.itSeoul: Toast.makeText(this, "서울", Toast.LENGTH_SHORT).show(); return true; case R.id.itBusan: Toast.makeText(this, "부산", Toast.LENGTH_SHORT).show(); return true; case R.id.itNewYork: Toast.makeText(this, "뉴욕", Toast.LENGTH_SHORT).show(); return true; case R.id.itVenice: Toast.makeText(this, "베니스", Toast.LENGTH_SHORT).show(); return true; } return false; } }
package com.lidaye.shopIndex.mapper; import com.lidaye.shopIndex.domain.vo.ShopVo; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ShopMapper { List<ShopVo> findShopByCateId(@Param("cid") int cid); List<ShopVo> findShopByShopName(@Param("name") String name,@Param("type") Integer type); }
package com.pykj.ykz.chapter4.intercept; import java.lang.reflect.Method; /** * @description: TODO * @author: zhangpengxiang * @time: 2020/4/21 10:48 */ public class Invocation { private Object[] params; private Method method; private Object target; public Invocation(Object target, Method method, Object[] params) { this.params = params; this.method = method; this.target = target; } public Object proceed() throws Exception { return method.invoke(target, params); } }
import java.util.LinkedList; public class Algorithm { final static int V = 4; public static boolean DFSColorFC(DigraphAM1 A) { return DFSColorFCAux(A, 1); } private static boolean DFSColorFCAux(DigraphAM1 A , int color) { int D[][] = DigraphAM1.getM(); int colorArray[] = new int[V]; for (int i = 0; i < V; ++i) colorArray[i] = -1; colorArray[color] = 1; LinkedList<Integer> L = new LinkedList<Integer>(); L.add(color); while (L.size() != 0) { int u = L.poll(); if (D[u][u] == 1) return false; for (int t = 0; t < V; t++) { if (D[u][t] == 1 && colorArray[t] == -1) { colorArray[t] = 1-colorArray[u]; L.add(t); } else if (D[u][t] == 1 && colorArray[t] == colorArray[u]) return false; } } return true; } }
package cx.fam.tak0294.NoteBook.Note; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.view.View; import cx.fam.tak0294.Utils.*; public class NoteBackground extends View { public NoteBackground(Context context) { super(context); // TODO 自動生成されたコンストラクター・スタブ } protected void onDraw(Canvas canvas) { //canvas.drawColor(Color.CYAN); Paint m_currentPaint = new Paint(); m_currentPaint.setColor(Color.GRAY); m_currentPaint.setStrokeWidth(1); m_currentPaint.setAntiAlias(true); m_currentPaint.setStyle(Style.STROKE); Rect screenSize = DisplayUtil.getScreenRect(getContext()); for(int ii=0;ii<screenSize.height();ii+=NoteGlobal.LINE_HEIGHT) { canvas.drawLine(NoteGlobal.NOTE_MARGIN_LEFT, ii*1.05f, screenSize.width()-NoteGlobal.NOTE_MARGIN_LEFT-NoteGlobal.NOTE_MARGIN_RIGHT, ii*1.05f, m_currentPaint); } } }
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; public class HelloActivity extends Activity{ private ImageView splesh; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_hello); ImageView logo_com; ImageView logo_inner; ImageView logo_outer; logo_com=(ImageView)this.findViewById(R.id.myImageView); logo_inner=(ImageView)this.findViewById(R.id.logo_inner); logo_outer=(ImageView)this.findViewById(R.id.logo_outer); Animation comAnimation = AnimationUtils.loadAnimation(this, R.anim.com_anim); Animation innerAnimation=AnimationUtils.loadAnimation(this, R.anim.logo_inner); Animation outerAnimation=AnimationUtils.loadAnimation(this, R.anim.logo_outer); logo_inner.startAnimation(innerAnimation); logo_com.startAnimation(comAnimation); logo_outer.startAnimation(outerAnimation); } }
package com.soldevelo.vmi.validation; import com.soldevelo.vmi.args.Arguments; import java.io.File; import java.util.ArrayList; import java.util.List; public class ArgumentValidator { public List<ValidationError> validateArgs(Arguments args) { List<ValidationError> errors = new ArrayList<ValidationError>(); validateConfig(args, errors); return errors; } private void validateConfig(Arguments args, List<ValidationError> errors) { if (args.getConfig() == null) { errors.add(new ValidationError("config", ErrorConstants.NO_CONFIG)); } else if (!new File(args.getConfig()).isFile()) { errors.add(new ValidationError("config", ErrorConstants.CONFIG_DOESNT_EXIST, args.getConfig())); } } }
package com.pandame.anggarisky.validcode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btn_submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_submit = (Button) findViewById(R.id.btn_submit); btn_submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Your code is valid!", Toast.LENGTH_SHORT).show(); } }); } }
package com.example.zozen.mypanichenv2.Models; import java.util.List; public class Menu { private List<Ingredient> ListIngredient; private String name; private String type; private String id; public Menu(List<Ingredient> listIngredient, String name, String type) { ListIngredient = listIngredient; this.name = name; this.type = type; } public Menu(String name, String type) { this.name = name; this.type = type; } public Menu(String name, String type, String id) { this.name = name; this.type = type; this.id = id; } public String getName() { return name; } public String getType() { return type; } public List<Ingredient> getListIngredient() { return ListIngredient; } @Override public String toString() { return "name : " + this.name + "class !!!!!"; } public String getID() { return id; } }
package apiAlquilerVideoJuegos.servicios; import java.util.List; import apiAlquilerVideoJuegos.modelos.Empresa; public interface EmpresaServicio { public List<Empresa> obtener(); public Empresa obtenerEmpresa(Long id); public boolean guardar(Empresa empresa); public boolean eliminar(Long id); }
package com.oa.user.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.oa.user.dao.UserInfoDao; import com.oa.user.form.UserInfo; @Service public class UserInfoServiceImpl implements UserInfoService{ @Autowired private UserInfoDao userInfoDao; @Override public void addUser(UserInfo userInfo) { userInfoDao.addUser(userInfo); } @Override public List<UserInfo> selectAllUser() { return userInfoDao.selectAllUser(); } @Override public UserInfo selectUserByName(String userName) { return userInfoDao.selectUserByName(userName); } @Override public UserInfo selectUserById(int id) { return userInfoDao.selectUserById(id); } @Override public void removeUser(int id) { userInfoDao.removeUser(id); } @Override public void updateUser(UserInfo userInfo) { userInfoDao.updateUser(userInfo); } @Override public void deleteUser(int id) { userInfoDao.deleteUser(id); } @Override public UserInfo selectUserByNameAndPassword(String userName, String password) { return userInfoDao.selectUserByNameAndPassword(userName,password); } }
package alien4cloud.deployment; import javax.annotation.Resource; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.model.deployment.Deployment; import alien4cloud.model.deployment.DeploymentTopology; import alien4cloud.orchestrators.plugin.IOrchestratorPlugin; import alien4cloud.paas.OrchestratorPluginService; import alien4cloud.paas.model.PaaSDeploymentContext; /** * Manages topology un-deployment. */ @Service @Slf4j public class UndeployService { @Inject private OrchestratorPluginService orchestratorPluginService; @Inject private DeploymentService deploymentService; @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDao; @Inject private DeploymentRuntimeStateService deploymentRuntimeStateService; /** * Un-deploy a deployment object * * @param deploymentId deployment id to deploy */ public synchronized void undeploy(String deploymentId) { Deployment deployment = deploymentService.getOrfail(deploymentId); undeploy(deployment); } public synchronized void undeployEnvironment(String environmentId) { Deployment deployment = deploymentService.getActiveDeployment(environmentId); if (deployment != null) { undeploy(deployment); } else { log.warn("No deployment found for environment " + environmentId); } } /** * Un-deploy from a deployment setup. * * @param deploymentTopology setup object containing information to deploy */ public synchronized void undeploy(DeploymentTopology deploymentTopology) { Deployment activeDeployment = deploymentService.getActiveDeploymentOrFail(deploymentTopology.getEnvironmentId()); undeploy(activeDeployment); } private void undeploy(Deployment deployment) { log.info("Un-deploying deployment [{}] on cloud [{}]", deployment.getId(), deployment.getOrchestratorId()); IOrchestratorPlugin orchestratorPlugin = orchestratorPluginService.getOrFail(deployment.getOrchestratorId()); DeploymentTopology deployedTopology = deploymentRuntimeStateService.getRuntimeTopology(deployment.getId()); PaaSDeploymentContext deploymentContext = new PaaSDeploymentContext(deployment, deployedTopology); orchestratorPlugin.undeploy(deploymentContext, null); alienDao.save(deployment); log.info("Un-deployed deployment [{}] on cloud [{}]", deployment.getId(), deployment.getOrchestratorId()); } }
package cn.com.onlinetool.fastpay.pay.wxpay.domain; import cn.com.onlinetool.fastpay.pay.wxpay.config.WXPayConfig; import cn.com.onlinetool.fastpay.pay.wxpay.constants.WXPayConstants; import org.apache.http.conn.ConnectTimeoutException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; /** * @author choice * @description: * @date 2019-06-06 11:22 * */ public class WXPayDomainSimpleImpl implements WXPayDomain { private WXPayDomainSimpleImpl(){} private static class WxpayDomainHolder{ private static WXPayDomain holder = new WXPayDomainSimpleImpl(); } public static WXPayDomain instance(){ return WxpayDomainHolder.holder; } @Override public synchronized void report(final String domain, long elapsedTimeMillis, final Exception ex) { DomainStatics info = domainData.get(domain); if(info == null){ info = new DomainStatics(domain); domainData.put(domain, info); } if(ex == null){ //success if(info.succCount >= 2){ //continue succ, clear error count info.connectTimeoutCount = info.dnsErrorCount = info.otherErrorCount = 0; }else{ ++info.succCount; } }else if(ex instanceof ConnectTimeoutException){ info.succCount = info.dnsErrorCount = 0; ++info.connectTimeoutCount; }else if(ex instanceof UnknownHostException){ info.succCount = 0; ++info.dnsErrorCount; }else{ info.succCount = 0; ++info.otherErrorCount; } } @Override public synchronized DomainInfo getDomain(final WXPayConfig config) { DomainStatics primaryDomain = domainData.get(WXPayConstants.DOMAIN_API); if(primaryDomain == null || primaryDomain.isGood()) { return new DomainInfo(WXPayConstants.DOMAIN_API, true); } long now = System.currentTimeMillis(); if(switchToAlternateDomainTime == 0){ switchToAlternateDomainTime = now; return new DomainInfo(WXPayConstants.DOMAIN_API2, false); }else if(now - switchToAlternateDomainTime < MIN_SWITCH_PRIMARY_MSEC){ DomainStatics alternateDomain = domainData.get(WXPayConstants.DOMAIN_API2); if(alternateDomain == null || alternateDomain.isGood() || alternateDomain.badCount() < primaryDomain.badCount()){ return new DomainInfo(WXPayConstants.DOMAIN_API2, false); }else{ return new DomainInfo(WXPayConstants.DOMAIN_API, true); } }else{ //force switch back switchToAlternateDomainTime = 0; primaryDomain.resetCount(); DomainStatics alternateDomain = domainData.get(WXPayConstants.DOMAIN_API2); if(alternateDomain != null){ alternateDomain.resetCount(); } return new DomainInfo(WXPayConstants.DOMAIN_API, true); } } static class DomainStatics { final String domain; int succCount = 0; int connectTimeoutCount = 0; int dnsErrorCount =0; int otherErrorCount = 0; DomainStatics(String domain) { this.domain = domain; } void resetCount(){ succCount = connectTimeoutCount = dnsErrorCount = otherErrorCount = 0; } boolean isGood(){ return connectTimeoutCount <= 2 && dnsErrorCount <= 2; } int badCount(){ return connectTimeoutCount + dnsErrorCount * 5 + otherErrorCount / 4; } } private final int MIN_SWITCH_PRIMARY_MSEC = 3 * 60 * 1000; private long switchToAlternateDomainTime = 0; private Map<String, DomainStatics> domainData = new HashMap<>(); }
package ru.avokin.uidiff.diff.common.controller; import ru.avokin.uidiff.common.controller.AbstractViewListenerImpl; import ru.avokin.uidiff.diff.common.view.DiffViewListener; /** * User: Andrey Vokin * Date: 03.10.2010 */ public class DiffViewListenerImpl extends AbstractViewListenerImpl implements DiffViewListener { public DiffViewListenerImpl(AbstractDiffController controller) { super(controller); } protected AbstractDiffController getController() { return (AbstractDiffController) controller; } public void nextDifference() { getController().nextDifference(); } public void previousDifference() { getController().previousDifference(); } }
/* * [40] Combination Sum II * * https://leetcode-cn.com/problems/combination-sum-ii/description/ * * algorithms * Medium (48.65%) * Total Accepted: 2.5K * Total Submissions: 5.1K * Testcase Example: '[10,1,2,7,6,1,5]\n8' * * 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 * * candidates 中的每个数字在每个组合中只能使用一次。 * * 说明: * * * 所有数字(包括目标数)都是正整数。 * 解集不能包含重复的组合。  * * * 示例 1: * * 输入: candidates = [10,1,2,7,6,1,5], target = 8, * 所求解集为: * [ * ⁠ [1, 7], * ⁠ [1, 2, 5], * ⁠ [2, 6], * ⁠ [1, 1, 6] * ] * * * 示例 2: * * 输入: candidates = [2,5,2,1,2], target = 5, * 所求解集为: * [ * [1,2,2], * [5] * ] * */ class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<List<Integer>>(); getResult(result, new ArrayList<Integer>(), candidates, target, 0); return result; } private void getResult(List<List<Integer>> result,List<Integer>current,int candidates[],int target,int start){ if(target==0){ result.add(new ArrayList<>(current)); return; } if(target<0){ return; } for(int i=start;i<candidates.length && target>=candidates[i];i++){ current.add(candidates[i]); getResult(result, current, candidates, target - candidates[i], i+1); current.remove(current.size()-1); while(i<candidates.length-1 && candidates[i]==candidates[i+1]){ //不是最后一个 & 连续相同 i++; } } } }