text
stringlengths
10
2.72M
/* $Id$ */ package djudge.judge.dcompiler; public class CompilerTask { /* * Files to compile */ DistributedFileset files; /* * Language ID */ String languageId; //String mainFile; public CompilerTask() { // TODO Auto-generated constructor stub } public CompilerTask(String filename, String languageId) { files = new DistributedFileset(filename); this.languageId = languageId; } }
package com.game.chess.api.security.filter; import lombok.Builder; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; import javax.servlet.http.HttpServletRequest; @Builder public class ApiKeyFilter extends AbstractPreAuthenticatedProcessingFilter { private final String header; @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return request.getHeader(header); } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { // no credentials for ApiKey return null; } }
package maze.test; import static org.junit.Assert.*; import java.awt.Point; import org.junit.Test; import maze.logic.*; public class TestMazeWithStaticDragon { char [][] m1 = {{'X', 'X', 'X', 'X', 'X'}, {'X', ' ', ' ', 'H', 'S'}, {'X', ' ', 'X', ' ', 'X'}, {'X', 'E', ' ', 'D', 'X'}, {'X', 'X', 'X', 'X', 'X'}}; @Test public void testMoveHeroToFreeCell() { Maze maze = new Maze(m1); assertEquals(new Point(3,1), maze.getHeroPosition()); maze.update('o'); assertEquals(new Point(2,1), maze.getHeroPosition()); } @Test public void testMoveHeroToWallCell() { Maze maze = new Maze(m1); assertEquals(new Point(3,1), maze.getHeroPosition()); maze.update('n'); assertEquals(new Point(3,1), maze.getHeroPosition()); } /* @Test public void testHeroDies() { Maze maze = new Maze(m1); assertEquals(MazeStatus.HeroUnarmed, maze.getStatus()); maze.moveHeroDown(); assertEquals(MazeStatus.HeroDied, maze.getStatus()); }*/ }
package com.javarush.task.task18.task1821; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; /* Встречаемость символов */ public class Solution { public static void main(String[] args) throws IOException { Map<Character, Integer> map = new HashMap<>(); try(FileInputStream fileInputStream = new FileInputStream(args[0])) { while (fileInputStream.available() > 0) { char c = (char) fileInputStream.read(); // перенос строки и пробел тоже символы и их нужно посчитать // if (c == ' ' || c == '\n'){ // continue; // } if(map.containsKey(c)){ int val = map.get(c); map.put(c, ++val); } else { map.put(c, 1); } } } List<Character> list = new ArrayList<>(map.keySet()); Collections.sort(list); for(Character ch : list){ System.out.println(ch + " " + map.get(ch)); } } } // int[] aSCII = new int[128]; // try (FileReader reader = new FileReader(args[0])) { // while (reader.ready()) { // aSCII[reader.read()]++; // } // } // for (int i = 0; i < aSCII.length; i++) { // if (aSCII[i] != 0) { // System.out.println((char) i + " " + aSCII[i]); // } // }
public class Citation implements CitationAPI { public static void main(String[] args) { // } public String getAuthor() { } public String getAccessedDate() { } public String getPublishedDate() { } public String getURL() { } public String sort(); }
import play.*; import play.libs.*; import java.util.*; import com.avaje.ebean.*; import models.*; public class Global extends GlobalSettings { /* public void onStart(Application app) { InitialData.insert(app); } static class InitialData { public static void insert(Application app) { } } */ }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : PolicyElucidationServer.java * PACKAGE : com.anssy.inter.service.server * CREATE DATE : 2016-8-3 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.inter.base.server; import com.anssy.inter.base.vo.NewsPageVo; import com.anssy.inter.base.vo.NewsVo; import com.anssy.venturebar.activity.vo.PvVo; import com.anssy.venturebar.base.dao.NewsPolicyDao; import com.anssy.venturebar.base.entity.NewsEntity; import com.anssy.webcore.common.BaseConstants; import com.anssy.webcore.common.DBHelper; import com.anssy.webcore.common.DateTimeUtil; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.util.List; /** * @author make it * @version SVN #V1# #2016-8-3# * 资讯_政策解读 */ @Service("newsPolicyServer") public class NewsPolicyServer { private static Logger logger = Logger.getLogger(NewsPolicyServer.class); @Resource private NewsPolicyDao policyDao; /** * 查询政策解读信息 */ public List<NewsEntity> findList(NewsVo vo) { NewsPageVo pageVo = new NewsPageVo(); pageVo.setBeing((vo.getPage() - 1) * BaseConstants.PAGE_SIZE + 1); pageVo.setEnd((vo.getPage() - 1) * BaseConstants.PAGE_SIZE + BaseConstants.PAGE_SIZE); if (StringUtils.isNotBlank(vo.getSearch())) { pageVo.setSearch(vo.getSearch()); } return policyDao.findList(pageVo); } /** * 查询政策的第一条数据 */ public Date findBeginUpdate() { return policyDao.findBeginUpdate(); } /** * 发布政策信息 */ @Transactional(propagation = Propagation.REQUIRED) public boolean releaseNews(NewsEntity entity) throws Exception { boolean flag = false; if (policyDao.insertPolicy(entity) > 0) { flag = true; } return flag; } /** * 清除全部表数据 */ @Transactional(propagation = Propagation.REQUIRED) public boolean deleteAllData() throws Exception { boolean flag = false; if (policyDao.deleteAllData() > 0) { if (policyDao.deleteAllData() > 0) { flag = true; } } return flag; } private static boolean isRun = false; /** * 从创业在线拉取政策数据 (定时) */ public void loadPolcyFormStartupOnline() { // 防止重复同步 if (isRun)return; isRun = true; // Date update_datetime = findBeginUpdate(); StringBuffer sqlSb = new StringBuffer("select id,title,tb_instlink,update_time from app_zczx"); // SQL语句 // if (update_datetime != null) { // String updateTime = DateTimeUtil.getFormatTime(update_datetime); // sqlSb.append(" where update_time > '") // .append(updateTime) // .append("' order by update_time"); // SQL语句 // logger.error("\n=============\nupdateTime : " + updateTime + "\n================"); // } db = new DBHelper(sqlSb.toString());//创建DBHelper对象 try { ret = db.pst.executeQuery();//执行语句,得到结果集 // 清除全部表数据 deleteAllData(); while (ret.next()) { String id = ret.getString(1); String title = ret.getString(2); String url = ret.getString(3); String date = ret.getString(4); logger.error("title : " + title + "\nurl : " + url + "\ndate : " + date); if (title != null && url != null && date != null) { NewsEntity entity = new NewsEntity(); entity.setTitle(title); entity.setUrl(url); entity.setUpdateTime(DateTimeUtil.getFormatDate(date)); releaseNews(entity); } } //显示数据 ret.close(); db.close();//关闭连接 } catch (SQLException e) { e.printStackTrace(); logger.error("创业在线数据访问异常啦!"); } catch (Exception e) { e.printStackTrace(); logger.error("数据储存异常啦!"); } finally { db.close();//关闭连接 isRun = false; db = null; ret = null; } } DBHelper db = null; ResultSet ret = null; }
package com.filestore.monitor; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class DataStoreMonitoringProcessDriver { private static Map<String, ScheduledThreadPoolExecutor> executors = new HashMap<>(); private DataStoreMonitoringProcessDriver() { } public static void init(String storeLocation) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); executor.scheduleWithFixedDelay(new DataStoreMonitoringProcess(storeLocation), 0, 1, TimeUnit.SECONDS); executors.put(DataStoreMonitoringProcess.class.getSimpleName(), executor); } }
package com.ziaan.scorm; import java.io.IOException; import javax.servlet.ServletInputStream; class MultipartInputStreamHandler { public MultipartInputStreamHandler(ServletInputStream in, int totalExpected) { totalRead = 0; buf = new byte[8192]; this.in = in; this.totalExpected = totalExpected; } public String readLine() throws IOException { StringBuffer sbuf = new StringBuffer(); int result; do { result = readLine(buf, 0, buf.length); if ( result != -1) sbuf.append(new String(buf, 0, result, "KSC5601") ); } while ( result == buf.length); if ( sbuf.length() == 0) { return null; } else { sbuf.setLength(sbuf.length() - 2); return sbuf.toString(); } } public int readLine(byte b[], int off, int len) throws IOException { if ( totalRead >= totalExpected) return -1; int result = in.readLine(b, off, len); if ( result > 0) totalRead += result; return result; } ServletInputStream in; int totalExpected; int totalRead; byte buf[]; }
package Hackathon; import java.util.Scanner; public class Battle { public static final int minEnc = 1, maxEnc = 2, encNumber = 1, range = maxEnc - minEnc + 1; public static int rand, attack, hitDMG, hitChance, merch, city = 0; public static void battleSequence(int minRange, int maxRange, String eType, String aType, int eMaxHit, int eMinHit, int enemyHP, int maxFlee, int minFlee, int rewardGold, int rewardPoints, int heroHit, String killText, String deathFlavor, char enemyAbility) { Scanner input = new Scanner(System.in); int poisonCount = 0; //initialize hero poisoned counter int ePoisonCount = 0; // initialize enemy poisoned counter int stunCount = 0; //initialize hero stun int eStunCount = 0; int battleDec = 0; attack = Stats.getMaxDMG ( ) - Stats.getMinDMG() + 1; while (enemyHP > 0) //fight sequence { eStunCount--; if (eStunCount < 1) { int damage = (int) ( Math.random ( ) * maxRange + minRange ); //enemy attack range System.out.println ( eType + aType + " for " + damage + " damage."); hitChance = (int) ( Math.random ( ) * eMaxHit + eMinHit); //enemy hit chance if (Stats.evade > hitChance) //if evade is greater than hit { System.out.println ( "But Misses!" ); } else { Stats.setHp (-damage ); //player attacked System.out.println ( "-" + damage + " HP. " + "HP is " + Stats.hp + "/" + Stats.hpMax); //if enemy ability type "v" vampirism if (enemyAbility == 'v') { double vamp = damage * 0.25; // heals 25% damage given int iVamp = (int) vamp; // change from double to int if (iVamp > 0) { // output if necessary System.out.println ( eType + " heals " + iVamp + " HP" ); enemyHP += iVamp; } } else if (enemyAbility == 'p' && poisonCount < 1) { int poison = (int) (Math.random ( ) * 3 + 1); if (poison == 3) { System.out.println ( "You're Poisoned!" ); poisonCount = 3; } } else if (enemyAbility == 's' && stunCount < 1) { int stun = (int) (Math.random ( ) * 8 + 1); if (stun == 5) { System.out.println ( "You're Stunned! (1 turn)\n" ); stunCount = 2; } } if (Stats.getHp() < 1) //on death condition, reset variables to go to game over { enemyHP = 0; Stats.setBattleCount(5); } } } if (poisonCount > 0 ){ poisonCount--; System.out.println ( "-2 HP (Poison), left: " + poisonCount); Stats.setHp(-2); } //battle decision stunCount--; if (Stats.getHp() > 0 && stunCount < 1) { System.out.println ( "0 - Flee\n1 - Attack" ); System.out.println ( "3 - Dynamite: " + Stats.getDynamite()); System.out.println ( "5 - Health Potion: " + Stats.getHpPot() ); battleDec = input.nextInt(); //flee switch (battleDec) { //flee case 0: hitChance = (int) ( Math.random ( ) * maxFlee + minFlee); //chance to flee if (Stats.evade > hitChance) { //flee successful System.out.println ( "You run away! Coward!" ); enemyHP = 0; } else { //flee unsuccessful System.out.println ( "You try to run, but you trip and fall on your face." ); } break; //attack case 1: hitDMG = (int) ( Math.random ( ) * attack + Stats.getMinDMG()); //possible damage range hitChance = (int) ( Math.random ( ) * heroHit + 1); //chance to hit if (Stats.getDex() >= hitChance) //if dex is at least heroHit chance { System.out.println ( "You hit for " + hitDMG + " DMG" ); enemyHP -= hitDMG; //character ability Vamp if (Stats.getvRapier() == 0 || Stats.getsKatana() == 0) { System.out.println ( "HP + 1" ); Stats.setHp (1); } //character ability poison else if (Stats.getcKukri() == 0 && ePoisonCount < 1) { int ePoison = (int) (Math.random ( ) * 3 + 1); if (ePoison == 3) { System.out.println ( eType + " Poisoned!" ); ePoisonCount = 3; } } else if (Stats.getlAxe() == 0) { int eStun = (int) (Math.random ( ) * 7 + 1); if (eStun == 3) { System.out.println ( eType + " Stunned!" ); eStunCount = 2; } } } else { System.out.println ( "You miss! Lame!" ); } if (ePoisonCount > 0) { System.out.println ( eType + " -2 HP (Poison), Left: " + ePoisonCount ); enemyHP -= 2; ePoisonCount--; } break; case 3: if (Stats.getDynamite() > 0) { System.out.println ( "You light the wick and toss the dynamite at the " + eType ); System.out.println ( "dealing 30 damage! Your reckless action deals 5 damage to you as well" ); enemyHP -= 30; Stats.setHp (-5); Stats.setDynamite(-1); } else { System.out.println ( "Idiot! You have no explosives in your inventory!" ); } break; //heal case 5: if (Stats.getHpPot() > 0) { System.out.println ( "That Sauce is Awesome!\n +50 HP" ); Stats.setHpPot(-1); //used potion Stats.setHp (50); // heal } else { System.out.println ( "Fool! You have no bottles in supply!" ); } } } } if (Stats.getHp() > 0 && battleDec != 0) { //make sure hero did not die for reward System.out.println ( killText + eType + deathFlavor ); Stats.setGold(rewardGold); // gold Stats.setAreaCount(1); } } public static void enemies() { int enemy = (int) ( Math.random ( ) * 9 + 1); //random enemy switch (enemy) { case 1: System.out.println ("Its a bear!" ); //Bear fight char enemyAbility = 'a'; //enemy special ability class ( none) int enemyHP = 15; //enemy health initialize String eType = "Bear"; //type of enemy String aType = " Swipes"; //attack style String killText = "You killed a "; //type of death String deathFlavor = "! +80 gold for some reason"; //flavor text on enemy death int minRange = 3, maxRange = 8; // enemy damage range; int eMinHit = 4, eMaxHit = 10; // enemy chance to hit int minFlee = 4, maxFlee = 8; // chance to flee from enemy int heroHit = 8; // chance to hit enemy int rewardGold = 80, rewardPoints = 50; Battle.battleSequence ( minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility ); break; case 2: System.out.println ("The ground explodes in front of you and a glistening insect crawls from the chasm" ); //Ferns enemyAbility = 's'; enemyHP = 35; eType = "Crystal Scorpion"; aType = " Stings"; killText = "You crush the "; deathFlavor = " and find it has a diamond for a heart. +114 Gold! "; minRange = 5; maxRange = 7; eMinHit = 5; eMaxHit = 12; minFlee = 4; maxFlee = 8; heroHit = 9; rewardGold = 114; rewardPoints = 155; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); break; case 3: System.out.println ( "An Elf appears... to be very Menacing!" ); enemyAbility = 'a'; enemyHP = 15; eType = "Crazy Elf"; aType = " attacks"; killText = "You killed a "; deathFlavor = ". and robbed his corpse of 72 gold! Awesome!"; minRange = 3; maxRange = 5; eMinHit = 6; eMaxHit = 10; minFlee = 4; maxFlee = 8; heroHit = 8; rewardGold = 72; rewardPoints = 30; Battle.battleSequence ( minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility ); break; case 4: System.out.println ( "Its a Giant Sewer Rat! " ); //Sewer Rat enemyAbility = 'a'; enemyHP = 25; eType = "Sewer Rat"; aType = " bites"; killText = "You killed a Giant "; deathFlavor = "! Gross!\nOne of the locals witnessed your heroic deed and hands you 110 gold"; minRange = 5; maxRange = 8; eMinHit = 6; eMaxHit = 12; minFlee = 6; maxFlee = 6; heroHit = 9; rewardGold = 110; rewardPoints = 250; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); break; case 5: System.out.println ("A robed figure leaps from the shadows and stabs at you without warning" ); //cultist enemyAbility = 'p'; enemyHP = 30; eType = "Cultist"; aType = " stabs wildly"; killText = "You decapitate the "; deathFlavor = " of Chaos...\ntheir purse holds 124 gold."; minRange = 5; maxRange = 8; eMinHit = 5; eMaxHit = 12; minFlee = 5; maxFlee = 7; heroHit = 8; rewardGold = 124; rewardPoints = 110; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); break; case 6: System.out.println ("A Giant Leech! Disgusting!" ); //leech enemyAbility = 'v'; enemyHP = 24; eType = "Leech"; aType = " bites"; killText = "You Skewer the Giant "; deathFlavor = ". Gross! it expells 80 gold"; minRange = 3; maxRange = 8; eMinHit = 4; eMaxHit = 12; minFlee = 4; maxFlee = 8; heroHit = 8; rewardGold = 80; rewardPoints = 70; Battle.battleSequence ( minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility ); break; case 7: System.out.println ("The sky darkens. You look above to see an enormous colony of thirsty Vampire Bats" ); //bat enemyAbility = 'v'; enemyHP = 40; eType = "Vampire Bat"; aType = " swoops"; killText = "You slaughter the colony of "; deathFlavor = "s and the crowd throws 150 gold at you."; minRange = 7; maxRange = 5; eMinHit = 5; eMaxHit = 12; minFlee = 5; maxFlee = 7; heroHit = 9; rewardGold = 150; rewardPoints = 140; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); break; case 8: System.out.println ("The nerby ferns begin to hiss. They uproot themselves and lash at you with their barbed stolons" ); //Ferns enemyAbility = 'a'; enemyHP = 35; eType = "Fern Feind"; aType = " whips "; killText = "You dice the "; deathFlavor = "s and clip their buds worth 5 gold a piece. +85 gold"; minRange = 5; maxRange = 8; eMinHit = 5; eMaxHit = 12; minFlee = 4; maxFlee = 8; heroHit = 9; rewardGold = 160; rewardPoints = 125; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); break; case 9: System.out.println ("An octopus-like plant wants to devour you!" ); //bat enemyAbility = 'p'; enemyHP = 50; eType = "Malboro Red"; aType = " swats"; killText = "You slay the "; deathFlavor = ". upon death it spews 200 gold."; minRange = 6; maxRange = 9; eMinHit = 5; eMaxHit = 12; minFlee = 5; maxFlee = 7; heroHit = 9; rewardGold = 200; rewardPoints = 170; Battle.battleSequence(minRange, maxRange, eType, aType, eMaxHit, eMinHit, enemyHP, maxFlee, minFlee, rewardGold, rewardPoints, heroHit, killText, deathFlavor, enemyAbility); } Stats.setBattleCount(1); if (Stats.getBattleCount() < 4) { System.out.println ( "\nNext Battle!\n" ); } else { System.out.println ( "You head back to town..." ); } } }
package com.git.cloud.bill.model.vo; import java.util.List; public class BillPageParamVo { private String billMonth; private Integer pageNo; private Integer pageSize; private List<String> custIdList; private List<String> extCustIds; private Integer billFeeMin; private Integer billFeeMax; private String startDate; private String endDate; private String serviceType; private String extCustId; private String tenantId; private String status; private PageInfo pageInfo; private String beginTime; private String endTime; private String optType; private String totalAmount; public String getTotalAmount() { return totalAmount; } public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; } public String getBeginTime() { return beginTime; } public void setBeginTime(String beginTime) { this.beginTime = beginTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getOptType() { return optType; } public void setOptType(String optType) { this.optType = optType; } public PageInfo getPageInfo() { return pageInfo; } public void setPageInfo(PageInfo pageInfo) { this.pageInfo = pageInfo; } public String getExtCustId() { return extCustId; } public void setExtCustId(String extCustId) { this.extCustId = extCustId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<String> getExtCustIds() { return extCustIds; } public void setExtCustIds(List<String> extCustIds) { this.extCustIds = extCustIds; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getBillMonth() { return billMonth; } public void setBillMonth(String billMonth) { this.billMonth = billMonth; } public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getBillFeeMin() { return billFeeMin; } public void setBillFeeMin(Integer billFeeMin) { this.billFeeMin = billFeeMin; } public Integer getBillFeeMax() { return billFeeMax; } public void setBillFeeMax(Integer billFeeMax) { this.billFeeMax = billFeeMax; } public List<String> getCustIdList() { return custIdList; } public void setCustIdList(List<String> custIdList) { this.custIdList = custIdList; } @Override public String toString() { return "BillPageParamVo [billMonth=" + billMonth + ", pageNo=" + pageNo + ", pageSize=" + pageSize + ", custIdList=" + custIdList + ", billFeeMin=" + billFeeMin + ", billFeeMax=" + billFeeMax + "]"; } }
package pojo.valueObject.assist; import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; import pojo.valueObject.domain.ProjectVO; import pojo.valueObject.domain.TeamVO; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; /** * Created by geyao on 2017/2/20. */ @Entity @Table(name = "team_project") public class TeamProjectVO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne(targetEntity = TeamVO.class) @JoinColumn(name = "teamId", referencedColumnName = "id") private TeamVO teamVO; @ManyToOne(targetEntity = ProjectVO.class) @JoinColumn(name = "projectId", referencedColumnName = "id") private ProjectVO projectVO; private String showUrl; private Integer score; private Boolean applyFlag; public TeamProjectVO() { super(); } @Override public String toString() { return "TeamProjectVO{" + "id=" + id + ", teamVO=" + teamVO.getId() + ", projectVO=" + projectVO.getId() + ", showUrl='" + showUrl + '\'' + ", score=" + score + ", applyFlag=" + applyFlag + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public TeamVO getTeamVO() { return teamVO; } public void setTeamVO(TeamVO teamVO) { this.teamVO = teamVO; } public ProjectVO getProjectVO() { return projectVO; } public void setProjectVO(ProjectVO projectVO) { this.projectVO = projectVO; } public String getShowUrl() { return showUrl; } public void setShowUrl(String showUrl) { this.showUrl = showUrl; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public Boolean getApplyFlag() { return applyFlag; } public void setApplyFlag(Boolean applyFlag) { this.applyFlag = applyFlag; } }
package com.ssafy.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import com.ssafy.entity.Saegim; public interface SaegimRepository extends JpaRepository<Saegim, Integer> { Saegim findById(Long id); List<Saegim> findByUserId(Long userId); List<Saegim> findAll(); long count(); @Transactional Long removeById(Long id); String updatePointQuery = "UPDATE saegim SET point=ST_GEOMFROMTEXT(:point) WHERE id= :sid"; @Modifying @Transactional @Query(nativeQuery=true, value=updatePointQuery) void savePointInSaegim(Long sid, String point); String selectLatLngQuery = "SELECT id " + "FROM saegim AS s " + "WHERE MBRCONTAINS(ST_LINEFROMTEXT(CONCAT('LINESTRING(', :lat1, ' ', :lng1, ',', :lat2, ' ', :lng2, ')')), s.point)"; @Modifying @Transactional @Query(nativeQuery=true, value=selectLatLngQuery) List<Long> findSomething(String lat1, String lng1, String lat2, String lng2); }
package com.capstone.videoeffect; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import java.io.File; import java.text.DecimalFormat; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ShareCompat; import androidx.core.content.FileProvider; public class PreviewActivity extends AppCompatActivity { private VideoView videoView; private SeekBar seekBar; private int stopPosition; private static final String POSITION = "position"; private static final String FILEPATH = "filepath"; TextView tvstarttime, tvendtime; private Handler mHandler = new Handler(); ImageView ivplaypause; ImageView btcancel, btshare; TextView tvfilename, tvfilesize, tvduration, tvstorepath; String filePath; Boolean fromMyVideos = false; Toolbar toolbar; @Override public void onBackPressed() { if (fromMyVideos) { super.onBackPressed(); } else { super.onBackPressed(); Intent intent = new Intent(PreviewActivity.this, VideoHomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } public void setActionBar(String title) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle(title); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preview); toolbar = findViewById(R.id.toolbar); setActionBar(getResources().getString(R.string.app_name)); Intent intent = getIntent(); if (intent!=null) { fromMyVideos = intent.getBooleanExtra("fromMyVideos",false); } videoView = (VideoView) findViewById(R.id.videoView1); seekBar = (SeekBar) findViewById(R.id.seekBar); tvstarttime = findViewById(R.id.tvstarttime); tvendtime = findViewById(R.id.tvendtime); btcancel = findViewById(R.id.btcancel); btshare = findViewById(R.id.btshare); tvfilename = findViewById(R.id.tvfilename); tvfilesize = findViewById(R.id.tvfilesize); tvduration = findViewById(R.id.tvduration); tvstorepath = findViewById(R.id.tvstorepath); filePath = getIntent().getStringExtra(FILEPATH); String filename = filePath.substring(filePath.lastIndexOf("/") + 1); File file = new File(filePath); int file_size = Integer.parseInt(String.valueOf(file.length() / 1024)); tvfilename.setText(filename); tvfilesize.setText(size(file_size)); tvstorepath.setText(filePath); videoView.setVideoURI(Uri.parse(filePath)); videoView.start(); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); // seekBar.setMax(videoView.getDuration()); // seekBar.postDelayed(onEverySecond, 1000); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(updateTimeTask); videoView.seekTo(seekBar.getProgress()); updateProgressBar(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(updateTimeTask); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { // this is when actually seekbar has been seeked to a new position videoView.seekTo(progress); } } }); updateProgressBar(); ivplaypause = findViewById(R.id.ivplaypause); if (videoView.isPlaying()) { videoView.pause(); ivplaypause.setImageResource(R.drawable.play); } else { videoView.start(); ivplaypause.setImageResource(R.drawable.pause); } ivplaypause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (videoView.isPlaying()) { videoView.pause(); ivplaypause.setImageResource(R.drawable.play); } else { videoView.start(); ivplaypause.setImageResource(R.drawable.pause); } } }); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog diaBox = AskOption(); diaBox.show(); } }); btshare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String recommendation_text = "Download this app for creating amazing Video effects: "; File videoFile = new File(filePath); Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", videoFile); ShareCompat.IntentBuilder.from(PreviewActivity.this) .setStream(contentUri) .setType("video/mp4") .setText(recommendation_text + "https://play.google.com/store/apps/details?id=" + getPackageName()) .setChooserTitle("Share video...") .startChooser(); } }); } private void updateProgressBar() { mHandler.postDelayed(updateTimeTask, 100); } private Runnable updateTimeTask = new Runnable() { public void run() { seekBar.setProgress(videoView.getCurrentPosition()); seekBar.setMax(videoView.getDuration()); int elapsed = videoView.getDuration(); elapsed = elapsed / 1000; long s = elapsed % 60; long m = (elapsed / 60) % 60; long h = (elapsed / (60 * 60)) % 24; if (h > 0) { tvendtime.setText(String.format("%d:%02d:%02d", h, m, s)); tvduration.setText(String.format("%d:%02d:%02d", h, m, s)); } else { tvendtime.setText(String.format("%02d:%02d", m, s)); tvduration.setText(String.format("%02d:%02d", m, s)); } int currenttime = videoView.getCurrentPosition(); currenttime = currenttime / 1000; long ss = currenttime % 60; long mm = (currenttime / 60) % 60; long hh = (currenttime / (60 * 60)) % 24; if (h > 0) tvstarttime.setText(String.format("%d:%02d:%02d", hh, mm, ss)); else tvstarttime.setText(String.format("%02d:%02d", mm, ss)); mHandler.postDelayed(this, 100); } }; @Override protected void onPause() { super.onPause(); stopPosition = videoView.getCurrentPosition(); //stopPosition is an int videoView.pause(); } @Override protected void onResume() { super.onResume(); videoView.seekTo(stopPosition); videoView.start(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle arrow click here if (item.getItemId() == android.R.id.home) { finish(); // close this activity and return to preview activity (if there is any) } return super.onOptionsItemSelected(item); } public String size(int size) { String hrSize = ""; double m = size / 1024.0; DecimalFormat dec = new DecimalFormat("0.00"); if (m > 1) { hrSize = dec.format(m).concat(" MB"); } else { hrSize = dec.format(size).concat(" KB"); } return hrSize; } private AlertDialog AskOption() { AlertDialog myQuittingDialogBox = new AlertDialog.Builder(this) //set message, title, and icon .setTitle("Delete") .setMessage("Are you sure you want to Delete?") .setIcon(R.drawable.android_delete_black) .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //your deleting code File fdelete = new File(filePath); if (fdelete.exists()) { if (fdelete.delete()) { // System.out.println("file Deleted :" + filePath); Toast.makeText(PreviewActivity.this, "file Deleted :" + filePath, Toast.LENGTH_LONG).show(); } else { // System.out.println("file not Deleted :" + filePath); Toast.makeText(PreviewActivity.this, "file not Deleted :" + filePath, Toast.LENGTH_LONG).show(); } } Intent intent = new Intent(PreviewActivity.this, VideoHomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); dialog.dismiss(); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); return myQuittingDialogBox; } }
package com.test04; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; // TODO : 002. <bean id="userService" class="com.test04.UserServiceImpl">을 annotation으로 @Component("userService") public class UserServiceImpl implements UserService { // TODO : 003. <bean id="myUser01" class="com.test04.UserDto">를 annotation으로 @Resource(name="myUser01") // Resource 우선(자바것이라서), Qualifier는 스프링것이라서 나중에 private UserDto dto; @Override public void addUser() { System.out.println("추가된 멤버 : " + dto.getName()); } }
package com.finahub.coding.server.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBConnection { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/codingtest"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static Connection getH2Connection() { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 3: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql=null; /* * sql = "CREATE TABLE BANKINFO " + * "(Bank_id INTEGER not NULL PRIMARY KEY, " + " Bank_Name VARCHAR(255), " + * "Credit_Card_Amount double, " + " Debit_Card_Amount double, " + * " PRIMARY KEY ( Bank_id ))"; * * * * stmt.executeUpdate(sql); */ System.out.println("Created table in given database..."); sql ="insert into BANKINFO (Bank_id,Bank_Name, Credit_Card_Amount, Debit_Card_Amount) values (" +3+",'poi',"+800.0+","+10.0+")"; int i =stmt.executeUpdate(sql); System.out.println("data inserted successfully" +i); /* * sql= "select * from BANKINFO"; ResultSet rs= stmt.executeQuery(sql); * * while(rs.next()) { System.out.println(rs.getInt(1)); * System.out.println(rs.getString(2)); System.out.println(rs.getDouble(3)); * System.out.println(rs.getDouble(4)); } */ // STEP 4: Clean-up environment stmt.close(); conn.close(); } catch(SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try{ if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } //end finally try } //end try System.out.println("Goodbye!"); return conn; } public static void main(String[] args) { getH2Connection(); } }
package com.theshoes.jsp.shoes.model.dto; public class ShoesImgDTO { private int shoesThumbNo; private int stNo; private String originalName; private String savedName; private String savePath; private String fileType; private String thumbnailPath; private String status; }
package com._520it.wms.query; import com._520it.wms.util.DateUtil; import lombok.Getter; import lombok.Setter; import java.util.Date; @Setter @Getter public class OrderBillQueryObject extends BaseAuditQueryObject { private Long supplierId = -1L; // 供应商id }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.types.confirmation; import pl.edu.icm.unity.Constants; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.types.JsonSerializable; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Stores information about confirmation. * * @author P. Piernik * */ public class ConfirmationInfo implements JsonSerializable { private boolean confirmed; private long confirmationDate; private int sentRequestAmount; public ConfirmationInfo() { } public ConfirmationInfo(int sentRequestAmount) { this.sentRequestAmount = sentRequestAmount; } public ConfirmationInfo(boolean confirmed) { this.confirmed = confirmed; if (confirmed) this.confirmationDate = System.currentTimeMillis(); } public boolean isConfirmed() { return confirmed; } public void setConfirmed(boolean confirmed) { this.confirmed = confirmed; } public long getConfirmationDate() { return confirmationDate; } public void setConfirmationDate(long confirmationDate) { this.confirmationDate = confirmationDate; } public int getSentRequestAmount() { return sentRequestAmount; } public void setSentRequestAmount(int sendedRequestAmount) { this.sentRequestAmount = sendedRequestAmount; } @Override public String getSerializedConfiguration() throws InternalException { ObjectNode main = Constants.MAPPER.createObjectNode(); main.put("confirmed", isConfirmed()); main.put("confirmationDate", getConfirmationDate()); main.put("sentRequestAmount", getSentRequestAmount()); try { return Constants.MAPPER.writeValueAsString(main); } catch (JsonProcessingException e) { throw new InternalException("Can't serialize ConfirmationData to JSON", e); } } @Override public void setSerializedConfiguration(String json) throws InternalException { JsonNode jsonN; try { jsonN = Constants.MAPPER.readTree(new String(json)); } catch (Exception e) { throw new InternalException("Can't deserialize ConfirmationData from JSON", e); } setConfirmed(jsonN.get("confirmed").asBoolean(false)); setConfirmationDate(jsonN.get("confirmationDate").asLong()); setSentRequestAmount(jsonN.get("sentRequestAmount").asInt()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ConfirmationInfo)) return false; ConfirmationInfo other = (ConfirmationInfo) obj; if (confirmed != other.isConfirmed()) return false; if (confirmationDate != other.getConfirmationDate()) return false; if (sentRequestAmount != other.getSentRequestAmount()) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (confirmationDate ^ (confirmationDate >>> 32)); result = prime * result + (confirmed ? 1231 : 1237); result = prime * result + sentRequestAmount; return result; } }
package com.lovers.java.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; public class WorkflowTaskExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public WorkflowTaskExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTaskIdIsNull() { addCriterion("task_id is null"); return (Criteria) this; } public Criteria andTaskIdIsNotNull() { addCriterion("task_id is not null"); return (Criteria) this; } public Criteria andTaskIdEqualTo(Integer value) { addCriterion("task_id =", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotEqualTo(Integer value) { addCriterion("task_id <>", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThan(Integer value) { addCriterion("task_id >", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThanOrEqualTo(Integer value) { addCriterion("task_id >=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThan(Integer value) { addCriterion("task_id <", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThanOrEqualTo(Integer value) { addCriterion("task_id <=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdIn(List<Integer> values) { addCriterion("task_id in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotIn(List<Integer> values) { addCriterion("task_id not in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdBetween(Integer value1, Integer value2) { addCriterion("task_id between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotBetween(Integer value1, Integer value2) { addCriterion("task_id not between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andBusinessIdIsNull() { addCriterion("business_id is null"); return (Criteria) this; } public Criteria andBusinessIdIsNotNull() { addCriterion("business_id is not null"); return (Criteria) this; } public Criteria andBusinessIdEqualTo(Integer value) { addCriterion("business_id =", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdNotEqualTo(Integer value) { addCriterion("business_id <>", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdGreaterThan(Integer value) { addCriterion("business_id >", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdGreaterThanOrEqualTo(Integer value) { addCriterion("business_id >=", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdLessThan(Integer value) { addCriterion("business_id <", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdLessThanOrEqualTo(Integer value) { addCriterion("business_id <=", value, "businessId"); return (Criteria) this; } public Criteria andBusinessIdIn(List<Integer> values) { addCriterion("business_id in", values, "businessId"); return (Criteria) this; } public Criteria andBusinessIdNotIn(List<Integer> values) { addCriterion("business_id not in", values, "businessId"); return (Criteria) this; } public Criteria andBusinessIdBetween(Integer value1, Integer value2) { addCriterion("business_id between", value1, value2, "businessId"); return (Criteria) this; } public Criteria andBusinessIdNotBetween(Integer value1, Integer value2) { addCriterion("business_id not between", value1, value2, "businessId"); return (Criteria) this; } public Criteria andStartUserIdIsNull() { addCriterion("start_user_id is null"); return (Criteria) this; } public Criteria andStartUserIdIsNotNull() { addCriterion("start_user_id is not null"); return (Criteria) this; } public Criteria andStartUserIdEqualTo(Integer value) { addCriterion("start_user_id =", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdNotEqualTo(Integer value) { addCriterion("start_user_id <>", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdGreaterThan(Integer value) { addCriterion("start_user_id >", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("start_user_id >=", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdLessThan(Integer value) { addCriterion("start_user_id <", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdLessThanOrEqualTo(Integer value) { addCriterion("start_user_id <=", value, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdIn(List<Integer> values) { addCriterion("start_user_id in", values, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdNotIn(List<Integer> values) { addCriterion("start_user_id not in", values, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdBetween(Integer value1, Integer value2) { addCriterion("start_user_id between", value1, value2, "startUserId"); return (Criteria) this; } public Criteria andStartUserIdNotBetween(Integer value1, Integer value2) { addCriterion("start_user_id not between", value1, value2, "startUserId"); return (Criteria) this; } public Criteria andStartUserNameIsNull() { addCriterion("start_user_name is null"); return (Criteria) this; } public Criteria andStartUserNameIsNotNull() { addCriterion("start_user_name is not null"); return (Criteria) this; } public Criteria andStartUserNameEqualTo(String value) { addCriterion("start_user_name =", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameNotEqualTo(String value) { addCriterion("start_user_name <>", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameGreaterThan(String value) { addCriterion("start_user_name >", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameGreaterThanOrEqualTo(String value) { addCriterion("start_user_name >=", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameLessThan(String value) { addCriterion("start_user_name <", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameLessThanOrEqualTo(String value) { addCriterion("start_user_name <=", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameLike(String value) { addCriterion("start_user_name like", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameNotLike(String value) { addCriterion("start_user_name not like", value, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameIn(List<String> values) { addCriterion("start_user_name in", values, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameNotIn(List<String> values) { addCriterion("start_user_name not in", values, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameBetween(String value1, String value2) { addCriterion("start_user_name between", value1, value2, "startUserName"); return (Criteria) this; } public Criteria andStartUserNameNotBetween(String value1, String value2) { addCriterion("start_user_name not between", value1, value2, "startUserName"); return (Criteria) this; } public Criteria andStartTimeIsNull() { addCriterion("start_time is null"); return (Criteria) this; } public Criteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return (Criteria) this; } public Criteria andStartTimeEqualTo(Date value) { addCriterion("start_time =", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotEqualTo(Date value) { addCriterion("start_time <>", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThan(Date value) { addCriterion("start_time >", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThanOrEqualTo(Date value) { addCriterion("start_time >=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThan(Date value) { addCriterion("start_time <", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThanOrEqualTo(Date value) { addCriterion("start_time <=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeIn(List<Date> values) { addCriterion("start_time in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotIn(List<Date> values) { addCriterion("start_time not in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeBetween(Date value1, Date value2) { addCriterion("start_time between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotBetween(Date value1, Date value2) { addCriterion("start_time not between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andEndUserIdIsNull() { addCriterion("end_user_id is null"); return (Criteria) this; } public Criteria andEndUserIdIsNotNull() { addCriterion("end_user_id is not null"); return (Criteria) this; } public Criteria andEndUserIdEqualTo(Integer value) { addCriterion("end_user_id =", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdNotEqualTo(Integer value) { addCriterion("end_user_id <>", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdGreaterThan(Integer value) { addCriterion("end_user_id >", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("end_user_id >=", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdLessThan(Integer value) { addCriterion("end_user_id <", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdLessThanOrEqualTo(Integer value) { addCriterion("end_user_id <=", value, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdIn(List<Integer> values) { addCriterion("end_user_id in", values, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdNotIn(List<Integer> values) { addCriterion("end_user_id not in", values, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdBetween(Integer value1, Integer value2) { addCriterion("end_user_id between", value1, value2, "endUserId"); return (Criteria) this; } public Criteria andEndUserIdNotBetween(Integer value1, Integer value2) { addCriterion("end_user_id not between", value1, value2, "endUserId"); return (Criteria) this; } public Criteria andEndUserNameIsNull() { addCriterion("end_user_name is null"); return (Criteria) this; } public Criteria andEndUserNameIsNotNull() { addCriterion("end_user_name is not null"); return (Criteria) this; } public Criteria andEndUserNameEqualTo(String value) { addCriterion("end_user_name =", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameNotEqualTo(String value) { addCriterion("end_user_name <>", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameGreaterThan(String value) { addCriterion("end_user_name >", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameGreaterThanOrEqualTo(String value) { addCriterion("end_user_name >=", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameLessThan(String value) { addCriterion("end_user_name <", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameLessThanOrEqualTo(String value) { addCriterion("end_user_name <=", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameLike(String value) { addCriterion("end_user_name like", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameNotLike(String value) { addCriterion("end_user_name not like", value, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameIn(List<String> values) { addCriterion("end_user_name in", values, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameNotIn(List<String> values) { addCriterion("end_user_name not in", values, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameBetween(String value1, String value2) { addCriterion("end_user_name between", value1, value2, "endUserName"); return (Criteria) this; } public Criteria andEndUserNameNotBetween(String value1, String value2) { addCriterion("end_user_name not between", value1, value2, "endUserName"); return (Criteria) this; } public Criteria andEndTimeIsNull() { addCriterion("end_time is null"); return (Criteria) this; } public Criteria andEndTimeIsNotNull() { addCriterion("end_time is not null"); return (Criteria) this; } public Criteria andEndTimeEqualTo(Date value) { addCriterion("end_time =", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotEqualTo(Date value) { addCriterion("end_time <>", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeGreaterThan(Date value) { addCriterion("end_time >", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeGreaterThanOrEqualTo(Date value) { addCriterion("end_time >=", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeLessThan(Date value) { addCriterion("end_time <", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeLessThanOrEqualTo(Date value) { addCriterion("end_time <=", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeIn(List<Date> values) { addCriterion("end_time in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotIn(List<Date> values) { addCriterion("end_time not in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeBetween(Date value1, Date value2) { addCriterion("end_time between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotBetween(Date value1, Date value2) { addCriterion("end_time not between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andNodeIdIsNull() { addCriterion("node_id is null"); return (Criteria) this; } public Criteria andNodeIdIsNotNull() { addCriterion("node_id is not null"); return (Criteria) this; } public Criteria andNodeIdEqualTo(Integer value) { addCriterion("node_id =", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdNotEqualTo(Integer value) { addCriterion("node_id <>", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdGreaterThan(Integer value) { addCriterion("node_id >", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdGreaterThanOrEqualTo(Integer value) { addCriterion("node_id >=", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdLessThan(Integer value) { addCriterion("node_id <", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdLessThanOrEqualTo(Integer value) { addCriterion("node_id <=", value, "nodeId"); return (Criteria) this; } public Criteria andNodeIdIn(List<Integer> values) { addCriterion("node_id in", values, "nodeId"); return (Criteria) this; } public Criteria andNodeIdNotIn(List<Integer> values) { addCriterion("node_id not in", values, "nodeId"); return (Criteria) this; } public Criteria andNodeIdBetween(Integer value1, Integer value2) { addCriterion("node_id between", value1, value2, "nodeId"); return (Criteria) this; } public Criteria andNodeIdNotBetween(Integer value1, Integer value2) { addCriterion("node_id not between", value1, value2, "nodeId"); return (Criteria) this; } public Criteria andLinkIdIsNull() { addCriterion("link_id is null"); return (Criteria) this; } public Criteria andLinkIdIsNotNull() { addCriterion("link_id is not null"); return (Criteria) this; } public Criteria andLinkIdEqualTo(Integer value) { addCriterion("link_id =", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdNotEqualTo(Integer value) { addCriterion("link_id <>", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdGreaterThan(Integer value) { addCriterion("link_id >", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdGreaterThanOrEqualTo(Integer value) { addCriterion("link_id >=", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdLessThan(Integer value) { addCriterion("link_id <", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdLessThanOrEqualTo(Integer value) { addCriterion("link_id <=", value, "linkId"); return (Criteria) this; } public Criteria andLinkIdIn(List<Integer> values) { addCriterion("link_id in", values, "linkId"); return (Criteria) this; } public Criteria andLinkIdNotIn(List<Integer> values) { addCriterion("link_id not in", values, "linkId"); return (Criteria) this; } public Criteria andLinkIdBetween(Integer value1, Integer value2) { addCriterion("link_id between", value1, value2, "linkId"); return (Criteria) this; } public Criteria andLinkIdNotBetween(Integer value1, Integer value2) { addCriterion("link_id not between", value1, value2, "linkId"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table workflow_task * * @mbg.generated do_not_delete_during_merge Wed Sep 25 10:59:33 CST 2019 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table workflow_task * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package end2end; import enums.TestConstants; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; public class E2E { //Total practice UI element public static void main(String[] args) throws InterruptedException { System.setProperty(TestConstants.CHROME_DRIVER.toString(), TestConstants.DRIVER_PATH.toString()); WebDriver driver = new ChromeDriver(); driver.get("https://www.spicejet.com/"); WebElement from, to, departDate, returnDate, checkbox; Select passengers; /* Dropdown */ Thread.sleep(2000); /* from */ from = driver.findElement(By.xpath(".//*[@id=\"ctl00_mainContent_ddl_originStation1_CTXT\"]")); from.click(); Thread.sleep(2000); driver.findElement(By.xpath("//a[@value=\"BLR\"]")).click(); Thread.sleep(2000); /* to */ to = driver.findElement(By.xpath("//*[@id=\"ctl00_mainContent_ddl_destinationStation1_CTXT\"]")); to.click(); Thread.sleep(2000); driver.findElement(By.xpath("(//a[@value=\"MAA\"])[2]")).click(); Thread.sleep(2000); /* Calendar */ /* depart date */ departDate = driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/div[1]/table/tbody/tr[4]/td[2]/a")); //*[@id="ui-datepicker-div"]/div[1]/table/tbody/tr[4]/td[2]/a departDate.click(); Thread.sleep(2000); returnDate = driver.findElement(By.xpath("//*[@id=\"Div1\"]")); if(returnDate.getAttribute("style").contains("1")) { System.out.println("enable!"); Assert.assertTrue(false); } else { System.out.println("disable!"); Assert.assertTrue(true); } /* Select */ /* Select passengers */ driver.findElement(By.xpath("//*[@id=\"divpaxinfo\"]")).click(); Thread.sleep(2000); passengers = new Select(driver.findElement(By.xpath("//*[@id=\"ctl00_mainContent_ddl_Adult\"]"))); passengers.selectByValue("4"); Thread.sleep(2000); /* Checkbox */ checkbox = driver.findElement(By.xpath("//*[@id=\"ctl00_mainContent_chk_friendsandfamily\"]")); checkbox.click(); /* click the search button */ driver.findElement(By.xpath("//*[@id=\"ctl00_mainContent_btn_FindFlights\"]")).click(); Thread.sleep(3000); driver.close(); } }
/** * <copyright> * </copyright> * * $Id$ */ package ssl.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import ssl.Specification; import ssl.SslPackage; import ssl.Testcase; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Specification</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link ssl.impl.SpecificationImpl#getTestcases <em>Testcases</em>}</li> * </ul> * </p> * * @generated */ public class SpecificationImpl extends EObjectImpl implements Specification { /** * The cached value of the '{@link #getTestcases() <em>Testcases</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTestcases() * @generated * @ordered */ protected EList<Testcase> testcases; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SpecificationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SslPackage.Literals.SPECIFICATION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Testcase> getTestcases() { if (testcases == null) { testcases = new EObjectContainmentEList<Testcase>(Testcase.class, this, SslPackage.SPECIFICATION__TESTCASES); } return testcases; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SslPackage.SPECIFICATION__TESTCASES: return ((InternalEList<?>)getTestcases()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SslPackage.SPECIFICATION__TESTCASES: return getTestcases(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SslPackage.SPECIFICATION__TESTCASES: getTestcases().clear(); getTestcases().addAll((Collection<? extends Testcase>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SslPackage.SPECIFICATION__TESTCASES: getTestcases().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SslPackage.SPECIFICATION__TESTCASES: return testcases != null && !testcases.isEmpty(); } return super.eIsSet(featureID); } } //SpecificationImpl
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.properties.ui.celleditor; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.internal.resources.File; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILazyContentProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog; import org.eclipse.ui.dialogs.SearchPattern; import org.eclipse.ui.ide.ResourceUtil; import org.eclipse.ui.internal.WorkbenchMessages; import org.neuro4j.studio.core.util.FlowUtils; import org.neuro4j.studio.core.util.PropetiesConstants; public class FlowFilteredResourcesSelectionDialog extends ElementListSelectionDialog { public FlowFilteredResourcesSelectionDialog(Shell parent, ILabelProvider renderer) { super(parent, renderer); container = ResourcesPlugin.getWorkspace().getRoot(); typeMask = IResource.FILE | IResource.FOLDER | IResource.PROJECT; IWorkbenchWindow ww = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); if (ww != null) { IWorkbenchPage activePage = ww.getActivePage(); if (activePage != null) { IResource resource = null; IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activeEditor == activePage.getActivePart()) { IEditorInput editorInput = activeEditor.getEditorInput(); resource = ResourceUtil.getResource(editorInput); } else { ISelection selection = ww.getSelectionService() .getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.size() == 1) { resource = ResourceUtil .getResource(structuredSelection .getFirstElement()); } } } if (resource != null) { if (!(resource instanceof IContainer)) { resource = resource.getParent(); } searchContainer = (IContainer) resource; } } } } protected ItemsFilter createFilter() { return new ResourceFilter(container, searchContainer, isDerived, typeMask); } public void fillContentProvider() throws CoreException { ItemsFilter itemsFilter = createFilter(); this.filter = itemsFilter; contentProvider = new ContentProvider(); IProgressMonitor progressMonitor = new NullProgressMonitor(); if (itemsFilter instanceof ResourceFilter) container.accept(new ResourceProxyVisitor(contentProvider, (ResourceFilter) itemsFilter, progressMonitor), IResource.NONE); setElements(contentProvider.getSortedItems()); if (progressMonitor != null) progressMonitor.done(); } private IContainer container; private IContainer searchContainer; private int typeMask; private Text pattern; private boolean isDerived; private ItemsFilter filter; // private List lastCompletedResult; private Map<IProject, List<String>> projectSources = new HashMap<IProject, List<String>>(); // private ItemsFilter lastCompletedFilter; private ContentProvider contentProvider; private ItemsListSeparator itemsListSeparator; private TableViewer list; public String getElementName(Object item) { IResource resource = (IResource) item; return resource.getName(); } private class ContentProvider extends AbstractContentProvider implements IStructuredContentProvider, ILazyContentProvider { // private SelectionHistory selectionHistory; /** * Raw result of the searching (unsorted, unfiltered). * <p> * Standard object flow: <code>items -> lastSortedItems -> lastFilteredItems</code> */ private Set<String> items; /** * Items that are duplicates. */ private Set duplicates; /** * List of <code>ViewerFilter</code>s to be used during filtering */ private List filters; /** * Result of the last filtering. * <p> * Standard object flow: <code>items -> lastSortedItems -> lastFilteredItems</code> */ private List lastFilteredItems; /** * Result of the last sorting. * <p> * Standard object flow: <code>items -> lastSortedItems -> lastFilteredItems</code> */ private List lastSortedItems; /** * Used for <code>getFilteredItems()</code> method canceling (when the * job that invoked the method was canceled). * <p> * Method canceling could be based (only) on monitor canceling unfortunately sometimes the method * <code>getFilteredElements()</code> could be run with a null monitor, the <code>reset</code> flag have to be * left intact. */ private boolean reset; /** * Creates new instance of <code>ContentProvider</code>. */ public ContentProvider() { this.items = Collections.synchronizedSet(new HashSet(2048)); this.duplicates = Collections.synchronizedSet(new HashSet(256)); this.lastFilteredItems = new ArrayList(); this.lastSortedItems = Collections.synchronizedList(new ArrayList( 2048)); } // /** // * Sets selection history. // * // * @param selectionHistory // * The selectionHistory to set. // */ // public void setSelectionHistory(SelectionHistory selectionHistory) { // this.selectionHistory = selectionHistory; // } // // /** // * @return Returns the selectionHistory. // */ // public SelectionHistory getSelectionHistory() { // return selectionHistory; // } // // /** // * Removes all content items and resets progress message. // */ // public void reset() { // reset = true; // this.items.clear(); // this.duplicates.clear(); // this.lastSortedItems.clear(); // } /** * Stops reloading cache - <code>getFilteredItems()</code> method. */ public void stopReloadingCache() { reset = true; } /** * Adds filtered item. * * @param item * @param itemsFilter */ public void add(Object item, ItemsFilter itemsFilter) { if (itemsFilter == filter) { if (itemsFilter != null) { if (itemsFilter.matchItem(item)) { List<String> startNodes = getFlowsWithStartNodes(item); this.items.addAll(startNodes); } } else { List<String> startNodes = getFlowsWithStartNodes(item); this.items.addAll(startNodes); } } } /** * Add all history items to <code>contentProvider</code>. * * @param itemsFilter */ // public void addHistoryItems(ItemsFilter itemsFilter) { // if (this.selectionHistory != null) { // Object[] items = this.selectionHistory.getHistoryItems(); // for (int i = 0; i < items.length; i++) { // Object item = items[i]; // if (itemsFilter == filter) { // if (itemsFilter != null) { // if (itemsFilter.matchItem(item)) { // if (itemsFilter.isConsistentItem(item)) { // this.items.add(item.toString()); // } else { // this.selectionHistory.remove(item); // } // } // } // } // } // } // } // // /** // * Refresh dialog. // */ // public void refresh() { // //scheduleRefresh(); // } // // /** // * Removes items from history and refreshes the view. // * // * @param item // * to remove // * // * @return removed item // */ // public Object removeHistoryElement(Object item) { // if (this.selectionHistory != null) // this.selectionHistory.remove(item); // if (filter == null || filter.getPattern().length() == 0) { // items.remove(item); // duplicates.remove(item); // this.lastSortedItems.remove(item); // } // // synchronized (lastSortedItems) { // Collections.sort(lastSortedItems); // } // return item; // } // /** // * Adds item to history and refresh view. // * // * @param item // * to add // */ // public void addHistoryElement(Object item) { // if (this.selectionHistory != null) // this.selectionHistory.accessed(item); // if (filter == null || !filter.matchItem(item)) { // this.items.remove(item); // this.duplicates.remove(item); // this.lastSortedItems.remove(item); // } // synchronized (lastSortedItems) { // Collections.sort(lastSortedItems); // } // this.refresh(); // } /** * @param item * @return <code>true</code> if given item is part of the history */ // public boolean isHistoryElement(Object item) { // if (this.selectionHistory != null) { // return this.selectionHistory.contains(item); // } // return false; // } /** * Sets/unsets given item as duplicate. * * @param item * item to change * * @param isDuplicate * duplicate flag */ public void setDuplicateElement(Object item, boolean isDuplicate) { if (this.items.contains(item)) { if (isDuplicate) this.duplicates.add(item); else this.duplicates.remove(item); } } // /** // * Indicates whether given item is a duplicate. // * // * @param item // * item to check // * @return <code>true</code> if item is duplicate // */ // public boolean isDuplicateElement(Object item) { // return duplicates.contains(item); // } // /** // * Load history from memento. // * // * @param memento // * memento from which the history will be retrieved // */ // public void loadHistory(IMemento memento) { // if (this.selectionHistory != null) // this.selectionHistory.load(memento); // } // /** // * Save history to memento. // * // * @param memento // * memento to which the history will be added // */ // public void saveHistory(IMemento memento) { // if (this.selectionHistory != null) // this.selectionHistory.save(memento); // } /** * Gets sorted items. * * @return sorted items */ public Object[] getSortedItems() { if (lastSortedItems.size() != items.size()) { synchronized (lastSortedItems) { lastSortedItems.clear(); lastSortedItems.addAll(items); Collections.sort(lastSortedItems); } } return lastSortedItems.toArray(); } // // /** // * Remember result of filtering. // * // * @param itemsFilter // */ // public void rememberResult(ItemsFilter itemsFilter) { // List itemsList = Collections.synchronizedList(Arrays // .asList(getSortedItems())); // // synchronization // if (itemsFilter == filter) { // lastCompletedFilter = itemsFilter; // lastCompletedResult = itemsList; // } // // } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.IStructuredContentProvider#getElements( * java.lang.Object) */ public Object[] getElements(Object inputElement) { return lastFilteredItems.toArray(); } // public int getNumberOfElements() { // return lastFilteredItems.size(); // } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse * .jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILazyContentProvider#updateElement(int) */ public void updateElement(int index) { FlowFilteredResourcesSelectionDialog.this.list.replace((lastFilteredItems .size() > index) ? lastFilteredItems.get(index) : null, index); } /** * Main method responsible for getting the filtered items and checking * for duplicates. It is based on the * {@link FilteredItemsSelectionDialog.ContentProvider#getFilteredItems(Object, IProgressMonitor)} . * * @param checkDuplicates * <code>true</code> if data concerning elements duplication * should be computed - it takes much more time than standard * filtering * * @param monitor * progress monitor */ // public void reloadCache(boolean checkDuplicates, // IProgressMonitor monitor) { // // reset = false; // // if (monitor != null) { // // the work is divided into two actions of the same length // int totalWork = checkDuplicates ? 200 : 100; // // monitor.beginTask( // WorkbenchMessages.FilteredItemsSelectionDialog_cacheRefreshJob, // totalWork); // } // // // the TableViewer's root (the input) is treated as parent // // lastFilteredItems = Arrays.asList(getFilteredItems(list.getInput(), // monitor != null ? new SubProgressMonitor(monitor, 100) // : null)); // // if (reset || (monitor != null && monitor.isCanceled())) { // if (monitor != null) // monitor.done(); // return; // } // // if (checkDuplicates) { // checkDuplicates(monitor); // } // if (monitor != null) // monitor.done(); // } // private void checkDuplicates(IProgressMonitor monitor) { // synchronized (lastFilteredItems) { // IProgressMonitor subMonitor = null; // int reportEvery = lastFilteredItems.size() / 20; // if (monitor != null) { // subMonitor = new SubProgressMonitor(monitor, 100); // subMonitor // .beginTask( // WorkbenchMessages.FilteredItemsSelectionDialog_cacheRefreshJob_checkDuplicates, // 5); // } // HashMap helperMap = new HashMap(); // for (int i = 0; i < lastFilteredItems.size(); i++) { // if (reset // || (subMonitor != null && subMonitor.isCanceled())) // return; // Object item = lastFilteredItems.get(i); // // if (!(item instanceof ItemsListSeparator)) { // Object previousItem = helperMap.put( // getElementName(item), item); // if (previousItem != null) { // setDuplicateElement(previousItem, true); // setDuplicateElement(item, true); // } else { // setDuplicateElement(item, false); // } // } // // if (subMonitor != null && reportEvery != 0 // && (i + 1) % reportEvery == 0) // subMonitor.worked(1); // } // helperMap.clear(); // } // } // /** // * Returns an array of items filtered using the provided // * <code>ViewerFilter</code>s with a separator added. // * // * @param parent // * the parent // * @param monitor // * progress monitor, can be <code>null</code> // * @return an array of filtered items // */ // protected Object[] getFilteredItems(Object parent, // IProgressMonitor monitor) { // int ticks = 100; // if (monitor == null) { // monitor = new NullProgressMonitor(); // } // // monitor.beginTask( // WorkbenchMessages.FilteredItemsSelectionDialog_cacheRefreshJob_getFilteredElements, // ticks); // if (filters != null) { // ticks /= (filters.size() + 2); // } else { // ticks /= 2; // } // // // get already sorted array // Object[] filteredElements = getSortedItems(); // // monitor.worked(ticks); // // // filter the elements using provided ViewerFilters // if (filters != null && filteredElements != null) { // for (Iterator iter = filters.iterator(); iter.hasNext();) { // ViewerFilter f = (ViewerFilter) iter.next(); // filteredElements = f.filter(list, parent, filteredElements); // monitor.worked(ticks); // } // } // // if (filteredElements == null || monitor.isCanceled()) { // monitor.done(); // return new Object[0]; // } // // ArrayList preparedElements = new ArrayList(); // boolean hasHistory = false; // // if (filteredElements.length > 0) { // if (isHistoryElement(filteredElements[0])) { // hasHistory = true; // } // } // // int reportEvery = filteredElements.length / ticks; // // // add separator // for (int i = 0; i < filteredElements.length; i++) { // Object item = filteredElements[i]; // // if (hasHistory && !isHistoryElement(item)) { // preparedElements.add(itemsListSeparator); // hasHistory = false; // } // // preparedElements.add(item); // // if (reportEvery != 0 && ((i + 1) % reportEvery == 0)) { // monitor.worked(1); // } // } // // monitor.done(); // // return preparedElements.toArray(); // } // /** // * Adds a filter to this content provider. For an example usage of such // * filters look at the project <code>org.eclipse.ui.ide</code>, class // * <code>org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.CustomWorkingSetFilter</code> // * . // * // * // * @param filter // * the filter to be added // */ // public void addFilter(ViewerFilter filter) { // if (filters == null) { // filters = new ArrayList(); // } // filters.add(filter); // // currently filters are only added when dialog is restored // // if it is changed, refreshing the whole TableViewer should be // // added // } } protected class ResourceFilter extends ItemsFilter { private boolean showDerived = false; private IContainer filterContainer; /** * Container path pattern. Is <code>null</code> when only a file name * pattern is used. * * @since 3.6 */ private SearchPattern containerPattern; /** * Container path pattern, relative to the current searchContainer. Is <code>null</code> if there's no search * container. * * @since 3.6 */ private SearchPattern relativeContainerPattern; /** * Camel case pattern for the name part of the file name (without * extension). Is <code>null</code> if there's no extension. * * @since 3.6 */ SearchPattern namePattern; /** * Camel case pattern for the file extension. Is <code>null</code> if * there's no extension. * * @since 3.6 */ SearchPattern extensionPattern; private int filterTypeMask; /** * Creates new ResourceFilter instance * * @param container * @param showDerived * flag which determine showing derived elements * @param typeMask */ public ResourceFilter(IContainer container, boolean showDerived, int typeMask) { super(); this.filterContainer = container; this.showDerived = showDerived; this.filterTypeMask = typeMask; } /** * Creates new ResourceFilter instance * * @param container * @param searchContainer * IContainer to use for performing relative search * @param showDerived * flag which determine showing derived elements * @param typeMask * @since 3.6 */ private ResourceFilter(IContainer container, IContainer searchContainer, boolean showDerived, int typeMask) { this(container, showDerived, typeMask); String stringPattern = getPattern(); String filenamePattern; int sep = stringPattern.lastIndexOf(IPath.SEPARATOR); if (sep != -1) { filenamePattern = stringPattern.substring(sep + 1, stringPattern.length()); if ("*".equals(filenamePattern)) //$NON-NLS-1$ filenamePattern = "**"; //$NON-NLS-1$ if (sep > 0) { if (filenamePattern.length() == 0) // relative patterns // don't need a file // name filenamePattern = "**"; //$NON-NLS-1$ String containerPattern = stringPattern.substring(0, sep); if (searchContainer != null) { relativeContainerPattern = new SearchPattern( SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_PATTERN_MATCH); relativeContainerPattern.setPattern(searchContainer .getFullPath().append(containerPattern) .toString()); } if (!containerPattern.startsWith("" + IPath.SEPARATOR)) //$NON-NLS-1$ containerPattern = IPath.SEPARATOR + containerPattern; this.containerPattern = new SearchPattern( SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_PREFIX_MATCH | SearchPattern.RULE_PATTERN_MATCH); this.containerPattern.setPattern(containerPattern); } patternMatcher.setPattern(filenamePattern); } else { filenamePattern = stringPattern; } int lastPatternDot = filenamePattern.lastIndexOf('.'); if (lastPatternDot != -1) { char last = filenamePattern .charAt(filenamePattern.length() - 1); if (last != ' ' && last != '<' && getMatchRule() != SearchPattern.RULE_EXACT_MATCH) { namePattern = new SearchPattern(); namePattern.setPattern(filenamePattern.substring(0, lastPatternDot)); extensionPattern = new SearchPattern(); extensionPattern.setPattern(filenamePattern .substring(lastPatternDot + 1)); } } } /** * Creates new ResourceFilter instance */ public ResourceFilter() { this(container, searchContainer, isDerived, typeMask); } /** * @param item * Must be instance of IResource, otherwise <code>false</code> will be returned. * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isConsistentItem(java.lang.Object) */ public boolean isConsistentItem(Object item) { if (!(item instanceof IResource)) { return false; } IResource resource = (IResource) item; if (this.filterContainer.findMember(resource.getFullPath()) != null) return true; return false; } /** * @param item * Must be instance of IResource, otherwise <code>false</code> will be returned. * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchItem(java.lang.Object) */ public boolean matchItem(Object item) { if (!(item instanceof IResource)) { return false; } IResource resource = (IResource) item; if ((!this.showDerived && resource.isDerived()) || ((this.filterTypeMask & resource.getType()) == 0)) return false; String name = resource.getName(); if (nameMatches(name)) { if (containerPattern != null) { // match full container path: String containerPath = resource.getParent().getFullPath() .toString(); if (containerPattern.matches(containerPath)) return true; // match path relative to current selection: if (relativeContainerPattern != null) return relativeContainerPattern.matches(containerPath); return false; } return true; } return false; } private boolean nameMatches(String name) { if (namePattern != null) { // fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212565 int lastDot = name.lastIndexOf('.'); if (lastDot != -1 && namePattern.matches(name.substring(0, lastDot)) && extensionPattern .matches(name.substring(lastDot + 1))) { return true; } } return matches(name); } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter# * isSubFilter * (org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ public boolean isSubFilter(ItemsFilter filter) { if (!super.isSubFilter(filter)) return false; if (filter instanceof ResourceFilter) { ResourceFilter resourceFilter = (ResourceFilter) filter; if (this.showDerived == resourceFilter.showDerived) { if (containerPattern == null) { return resourceFilter.containerPattern == null; } else if (resourceFilter.containerPattern == null) { return false; } else { return containerPattern .equals(resourceFilter.containerPattern); } } } return false; } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter# * equalsFilter * (org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ public boolean equalsFilter(ItemsFilter iFilter) { if (!super.equalsFilter(iFilter)) return false; if (iFilter instanceof ResourceFilter) { ResourceFilter resourceFilter = (ResourceFilter) iFilter; if (this.showDerived == resourceFilter.showDerived) { if (containerPattern == null) { return resourceFilter.containerPattern == null; } else if (resourceFilter.containerPattern == null) { return false; } else { return containerPattern .equals(resourceFilter.containerPattern); } } } return false; } /** * Check show derived flag for a filter * * @return true if filter allow derived resources false if not */ public boolean isShowDerived() { return showDerived; } } protected abstract class ItemsFilter { protected SearchPattern patternMatcher; /** * Creates new instance of ItemsFilter. */ public ItemsFilter() { this(new SearchPattern()); } /** * Creates new instance of ItemsFilter. * * @param searchPattern * the pattern to be used when filtering */ public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ".n4j"; //$NON-NLS-1$ if (pattern != null && !pattern.getText().equals("*")) { //$NON-NLS-1$ stringPattern = pattern.getText(); } patternMatcher.setPattern(stringPattern); } /** * Check if the given filter is a sub-filter of this filter. The default * implementation checks if the <code>SearchPattern</code> from the * given filter is a sub-pattern of the one from this filter. * <p> * <i>WARNING: This method is <b>not</b> defined in reading order, i.e. <code>a.isSubFilter(b)</code> is * <code>true</code> iff <code>b</code> is a sub-filter of <code>a</code>, and not vice-versa. </i> * </p> * * @param filter * the filter to be checked, or <code>null</code> * @return <code>true</code> if the given filter is sub-filter of this * filter, <code>false</code> if the given filter isn't a * sub-filter or is <code>null</code> * * @see org.eclipse.ui.dialogs.SearchPattern#isSubPattern(org.eclipse.ui.dialogs.SearchPattern) */ public boolean isSubFilter(ItemsFilter filter) { if (filter != null) { return this.patternMatcher.isSubPattern(filter.patternMatcher); } return false; } /** * Checks whether the provided filter is equal to the current filter. * The default implementation checks if <code>SearchPattern</code> from * current filter is equal to the one from provided filter. * * @param filter * filter to be checked, or <code>null</code> * @return <code>true</code> if the given filter is equal to current * filter, <code>false</code> if given filter isn't equal to * current one or if it is <code>null</code> * * @see org.eclipse.ui.dialogs.SearchPattern#equalsPattern(org.eclipse.ui.dialogs.SearchPattern) */ public boolean equalsFilter(ItemsFilter filter) { if (filter != null && filter.patternMatcher.equalsPattern(this.patternMatcher)) { return true; } return false; } /** * Checks whether the pattern's match rule is camel case. * * @return <code>true</code> if pattern's match rule is camel case, <code>false</code> otherwise */ public boolean isCamelCasePattern() { return patternMatcher.getMatchRule() == SearchPattern.RULE_CAMELCASE_MATCH; } /** * Returns the pattern string. * * @return pattern for this filter * * @see SearchPattern#getPattern() */ public String getPattern() { return patternMatcher.getPattern(); } /** * Returns the rule to apply for matching keys. * * @return an implementation-specific match rule * * @see SearchPattern#getMatchRule() for match rules returned by the * default implementation */ public int getMatchRule() { return patternMatcher.getMatchRule(); } /** * Matches text with filter. * * @param text * the text to match with the filter * @return <code>true</code> if text matches with filter pattern, <code>false</code> otherwise */ protected boolean matches(String text) { return patternMatcher.matches(text); } /** * General method for matching raw name pattern. Checks whether current * pattern is prefix of name provided item. * * @param item * item to check * @return <code>true</code> if current pattern is a prefix of name * provided item, <code>false</code> if item's name is shorter * than prefix or sequences of characters don't match. */ public boolean matchesRawNamePattern(Object item) { String prefix = patternMatcher.getPattern(); String text = getElementName(item); if (text == null) return false; int textLength = text.length(); int prefixLength = prefix.length(); if (textLength < prefixLength) { return false; } for (int i = prefixLength - 1; i >= 0; i--) { if (Character.toLowerCase(prefix.charAt(i)) != Character .toLowerCase(text.charAt(i))) return false; } return true; } /** * Matches an item against filter conditions. * * @param item * @return <code>true<code> if item matches against filter conditions, <code>false</code> otherwise */ public abstract boolean matchItem(Object item); /** * Checks consistency of an item. Item is inconsistent if was changed or * removed. * * @param item * @return <code>true</code> if item is consistent, <code>false</code> if item is inconsistent */ public abstract boolean isConsistentItem(Object item); } protected abstract class AbstractContentProvider { /** * Adds the item to the content provider iff the filter matches the * item. Otherwise does nothing. * * @param item * the item to add * @param itemsFilter * the filter * * @see FilteredItemsSelectionDialog.ItemsFilter#matchItem(Object) */ public abstract void add(Object item, ItemsFilter itemsFilter); } /** * ResourceProxyVisitor to visit resource tree and get matched resources. * During visit resources it updates progress monitor and adds matched * resources to ContentProvider instance. */ private class ResourceProxyVisitor implements IResourceProxyVisitor { private AbstractContentProvider proxyContentProvider; private ResourceFilter resourceFilter; private IProgressMonitor progressMonitor; private List projects; /** * Creates new ResourceProxyVisitor instance. * * @param contentProvider * @param resourceFilter * @param progressMonitor * @throws CoreException */ public ResourceProxyVisitor(AbstractContentProvider contentProvider, ResourceFilter resourceFilter, IProgressMonitor progressMonitor) throws CoreException { super(); this.proxyContentProvider = contentProvider; this.resourceFilter = resourceFilter; this.progressMonitor = progressMonitor; IResource[] resources = container.members(); this.projects = new ArrayList(Arrays.asList(resources)); if (progressMonitor != null) progressMonitor .beginTask( WorkbenchMessages.FilteredItemsSelectionDialog_searchJob_taskName, projects.size()); } /* * (non-Javadoc) * * @see * org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse * .core.resources.IResourceProxy) */ public boolean visit(IResourceProxy proxy) { if (progressMonitor.isCanceled()) return false; IResource resource = proxy.requestResource(); if (this.projects.remove((resource.getProject())) || this.projects.remove((resource))) { progressMonitor.worked(1); } proxyContentProvider.add(resource, resourceFilter); if (resource.getType() == IResource.FOLDER && resource.isDerived() && !resourceFilter.isShowDerived()) { return false; } if (resource.getType() == IResource.FILE) { return false; } return true; } } // protected static abstract class SelectionHistory { // // private static final String DEFAULT_ROOT_NODE_NAME = "historyRootNode"; //$NON-NLS-1$ // // private static final String DEFAULT_INFO_NODE_NAME = "infoNode"; //$NON-NLS-1$ // // private static final int MAX_HISTORY_SIZE = 60; // // private final Set historyList; // // private final String rootNodeName; // // private final String infoNodeName; // // private SelectionHistory(String rootNodeName, String infoNodeName) { // // historyList = Collections.synchronizedSet(new LinkedHashSet() { // // private static final long serialVersionUID = 0L; // // /* // * (non-Javadoc) // * // * @see java.util.LinkedList#add(java.lang.Object) // */ // public boolean add(Object arg0) { // if (this.size() >= MAX_HISTORY_SIZE) { // Iterator iterator = this.iterator(); // iterator.next(); // iterator.remove(); // } // return super.add(arg0); // } // // }); // // this.rootNodeName = rootNodeName; // this.infoNodeName = infoNodeName; // } // // /** // * Creates new instance of <code>SelectionHistory</code>. // */ // public SelectionHistory() { // this(DEFAULT_ROOT_NODE_NAME, DEFAULT_INFO_NODE_NAME); // } // // /** // * Adds object to history. // * // * @param object // * the item to be added to the history // */ // public synchronized void accessed(Object object) { // historyList.remove(object); // historyList.add(object); // } // // /** // * Returns <code>true</code> if history contains object. // * // * @param object // * the item for which check will be executed // * @return <code>true</code> if history contains object // * <code>false</code> in other way // */ // public synchronized boolean contains(Object object) { // return historyList.contains(object); // } // // /** // * Returns <code>true</code> if history is empty. // * // * @return <code>true</code> if history is empty // */ // public synchronized boolean isEmpty() { // return historyList.isEmpty(); // } // // /** // * Remove element from history. // * // * @param element // * to remove form the history // * @return <code>true</code> if this list contained the specified // * element // */ // public synchronized boolean remove(Object element) { // return historyList.remove(element); // } // // /** // * Load history elements from memento. // * // * @param memento // * memento from which the history will be retrieved // */ // public void load(IMemento memento) { // // XMLMemento historyMemento = (XMLMemento) memento // .getChild(rootNodeName); // // if (historyMemento == null) { // return; // } // // IMemento[] mementoElements = historyMemento // .getChildren(infoNodeName); // for (int i = 0; i < mementoElements.length; ++i) { // IMemento mementoElement = mementoElements[i]; // Object object = restoreItemFromMemento(mementoElement); // if (object != null) { // historyList.add(object); // } // } // } // // /** // * Save history elements to memento. // * // * @param memento // * memento to which the history will be added // */ // public void save(IMemento memento) { // // IMemento historyMemento = memento.createChild(rootNodeName); // // Object[] items = getHistoryItems(); // for (int i = 0; i < items.length; i++) { // Object item = items[i]; // IMemento elementMemento = historyMemento // .createChild(infoNodeName); // storeItemToMemento(item, elementMemento); // } // // } // // /** // * Gets array of history items. // * // * @return array of history elements // */ // public synchronized Object[] getHistoryItems() { // return historyList.toArray(); // } // // /** // * Creates an object using given memento. // * // * @param memento // * memento used for creating new object // * // * @return the restored object // */ // protected abstract Object restoreItemFromMemento(IMemento memento); // // /** // * Store object in <code>IMemento</code>. // * // * @param item // * the item to store // * @param memento // * the memento to store to // */ // protected abstract void storeItemToMemento(Object item, IMemento memento); // // } // private class ResourceSelectionHistory extends SelectionHistory { // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory // * #restoreItemFromMemento(org.eclipse.ui.IMemento) // */ // protected Object restoreItemFromMemento(IMemento element) { // ResourceFactory resourceFactory = new ResourceFactory(); // IResource resource = (IResource) resourceFactory // .createElement(element); // return resource; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory // * #storeItemToMemento(java.lang.Object, org.eclipse.ui.IMemento) // */ // protected void storeItemToMemento(Object item, IMemento element) { // IResource resource = (IResource) item; // ResourceFactory resourceFactory = new ResourceFactory(resource); // resourceFactory.saveState(element); // } // // } private class ItemsListSeparator { private String name; // /** // * Creates a new instance of the class. // * // * @param name // * the name of the separator // */ // public ItemsListSeparator(String name) { // this.name = name; // } // // /** // * Returns the name of this separator. // * // * @return the name of the separator // */ // public String getName() { // return name; // } } // // public boolean isHistoryElement(Object item) { // return this.contentProvider.isHistoryElement(item); // } private List<String> getFlowsWithStartNodes(Object f) { File file = (File) f; List<String> startNodes = new ArrayList<String>(); String packageName = getFlowPackage(file); for (String eid : getNetwork(file, packageName)) { startNodes.add(packageName + "-" + eid); } return startNodes; } @SuppressWarnings("restriction") private String getFlowPackage(File file) { String fileRelativePath = file.getProjectRelativePath().toPortableString(); List<String> sourceFolders = getSourceDirectories(file.getProject()); String path = getFilePathWithPackage(sourceFolders, new StringBuilder("/").append(file.getProject().getName()).append("/").append(fileRelativePath).toString()); return path; } private String getFilePathWithPackage(List<String> sourceFolders, String fileRelativePath) { String name = null; for (String source : sourceFolders) { if (fileRelativePath.startsWith(source)) { return fileRelativePath.replaceFirst(source, "").replace("/", ".").replace("." + PropetiesConstants.FLOW_FILE_EXT, ""); } } return name; } @SuppressWarnings("restriction") private List<String> getNetwork(File iResource, String flow) { List<String> list = Collections.emptyList(); InputStream fis = null; try { fis = iResource.getContents(); if (null != fis) { list = FlowUtils.getStartNodeList(fis, flow); } } catch (CoreException e) { e.printStackTrace(); } return list; } private List<String> getSourceDirectories(IProject project) { if (project == null) return null; List<String> ret = projectSources.get(project); if (ret != null) { return ret; } else { ret = new ArrayList<String>(); } IJavaProject javaProject = JavaCore.create(project); try { IPackageFragmentRoot[] packageFragmentRoot = javaProject.getAllPackageFragmentRoots(); for (int i = 0; i < packageFragmentRoot.length; i++) { if (packageFragmentRoot[i].getKind() == IPackageFragmentRoot.K_SOURCE && !packageFragmentRoot[i].isArchive()) ret.add(packageFragmentRoot[i].getPath().toPortableString() + "/"); } } catch (JavaModelException e) { e.printStackTrace(); return Collections.EMPTY_LIST; } projectSources.put(project, ret); return ret; } }
package vista.Productos; import java.awt.event.ActionEvent; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import controlador.*; public class FormAltaProducto extends javax.swing.JFrame { private JLabel lblNombre; private JLabel lblPtoPedido; private JLabel lblPtoRefill; private JLabel lblProveedores; private JLabel lblCantidad; private JTextField txtNombre; private JTextField txtPtoRefill; private JTextField txtPtoPedido; private JTextField txtCantidad; private AbstractAction cerrarAction; private AbstractAction aceptarAction; private JButton btnCancelar; private JButton btnAceptar; private JComboBox cmbProveedores; public FormAltaProducto() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); this.setPreferredSize(new java.awt.Dimension(480, 230)); this.setTitle("Alta de Producto"); { lblNombre = new JLabel(); getContentPane().add(lblNombre); lblNombre.setText("NOMBRE: "); lblNombre.setBounds(12, 12, 229, 14); } { lblCantidad = new JLabel(); getContentPane().add(lblCantidad); lblCantidad.setText("CANTIDAD: "); lblCantidad.setBounds(12, 35, 229, 14); } { lblPtoPedido = new JLabel(); getContentPane().add(lblPtoPedido); lblPtoPedido.setText("PUNTO DE PEDIDO: "); lblPtoPedido.setBounds(12, 58, 229, 14); } { lblPtoRefill = new JLabel(); getContentPane().add(lblPtoRefill); lblPtoRefill.setText("PUNTO DE REABASTECIMIENTO: "); lblPtoRefill.setBounds(12, 81, 229, 14); } { lblProveedores = new JLabel(); getContentPane().add(lblProveedores); lblProveedores.setText("PROVEEDOR: "); lblProveedores.setBounds(12, 104, 229, 14); } { txtNombre = new JTextField(); getContentPane().add(txtNombre); txtNombre.setBounds(223, 9, 237, 21); } { txtCantidad = new JTextField(); getContentPane().add(txtCantidad); txtCantidad.setBounds(223, 32, 86, 21); } { txtPtoPedido = new JTextField(); getContentPane().add(txtPtoPedido); txtPtoPedido.setBounds(223, 55, 86, 21); } { txtPtoRefill = new JTextField(); getContentPane().add(txtPtoRefill); txtPtoRefill.setBounds(223, 78, 86, 21); } { Vector vp = getProveedoresViewVector(Restaurante.getRestaurante().getProveedoresView()); cmbProveedores = new JComboBox(vp); getContentPane().add(cmbProveedores); cmbProveedores.setBounds(223, 101, 237, 21); } { btnAceptar = new JButton(); getContentPane().add(btnAceptar); btnAceptar.setText("Aceptar"); btnAceptar.setBounds(127, 151, 96, 25); btnAceptar.setFont(new java.awt.Font("Tahoma",1,11)); btnAceptar.setAction(getAceptarAction()); } { btnCancelar = new JButton(); getContentPane().add(btnCancelar); btnCancelar.setText("Cancelar"); btnCancelar.setBounds(253, 151, 96, 25); btnCancelar.setFont(new java.awt.Font("Tahoma",1,11)); btnCancelar.setAction(getCerrarAction()); } this.pack(); this.setSize(480, 230); } catch (Exception e) { e.printStackTrace(); } } private AbstractAction getAceptarAction() { if(aceptarAction == null) { aceptarAction = new AbstractAction("Aceptar", null) { public void actionPerformed(ActionEvent evt) { try{ String sProveedor = cmbProveedores.getSelectedItem().toString().substring(0,11); Restaurante.getRestaurante().altaDeProductoFromView(txtNombre.getText(), Integer.parseInt(txtCantidad.getText()), Integer.parseInt(txtPtoPedido.getText()), Integer.parseInt(txtPtoRefill.getText()), sProveedor); JOptionPane.showMessageDialog(null, "Producto creado con exito.", "Alta de Producto", JOptionPane.INFORMATION_MESSAGE); txtNombre.setText(""); txtCantidad.setText(""); txtPtoPedido.setText(""); txtPtoRefill.setText(""); } catch (Exception e){ JOptionPane.showMessageDialog(null, "Cantidad, punto de pedido y reabastecimiento deben contener valores enteros.", "Error en la carga de datos", JOptionPane.WARNING_MESSAGE); } } }; } return aceptarAction; } private AbstractAction getCerrarAction() { if(cerrarAction == null) { cerrarAction = new AbstractAction("Cerrar", null) { public void actionPerformed(ActionEvent evt) { dispose(); } }; } return cerrarAction; } public Vector getProveedoresViewVector(Vector<ProveedorView> vpv){ Vector mv = new Vector(); for (int i= 0; i < vpv.size(); i++){ String aux = String.valueOf(vpv.elementAt(i).getCuit()) + " - " + vpv.elementAt(i).getRazonsocial(); mv.add(aux); } return mv; } }
package com.design.patterns.tests; import com.design.patterns.creationals.factoryMethod.BasePizzaFactory; import com.design.patterns.creationals.factoryMethod.Pizza; import com.design.patterns.creationals.factoryMethod.PizzaFactory; public class TestFactoryMethod implements ITestPattern { @Override public void test() { System.out.println("Usando el patron Factory Method. \n"); BasePizzaFactory pizzaFactory = new PizzaFactory(); Pizza cheesePizza = pizzaFactory.createPizza("cheese"); Pizza veggiePizza = pizzaFactory.createPizza("veggie"); Pizza pepperoniPizza = pizzaFactory.createPizza("pepperoni"); } }
package com.restcode.restcode.resource; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class SavePlanResource { @NotNull @NotBlank @Size(max = 100) private String name; @NotNull private Double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.aop.target.CommonsPool2TargetSource; /** * @author Juergen Hoeller */ class Spr15042Tests { @Test void poolingTargetSource() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PoolingTargetSourceConfig.class); context.close(); } @Configuration static class PoolingTargetSourceConfig { @Bean @Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) public ProxyFactoryBean myObject() { ProxyFactoryBean pfb = new ProxyFactoryBean(); pfb.setTargetSource(poolTargetSource()); return pfb; } @Bean public CommonsPool2TargetSource poolTargetSource() { CommonsPool2TargetSource pool = new CommonsPool2TargetSource(); pool.setMaxSize(3); pool.setTargetBeanName("myObjectTarget"); return pool; } @Bean(name = "myObjectTarget") @Scope(scopeName = "prototype") public Object myObjectTarget() { return new Object(); } } }
package interview.pinduoduo.C; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String result = ""; // 保存结果 int n = sc.nextInt(); //彩票数字个数 int k = sc.nextInt(); // 至少有k个相同 sc.nextLine(); //去掉空格 String str = sc.nextLine(); char[] ch = str.toCharArray(); int[] cnt = new int[10]; // 记录每个数字出现的次数 for (char c : ch) { cnt[c-'0'] ++; if(cnt[c-'0'] >= k) { System.out.println(0); System.out.println(ch); return; } } int min = Integer.MAX_VALUE; char[] res = new char[n]; for(int i = 0; i < 10; i++) { int chaju = k - cnt[i]; char[] tmp = new char[n]; for(int j = 0; j < n; j++) tmp[j] = ch[j]; int now = 0; int left = i - 1; int right = i + 1; while(chaju > 0) { // 如果右边小于10 if(right < 10) { int index = 0; while(index < n && chaju > 0) { if(tmp[index]-'0'==right) { chaju--; now += right - i; tmp[index] = (char)(i+'0'); } index++; } } //如果左边大于0, if(left >= 0) { int index = n - 1; while(chaju > 0 && index >= 0) { if(tmp[index] - '0' == left) { chaju--; now += i - left; tmp[index] = (char) (i+'0'); } index--; } } right++; left--; } if(now < min) { min = now; res = tmp; } } System.out.println(min); System.out.println(res); } }
package com.zc.base.bla.modules.menu.bo; import com.zc.base.bla.modules.menu.entity.Privilege; public class PrivilegeBo extends Privilege { private static final long serialVersionUID = 1L; private String id; private String text; private boolean isLeaf; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public boolean isLeaf() { return this.isLeaf; } public void setLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } }
package org.firstinspires.ftc.teamcode.Autonomous.StatesAuton; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.hardware.DcMotor; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.teamcode.Autonomous.Methods.NewAutonMethods; import org.firstinspires.ftc.teamcode.Hardware.Movement; @Autonomous(name = "Blue Right", group = "Autonomous") public class blueRight extends OpMode { NewAutonMethods robot = new NewAutonMethods(); public boolean ZoneA = true, ZoneB = false, ZoneC = false; public void init() { robot.initNew(hardwareMap, telemetry); // init all ur motors and crap (NOTE: DO NOT INIT GYRO OR VISION IN THIS METHOD) new Thread() { public void run() { robot.initGyro(); telemetry.addData("Gyro Initialized", robot.isGyroInit()); } }.start(); } /* * Code to run REPEATEDLY after the driver hits INIT, but before they hit PLAY */ @Override public void init_loop() { } /* * Code to run ONCE when the driver hits PLAY */ @Override public void start() { robot.runtime.reset(); robot.changeRunMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } /* * Code to run REPEATEDLY after the driver hits PLAY but before they hit STOP */ @Override public void loop() { switch (robot.command) { case 0: if (ZoneA) { robot.command = 1; } else if (ZoneB) { robot.command = 100; } else if (ZoneC) { robot.command = 1000; } //Zone A case 1: robot.setTarget(Movement.FORWARD, 180); break; case 2: robot.finishDrive(); break; case 3: robot.setTarget(Movement.LEFTSTRAFE, 30); break; case 4: robot.finishDrive(); break; case 5: robot.lowerWobble(); if (robot.runtime.milliseconds() > 500) { robot.openWobbleServo(); robot.command++; } break; case 6: robot.raiseWobble(); if (robot.runtime.milliseconds() > 500) { robot.command++; } break; case 7: robot.setTarget(Movement.RIGHTSTRAFE, 30); break; case 8: robot.finishDrive(); break; //Zone B case 101: robot.setTarget(Movement.FORWARD, 210); break; case 102: robot.finishDrive(); break; case 103: robot.lowerWobble(); if (robot.runtime.milliseconds() > 500) { robot.openWobbleServo(); robot.command++; } break; case 104: robot.raiseWobble(); if (robot.runtime.milliseconds() > 500) { robot.command++; } break; case 105: robot.setTarget(Movement.BACKWARD, 60); break; case 106: robot.finishDrive(); break; //Zone C case 1001: robot.setTarget(Movement.FORWARD, 240); break; case 1002: robot.finishDrive(); break; case 1003: robot.lowerWobble(); if (robot.runtime.milliseconds() > 500) { robot.openWobbleServo(); robot.command++; } break; case 1004: robot.raiseWobble(); if (robot.runtime.milliseconds() > 500) { robot.command++; } break; case 1005: robot.setTarget(Movement.BACKWARD, 90); break; case 1006: robot.finishDrive(); break; } telemetry.addData("Case:", robot.command); telemetry.addData("FL Power", robot.FL.getPower()); telemetry.addData("FL Current", robot.FL.getCurrentPosition()); telemetry.addData("FL Target", robot.FL.getTargetPosition()); telemetry.update(); } }
package br.com.alura.streams; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.OptionalDouble; import java.util.stream.Collectors; public class ExemploCursos { public static void main(String[] args) { List<Curso> cursos = new ArrayList<>(); cursos.add(new Curso("Python", 45)); cursos.add(new Curso("Javascript", 150)); cursos.add(new Curso("Java 8", 113)); cursos.add(new Curso("C", 55)); cursos.sort(Comparator.comparing(Curso::getNumAlunos)); cursos.stream().filter(c -> c.getNumAlunos() >= 100).mapToInt(Curso::getNumAlunos).sum(); OptionalDouble media = cursos.stream().filter(c -> c.getNumAlunos() >= 100).mapToInt(Curso::getNumAlunos) .average(); System.out.println(media); cursos.stream().filter(c -> c.getNumAlunos() >= 100).findAny().ifPresent(c -> System.out.println(c.getNome())); // converting a stream to a List List<Curso> cursosFiltrados = cursos.stream().filter(c -> c.getNumAlunos() >= 100).collect(Collectors.toList()); for (Curso curso : cursosFiltrados) { System.out.println(curso.getNome()); } // converting a stream to a Map cursos.stream().filter(c -> c.getNumAlunos() >= 100) .collect(Collectors.toMap(c -> c.getNome(), c -> c.getNumAlunos())) .forEach((nome, alunos) -> System.out.println(nome + " tem " + alunos + " alunos")); } }
/* * Copyright 2019 WeBank * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.wedatasphere.qualitis.rule.controller; import com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException; import com.webank.wedatasphere.qualitis.response.GeneralResponse; import com.webank.wedatasphere.qualitis.response.GetAllResponse; import com.webank.wedatasphere.qualitis.rule.request.AddRuleTemplateRequest; import com.webank.wedatasphere.qualitis.rule.request.DeleteRuleTemplateRequest; import com.webank.wedatasphere.qualitis.rule.request.ModifyRuleTemplateRequest; import com.webank.wedatasphere.qualitis.rule.response.RuleTemplateResponse; import com.webank.wedatasphere.qualitis.rule.service.RuleTemplateService; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * @author howeye */ @Path("api/v1/admin/rule_template") public class RuleTemplateAdminController { @Autowired private RuleTemplateService ruleTemplateService; private static final Logger LOGGER = LoggerFactory.getLogger(RuleTemplateAdminController.class); @POST @Path("multi/add") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<RuleTemplateResponse> addMultiRuleTemplate(AddRuleTemplateRequest request) throws UnExpectedRequestException { try { return new GeneralResponse<>("200", "{&ADD_RULE_TEMPLATE_SUCCESSFULLY}", ruleTemplateService.addRuleTemplate(request)); } catch (UnExpectedRequestException e) { throw new UnExpectedRequestException(e.getMessage()); } catch (Exception e) { LOGGER.error("Failed to find multi rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_ADD_RULE_TEMPLATE}", null); } } @POST @Path("multi/modify") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<RuleTemplateResponse> modifyMultiRuleTemplate(ModifyRuleTemplateRequest request) throws UnExpectedRequestException { try { RuleTemplateResponse response = ruleTemplateService.modifyRuleTemplate(request); return new GeneralResponse<>("200", "{&MODIFY_RULE_TEMPLATE_SUCCESSFULLY}", response); } catch (UnExpectedRequestException e) { throw new UnExpectedRequestException(e.getMessage()); } catch (Exception e) { LOGGER.error("Failed to modify rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_MODIFY_RULE_TEMPLATE}", null); } } @POST @Path("multi/delete/{template_id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<GetAllResponse<RuleTemplateResponse>> deleteMultiRuleTemplate(@PathParam("template_id") Long templateId) throws UnExpectedRequestException { try { ruleTemplateService.deleteRuleTemplate(templateId); return new GeneralResponse<>("200", "{&DELETE_RULE_TEMPLATE_SUCCESSFULLY}", null); } catch (UnExpectedRequestException e) { LOGGER.error("Failed to find delete rule templates, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&CANNOT_DELETE_TEMPLATE}", null); } catch (Exception e) { LOGGER.error("Failed to find delete rule templates, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_DELETE_RULE_TEMPLATE}", null); } } @POST @Path("default/add") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<RuleTemplateResponse> addDefaultRuleTemplate(AddRuleTemplateRequest request) throws UnExpectedRequestException { try { return new GeneralResponse<>("200", "{&ADD_RULE_TEMPLATE_SUCCESSFULLY}", ruleTemplateService.addRuleTemplate(request)); } catch (UnExpectedRequestException e) { throw new UnExpectedRequestException(e.getMessage()); } catch (Exception e) { LOGGER.error("Failed to find multi rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_ADD_RULE_TEMPLATE}", null); } } @POST @Path("default/modify") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<RuleTemplateResponse> modifyDefaultRuleTemplate(ModifyRuleTemplateRequest request) throws UnExpectedRequestException { try { return new GeneralResponse<>("200", "{&MODIFY_RULE_TEMPLATE_SUCCESSFULLY}", ruleTemplateService.modifyRuleTemplate(request)); } catch (UnExpectedRequestException e) { throw new UnExpectedRequestException(e.getMessage()); } catch (Exception e) { LOGGER.error("Failed to modify rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_MODIFY_RULE_TEMPLATE}", null); } } @POST @Path("default/delete/{template_id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<GetAllResponse<RuleTemplateResponse>> deleteDefaultRuleTemplate(@PathParam("template_id") Long templateId) throws UnExpectedRequestException { try { ruleTemplateService.deleteRuleTemplate(templateId); return new GeneralResponse<>("200", "{&DELETE_RULE_TEMPLATE_SUCCESSFULLY}", null); } catch (UnExpectedRequestException e) { LOGGER.error("Failed to find delete rule templates, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&CANNOT_DELETE_TEMPLATE}", null); } catch (Exception e) { LOGGER.error("Failed to find delete rule templates, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_DELETE_RULE_TEMPLATE}", null); } } @POST @Path("delete/all") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<GetAllResponse<RuleTemplateResponse>> deleteAllRuleTemplate(DeleteRuleTemplateRequest request) throws UnExpectedRequestException { try { DeleteRuleTemplateRequest.checkRequest(request); for (Long templateId : request.getRuleTemplateIdList()) { ruleTemplateService.deleteRuleTemplate(templateId); } return new GeneralResponse<>("200", "{&DELETE_RULE_TEMPLATE_SUCCESSFULLY}", null); } catch (UnExpectedRequestException e) { LOGGER.error("Failed to find delete rule templates, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&CANNOT_DELETE_TEMPLATE}", null); } catch (Exception e) { LOGGER.error("Failed to find multi rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_DELETE_RULE_TEMPLATE}", null); } } @GET @Path("modify/detail/{template_id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public GeneralResponse<RuleTemplateResponse> getModifyRuleTemplateDetail(@PathParam("template_id") Long templateId) throws UnExpectedRequestException { try { return new GeneralResponse<>("200", "{&GET_RULE_TEMPLATE_SUCCESSFULLY}", ruleTemplateService.getModifyRuleTemplateDetail(templateId)); } catch (UnExpectedRequestException e) { throw new UnExpectedRequestException(e.getMessage()); } catch (Exception e) { LOGGER.error("Failed to modify rule_template, caused by: {}", e.getMessage(), e); return new GeneralResponse<>("500", "{&FAILED_TO_GET_RULE_TEMPLATE}", null); } } }
package searchnsort; public class SearchInterspersed { public static int find(String[] words, String word) { if (words.length == 0) return -1; return find(words, word, 0, words.length - 1); } private static int find(String[] words, String word, int start, int end) { if (start >= end) return -1; int middle = (start + end) / 2; int left = middle; while (left > start && words[left].length() == 0) left--; if (words[left].equals(word)) return left; else if (!words[left].isEmpty() && word.compareTo(words[left]) < 0) return find(words, word, start, left - 1); int right = middle; while (right < end && words[right].isEmpty()) right++; if (words[right].equals(word)) return right; else if (words[right].isEmpty()) return -1; else return find(words, word, right + 1, end); } }
package com.example.jiyushi1.dis.model; /** * Created by jiyushi1 on 7/23/15. */ public class ShopList { private String shopName; private String special; private int iconID; public int getIconID() { return iconID; } public void setIconID(int iconID) { this.iconID = iconID; } public ShopList(String shopName,String special,int iconID){ setShopName(shopName); setSpecial(special); setIconID(iconID); } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getSpecial() { return special; } public void setSpecial(String special) { this.special = special; } }
package kiemtra; abstract public class Nhanvien { public String ma; public String hoTen; public double luong; abstract public double getLuong(); public Nhanvien(String ma, String hoTen, double luong) { super(); this.ma = ma; this.hoTen = hoTen; this.luong = luong; } // public String getHocLuc() { // double diemTrungBinh = getDiemTrungBinh(); // if(diemTrungBinh<5) { // return "Hoc luc yeu"; // }else if(5<=diemTrungBinh && diemTrungBinh<6.5) { // return "Hoc luc trung binh"; // }else if(6.5<=diemTrungBinh && diemTrungBinh<7.5) { // return "Hoc luc kha"; // }else if(7.5<=diemTrungBinh && diemTrungBinh<9) { // return "Hoc luc gioi"; // }else{ // return "Hoc luc xuat sac"; // } // } public void xuat() { System.out.println("Ma nhan vien :"+ma); System.out.println("Ho ten nhan vien :"+hoTen); System.out.println("Luong nhan vien :"+luong); } }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-24 * Time: 下午9:13 * To change this template use File | Settings | File Templates. */ public class MyDepthFirstSearch { private MyGraph G; private final int s; private boolean marked[]; private int edgeTo[]; private int count; public MyDepthFirstSearch(MyGraph G, int s) { this.G = G; marked = new boolean[G.V()]; edgeTo = new int[G.V()]; this.s = s; dfs(s); } private void dfs(int v) { marked[v] = true; count++; for(int w : G.adj(v)) { if(!marked(w)) { edgeTo[w] = v; dfs(w); } } } public boolean marked(int v) { return marked[v]; } public int count() { return count; } }
package com.java.locks; import java.util.Arrays; public class SelectLowerElement { public int[] swapArray(int[] swap) { int len = swap.length; int lowerIndex; for (int i = 0; i < len; i++) { lowerIndex = selectLowerNum(swap, i); if (lowerIndex != i) { swap[i] ^= swap[lowerIndex]; swap[lowerIndex] ^= swap[i]; swap[i] ^= swap[lowerIndex]; } } return swap; } private int selectLowerNum(int[] data, int start) { int len = data.length; int lower = data[start]; int lowerIndex = start; for (int i = start+1; i < len; i++) { if (data[i] < lower) { lower = data[i]; lowerIndex = i; } } return lowerIndex; } public static void main(String[] args) { SelectLowerElement element = new SelectLowerElement(); int[] arr = {3, 1, 4,6, 5}; int[] ints = element.swapArray(arr); for (int i = 0; i < ints.length; i++) { System.out.println(ints[i]); } } }
package com.example.front_end_of_clean_up_the_camera_app.UserHome; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Message; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.front_end_of_clean_up_the_camera_app.Adapter.DiscussMessageAdapter; import com.example.front_end_of_clean_up_the_camera_app.MessageCalss.DiscussMessage; import com.example.front_end_of_clean_up_the_camera_app.MessageCalss.SellerMessage; import com.example.front_end_of_clean_up_the_camera_app.R; import com.example.front_end_of_clean_up_the_camera_app.Tools.LoadingWindow; import com.example.front_end_of_clean_up_the_camera_app.Tools.ServerConnection; import com.example.front_end_of_clean_up_the_camera_app.UserHomeActivity; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.os.Handler; public class Seller_Msg_Activity extends AppCompatActivity{ public static final int SETDETAIL = 0; public static final int MAKEORDER_SUCCESS = 1; public static final int MAKEORDER_FAIL = 2; private List<DiscussMessage> discussMessageList; private TextView sellerName_textView; private TextView sellerAddress_textView; private TextView sellerStatu_textView; private TextView sellerScore_textView; private TextView sellerCost_textView; private Button make_order_button; private Button make_chat_button; private LoadingWindow loadingWindow = null; private String userId = null; private String sellerId = null; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case SETDETAIL://get seller message detail Bundle bundle = msg.getData(); SellerMessage sellerMessage = (SellerMessage)bundle.getSerializable("sellerMsg"); setDetail(sellerMessage); if(loadingWindow != null){ loadingWindow.dismiss(); loadingWindow = null; } break; case MAKEORDER_SUCCESS://success send order message to backend, turn to order fragment if(loadingWindow != null){ loadingWindow.dismiss(); loadingWindow = null; } Intent intent = new Intent(Seller_Msg_Activity.this, UserHomeActivity.class); break; case MAKEORDER_FAIL:// if(loadingWindow != null){ loadingWindow.dismiss(); loadingWindow = null; } Toast.makeText(getApplicationContext(), "下单失败,请重试", Toast.LENGTH_SHORT).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.seller_msg_layout); SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE); userId = sharedPreferences.getString("userId", ""); sharedPreferences = getSharedPreferences("seller", Context.MODE_PRIVATE); sellerId = sharedPreferences.getString("sellerId", ""); sellerName_textView = (TextView)findViewById(R.id.seller_msg_sellerName_textView); sellerAddress_textView = (TextView)findViewById(R.id.seller_msg_sellerAddress_textView); sellerStatu_textView = (TextView)findViewById(R.id.seller_msg_sellerStatu_textView); sellerScore_textView = (TextView)findViewById(R.id.seller_msg_sellerScore_textView); sellerCost_textView = (TextView)findViewById(R.id.seller_msg_sellerCost_textView); // set top bar of view Toolbar toolbar = (Toolbar)findViewById(R.id.seller_msg_toolbar); setSupportActionBar(toolbar); setTitle("blabla"); // init button make_order_button = findViewById(R.id.seller_msg_makeOrder_button); make_chat_button = findViewById(R.id.seller_msg_makeChat_button); final ActionBar actionBar = getSupportActionBar(); if(actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // set button onClicked event setButtonOnClickedLinstener(); // set discussion recyclerView RecyclerView dmRecyclerView; DiscussMessageAdapter discussMessageAdapter; initDiscussMessageList(); dmRecyclerView = (RecyclerView)findViewById(R.id.seller_msg_discuss_recyclerView); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); dmRecyclerView.setLayoutManager(linearLayoutManager); discussMessageAdapter = new DiscussMessageAdapter(this, discussMessageList); dmRecyclerView.setAdapter(discussMessageAdapter); loadingWindow = new LoadingWindow(this); loadingWindow.show(); getDetail(); } private void initDiscussMessageList(){ discussMessageList = new ArrayList<>(); String userDiscussion = "blablablablablablablablablablablablablablablablablablablablablablablabla" + "blablablablablablablablablablablablablablablabla"; DiscussMessage discussMessage = new DiscussMessage("李*华", new Date(),"4.9", "服务很认真,很满意"); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("王*", new Date(),"4.8", "下单之后等了很久才派人过来检查,好在服务态度很认真,挺好的"); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("林*梅", new Date(),"4.8", "出门在外还是要多注意隐私安全啊,第一次使用这个app,有专业认真检查之后住酒店放心安心多了!"); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", "blablabla"); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", userDiscussion); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", userDiscussion); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", userDiscussion+userDiscussion); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", "blablabla"); discussMessageList.add(discussMessage); discussMessage = new DiscussMessage("username", new Date(),"4.9", userDiscussion); discussMessageList.add(discussMessage); } private void setButtonOnClickedLinstener(){ make_order_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "make_order_button", Toast.LENGTH_SHORT).show(); makeOrder(); } }); make_chat_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "make_chat_button", Toast.LENGTH_SHORT).show(); } }); } //get init data of seller message private void getDetail(){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = new ServerConnection("getShopInfo", "POST").getConnection(); BufferedReader reader = null; try{ connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); OutputStream outputStream = connection.getOutputStream(); String orderMsg = "id=" + sellerId; outputStream.write(orderMsg.getBytes()); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder respond = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ respond.append(line); } JSONObject jsonObject = new JSONObject(respond.toString()); String result = jsonObject.getString("result"); if(result != null){ switch (result){ case "200": String score = jsonObject.getString("score"); String address = jsonObject.getString("address"); String intro = jsonObject.getString("intro"); String name = jsonObject.getString("name"); String status = jsonObject.getString("status"); SellerMessage sellerMessage = new SellerMessage(sellerId, name, intro, address, "0.1", score, "100", status); Bundle bundle = new Bundle(); bundle.putSerializable("sellerMsg", sellerMessage); Message msg = new Message(); msg.what = SETDETAIL; msg.setData(bundle); handler.sendMessage(msg); break; case "404": break; default: } } }catch (Exception e){ e.printStackTrace(); Log.e("getShopInfo", e + e.getMessage()); } } }).start(); } private void setDetail(SellerMessage sellerMessage){ sellerName_textView.setText(sellerMessage.getSellerName()); sellerAddress_textView.setText(sellerMessage.getSellerAddress()); sellerStatu_textView.setText(sellerMessage.getStatus()); sellerScore_textView.setText(sellerMessage.getSellerScore()); sellerCost_textView.setText(sellerMessage.getSellerCost()); } private void makeOrder(){ loadingWindow = new LoadingWindow(this); loadingWindow.show(); new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = new ServerConnection("makeOrder", "POST").getConnection(); BufferedReader reader = null; try{ connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); OutputStream outputStream = connection.getOutputStream(); String orderMsg = "userId=" + userId + "&sellerId=" + sellerId; outputStream.write(orderMsg.getBytes()); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder respond = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ respond.append(line); } JSONObject jsonObject = new JSONObject(respond.toString()); String result = jsonObject.getString("result"); if(result != null){ switch (result){ case "200": break; case "404": break; default: } } }catch (Exception e){ e.printStackTrace(); Log.e("makeOrderError: ", e + e.getMessage()); } } }).start(); } }
package com.longfellow.listnode; /** * @author longfellow * O(1) 时间复杂度删除链表 */ public class DeleteListNode { public ListNode solution(ListNode head, ListNode target) { if (target == null) { return head; } if (target.next == null) { ListNode tmp = head; while (tmp.next != target) { tmp = tmp.next; } tmp.next = null; } else { target.val = target.next.val; target.next = target.next.next; } return head; } }
package com.example.smsviawifi; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; public class OldSmsRetriever extends Thread { public static final String SMS_EXTRA_NAME = "pdus"; public static final String SMS_URI = "content://sms"; public static final String ADDRESS = "address"; public static final String PERSON = "person"; public static final String DATE = "date"; public static final String READ = "read"; public static final String STATUS = "status"; public static final String TYPE = "type"; public static final String BODY = "body"; public static final String SEEN = "seen"; public static final String SNIPPET = "snippet"; public static Context context = MyApplication.getAppContext(); public static void readOldSms() { Log.d("WIFISMS", "Starting reading old sms."); ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(Uri.parse("content://sms"), null, null, null, null); int indexBody = cursor.getColumnIndex(BODY); int indexAddr = cursor.getColumnIndex(ADDRESS); int indexDate = cursor.getColumnIndex(DATE); int indexType = cursor.getColumnIndex(TYPE); int indexRead = cursor.getColumnIndex(READ); if (indexAddr < 0 || !cursor.moveToFirst()) return; SMS.smsList.clear(); do { String smsDate = null; try { String date = cursor.getString(indexDate); Long timestamp = Long.parseLong(date); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestamp); Date finaldate = (Date) calendar.getTime(); DateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss", Locale.US); smsDate = dateFormat.format(finaldate); } catch (Exception e) { Log.e("WIFISMS", e.toString()); } SMS rev_sms = new SMS(smsDate, cursor.getString(indexBody), cursor.getString(indexAddr), ContactsRetriever.getContactId(cursor.getString(indexAddr), context), cursor.getString(indexType), cursor.getString(indexBody), ContactsRetriever.getContactName( cursor.getString(indexAddr), context), cursor.getString(indexRead)); SMS.smsList.add(rev_sms); } while (cursor.moveToNext()); Log.d("WIFISMS", "All sms loaded."); update_message_files(); String newmsg = "{\"newmsg\":\"0\"}"; FileRead.writeFile(context.getFilesDir().getPath() + File.separator + "Data" + File.separator + "messages" + File.separator, "newmsg.json", newmsg); cursor.close(); synchronized (MainActivity.lock) { MainActivity.messagesLoaded = true; } } public static void update_message_files() { String message = ""; String message_list = ""; try { message_list = "{\"conversations\":["; String conv; // int count; // ArrayList<SMS> convList = new ArrayList<SMS>(); ArrayList<String> loadedCovs = new ArrayList<String>(); boolean doneLoading = false; while (!doneLoading) { conv = "-1"; // count = 30; String ID = ""; for (SMS s : SMS.smsList) { String tmp = s.getnumber(); if (!loadedCovs.contains(tmp)) { if (conv.equals("-1")) { conv = s.getnumber(); message += "{" + "\"number\":\"" + s.getnumber().replaceAll("-", "") + "\"," + "\"ID\":\"" + (s.getid() == "" ? s.getnumber() : s .getid()) + "\"," + "\"name\":\"" + (s.getname() == "" ? s.getnumber() : s .getname()) + "\"," + "\"messages\":["; message_list += "{" + "\"number\":\"" + s.getnumber().replaceAll("-", "") + "\"," + "\"ID\":\"" + (s.getid() == "" ? s.getnumber() : s .getid()) + "\"," + "\"name\":\"" + (s.getname() == "" ? s.getnumber() : s .getname()) + "\"," + "\"message\":\"" + s.getSnippet().replaceAll("\"", "\\\\\"") .replaceAll("\n", "\\\\n") + "\"," + "\"read\":\"" + s.getRead() + "\""; ID = (s.getid() == "" ? s.getnumber() : s.getid()); } if (s.getnumber() == null) { // if (count > 0) message += "{\"dir\":\"" + s.getType() + "\",\"body\":\"" + s.getbody().replaceAll("\"", "\\\\\"") .replaceAll("\n", "\\\\n") + "\",\"time\":\"" + s.getdate() + "\"},"; // convList.add(s); // count--; } else if (s.getnumber().equals(conv)) { // if (count > 0) message += "{\"dir\":\"" + s.getType() + "\",\"body\":\"" + s.getbody().replaceAll("\"", "\\\\\"") .replaceAll("\n", "\\\\n") + "\",\"time\":\"" + s.getdate() + "\"},"; // convList.add(s); // count--; } } } if (conv.equals("-1")) { doneLoading = true; } else { loadedCovs.add(conv); Log.e("WIFISMS", "loaded conv :" + conv); } message = message.substring(0, message.length() - 1); message += "]},"; message_list += "},"; message = message.substring(0, message.length() - 1); FileRead.writeFile(context.getFilesDir().getPath() + File.separator + "Data" + File.separator + "messages" + File.separator, "messages-" + ID + ".json", message); message = ""; } } catch (Exception e) { Log.e("WIFISMS", "message string error :" + e.toString()); } message_list = message_list.substring(0, message_list.length() - 1); message_list += "]}"; FileRead.writeFile(context.getFilesDir().getPath() + File.separator + "Data" + File.separator + "messages" + File.separator, "messages-list.json", message_list); } @Override public void run() { // TODO Auto-generated method stub super.run(); readOldSms(); } }
package view.sentences_manager; import java.awt.Color; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import model.SentencesManager; import view.DefaultGridPanel; import view.StyleParameters; import view.customized_widgets.CustomizedButton; import view.customized_widgets.CustomizedComboBox; import view.customized_widgets.CustomizedLabel; public class RemoveSentencePanel extends DefaultGridPanel { private SentencesManager sentencesManager; private CustomizedLabel sentenceChoiceLabel; private CustomizedComboBox sentenceChoiceCombo; private CustomizedButton validationButton; private JLabel messageLabel; private String packageName; private String sentence; public RemoveSentencePanel(SentencesManager sentencesManager, JLabel messageLabel) { super(); this.sentencesManager = sentencesManager; setLayout(new GridBagLayout()); this.messageLabel = messageLabel; packageName = ""; sentence = ""; sentenceChoiceLabel = new CustomizedLabel("Sentence to remove : "); sentenceChoiceCombo = new CustomizedComboBox(sentencesManager.getSentenceNames(packageName)); sentenceChoiceCombo.addActionListener(new SentenceChoiceListener()); validationButton = new CustomizedButton("Remove"); validationButton.addActionListener(new ValidationListener()); addComponent(sentenceChoiceLabel, 0, 0, 1, 1); addComponent(sentenceChoiceCombo, 1, 0, 1, 1); addComponent(validationButton, 0, 1, 2, 1); if (sentenceChoiceCombo.getSelectedItem() != null) sentence = sentenceChoiceCombo.getSelectedItem().toString(); } public void setPackageName(String packageName) { System.out.println(packageName); this.packageName = packageName; } public void update() { remove(sentenceChoiceCombo); sentenceChoiceCombo = new CustomizedComboBox(sentencesManager.getSentenceNames(packageName)); sentenceChoiceCombo.addActionListener(new SentenceChoiceListener()); if (sentenceChoiceCombo.getSelectedItem() != null) sentence = sentenceChoiceCombo.getSelectedItem().toString(); addComponent(sentenceChoiceCombo, 1, 0, 1, 1); revalidate(); repaint(); } public class SentenceChoiceListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { CustomizedComboBox cb = (CustomizedComboBox) e.getSource(); sentence = cb.getSelectedItem().toString(); } } public class ValidationListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (!sentencesManager.removeSentence(sentence, packageName)) { messageLabel.setText("Error with database."); messageLabel.setForeground(Color.red); } else { messageLabel.setText("Sentence has been removed."); messageLabel.setForeground(Color.green); update(); } } } }
package de.varylab.discreteconformal.heds.adapter; import java.util.HashSet; import java.util.Set; import de.jtem.halfedgetools.adapter.AbstractTypedAdapter; import de.jtem.halfedgetools.adapter.AdapterSet; import de.jtem.halfedgetools.adapter.type.Color; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo; @Color public class BranchPointColorAdapter extends AbstractTypedAdapter<CoVertex, CoEdge, CoFace, double[]> { private Set<CoVertex> rootCopySet = new HashSet<CoVertex>(); private Set<CoVertex> branchSet = new HashSet<CoVertex>(); private double[] colorNormal = {0.5, 0.5, 0.5}, colorMarked = {1.0, 0.0, 0.0}, colorMarked2 = {0.0, 1.0, 0.0}; public BranchPointColorAdapter() { super(CoVertex.class, null, null, double[].class, true, false); } public void setContext(CuttingInfo<CoVertex, CoEdge, CoFace> context) { rootCopySet = context.getCopies(context.cutRoot); branchSet = context.getBranchSet(); } @Override public double[] getVertexValue(CoVertex v, AdapterSet a) { if (rootCopySet.contains(v)) { return colorMarked; } else if (branchSet.contains(v)) { return colorMarked2; } else { return colorNormal; } } @Override public double getPriority() { return 1; } }
package uk.co.tekkies.readings.day; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.Calendar; import uk.co.tekkies.readings.R; import uk.co.tekkies.readings.model.Passage; import uk.co.tekkies.readings.util.DatabaseHelper; public class DayModel1 implements DayModel { @Override public void load(DayPresenter presenter, DayView dayView, Calendar calendar) { Context context = ((android.support.v4.app.Fragment)dayView).getActivity(); DatabaseHelper databaseHelper = new DatabaseHelper(context); try { SQLiteDatabase sqliteDatabase = databaseHelper.getWritableDatabase(); String[] params = { Integer.toString(calendar.get(Calendar.MONTH) + 1), Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)) }; final String QUERY = " SELECT Coalesce(book.Name || ' ' || override, book.Name || ' ' || passage.chapter) AS passage, summary.summary_text, passage._id" + " FROM plan" + " LEFT JOIN passage ON passage._id = plan.passage_id" + " LEFT JOIN book ON book._id = passage.book_id" + " LEFT JOIN summary ON summary.book_id = book._id AND summary.chapter = passage.chapter" + " WHERE month = ? and day = ?"; Cursor cursor = sqliteDatabase .rawQuery(QUERY, params); cursor.moveToFirst(); while (!cursor.isAfterLast()) { presenter.addItem(new Passage(cursor.getString(0), cursor.isNull(1) ? context.getString(R.string.sorry_no_summary_available_yet) : cursor.getString(1), cursor.getInt(2))); cursor.moveToNext(); } cursor.close(); presenter.notifyDataSetChanged(); } finally { databaseHelper.close(); } } }
package io.pivotal.racquetandroid.view; import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import io.pivotal.racquetandroid.R; import io.pivotal.racquetandroid.RacquetApplication; import io.pivotal.racquetandroid.util.CircleTransform; public class ProfileView extends LinearLayout { @Bind(R.id.profile_name) TextView profileNameView; @Bind(R.id.profile_image) ImageView profileImageView; @Inject Picasso picasso; public ProfileView(Context context) { super(context); init(); } public ProfileView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ProfileView, 0, 0); init(); try { setProfileName(attributes.getString(R.styleable.ProfileView_profile_name)); setProfileImageUrl(attributes.getString(R.styleable.ProfileView_profile_image_src)); } finally { attributes.recycle(); } } private void init() { RacquetApplication.getApplication().getApplicationComponent().inject(this); LayoutInflater.from(getContext()).inflate(R.layout.view_profile, this); ButterKnife.bind(this); } public void setProfileName(String name) { profileNameView.setText(name); } public TextView getProfileName() { return profileNameView; } public void setProfileImageUrl(String imageUrl) { if (!TextUtils.isEmpty(imageUrl)) { picasso.load(imageUrl).transform(new CircleTransform()).placeholder(R.drawable.club).into(profileImageView); } } public ImageView getProfileImageView() { return profileImageView; } }
package com.atsbt.springboot.controller; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import com.atsbt.springboot.bean.TAdmin; import com.atsbt.springboot.service.TAdminService; /** * 控制层 * @Description: TODO * @Author: 上白书妖 * @Date: 2019年10月1日 下午12:42:54 */ @Controller public class TAdminController { @Autowired TAdminService adminService; @Autowired DataSource datasource; @PostMapping("/tologin") public String listAdmins() { List<TAdmin> list = adminService.listAdmins(); //[TAdmin [id=1, loginacct=superadmin, userpswd=123456, username=超级管理员, //email=admin@atguigu.com, createtime=2019-01-12 17:18:00], //TAdmin [id=2, loginacct=zhangsan, userpswd=123456, username=zhangsan,........省略.... System.out.println(list); System.out.println(datasource);//HikariDataSource (HikariPool-1) return "service/login"; } public String testCloneGit() { System.out.println("半夜三更学狗叫,找抽!"); System.out.println("你是猪吗?还学狗叫......"); } }
package bean; public class AdminLoginBean { private Integer a_id; private String a_account; private String a_password; public Integer getaId() { return a_id; } public void setaId(Integer aId) { this.a_id = aId; } public String getaAccount() { return a_account; } public void setaAccount(String aAccount) { this.a_account = aAccount == null ? null : aAccount.trim(); } public String getaPassword() { return a_password; } public void setaPassword(String aPassword) { this.a_password = aPassword == null ? null : aPassword.trim(); } }
package com.minrisoft; public class Test { public static void main(String[] args) { System.out.println("克隆之前:"); Employee employee1 = new Employee();// 创建Employee对象employee1 employee1.setName("张XX");// 为employee1设置姓名 employee1.setAge(30);// 为employee1设置年龄 System.out.println("员工1的信息:"); System.out.println(employee1); // 输出employee1的信息 System.out.println("克隆之后:"); Employee employee2 = employee1; // 将employee1赋值给employee2 employee2.setName("李XX");// 为employee2设置姓名 employee2.setAge(24);// 为employee2设置年龄 System.out.println("员工1的信息:"); System.out.println(employee1);// 输出employee1的信息 System.out.println("员工2的信息:"); System.out.println(employee2);// 输出employee2的信息 } }
import java.io.IOException; import java.net.URISyntaxException; import utilities.userSession; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import org.xml.sax.SAXException; import utilities.centerDesktop; /* * 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. */ /** * * @author kishor */ public class Menu extends javax.swing.JFrame { /** * Creates new form dataentry */ userSession eUser; public Menu(userSession eUser) { initComponents(); this.eUser = eUser; username.setText(eUser.getUserName() +" / "+ eUser.getUserRole()); this.userPermission(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ private void userPermission(){ menu_add_user.setEnabled(false); menu_company.setEnabled(false); menu_country.setEnabled(false); menu_edit_user.setEnabled(false); menu_office.setEnabled(false); menu_tools.setEnabled(false); customs_import.setVisible(false); custom_export.setVisible(false); if (eUser.getUserRole()==3) { // super user all menu_tools.setEnabled(true); menu_add_user.setEnabled(true); menu_company.setEnabled(true); menu_country.setEnabled(true); menu_edit_user.setEnabled(true); menu_office.setEnabled(true); menu_tools.setEnabled(false); customs_import.setVisible(true); custom_export.setVisible(true); } if (eUser.getUserRole()== 2 ) { // admin user menu_tools.setEnabled(true); menu_add_user.setEnabled(true); menu_company.setEnabled(true); menu_country.setEnabled(true); menu_edit_user.setEnabled(true); menu_office.setEnabled(true); customs_import.setVisible(true); custom_export.setVisible(true); } if (eUser.getUserRole()== 0 ) { // import staff customs_import.setVisible(true); } if (eUser.getUserRole()==1) { // export staff custom_export.setVisible(true); } // if((eUser.getUserRole()==2)){ // menu_add_user.setEnabled(true); // menu_company.setEnabled(true); // menu_country.setEnabled(true); // menu_edit_user.setEnabled(true); // menu_office.setEnabled(true); // // } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jMenu3 = new javax.swing.JMenu(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem8 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); username = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); desktop = new javax.swing.JDesktopPane(); jMenuBar1 = new javax.swing.JMenuBar(); main_menu = new javax.swing.JMenu(); menu_add_user = new javax.swing.JMenuItem(); menu_edit_user = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); menu_company = new javax.swing.JMenuItem(); menu_office = new javax.swing.JMenuItem(); menu_country = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); menu_logout = new javax.swing.JMenuItem(); menu_exit = new javax.swing.JMenuItem(); jMenu8 = new javax.swing.JMenu(); customs_import = new javax.swing.JMenu(); data_input = new javax.swing.JMenuItem(); edit_data = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); release_import = new javax.swing.JMenuItem(); custom_export = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); jMenuItem7 = new javax.swing.JMenuItem(); jMenu10 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); report_by_date = new javax.swing.JMenu(); report_date_wise = new javax.swing.JMenuItem(); report_date_date_hscode = new javax.swing.JMenuItem(); report_hscode = new javax.swing.JMenu(); report_hs_code_s = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); jMenu9 = new javax.swing.JMenu(); menu_tools = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); tools_restore = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); help_help = new javax.swing.JMenuItem(); help_about = new javax.swing.JMenuItem(); jMenu3.setText("jMenu3"); jMenuItem6.setText("jMenuItem6"); jMenuItem8.setText("jMenuItem8"); jMenuItem2.setText("jMenuItem2"); jMenuItem1.setText("jMenuItem1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("CUSTOM MANAGEMENT SYSTEM"); username.setText("username"); jLabel1.setText("Welcome "); desktop.setBorder(new javax.swing.border.MatteBorder(null)); desktop.setDragMode(javax.swing.JDesktopPane.OUTLINE_DRAG_MODE); jScrollPane1.setViewportView(desktop); jMenuBar1.setBackground(new java.awt.Color(204, 153, 0)); jMenuBar1.setForeground(new java.awt.Color(51, 51, 255)); main_menu.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(255, 0, 51))); main_menu.setText("Main"); menu_add_user.setText("Add User"); menu_add_user.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_add_userActionPerformed(evt); } }); main_menu.add(menu_add_user); menu_edit_user.setText("Edit User"); menu_edit_user.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_edit_userActionPerformed(evt); } }); main_menu.add(menu_edit_user); main_menu.add(jSeparator1); menu_company.setText("Company (Add/Edit)"); menu_company.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_companyActionPerformed(evt); } }); main_menu.add(menu_company); menu_office.setText("Office (Add/Edit)"); menu_office.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_officeActionPerformed(evt); } }); main_menu.add(menu_office); menu_country.setText("Country (Add/Edit)"); menu_country.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_countryActionPerformed(evt); } }); main_menu.add(menu_country); main_menu.add(jSeparator3); menu_logout.setText("Logout"); menu_logout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_logoutActionPerformed(evt); } }); main_menu.add(menu_logout); menu_exit.setText("Exit"); menu_exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menu_exitActionPerformed(evt); } }); main_menu.add(menu_exit); jMenuBar1.add(main_menu); jMenuBar1.add(jMenu8); customs_import.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); customs_import.setText("Customs Import "); data_input.setText("Data Input"); data_input.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { data_inputActionPerformed(evt); } }); customs_import.add(data_input); edit_data.setText("Edit Data"); edit_data.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edit_dataActionPerformed(evt); } }); customs_import.add(edit_data); customs_import.add(jSeparator2); release_import.setText("Release Import"); release_import.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { release_importActionPerformed(evt); } }); customs_import.add(release_import); jMenuBar1.add(customs_import); custom_export.setText("Customs Export"); jMenuItem4.setText("Enter Data"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); custom_export.add(jMenuItem4); jMenuItem5.setText("Edit Data"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); custom_export.add(jMenuItem5); custom_export.add(jSeparator5); jMenuItem7.setText("Release"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); custom_export.add(jMenuItem7); jMenuBar1.add(custom_export); jMenuBar1.add(jMenu10); jMenu2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jMenu2.setText("Reports "); report_by_date.setText("By date"); report_date_wise.setText("Datewise"); report_date_wise.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { report_date_wiseActionPerformed(evt); } }); report_by_date.add(report_date_wise); report_date_date_hscode.setText("Date and HSCODE"); report_date_date_hscode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { report_date_date_hscodeActionPerformed(evt); } }); report_by_date.add(report_date_date_hscode); jMenu2.add(report_by_date); report_hscode.setText("By HSCODE"); report_hs_code_s.setText("HSCODE"); report_hs_code_s.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { report_hs_code_sActionPerformed(evt); } }); report_hscode.add(report_hs_code_s); jMenu2.add(report_hscode); jMenu2.add(jSeparator4); jMenuBar1.add(jMenu2); jMenuBar1.add(jMenu9); menu_tools.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); menu_tools.setText("Tools "); jMenuItem3.setText("Backup"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); menu_tools.add(jMenuItem3); tools_restore.setText("Restore"); menu_tools.add(tools_restore); jMenuBar1.add(menu_tools); jMenu4.setText("Help"); help_help.setText("Help"); help_help.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { help_helpActionPerformed(evt); } }); jMenu4.add(help_help); help_about.setText("About......"); help_about.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { help_aboutActionPerformed(evt); } }); jMenu4.add(help_about); jMenuBar1.add(jMenu4); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(username) .addComponent(jLabel1))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void menu_add_userActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_add_userActionPerformed // TODO add your handling code here: Newuser adduser; try { adduser = new Newuser(eUser); desktop.add(adduser); centerDesktop centerDesktop = new centerDesktop(desktop, adduser); adduser.show(); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException | URISyntaxException ex) { JOptionPane.showMessageDialog(menu_company, ex); Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_menu_add_userActionPerformed private void menu_edit_userActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_edit_userActionPerformed // TODO add your handling code here: // edituser edit = new edituser(); // desktop.add(edit); // edit.show(); userEdit jt = new userEdit(eUser); desktop.add(jt); centerDesktop centerDesktop = new centerDesktop(desktop, jt); jt.show(); }//GEN-LAST:event_menu_edit_userActionPerformed private void help_helpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_help_helpActionPerformed // TODO add your handling code here: Help edit_help = new Help(); desktop.add(edit_help); centerDesktop centerDesktop = new centerDesktop(desktop, edit_help); edit_help.show(); }//GEN-LAST:event_help_helpActionPerformed private void help_aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_help_aboutActionPerformed // TODO add your handling code here: About edit_about = new About(); desktop.add(edit_about); centerDesktop centerDesktop = new centerDesktop(desktop, edit_about); edit_about.show(); }//GEN-LAST:event_help_aboutActionPerformed private void data_inputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_data_inputActionPerformed // TODO add your handling code here: Import edit_import = new Import(); desktop.add(edit_import); centerDesktop centerDesktop = new centerDesktop(desktop, edit_import); edit_import.show(); }//GEN-LAST:event_data_inputActionPerformed private void edit_dataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_dataActionPerformed // TODO add your handling code here: editimport e_port = new editimport(); desktop.add(e_port); centerDesktop centerDesktop = new centerDesktop(desktop, e_port); e_port.show(); }//GEN-LAST:event_edit_dataActionPerformed private void menu_companyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_companyActionPerformed // TODO add your handling code here: Editcompany company = new Editcompany(); desktop.add(company); centerDesktop centerDesktop = new centerDesktop(desktop, company); company.show(); }//GEN-LAST:event_menu_companyActionPerformed private void menu_officeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_officeActionPerformed // TODO add your handling code here: editoffice off = new editoffice(); desktop.add(off); centerDesktop centerDesktop = new centerDesktop(desktop, off); off.show(); }//GEN-LAST:event_menu_officeActionPerformed private void menu_countryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_countryActionPerformed // TODO add your handling code here: editcountry off = new editcountry(); desktop.add(off); centerDesktop centerDesktop = new centerDesktop(desktop, off); off.show(); }//GEN-LAST:event_menu_countryActionPerformed private void menu_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_exitActionPerformed // TODO add your handling code here: System.exit(1); }//GEN-LAST:event_menu_exitActionPerformed private void menu_logoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_logoutActionPerformed try { this.setVisible(false); Login ll = new Login(); ll.setVisible(true); } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | URISyntaxException ex) { Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_menu_logoutActionPerformed private void report_date_wiseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_report_date_wiseActionPerformed // TODO add your handling code here: Report_date rep = new Report_date(); desktop.add(rep); centerDesktop centerDesktop = new centerDesktop(desktop, rep); rep.show(); }//GEN-LAST:event_report_date_wiseActionPerformed private void report_date_date_hscodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_report_date_date_hscodeActionPerformed Report_date_hscode rep = new Report_date_hscode (); desktop.add(rep); centerDesktop centerDesktop = new centerDesktop(desktop, rep); rep.show(); }//GEN-LAST:event_report_date_date_hscodeActionPerformed private void report_hs_code_sActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_report_hs_code_sActionPerformed Report_hscode rep = new Report_hscode(); desktop.add(rep); centerDesktop centerDesktop = new centerDesktop(desktop, rep); rep.show(); }//GEN-LAST:event_report_hs_code_sActionPerformed private void release_importActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_release_importActionPerformed // TODO add your handling code here: importRelease release = new importRelease(eUser); desktop.add(release); centerDesktop centerDesktop = new centerDesktop(desktop, release); release.show(); }//GEN-LAST:event_release_importActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed // TODO add your handling code here: export exp = new export(); desktop.add(exp); centerDesktop centerDesktop = new centerDesktop(desktop, exp); exp.show(); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed // TODO add your handling code here: editexport exp = new editexport(); desktop.add(exp); centerDesktop centerDesktop = new centerDesktop(desktop, exp); exp.show(); }//GEN-LAST:event_jMenuItem5ActionPerformed private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed // TODO add your handling code here: exportRelease exp = new exportRelease(eUser); desktop.add(exp); centerDesktop centerDesktop = new centerDesktop(desktop, exp); exp.show(); }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed // TODO add your handling code here: String dbUserName = "root"; String dbPassword = "kishor"; String dbName = "test"; String path = "sqldabase.sql"; String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path; Process runtimeProcess; try { runtimeProcess = Runtime.getRuntime().exec(executeCmd); int processComplete = runtimeProcess.waitFor(); if (processComplete == 0) { JOptionPane.showMessageDialog(menu_company,"Backup created successfully"); System.out.println("Backup created successfully"); // return true; } else { System.out.println("Could not create the backup"); } } catch (IOException | InterruptedException ex) { System.out.println(ex); } }//GEN-LAST:event_jMenuItem3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Menu(null).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu custom_export; private javax.swing.JMenu customs_import; private javax.swing.JMenuItem data_input; private javax.swing.JDesktopPane desktop; private javax.swing.JMenuItem edit_data; private javax.swing.JMenuItem help_about; private javax.swing.JMenuItem help_help; private javax.swing.JLabel jLabel1; private javax.swing.JMenu jMenu10; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu8; private javax.swing.JMenu jMenu9; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JMenu main_menu; private javax.swing.JMenuItem menu_add_user; private javax.swing.JMenuItem menu_company; private javax.swing.JMenuItem menu_country; private javax.swing.JMenuItem menu_edit_user; private javax.swing.JMenuItem menu_exit; private javax.swing.JMenuItem menu_logout; private javax.swing.JMenuItem menu_office; private javax.swing.JMenu menu_tools; private javax.swing.JMenuItem release_import; private javax.swing.JMenu report_by_date; private javax.swing.JMenuItem report_date_date_hscode; private javax.swing.JMenuItem report_date_wise; private javax.swing.JMenuItem report_hs_code_s; private javax.swing.JMenu report_hscode; private javax.swing.JMenuItem tools_restore; private javax.swing.JLabel username; // End of variables declaration//GEN-END:variables }
package org.openmrs.module.mirebalais.setup; import org.apache.commons.lang.time.DateUtils; import org.openmrs.api.context.Context; import org.openmrs.module.emrapi.utils.GeneralUtils; import org.openmrs.module.paperrecord.CloseStaleCreateRequestsTask; import org.openmrs.module.paperrecord.CloseStalePullRequestsTask; import org.openmrs.module.paperrecord.PaperRecordConstants; import org.openmrs.scheduler.SchedulerException; import org.openmrs.scheduler.SchedulerService; import org.openmrs.scheduler.TaskDefinition; import java.util.Date; public class ArchivesSetup { public static void setupCloseStalePullRequestsTask() { SchedulerService schedulerService = Context.getSchedulerService(); TaskDefinition task = schedulerService.getTaskByName(PaperRecordConstants.TASK_CLOSE_STALE_PULL_REQUESTS); if (task == null) { task = new TaskDefinition(); task.setName(PaperRecordConstants.TASK_CLOSE_STALE_PULL_REQUESTS); task.setDescription(PaperRecordConstants.TASK_CLOSE_STALE_PULL_REQUESTS_DESCRIPTION); task.setTaskClass(CloseStalePullRequestsTask.class.getName()); task.setStartTime(DateUtils.addMinutes(new Date(), 5)); task.setRepeatInterval(new Long(3600)); // once an hour task.setStartOnStartup(true); try { schedulerService.scheduleTask(task); } catch (SchedulerException e) { throw new RuntimeException("Failed to schedule close stale pull requests task", e); } } else { boolean anyChanges = GeneralUtils.setPropertyIfDifferent(task, "description", PaperRecordConstants.TASK_CLOSE_STALE_PULL_REQUESTS_DESCRIPTION); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "taskClass", CloseStalePullRequestsTask.class.getName()); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "repeatInterval", new Long(3600)); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "startOnStartup", true); if (anyChanges) { schedulerService.saveTaskDefinition(task); } if (!task.getStarted()) { task.setStarted(true); try { schedulerService.scheduleTask(task); } catch (SchedulerException e) { throw new RuntimeException("Failed to schedule close stale pull requests task", e); } } } } public static void setupCloseStaleCreateRequestsTask() { SchedulerService schedulerService = Context.getSchedulerService(); TaskDefinition task = schedulerService.getTaskByName(PaperRecordConstants.TASK_CLOSE_STALE_CREATE_REQUESTS); if (task == null) { task = new TaskDefinition(); task.setName(PaperRecordConstants.TASK_CLOSE_STALE_CREATE_REQUESTS); task.setDescription(PaperRecordConstants.TASK_CLOSE_STALE_CREATE_REQUESTS_DESCRIPTION); task.setTaskClass(CloseStaleCreateRequestsTask.class.getName()); task.setStartTime(DateUtils.addMinutes(new Date(), 5)); task.setRepeatInterval(new Long(3600)); // once an hour task.setStartOnStartup(true); try { schedulerService.scheduleTask(task); } catch (SchedulerException e) { throw new RuntimeException("Failed to schedule close stale create requests task", e); } } else { boolean anyChanges = GeneralUtils.setPropertyIfDifferent(task, "description", PaperRecordConstants.TASK_CLOSE_STALE_CREATE_REQUESTS_DESCRIPTION); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "taskClass", CloseStaleCreateRequestsTask.class.getName()); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "repeatInterval", new Long(3600)); anyChanges |= GeneralUtils.setPropertyIfDifferent(task, "startOnStartup", true); if (anyChanges) { schedulerService.saveTaskDefinition(task); } if (!task.getStarted()) { task.setStarted(true); try { schedulerService.scheduleTask(task); } catch (SchedulerException e) { throw new RuntimeException("Failed to schedule close stale create requests task", e); } } } } }
package com.redsun.platf.util.convertor; /** * <p>Title : com.webapp </p> * <p>Description : </p> * <p>Copyright : Copyright (c) 2010</p> * <p>Company : FreedomSoft </p> * */ /** * @author Dick Pan * @version 1.0 * @since 1.0 * <p><H3>Change history</H3></p> * <p>2010/10/28 : Created </p> * */ public interface Convertor<S, T> { public T convert(S s); }
package org.cryptable.asn1.runtime.ber; import org.cryptable.asn1.runtime.ASN1Boolean; import org.cryptable.asn1.runtime.exception.ASN1Exception; /** * BERBoolean is the BER implementation of ASN1Boolean * * Created by david on 6/13/15. */ public class BERBoolean implements ASN1Boolean { private boolean asn1Boolean; /** * get boolean value * @return returns the boolean value of BER boolean */ public boolean getASN1Boolean() { return asn1Boolean; } /** * set the boolean value * * @param asn1Boolean boolean value to set */ public void setASN1Boolean(final boolean asn1Boolean) { this.asn1Boolean = asn1Boolean; } /** * default constructor, default false */ public BERBoolean() { this.asn1Boolean = false; } /** * parameterized constructor * * @param value set boolean value with construction */ public BERBoolean(final boolean value) { this.asn1Boolean = value; } /** * check if the length is indefinite (used in BER objects) * * @return the value of the indefinite length */ public boolean isIndefiniteLength() { return false; } /** * Get length for BER encoded Boolean * * @return This will return 3 */ public int getLength() { return 3; } /** * BER encoding of the boolean value * true: 0x01|0x01|0xFF * false: 0x01|Ox01|0x00 * * @return 3 bytes 0x01|0x01|value */ public byte[] encode() { byte[] value = { 0x01, 0x01, 0x00 }; if (asn1Boolean) { value[2] = (byte) 0xFF; } return value; } /** * BER decoding of the boolean array * * @param value binary value to be decoded * @throws ASN1Exception */ public void decode(byte[] value) throws ASN1Exception { if (value[0] != 0x01) throw new ASN1Exception("Wrong BERBoolean tag value [" + value[0] + "]"); if (value[1] != 0x01) throw new ASN1Exception("Wrong BERBoolean length value [" + value[1] + "]"); this.asn1Boolean = value[2] != 0x00; } }
package gui.db; import java.sql.SQLException; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.TimeZone; public class OracleDateFormat extends Format { private SimpleDateFormat df; public OracleDateFormat (final String pattern) { df = new SimpleDateFormat (pattern); df.setLenient (false); df.setTimeZone (TimeZone.getTimeZone ("Etc/GMT0")); // Zulu } @Override public StringBuffer format (final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { try { oracle.sql.TIMESTAMP time = (oracle.sql.TIMESTAMP) obj; java.util.Date date = time.dateValue(); toAppendTo.append (df.format (date)); } catch (SQLException x) { x.printStackTrace(); } return toAppendTo; } @Override public Object parseObject (String source, ParsePosition pos) { java.util.Date date = (java.util.Date) df.parseObject (source, pos); java.sql.Date sqlDate = new java.sql.Date (date.getTime()); return new oracle.sql.TIMESTAMP (sqlDate); } }
import java.util.ArrayList; public class Simulation implements Runnable{ ArrayList<Item> allItems; public Simulation(ArrayList<Item> al){ allItems=al; } @Override public void run() { // TODO Auto-generated method stub } }
package com.git.cloud.resmgt.common.service.impl; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.git.cloud.common.enums.EnumResouseHeader; import com.git.cloud.common.enums.RmHostType; import com.git.cloud.common.enums.RmVirtualType; import com.git.cloud.common.exception.RollbackableBizException; import com.git.cloud.common.interceptor.ResolveObjectUtils; import com.git.cloud.common.model.IsActiveEnum; import com.git.cloud.common.model.base.BaseBO; import com.git.cloud.common.support.Pagination; import com.git.cloud.common.support.PaginationParam; import com.git.cloud.excel.model.vo.DataStoreVo; import com.git.cloud.excel.model.vo.HostVo; import com.git.cloud.foundation.util.PwdUtil; import com.git.cloud.foundation.util.UUIDGenerator; import com.git.cloud.policy.model.vo.AllocIpParamVo; import com.git.cloud.policy.service.IComputePolicyService; import com.git.cloud.policy.service.IIpAllocToDeviceNewService; import com.git.cloud.policy.service.IRmVmParamService; import com.git.cloud.request.dao.IBmSrRrinfoDao; import com.git.cloud.request.model.po.BmSrRrinfoPo; import com.git.cloud.resmgt.common.CloudClusterConstants; import com.git.cloud.resmgt.common.dao.ICmDeviceDAO; import com.git.cloud.resmgt.common.dao.ICmHostDAO; import com.git.cloud.resmgt.common.dao.ICmPasswordDAO; import com.git.cloud.resmgt.common.dao.IRmDatacenterDAO; import com.git.cloud.resmgt.common.dao.IRmGeneralServerDAO; import com.git.cloud.resmgt.common.dao.IRmResPoolDAO; import com.git.cloud.resmgt.common.dao.IRmVmManageServerDAO; import com.git.cloud.resmgt.common.dao.IRmVmTypeDAO; import com.git.cloud.resmgt.common.dao.IRmVmwareLicenseDAO; import com.git.cloud.resmgt.common.model.bo.CmClusterHostNetShowBo; import com.git.cloud.resmgt.common.model.bo.CmClusterHostShowBo; import com.git.cloud.resmgt.common.model.bo.CmDeviceHostShowBo; import com.git.cloud.resmgt.common.model.bo.CmDeviceVMShowBo; import com.git.cloud.resmgt.common.model.bo.CmIpShowBo; import com.git.cloud.resmgt.common.model.po.CmDevicePo; import com.git.cloud.resmgt.common.model.po.CmHostDatastorePo; import com.git.cloud.resmgt.common.model.po.CmHostPo; import com.git.cloud.resmgt.common.model.po.CmLocalDiskPo; import com.git.cloud.resmgt.common.model.po.CmPasswordPo; import com.git.cloud.resmgt.common.model.po.CmVmDatastorePo; import com.git.cloud.resmgt.common.model.po.CmVmPo; import com.git.cloud.resmgt.common.model.po.RmDatacenterPo; import com.git.cloud.resmgt.common.model.po.RmDeviceVolumesRefPo; import com.git.cloud.resmgt.common.model.po.RmVirtualTypePo; import com.git.cloud.resmgt.common.model.po.RmVmManageServerPo; import com.git.cloud.resmgt.common.model.vo.CmDatastoreVo; import com.git.cloud.resmgt.common.model.vo.CmDeviceAndModelVo; import com.git.cloud.resmgt.common.model.vo.CmDeviceVo; import com.git.cloud.resmgt.common.model.vo.CmHostDatastoreRefVo; import com.git.cloud.resmgt.common.model.vo.CmHostRefVo; import com.git.cloud.resmgt.common.model.vo.CmHostVo; import com.git.cloud.resmgt.common.model.vo.CmStorageVo; import com.git.cloud.resmgt.common.model.vo.RmGeneralServerVo; import com.git.cloud.resmgt.common.model.vo.RmResPoolVo; import com.git.cloud.resmgt.common.service.ICmDeviceService; import com.git.cloud.resmgt.common.util.AutomationHostsManager; import com.git.cloud.resmgt.compute.dao.IOpenstackSynckDao; import com.git.cloud.resmgt.compute.dao.IRmCdpDAO; import com.git.cloud.resmgt.compute.dao.impl.RmClusterDAO; import com.git.cloud.resmgt.compute.model.po.RmClusterPo; import com.git.cloud.resmgt.network.dao.IProjectVpcDao; import com.git.cloud.resmgt.network.model.po.OpenstackIpAddressPo; import com.git.cloud.resmgt.network.model.vo.DeviceNetIP; import com.git.cloud.resmgt.network.model.vo.NetIPInfo; import com.git.cloud.resmgt.network.service.IVirtualNetworkService; import com.git.cloud.resmgt.openstack.dao.IFloatingIpDao; import com.git.cloud.resmgt.openstack.model.vo.FloatingIpVo; import com.git.cloud.resmgt.openstack.model.vo.VolumeDetailVo; import com.git.cloud.shiro.model.CertificatePo; import com.git.support.common.MesgFlds; import com.git.support.common.MesgRetCode; import com.git.support.common.VMFlds; import com.git.support.common.VMOpration; import com.git.support.constants.SAConstants; import com.git.support.invoker.common.impl.ResAdptInvokerFactory; import com.git.support.invoker.common.inf.IResAdptInvoker; import com.git.support.sdo.impl.BodyDO; import com.git.support.sdo.impl.DataObject; import com.git.support.sdo.impl.HeaderDO; import com.git.support.sdo.inf.IDataObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import edu.emory.mathcs.backport.java.util.Arrays; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * CopyRight(c) 2014 by GIT * * @Title: CmDeviceServiceImpl.java * @Package com.git.cloud.resmgt.common.service.impl * @Description: 设备管理功能, * @author lizhizhong * @date 2014-12-18 上午10:06:37 * @version V1.0 */ public class CmDeviceServiceImpl implements ICmDeviceService { private static Logger logger = LoggerFactory.getLogger(CmDeviceServiceImpl.class); private ICmDeviceDAO icmDeviceDAO; private IIpAllocToDeviceNewService iIpAllocToDeviceService; private ResAdptInvokerFactory resInvokerFactory; private IRmVmTypeDAO rmVmTypeDAO; private IRmVmManageServerDAO rmVmMgServerDAO; private IRmCdpDAO rmCdpDAO; private IRmDatacenterDAO rmDCDAO; private ICmPasswordDAO cmPasswordDAO; private IRmVmwareLicenseDAO vmLicenseDAO; private ICmHostDAO cmHostDAO; private IRmResPoolDAO rmResPoolDAO; private IRmGeneralServerDAO rmGeneralServerDAO; private RmClusterDAO rmClusterDAO; private IBmSrRrinfoDao bmSrRrinfoDao; private IComputePolicyService computePolicyService; private IOpenstackSynckDao openstackSynckDao; @Autowired private IFloatingIpDao floatingIpDao; @Autowired private IRmVmParamService rmVmParamService ; @Autowired private IProjectVpcDao projectVpcDao; @Autowired private IVirtualNetworkService virtualNetworkService; public IComputePolicyService getComputePolicyService() { return computePolicyService; } public void setComputePolicyService(IComputePolicyService computePolicyService) { this.computePolicyService = computePolicyService; } public IBmSrRrinfoDao getBmSrRrinfoDao() { return bmSrRrinfoDao; } public void setBmSrRrinfoDao(IBmSrRrinfoDao bmSrRrinfoDao) { this.bmSrRrinfoDao = bmSrRrinfoDao; } public RmClusterDAO getRmClusterDAO() { return rmClusterDAO; } public void setRmClusterDAO(RmClusterDAO rmClusterDAO) { this.rmClusterDAO = rmClusterDAO; } public IRmResPoolDAO getRmResPoolDAO() { return rmResPoolDAO; } public void setRmResPoolDAO(IRmResPoolDAO rmResPoolDAO) { this.rmResPoolDAO = rmResPoolDAO; } public ICmDeviceDAO getIcmDeviceDAO() { return icmDeviceDAO; } public void setIcmDeviceDAO(ICmDeviceDAO icmDeviceDAO) { this.icmDeviceDAO = icmDeviceDAO; } public IOpenstackSynckDao getOpenstackSynckDao() { return openstackSynckDao; } public void setOpenstackSynckDao(IOpenstackSynckDao openstackSynckDao) { this.openstackSynckDao = openstackSynckDao; } public String deviceInPool(List<HashMap<String, String>> h_list, List<HashMap<String, String>> d_list, List<HashMap<String, String>> p_list, List<HashMap<String, String>> ds_list, String dcName, String poolName, String cdpName, String clusterName) throws RollbackableBizException { //更新cm_host表集群id、顺序号、入池时间 icmDeviceDAO.updateDeviceOfBatch1(h_list); //更新cm_device表资源池id、设备名称 icmDeviceDAO.updateDeviceOfBatch2(d_list); // 设置用户名和密码 icmDeviceDAO.updateDeviceOfBatch3(p_list); // 批量的将指定携带的外挂存储设备关联到指定的物理机 if (ds_list.size() > 0) { icmDeviceDAO.updateDeviceOfBatch4(ds_list); } return null; } public String deviceInPoolLog(ArrayList<HashMap<String, String>> h_list, ArrayList<HashMap<String, String>> d_list, ArrayList<HashMap<String, String>> p_list, ArrayList<HashMap<String, String>> ds_list, String dcName, String poolName, String cdpName, String clusterName){ StringBuffer log = new StringBuffer(); log.append("设备"); for(HashMap<String,String> d:d_list){ log.append("["+d.get("device_name")+"]"); } log.append(",入数据中心["+dcName+"]"); log.append(",资源池["+poolName+"]"); log.append(",CDP["+cdpName+"]"); log.append(",集群["+clusterName+"]"); return log.toString(); } @Override public <T extends BaseBO> List<T> getCmDeviceHostInfo(String bizId, String deviceName, String sn) { Map<String, String> map = Maps.newHashMap(); map.put("bizId", bizId); map.put("deviceName", deviceName); map.put("sn", sn); List<CmClusterHostShowBo> list = null; try { // 根据输入条件,获取的物理机信息。 list = icmDeviceDAO.getCmDeviceHostInfo("selectCmHostInfo", map); // 根据输入条件,获取物理机对应的网络信息。 List<CmClusterHostNetShowBo> listNet = icmDeviceDAO.getCmDeviceHostNetInfo("selectCmHostNetInfo", map); // 各自循环主机信息列表和主机对应的网络信息列表,当主机id匹配的情况下,将网络信息列表的ip地址累串到主机信息列表的ip字段中。 for (CmClusterHostShowBo cmClusterHostShowBo : list) { for (CmClusterHostNetShowBo cmClusterHostNetShowBo : listNet) { if (cmClusterHostShowBo.getId().equals(cmClusterHostNetShowBo.getId()) && !"".equals(cmClusterHostNetShowBo.getIp())) { cmClusterHostShowBo.getIp_str().append(cmClusterHostNetShowBo.getIp() + ","); } } if (StringUtils.isNotBlank(cmClusterHostShowBo.getIp_str().toString())) { cmClusterHostShowBo.getIp_str().deleteCharAt(cmClusterHostShowBo.getIp_str().length() - 1); } } } catch (RollbackableBizException e) { logger.error("获取物理机详细信息时时发生异常:" + e); } finally {} return (List<T>) list; } @Override public <T extends BaseBO> T getCmDeviceHostInfo(String bizId) { CmDeviceHostShowBo hostInfo = null; try { RmClusterPo rmClusterPo=new RmClusterPo(); HostVo host = openstackSynckDao.selectHostByHostId(bizId); String clusterid =host.getClusterId(); try { //根据集群 id 查找所属的平台类型 rmClusterPo=openstackSynckDao.selectPlatByClusterId(clusterid); } catch (RollbackableBizException e1) { e1.printStackTrace(); } if("O".equalsIgnoreCase(rmClusterPo.getPlatformType())){ hostInfo = icmDeviceDAO.getCmDeviceHostInfo("selectCmDeviceHostOpenStackInfo", bizId); }else{ hostInfo = icmDeviceDAO.getCmDeviceHostInfo("selectCmDeviceHostInfo", bizId); if(hostInfo!=null){ if(hostInfo.getIpmiPwd()!=null && !"".equals(hostInfo.getIpmiPwd())){ hostInfo.setIpmiPwd(PwdUtil.decryption(hostInfo.getIpmiPwd())); } } } if(!"O".equalsIgnoreCase(rmClusterPo.getPlatformType())) { List<CmIpShowBo> cmIpShowBoList = icmDeviceDAO.selectCmIpInfo(bizId); hostInfo.setIpList(cmIpShowBoList); } } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("获取物理机详细信息时发生异常:" + e); ; } return (T) hostInfo; } @Override public <T extends BaseBO> T getCmDeviceVMInfo(String bizId) { CmDeviceVMShowBo vmInfo = new CmDeviceVMShowBo(); try { vmInfo = icmDeviceDAO.getCmDeviceHostInfo("selectCmDeviceVMInfo", bizId); List<CmIpShowBo> cmIpShowBoList=null; if(vmInfo!=null){ cmIpShowBoList = icmDeviceDAO.selectCmIpInfo(bizId); try { FloatingIpVo ipVo = floatingIpDao.findFloatingIpByDeviceId(bizId); if(ipVo != null){ CmIpShowBo bo = new CmIpShowBo(); bo.setRm_ip_type_name("弹性IP"); bo.setIp(ipVo.getFloatingIp()); cmIpShowBoList.add(bo); } } catch (Exception e) { // TODO Auto-generated catch block logger.error("异常exception",e); } vmInfo.setIpList(cmIpShowBoList); } } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("获取虚拟机详细信息时发生异常:" + e); } return (T) vmInfo; } @Override public Pagination<CmDeviceVo> getDevicePagination(PaginationParam paginationParam) { return icmDeviceDAO.pageQuery("findCmDeviceTotal", "findCmDevicePage", paginationParam); } @Override public String deleteCmDeviceList(String[] ids) { String data = ""; CmDeviceVo cmDeviceVO2 = null; for (String id : ids) { cmDeviceVO2 = new CmDeviceVo(); cmDeviceVO2.setId(id); cmDeviceVO2.setIsActive(IsActiveEnum.NO.getValue()); try { icmDeviceDAO.update("deleteCmDevice", cmDeviceVO2); } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("删除设备信息时:" + e); } data = "删除成功!"; } return data; } @Override public String deleteCmDeviceListLog(String[] ids) throws RollbackableBizException{ String logs = ""; if(ids != null) { for(int i=0 ; i<ids.length ; i++) { CmDeviceVo cmDeviceVo=icmDeviceDAO.findObjectByID("selectCmDeviceForLog", ids[i]); logs += "、" + cmDeviceVo.getDeviceName(); } } return logs.length() > 0 ? "【" + logs.substring(1) + "】" : ""; } @Override public CmDatastoreVo selectCmDatastoreById(String id) throws RollbackableBizException { return icmDeviceDAO.findObjectByID("selectOneCmDatastore", id); } @Override public void updateCmDeviceHost(Map map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); CmHostVo cmHostVo = new CmHostVo(); CmLocalDiskPo cmLocalDiskPo = new CmLocalDiskPo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); cmHostVo = (CmHostVo) map.get("cmHostVo"); cmLocalDiskPo = (CmLocalDiskPo) map.get("cmLocalDiskPo"); try { icmDeviceDAO.update("updateCmDevice", cmDeviceVo); icmDeviceDAO.update("updateOneCmHost", cmHostVo); icmDeviceDAO.update("updateCmLocalDiskPo", cmLocalDiskPo); } catch (RollbackableBizException e) { logger.error("修改物理机信息时发生异常:" + e); } } @Override public String updateCmDeviceHostLog(HashMap map) throws RollbackableBizException{ CmDeviceVo cmDeviceVo = new CmDeviceVo(); CmHostVo cmHostVo = new CmHostVo(); CmLocalDiskPo cmLocalDiskPo = new CmLocalDiskPo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); cmHostVo = (CmHostVo) map.get("cmHostVo"); cmLocalDiskPo = (CmLocalDiskPo) map.get("cmLocalDiskPo"); CmDeviceVo oldDevice=icmDeviceDAO.findObjectByID("selectCmDeviceForLog", cmDeviceVo.getId()); CmHostVo oldCmHostVo = icmDeviceDAO.findObjectByID("selectOneCmHost",cmHostVo.getId()); CmLocalDiskPo oldCmLocalDiskPo= icmDeviceDAO.findObjectByID("findCmLocalDiskPoById", cmLocalDiskPo.getId()); String logContent="设备表信息:"+ResolveObjectUtils.getObjectDifferentFieldString(oldDevice, cmDeviceVo, null); logContent+="物理机表信息:"+ResolveObjectUtils.getObjectDifferentFieldString(oldCmHostVo, cmHostVo, null); logContent+="外挂磁盘信息:"+ResolveObjectUtils.getObjectDifferentFieldString(oldCmLocalDiskPo, cmLocalDiskPo, null); return logContent; } @Override public void updateCmDeviceStorage(Map map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); CmStorageVo cmStorageVo = new CmStorageVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); cmStorageVo = (CmStorageVo) map.get("cmStorageVo"); try { icmDeviceDAO.update("updateCmDevice", cmDeviceVo); icmDeviceDAO.update("updateCmStorage", cmStorageVo); } catch (RollbackableBizException e) { logger.error("修改存储设备信息 时发生异常:" + e); } } @Override public String updateCmDeviceStorageLog(HashMap map) throws RollbackableBizException{ CmDeviceVo cmDeviceVo = new CmDeviceVo(); CmStorageVo cmStorageVo = new CmStorageVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); cmStorageVo = (CmStorageVo) map.get("cmStorageVo"); CmDeviceVo oldDevice= icmDeviceDAO.findObjectByID("selectCmDeviceForLog", cmDeviceVo.getId()); CmStorageVo oldCmStorageVo= icmDeviceDAO.findObjectByID("selectOneCmStorage", cmStorageVo.getId()); String logContent="设备表信息:"+ResolveObjectUtils.getObjectDifferentFieldString(oldDevice, cmDeviceVo, null); logContent+="存储表信息:"+ResolveObjectUtils.getObjectDifferentFieldString(oldCmStorageVo, cmStorageVo, null); return logContent; } @Override public CmHostDatastoreRefVo selectCmHostDatastoreRefVo(String id) throws RollbackableBizException { return icmDeviceDAO.findObjectByID("selectCmHostDatastoreRefByHostId", id); } public IIpAllocToDeviceNewService getiIpAllocToDeviceService() { return iIpAllocToDeviceService; } public void setiIpAllocToDeviceService(IIpAllocToDeviceNewService iIpAllocToDeviceService) { this.iIpAllocToDeviceService = iIpAllocToDeviceService; } @Override public Pagination<CmDatastoreVo> getDatastorePagination(PaginationParam paginationParam) { return icmDeviceDAO.pageQuery("findCmDatastoreTotal", "findCmDatastorePage", paginationParam); } @Override public void deleteCmDatastoreVo(CmDatastoreVo cmDatastoreVo) throws RollbackableBizException { icmDeviceDAO.update("deleteCmDatastoreVo", cmDatastoreVo); } @Override public void deleteCmDatastoreVoById(String[] ids) throws RollbackableBizException { if (ids.length > 0) { for (String id : ids) { CmDatastoreVo cmDatastoreVo = new CmDatastoreVo(); cmDatastoreVo = selectCmDatastoreById(id); icmDeviceDAO.update("deleteCmDatastoreVoById", cmDatastoreVo); } } } @Override public void updateCmDatastoreVo(CmDatastoreVo cmDatastoreVo) throws RollbackableBizException { icmDeviceDAO.update("updateCmDatastore", cmDatastoreVo); } @Override public void saveCmDeviceStorage(Map map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); CmStorageVo cmStorageVo = new CmStorageVo(); cmStorageVo = (CmStorageVo) map.get("cmStorageVo"); try { icmDeviceDAO.save("insertCmDevice", cmDeviceVo); icmDeviceDAO.save("insertCmStorge", cmStorageVo); } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("新增存储设备信息 时发生异常:" + e); } } @Override public String saveCmDeviceStorageLog(HashMap map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); CmStorageVo cmStorageVo = new CmStorageVo(); cmStorageVo = (CmStorageVo) map.get("cmStorageVo"); String logContent ="设备表信息:"+ ResolveObjectUtils.getObjectFieldString(cmDeviceVo, null); logContent += "存储表信息:"+ResolveObjectUtils.getObjectFieldString(cmStorageVo, null); // // 修改 // cmDeviceVo.getId() // ResolveObjectUtils.getObjectDifferentFieldString(oldDevice, cmDeviceVo, null); return logContent; } @Override public void saveCmHost(Map map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); CmHostVo cmHostVo = new CmHostVo(); cmHostVo = (CmHostVo) map.get("cmHostVo"); CmLocalDiskPo cmLocalDiskPo = new CmLocalDiskPo(); cmLocalDiskPo = (CmLocalDiskPo) map.get("cmLocalDiskPo"); try { icmDeviceDAO.save("insertCmDevice", cmDeviceVo); icmDeviceDAO.save("insertCmHost", cmHostVo); icmDeviceDAO.save("insertCmLocalDiskPo", cmLocalDiskPo); } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("新增物理机信息 时发生异常:" + e); } } @Override public String saveCmHostLog(HashMap map) { CmDeviceVo cmDeviceVo = new CmDeviceVo(); cmDeviceVo = (CmDeviceVo) map.get("cmDevicevo"); CmHostVo cmHostVo = new CmHostVo(); cmHostVo = (CmHostVo) map.get("cmHostVo"); String logContent ="设备表信息:"+ ResolveObjectUtils.getObjectFieldString(cmDeviceVo, null); logContent += "物理机表信息:"+ResolveObjectUtils.getObjectFieldString(cmHostVo, null); // // 修改 // cmDeviceVo.getId() // ResolveObjectUtils.getObjectDifferentFieldString(oldDevice, cmDeviceVo, null); return logContent; } @Override public List selectCmDeviceHost(String id) { List<Object> list = new ArrayList<Object>(); CmDeviceAndModelVo cmDeviceAndModelVo = new CmDeviceAndModelVo(); CmHostVo cmHostVo = new CmHostVo(); CmLocalDiskPo cmLocalDiskPo = new CmLocalDiskPo(); Integer i; Map<String, Object> map = Maps.newHashMap(); try { cmDeviceAndModelVo = icmDeviceDAO.findObjectByID("selectOneCmDevice", id); cmHostVo = icmDeviceDAO.findObjectByID("selectOneCmHost", id); if(cmHostVo.getIpmiPwd()!=null){ cmHostVo.setIpmiPwd(PwdUtil.decryption(cmHostVo.getIpmiPwd())); } i = icmDeviceDAO.findCmVmCount(id); map.put("vmCount", i); cmLocalDiskPo = icmDeviceDAO.findObjectByID("findCmLocalDiskPoById", id); list.add(cmDeviceAndModelVo); list.add(cmHostVo); list.add(map); list.add(cmLocalDiskPo); } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("查询物理机信息时发生异常:" + e); } return list; } @Override public CmHostDatastorePo selectCmHostDeafultDatastore(String id){ CmHostDatastorePo po = new CmHostDatastorePo(); try { po = icmDeviceDAO.findObjectByID("findCmDatastoreNameByHostId", id); } catch (RollbackableBizException e) { logger.error("查询物理机默认Datastore时发生异常:" + e); } return po; } @Override public CmVmDatastorePo selectCmVmDatastore(String id){ CmVmDatastorePo po = new CmVmDatastorePo(); try { po = icmDeviceDAO.findObjectByID("findCmDatastoreNameByVmId", id); } catch (RollbackableBizException e) { logger.error("查询虚拟机Datastore时发生异常:" + e); } return po; } public ResAdptInvokerFactory getResInvokerFactory() { return resInvokerFactory; } public void setResInvokerFactory(ResAdptInvokerFactory resInvokerFactory) { this.resInvokerFactory = resInvokerFactory; } public IRmGeneralServerDAO getRmGeneralServerDAO() { return rmGeneralServerDAO; } public void setRmGeneralServerDAO(IRmGeneralServerDAO rmGeneralServerDAO) { this.rmGeneralServerDAO = rmGeneralServerDAO; } /** * @param String dcId * @param vcHostIP,VCenter URL * @param vcHostUserName,VCenter 用户名 * @param vcHostPwd,VCenter 密码 * @param hostMgrIp,物理机IP * @param name,Nas存储别名 * @param path,Nas存储路径 * @param mgrIp,Nas存储IP * @param dcId,数据中心id * @return */ public String createNasInterface(String vcHostIP, String vcHostUserName, String vcHostPwd, String hostMgrIp, String name, String path, String mgrIp, String dcId) { String result = ""; // 日志,调试需要 String loginfo = "vc用户名:" + vcHostUserName + ";" + "vc密码:" + vcHostPwd; logger.debug(loginfo); try { HeaderDO header = HeaderDO.CreateHeaderDO(); header.setResourceClass(EnumResouseHeader.VM_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.VM_RES_TYPE.getValue()); header.setOperation(VMOpration.ADD_NAS); RmDatacenterPo dcPo = new RmDatacenterPo(); dcPo = rmDCDAO.getDataCenterById(dcId); header.set("DATACENTER_QUEUE_IDEN", dcPo.getQueueIden()); BodyDO body = BodyDO.CreateBodyDO(); List<Map<String, String>> dsList = new ArrayList<Map<String, String>>(); Map<String, String> map = new HashMap<String, String>(); map.put(VMFlds.VCENTER_URL, CloudClusterConstants.VCENTER_URL_HTTPS + vcHostIP + CloudClusterConstants.VCENTER_URL_SDK); map.put(VMFlds.VCENTER_USERNAME, vcHostUserName); map.put(VMFlds.VCENTER_PASSWORD, vcHostPwd); map.put(VMFlds.HOST_NAME, hostMgrIp); map.put(VMFlds.NAS_HOST_REMOTE_IP, mgrIp); map.put(VMFlds.NAS_REMOTE_PATH, path); map.put(VMFlds.NAS_LOCAL_PATH, name); dsList.add(map); body.setList(VMFlds.NAS_ADD_RECS, dsList); IDataObject reqData = DataObject.CreateDataObject(); reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); IDataObject rspData = null; IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { result = "请求响应失败!"; } else { HeaderDO rspHeader = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); if (MesgRetCode.SUCCESS.equals(rspHeader.getRetCode())) { result = "success"; } else { result = rspHeader.getRetMesg(); } } } catch (Exception e) { result = e.getMessage(); logger.error("异常exception",e); } return result; } /** * @Title: createHostInterface * @Description: TODO * @field: @param clusterId * @field: @param vcHostUserName * @field: @param vcHostPwd * @field: @param vcHostIP * @field: @param clusterEname * @field: @param hostId * @field: @param hostpasswd * @field: @param license * @field: @param hostname * @field: @param hostMgrIp * @field: @param dcId * @field: @return * @field: @throws RollbackableBizException * @return String * @throws */ public String createHostInterface(String vcHostUserName, String vcHostPwd, String vcHostIP, String clusterEname, String hostId, String hostpasswd, String license, String hostname, String hostMgrIp, String dcId) { String result = new String(); IDataObject reqData = DataObject.CreateDataObject(); // 日志,调试需要 String loginfo = "manage device:" + hostname + ";" + "vc用户名:" + vcHostUserName + ";" + "vc密码:" + vcHostPwd; logger.debug(loginfo); HeaderDO header = HeaderDO.CreateHeaderDO(); header.setResourceClass(EnumResouseHeader.VM_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.VM_RES_TYPE.getValue()); header.setOperation(VMOpration.CREATE_HOST); RmDatacenterPo dcPo = null; try { dcPo = rmDCDAO.getDataCenterById(dcId); } catch (RollbackableBizException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); String queueIden = dcPo!=null?dcPo.getQueueIden():""; //首先更新automation的hosts文件 /*try { result = UpdataAutomationHost(hostMgrIp,hostname,"add",dcId,queueIden,invoker); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); }*/ /*if(!result.equals(MesgRetCode.SUCCESS)) return result;*/ header.set("DATACENTER_QUEUE_IDEN", queueIden); reqData.setDataObject(MesgFlds.HEADER, header); BodyDO body = BodyDO.CreateBodyDO(); body.setString(VMFlds.VCENTER_URL, CloudClusterConstants.VCENTER_URL_HTTPS + vcHostIP + CloudClusterConstants.VCENTER_URL_SDK); body.setString(VMFlds.VCENTER_USERNAME, vcHostUserName); body.setString(VMFlds.VCENTER_PASSWORD, vcHostPwd); body.setString(VMFlds.CLUSTER_NAME, clusterEname); /* * body.setString(VMFlds.HOST_USERNAME, (String)hostUserObj[0]); body.setString(VMFlds.HOST_PASSWORD, * PwdUtil.decryption((String)hostUserObj[1])); */ body.setString(VMFlds.HOST_USERNAME, CloudClusterConstants.ESXI_ROOT_USERNAME); body.setString(VMFlds.HOST_PASSWORD, hostpasswd); body.setString(VMFlds.HOST_MANAGEMENT_IP, hostMgrIp); body.setString(VMFlds.VMK_ID, CloudClusterConstants.VMK0);// 增加管理流量参数 // body.setString(VMFlds.HOST_MANAGEMENT_IP, "128.192.161.50"); body.setBoolean(VMFlds.HOST_FORCE, true); // body.setString(VMFlds.HOST_NAME, hostname); body.setString(VMFlds.HOST_NAME, hostMgrIp); // body.setString(VMFlds.HOST_NAME, "128.192.161.50"); body.setString(VMFlds.LICENSE_KEY, license); IDataObject rspData = null; reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); try { rspData = invoker.invoke(reqData, 1200000); if (rspData == null) { result = "请求响应失败!"; } else { HeaderDO header1 = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); if (MesgRetCode.SUCCESS.equals(header1.getRetCode())) { result = "success"; } else { result = header1.getRetMesg(); } } } catch (Exception e) { result = e.getMessage(); logger.error("异常exception",e); } return result; } public IRmVmTypeDAO getRmVmTypeDAO() { return rmVmTypeDAO; } public void setRmVmTypeDAO(IRmVmTypeDAO rmVmTypeDAO) { this.rmVmTypeDAO = rmVmTypeDAO; } public IRmVmManageServerDAO getRmVmMgServerDAO() { return rmVmMgServerDAO; } public void setRmVmMgServerDAO(IRmVmManageServerDAO rmVmMgServerDAO) { this.rmVmMgServerDAO = rmVmMgServerDAO; } public IRmCdpDAO getRmCdpDAO() { return rmCdpDAO; } public void setRmCdpDAO(IRmCdpDAO rmCdpDAO) { this.rmCdpDAO = rmCdpDAO; } public IRmDatacenterDAO getRmDCDAO() { return rmDCDAO; } public void setRmDCDAO(IRmDatacenterDAO rmDCDAO) { this.rmDCDAO = rmDCDAO; } public IRmVmwareLicenseDAO getVmLicenseDAO() { return vmLicenseDAO; } public void setVmLicenseDAO(IRmVmwareLicenseDAO vmLicenseDAO) { this.vmLicenseDAO = vmLicenseDAO; } public ICmHostDAO getCmHostDAO() { return cmHostDAO; } public void setCmHostDAO(ICmHostDAO cmHostDAO) { this.cmHostDAO = cmHostDAO; } public ICmPasswordDAO getCmPasswordDAO() { return cmPasswordDAO; } public void setCmPasswordDAO(ICmPasswordDAO cmPasswordDAO) { this.cmPasswordDAO = cmPasswordDAO; } @Override public List selectCmStorage(String id) { List<Object> list = new ArrayList<Object>(); CmDeviceAndModelVo cmDeviceAndModelVo = new CmDeviceAndModelVo(); CmStorageVo cmStorageVo = new CmStorageVo(); try { cmDeviceAndModelVo = icmDeviceDAO.findObjectByID("selectOneCmDevice", id); cmStorageVo = icmDeviceDAO.findObjectByID("selectOneCmStorage", id); list.add(cmDeviceAndModelVo); list.add(cmStorageVo); } catch (RollbackableBizException e) { // TODO Auto-generated catch block logger.error("查询存储设备信息 时发生异常:" + e); } return list; } @Override public CmDeviceAndModelVo selectSNForTrim(String sn) throws RollbackableBizException { // TODO Auto-generated method stub return icmDeviceDAO.findObjectByID("selectSNfortrim", sn); } @Override public CmDeviceAndModelVo selectDeviceNameForTrim(String deviceName) throws RollbackableBizException { return icmDeviceDAO.findObjectByID("selectDeviceNamefortrim", deviceName); } @Override public CmDeviceAndModelVo selectSeatIdForTrim(String seatId) throws RollbackableBizException { // TODO Auto-generated method stub return icmDeviceDAO.findObjectByID("selectSeatIdForTrim", seatId); } public String destoryHostInterface(String managerServer,List<String> deviceNameList,Map<String,String> devMap) throws Exception{ String result; //获取cdp所在资源池ids RmVmManageServerPo vmManagerServerPo = null; List<RmVmManageServerPo> list= rmVmMgServerDAO.findByID("findRmVmManagerServerPo", managerServer); if(list.isEmpty()||list.size()==0){ throw new RuntimeException("get vm manager info error!"); }else{ vmManagerServerPo = list.get(0); } String userName = vmManagerServerPo.getUserName(); String password = ""; try { CmPasswordPo pwpo = cmPasswordDAO.findCmPasswordByResourceUser(managerServer, userName); password = pwpo.getPassword(); if(StringUtils.isBlank(password)) throw new Exception("获取ManagerServer["+managerServer+"] password is null"); password = PwdUtil.decryption(password); } catch (Exception e) { throw new RuntimeException(e); } RmDatacenterPo dcPo = rmDCDAO.getDataCenterById(vmManagerServerPo.getDatacenterId()); String dcId = dcPo.getId(); String dcQueue = dcPo.getQueueIden(); IDataObject reqData = DataObject.CreateDataObject(); HeaderDO header = HeaderDO.CreateHeaderDO(); header.set("DATACENTER_QUEUE_IDEN", dcQueue); header.setResourceClass(EnumResouseHeader.VM_RES_CLASS.getValue()); header.setResourceType(EnumResouseHeader.VM_RES_TYPE.getValue()); header.setOperation(VMOpration.DESTORY_HOST_RESOURCE); reqData.setDataObject(MesgFlds.HEADER, header); BodyDO body = BodyDO.CreateBodyDO(); body.setString(VMFlds.VCENTER_URL, CloudClusterConstants.VCENTER_URL_HTTPS+vmManagerServerPo.getManageIp()+CloudClusterConstants.VCENTER_URL_SDK); body.setString(VMFlds.VCENTER_USERNAME, userName); body.setString(VMFlds.VCENTER_PASSWORD, password); body.setList(VMFlds.DESTORY_RESOURCE_NAME, deviceNameList);//回收deviceName名称 body.setString(VMFlds.DESTORY_TYPE, "HOST"); IResAdptInvoker invoker = resInvokerFactory.findInvoker("AMQ"); IDataObject rspData = null; reqData.setDataObject(MesgFlds.HEADER, header); reqData.setDataObject(MesgFlds.BODY, body); try { rspData = invoker.invoke(reqData, 300000); if(rspData==null){ result="N"; }else{ HeaderDO header1 = rspData.getDataObject(MesgFlds.HEADER, HeaderDO.class); if(MesgRetCode.SUCCESS.equals(header1.getRetCode())){ result="success"; }else{ result=header1.getRetMesg(); } } } catch (Exception e) { throw new RuntimeException(e); } if(result.equals("success")){ /*for(String key :devMap.keySet()){ String hostIP = key; String hostName = devMap.get(key); UpdataAutomationHost(hostIP, hostName, "del", dcId, dcQueue,invoker); }*/ } return result; } @Override public CertificatePo findCertificatePath() throws RollbackableBizException { // TODO Auto-generated method stub return icmDeviceDAO.findCertificatePath(); } @Override public List<CmDeviceVo> getCmDevicePoNumber() throws RollbackableBizException { // TODO Auto-generated method stub return icmDeviceDAO.getCmDevicePoNumber(); } @Override public String isDeleteCmDeviceList(String[] ids) { String data = ""; CmHostVo cmHostVo = new CmHostVo(); CmStorageVo cmStorageVo = new CmStorageVo(); CmHostDatastoreRefVo cmHostDatastoreRefVo = new CmHostDatastoreRefVo(); int vmCount; if (ids != null && ids.length > 0) { for (String id : ids) { try { CmDeviceAndModelVo cmDeviceAndModelVo = new CmDeviceAndModelVo(); cmHostDatastoreRefVo = (CmHostDatastoreRefVo) icmDeviceDAO.findObjectByID( "selectCmHostDatastoreRefByHostId", id); cmHostVo = (CmHostVo) icmDeviceDAO.findObjectByID("selectOneCmHostByClusterId", id); cmStorageVo = icmDeviceDAO.findObjectByID("selectOneCmStorage", id); vmCount = icmDeviceDAO.findCmVmCount(id); cmDeviceAndModelVo = icmDeviceDAO.findObjectByID("selectOneCmDevice", id); if (cmHostVo != null && cmHostVo.getClusterId() != null) { data = "删除失败,您选择的设备中名称为" + cmDeviceAndModelVo.getDeviceName() + "的设备已经关联集群,无法删除!"; break; // 根据设备id查出对应的主机信息,判断是否有所属资源次 } else if (cmHostDatastoreRefVo != null) {// 用设备id去查主机与datastore关联表,判断主物理机下是否挂datastore data = "删除失败,您选择的设备中名称为" + cmDeviceAndModelVo.getDeviceName() + "的设备挂载了datastore的设备,无法删除!"; break; } else if (vmCount > 0) {// 用设备id去查虚拟机表,判断物理机下是否挂载虚拟机 data = "删除失败,您选择的设备中名称为" + cmDeviceAndModelVo.getDeviceName() + "的设备存在虚拟机,无法删除!"; break; } else if (cmStorageVo != null && cmStorageVo.getStorageChildPoolId() != null && !cmStorageVo.getStorageChildPoolId().equals("")) { data = "删除失败,您选择的设备中名称为" + cmDeviceAndModelVo.getDeviceName() + "的存储设备已有所属资源子池,无法删除!"; break; } else { data = ""; } } catch (RollbackableBizException e) { logger.error("查询删除条件:" + e); } } } return data; } public String UpdataAutomationHost(String hostIP,String hostName,String optType,String dcId,String dcQueue,IResAdptInvoker invoker) throws Exception{ //获取automation服务器信息 List<RmGeneralServerVo> serverList = rmGeneralServerDAO.findRmGeneralServerBydcId(dcId); if(serverList==null||serverList.isEmpty()){ throw new Exception("获取Automation服务器信息失败!"); } RmGeneralServerVo serverVo = serverList.get(0); String autoServerIp = serverVo.getServerIp(); String autoUser = serverVo.getUserName(); String autoUserPwd = PwdUtil.decryption(serverVo.getPassword()); Map<String,Object> contextParams = Maps.newHashMap(); contextParams.put("DC_QUEUE", dcQueue); contextParams.put(SAConstants.SERVER_IP, autoServerIp); //user:icmsauto contextParams.put(SAConstants.USER_NAME, autoUser); contextParams.put(SAConstants.USER_PASSWORD, autoUserPwd); //optType : add/del //TODO abandon String cmd = SAConstants.AUTOMATION_HOSTS_SHELL+" "+optType+" "+hostIP+" "+hostName; logger.info(cmd); contextParams.put(SAConstants.CMD_LIST, Arrays.asList(new String[]{cmd})); String result = AutomationHostsManager.updateHosts(invoker, contextParams); return result; } @Override public boolean selectCmClusterHostInfos(String id) throws RollbackableBizException { boolean flag = false; List<CmClusterHostShowBo> list = icmDeviceDAO.selectCmClusterHostInfos(id); if(list.size()>0){ flag = true; }else{ flag = false; } return flag; } @Override public void updatemDeviceHostIsInvc(Map map) { CmHostVo cmHostVo = new CmHostVo(); cmHostVo = (CmHostVo) map.get("cmHostVo"); try { icmDeviceDAO.update("updateIsInvcCmHost", cmHostVo); } catch (RollbackableBizException e) { logger.error("修改物理机信息时发生异常:" + e); } } @Override public List<Object> isGetRelevanceInfoList(String relevanceInfo) { if(relevanceInfo == null){ return null ; } List<Object> relevanceInfoList = JSONArray.toList(JSONArray.fromObject(relevanceInfo), HashMap.class) ; return relevanceInfoList ; } @Override public String selectBpmModelId(String modelName) throws RollbackableBizException { List<String> aa =icmDeviceDAO.selectBpmModelId(modelName) ; return aa.get(0); } /** * 初始化admin_param中的modelname */ @Override public String selectModelName() throws RollbackableBizException { String aa = icmDeviceDAO.selectModelName().get(0); return aa; } @Override public RmVirtualTypePo findVirtualTypeById(String clusterId) throws RollbackableBizException { RmClusterPo clusterPo = rmClusterDAO.findRmClusterPoById(clusterId); String vmTypeId = clusterPo.getVmType(); HashMap<String, String> params = Maps.newHashMap(); params.put("vmTypeId", vmTypeId); RmVirtualTypePo rmVmTypePo = rmVmTypeDAO.findRmVirtualTypeInfo("findRmVirtualTypeInfo", params); return rmVmTypePo; } @Override public CmDevicePo selectCmDevicePoById(String id) throws RollbackableBizException { CmDevicePo cmDevicePo = new CmDevicePo(); boolean isCmHost = this.isCmHost(id); boolean isCmVm = this.isCmVm(id); if(isCmHost){ //记录状态,PHYSICAL("H"):物理机 cmDevicePo.setHostType(RmHostType.PHYSICAL.getValue()); CmDeviceHostShowBo cmDeviceHostShowBo = this.getCmDeviceHostInfo(id); RmVirtualTypePo vmType = this.findVirtualTypeById(cmDeviceHostShowBo.getCdpId()); cmDevicePo.setVirtualType(vmType.getVirtualTypeCode()); } if(isCmVm){ //记录状态,VIRTUAL("V"):虚拟机 cmDevicePo.setHostType(RmHostType.VIRTUAL.getValue()); CmDeviceVMShowBo cmDeviceVMShowBo = this.getCmDeviceVMInfo(id); RmVirtualTypePo vmType = this.findVirtualTypeById(cmDeviceVMShowBo.getClusterId()); cmDevicePo.setVirtualType(vmType.getVirtualTypeCode()); } return cmDevicePo; } @Override public boolean isCmHost(String id) throws RollbackableBizException { Map<String, String> map = Maps.newHashMap(); map.put("id", id); CmDevicePo P = icmDeviceDAO.isCmHost(map); if(P!=null){ return true; }else{ return false; } } @Override public boolean isCmVm(String id) throws RollbackableBizException { Map<String, String> map = Maps.newHashMap(); map.put("id", id); CmDevicePo P = icmDeviceDAO.isCmVm(map); if(P!=null){ return true; }else{ return false; } } @Override public void updateCmdeviceRunningState(CmDevicePo cmDevicePo) throws RollbackableBizException { icmDeviceDAO.updateCmdeviceRunningState(cmDevicePo); } @Override public void deleteDatastoreInfo(String hostId, String datastoreId) throws RollbackableBizException { Map<String,Object> map = new HashMap<String,Object>(); map.put("hostId", hostId); map.put("datastoreId", datastoreId); icmDeviceDAO.deleteDatastoreInfo(map); } @Override public void saveDefaultDatastore(CmDevicePo cmDevicePo) throws RollbackableBizException { icmDeviceDAO.saveDefaultDatastore(cmDevicePo); icmDeviceDAO.update("updateCmHostDatastoreType", cmDevicePo); } @Override public CmDevicePo getDefaultDatastore(String hostId) throws RollbackableBizException { Map<String,String> map = new HashMap<String,String>(); map.put("hostId", hostId); return icmDeviceDAO.getDefaultDatastore(map); } @Override public List<CmDevicePo> findVMByHostId(String hostId) { HashMap<String,String> map = new HashMap<String,String>(); map.put("hostId", hostId); return icmDeviceDAO.findListByFieldsAndOrder("findVMByHostId",map); } public CmVmPo findPowerInfoByVmId(String vmId) throws RollbackableBizException{ return icmDeviceDAO.findPowerInfoByVmId(vmId); } @Override public String findVmIdByName(String deviceName) throws RollbackableBizException { return icmDeviceDAO.findVmIdByName(deviceName); } @Override public String findHostIpById(String id) throws RollbackableBizException { return icmDeviceDAO.findHostIpById(id); } @Override public String getPmRunningState(String hostId)throws RollbackableBizException { return icmDeviceDAO.getPmRunningState(hostId); } @Override public CmDevicePo findDeviceById(String id) throws RollbackableBizException { return icmDeviceDAO.findCmDeviceById(id); } @Override public List<CmDevicePo> findDeviceDefaultDatastore(String datastoreId)throws RollbackableBizException { return icmDeviceDAO.findDeviceDefaultDatastore(datastoreId); } public void updateCmDeviceLparId(CmDevicePo device) throws RollbackableBizException { icmDeviceDAO.update("updateCmDeviceLparId", device); } public void updateCmDeviceLparName(CmDevicePo device) throws RollbackableBizException { icmDeviceDAO.update("updateCmDeviceLparName", device); } public void updateCmDeviceProfileName(CmDevicePo device) throws RollbackableBizException { icmDeviceDAO.update("updateCmDeviceProfileName", device); } /** * * 查询最新创建的虚拟机信息,只有一条 */ @Override public CmDevicePo findNewDevcieByHostId()throws RollbackableBizException { return icmDeviceDAO.findNewDevcieByHostId(); } @Override public CmHostPo findDistribHost(String ipInfo)throws RollbackableBizException { return icmDeviceDAO.findDistribHost(ipInfo); } @Override public String findVmTypeCodeByVmId(String vmId) throws RollbackableBizException { HashMap<String, String> params = Maps.newHashMap(); params.put("vmId", vmId); RmVirtualTypePo rmVmTypePo = rmVmTypeDAO.findRmVirtualTypeInfo("findRmVirtualTypeByVmId", params); String vmTypeCode = ""; if(rmVmTypePo != null) { vmTypeCode = rmVmTypePo.getVirtualTypeCode(); } return vmTypeCode; } @Override public List<String> findVolumeTypeList(String availableZoneId) throws RollbackableBizException { List<String> Volume = icmDeviceDAO.findVolumeTypeList(availableZoneId); return Volume; } @Override public Pagination<CmHostPo> getHostConfigure(PaginationParam paginationParam) throws RollbackableBizException { return icmDeviceDAO.getHostConfigure(paginationParam); } @Override public Pagination<RmDeviceVolumesRefPo> getRmDeviceVolumesRefPoList(PaginationParam paginationParam) throws RollbackableBizException { return icmDeviceDAO.getRmDeviceVolumesRefPoList(paginationParam); } @Override public void saveRmDeviceVolumesRefPo(RmDeviceVolumesRefPo rmDeviceVolumesRefPo) throws RollbackableBizException { icmDeviceDAO.saveRmDeviceVolumesRefPo(rmDeviceVolumesRefPo); } @Override public void deleteRmDeviceVolumesRef(RmDeviceVolumesRefPo ref) throws RollbackableBizException { icmDeviceDAO.deleteRmDeviceVolumesRef(ref); } @Override public RmDeviceVolumesRefPo getRmDeviceVolumesRefByMap(HashMap<String, String> map) throws RollbackableBizException { return icmDeviceDAO.getRmDeviceVolumesRefByMap(map); } @Override public void updateRmDvRefVolumeId(RmDeviceVolumesRefPo ref) throws RollbackableBizException { icmDeviceDAO.updateRmDvRefVolumeId(ref); } @Override public void saveOpenstackVolume(VolumeDetailVo volumeVo) { // TODO Auto-generated method stub icmDeviceDAO.saveOpenstackVolume(volumeVo); } @Override public void updateVmProjectId(String vmId, String projectId) throws RollbackableBizException { icmDeviceDAO.updateVmProjectId(vmId, projectId); } @Override public <T extends BaseBO> T getCmDeviceVMInfoOpenstack(String bizId) throws Exception { CmDeviceVMShowBo vmInfo = icmDeviceDAO.getCmDeviceHostInfo("selectCmDeviceVMInfo", bizId); List<CmIpShowBo> cmIpShowBoList = new ArrayList<>(); try { List<OpenstackIpAddressPo> list = virtualNetworkService.selectIpAddressByDeviceId(bizId); if(list.size() > 0) { for(OpenstackIpAddressPo li : list) { CmIpShowBo bo = new CmIpShowBo(); bo.setRm_ip_type_name("管理IP"); bo.setIp(li.getIp()); cmIpShowBoList.add(bo); } } vmInfo.setIpList(cmIpShowBoList); } catch (Exception e) { throw new RollbackableBizException("查询opnestack虚拟机ip失败" + e); } return (T) vmInfo; } }
package com.image.infosys.imageprocess; import android.app.Activity; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.googlecode.tesseract.android.TessBaseAPI; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class Tess_OCR extends AppCompatActivity{ public static final String TESS_DATA = "/tessdata"; private static final String TAG = ImageActivity.class.getSimpleName(); private static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/Tess"; private TessBaseAPI tessBaseAPI; private final Activity activity; public Tess_OCR(String mCurrentPhotoPath, TextView textView, Activity Imageactivity){ System.out.println("mCurrentPhotoPath : "+DATA_PATH+TESS_DATA); this.prepareTessData(); activity = Imageactivity; // this.startOCR(mCurrentPhotoPath, textView); } private void prepareTessData(){ System.out.println("mCurrentPhotoPath : "+DATA_PATH +TESS_DATA); try{ // System.out.println(getExternalFilesDir(DATA_PATH+TESS_DATA)); // System.out.println("mCurrentPhotoPath : "+getExternalFilesDir(DATA_PATH+TESS_DATA)); // File dir = getExternalFilesDir(DATA_PATH+TESS_DATA); // File dir = new File(DATA_PATH+TESS_DATA); File folder = new File(Environment.getExternalStorageDirectory() + "/Tess"); boolean success = true; if (!folder.exists()) { success = folder.mkdirs(); } // if(!dir.isDirectory()){ // if (!dir.mkdir()) { // Toast.makeText(getApplicationContext(), "The folder " + dir.getPath() + "was not created", Toast.LENGTH_SHORT).show(); // } // } System.out.println("Success ; "+success); if (success) { AssetManager assetManager = activity.getAssets(); System.out.println("Asset Manager: " +assetManager.toString()); String fileList[] = assetManager.list(""); System.out.println("Assets File : " + fileList.length); for (int i = 0; i < fileList.length; i++) { Log.d("Files", "FileName:" + fileList[i]); } // for (String fileName : fileList) { // String pathToDataFile = Environment.getExternalStorageDirectory() + "/Tess" + "/" + fileName; // System.out.println("Data File : " + pathToDataFile); // // if (!(new File(pathToDataFile)).exists()) { // InputStream in = getAssets().open(fileName); // OutputStream out = new FileOutputStream(pathToDataFile); // byte[] buff = new byte[1024]; // int len; // while ((len = in.read(buff)) > 0) { // out.write(buff, 0, len); // } // in.close(); // out.close(); // } // } } else{ } } catch (Exception e) { Log.e(TAG+" Msg", e.getMessage()); } } private void startOCR(String mCurrentPhotoPath, TextView textView){ try{ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 6; Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options); String result = this.getText(bitmap); textView.setText(result); }catch (Exception e){ Log.e(TAG + " Start OCR ", e.getMessage()); } } private String getText(Bitmap bitmap){ try{ tessBaseAPI = new TessBaseAPI(); }catch (Exception e){ Log.e(TAG, e.getMessage()); } // String dataPath = getExternalFilesDir("/").getPath() + "/"; // System.out.print("Class Tess DataPath: "+dataPath); tessBaseAPI.init(DATA_PATH, "eng"); tessBaseAPI.setImage(bitmap); String retStr = "No result"; try{ retStr = tessBaseAPI.getUTF8Text(); }catch (Exception e){ Log.e(TAG + " getText ", e.getMessage()); } tessBaseAPI.end(); return retStr; } }
package br.com.candleanalyser.simulation; import java.text.NumberFormat; import java.text.SimpleDateFormat; import br.com.candleanalyser.engine.Candle; public class Operation { private long qtty; private Candle buyCandle; private Candle sellCandle; private double buyCost; private String buyInfo; private double sellCost; private String sellInfo; public Operation(long qtty, Candle buyCandle, double buyCost, String buyInfo) { this.qtty = qtty; this.buyCandle = buyCandle; this.buyCost = buyCost; this.buyInfo = buyInfo; } public void registerSell(Candle sellCandle, double sellCost, String sellInfo) { this.sellCandle = sellCandle; this.sellCost = sellCost; this.sellInfo = sellInfo; } public String getBuyInfo() { return buyInfo; } public String getSellInfo() { return sellInfo; } public long getQtty() { return qtty; } public Candle getBuyCandle() { return buyCandle; } public Candle getSellCandle() { return sellCandle; } public double getCost() { return sellCost + buyCost; } private void assertState() { if(sellCandle==null) throw new IllegalStateException("This operation was not finished yet. Some operations are not permited."); } public double getBuyDebit() { return qtty*buyCandle.getClose() + buyCost; } public double getSellCredit() { assertState(); return qtty*sellCandle.getClose() - sellCost; } public double getYield() { assertState(); return (getSellCredit()/getBuyDebit())-1; } public double getYieldMoney() { assertState(); return getSellCredit() - getBuyDebit(); } @Override public String toString() { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm"); String result = "Operation: buyDate=" + sdf.format(getBuyCandle().getDate()) + "; buyDebit=" + nf.format(getBuyDebit()) + "; buyValue=" + nf.format(getBuyCandle().getClose()) + "; qtty="+ getQtty(); if(sellCandle!=null) { result += "\n sellDate=" + sdf.format(getSellCandle().getDate()) + "; sellCredit=" + nf.format(getSellCredit()) + "; sellValue=" + nf.format(getSellCandle().getClose()) + "; yield=" + nf.format(getYield()*100) + "%; yieldMoney=" + nf.format(getYieldMoney()); } else { result += "\n No sell in this operation"; } return result; } }
package com.sirma.itt.javacourse.chat.client.managers; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import com.sirma.itt.javacourse.chat.client.controller.UIControler; import com.sirma.itt.javacourse.chat.client.threads.ClientThread; import com.sirma.itt.javacourse.chat.client.ui.ChatsPanel; import com.sirma.itt.javacourse.chat.client.ui.MainClientWindow; import com.sirma.itt.javacourse.chat.common.Message; import com.sirma.itt.javacourse.chat.common.MessageType; import com.sirma.itt.javacourse.chat.common.utils.LanguageController; /** * @author siliev * */ public class TestClientMessageInterpreter { private static final Logger LOGGER = Logger .getLogger(TestClientMessageInterpreter.class); @Spy private ClientMessageInterpretor interpreter; @Mock private ClientThread thread; @Spy private MainClientWindow window; @Mock private UIControler controler; /** * Set up before test method. * * @throws java.lang.Exception * something went wrong. */ @Before public void setUp() throws Exception { thread = Mockito.mock(ClientThread.class); window = Mockito.mock(MainClientWindow.class); // controler = Mockito.spy(UIControler.getInstance()); // controler.registerChatPanel(new ChatsPanel()); // controler.registerMainWindow(window); controler = Mockito.mock(UIControler.class); interpreter = Mockito.spy(new ClientMessageInterpretor(controler)); } /** * Test method for * {@link com.sirma.itt.javacourse.chat.client.managers.ClientMessageInterpretor#generateMessage(com.sirma.itt.javacourse.chat.common.Message.TYPE, long, java.lang.String, java.lang.String)} * . */ @Test public void testGenerateMessage() { assertTrue(interpreter.generateMessage(MessageType.MESSAGE, 0, "", "") instanceof Message); } /** * Test method for InterpretMessage method with MESSAGE */ @Test public void testInterpretMessageMessage() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.MESSAGE, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()) .displayMessage(message); } /** * Test method for InterpretMessage method with STARTCHAT */ @Test public void testInterpretMessageStartChat() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.STARTCHAT, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).createTab(message); } /** * Test method for InterpretMessage method with APPROVED */ @Test public void testInterpretMessageApproved() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.APPROVED, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).welcomeClient(message); } /** * Test method for InterpretMessage method with REFUSED */ @Test public void testInterpretMessageRefused() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.REFUSED, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).userNameRejected( message); } /** * Test method for InterpretMessage method with USERLISTADD */ @Test public void testInterpretMessageUserListAdd() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.USERLISTADD, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).updateUserListAdd( message); } /** * Test method for InterpretMessage method with USERLIST */ @Test public void testInterpretMessageUserList() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.USERLIST, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).updateUserList( message.getContent()); } /** * Test method for InterpretMessage method with USERLISTREMOVE */ @Test public void testInterpretMessageUserListRemove() { controler.registerChatPanel(new ChatsPanel()); Message message = new Message("[ test ]", 0, MessageType.USERLISTREMOVE, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()).updateUserListRemove( message.getContent()); } /** * Test method for InterpretMessage method with DISCONNECT */ @Test public void testInterpretMessageDisconnect() { controler.registerChatPanel(new ChatsPanel()); try { LanguageController.loadCurrentLanguage(); } catch (MalformedURLException e) { LOGGER.info(e.getMessage(), e); } Message message = new Message("[ test ]", 0, MessageType.DISCONNECT, "user"); interpreter.interpretMessage(message, null); Mockito.verify(controler, Mockito.atLeastOnce()) .displayMessage(message); } }
package cs261_project.controller; import java.util.Base64; import javax.annotation.Nullable; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import cs261_project.*; import cs261_project.data_structure.*; /** * Process group joining, template fetching and feedback submission for clients * @author Group 12 - Stephen Xu, JuanYan Huo, Ellen Tatum, JiaQi Lv, Alexander Odewale */ @Controller @RequestMapping("/attendee") public final class AttendeeProcessor { //Pattern matching for abusive language //however it can't deal with hidden abusal, for which neural network must be used //this is a base64 encoded message to avoid showing out the bad contents directly in the source code private static String ABUSIVE_PATTERN = "LiooZnVja3xzaGl0fGJpdGNofG1vdGhlcmZ1Y2tlcnxqZXJrfG1vcm9ufGJhc3RhcmR8c3Vja3xhc3N8ZGlja3xwdXNzeXxkYW1ufGhlbGx8d2Fua2VyfGlkaW90fGN1bnR8d2hvcmV8d2hvcmluZykuKg=="; static{ //decode the content AttendeeProcessor.ABUSIVE_PATTERN = new String(Base64.getDecoder().decode(AttendeeProcessor.ABUSIVE_PATTERN)); } public AttendeeProcessor(){ } @GetMapping("/feedbackForm") public final String serveFeedbackForm(@RequestParam("error") @Nullable String error, HttpSession session, Model model){ final Object eventid = session.getAttribute("EventID"); //if no active event has found if(eventid == null){ return "redirect:/joinEventPage"; } if(error != null){ //we don't need to inform user, just make them leaving the event without submitting the feedback model.addAttribute("error", "Your feedback has violated our community rules, please change your feedback content."); } final DatabaseConnection db = App.getInstance().getDbConnection(); //fetch event final Event event = db.LookupEvent(Integer.parseInt(eventid.toString())); //render event details and display model.addAttribute("Event", event); //find template final Template template = db.fetchTemplate(event.getEventID()); if(template != null){ //template exists for this event, send to client //we send all JSON to client and let the web browser to parse the template to reduce work load on the server model.addAttribute("question", template.getQuestions()); } return "feedbackForm"; } @PostMapping("/submitFeedback") public String processFeedback(Feedback feedback, HttpSession session, Model model){ final Object eventid = session.getAttribute("EventID"); //if no active event has found if(eventid == null){ return "redirect:/joinEventPage"; } final DatabaseConnection db = App.getInstance().getDbConnection(); //post processing final String fed_str = feedback.getFeedback(); //firstly don't submit feedback if it contains bad language if(fed_str.matches(AttendeeProcessor.ABUSIVE_PATTERN)){ return "redirect:/attendee/feedbackForm?error=" + "offensive"; } //secondly calculate the average score for the provided mood and the sentiment analyser feedback.setMood((byte)(0.5 * (feedback.getMood() + SentimentAnalyzer.getSentimentType(fed_str)))); //submit feedback to database feedback.setEventID(Integer.parseInt(eventid.toString())); final boolean status = db.submitFeedback(feedback); if(!status){ //feedback submission failed return "redirect:/feedbackForm"; } //after the feedback has been submitted, we should automatically make them leave the event //since we are not asking attendees to submit multiple feedback return IndexProcessor.renderRedirect( "Thank you, we have received your valuable feedback. Redirecting back to the home page...", "/attendee/leaveEvent", model); } @GetMapping("/leaveEvent") public final String handleLeaveEvent(HttpSession session){ //remove event session id session.removeAttribute("EventID"); session.invalidate(); return "redirect:/joinEventPage"; } }
package jikanganai.server.resolvers; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.pattern.PatternsCS; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import jikanganai.server.actors.ChargeCodeActorClassic; import jikanganai.server.entities.ChargeCode; import jikanganai.server.repositories.ChargeCodeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class ChargeCodeResolver implements GraphQLQueryResolver { @Autowired private ChargeCodeRepository repository; /** * graphql-java-tools will automatically pick up the schema.graphqls on * the classpath and match the Query function names to function names in * these GraphQLQueryResolvers. Hence schema names are important. * * @param id * @return */ public ChargeCode chargeCode(Integer id) { return repository.find(id); } public List<ChargeCode> chargeCodes() { return repository.all(); } public List<ChargeCode> chargeCodesActor() { // final ActorSystem<ChargeCodeActor.ChargeCodesRequest> actor = // ActorSystem.create(ChargeCodeActor.create(), "test"); ActorSystem system = ActorSystem.create("test-system"); ActorRef readingActorRef = system.actorOf( ChargeCodeActorClassic.props() ); CompletableFuture<Object> objectCompletableFuture = PatternsCS.ask( readingActorRef, new ChargeCodeActorClassic.FetchChargeCodes(), 1000 ).toCompletableFuture(); Object join = objectCompletableFuture.join(); if (join instanceof Collection) { ((Collection) join).stream().forEach(System.out::println); } readingActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); return null; } }
package gov.nih.nci.ctrp.importtrials.util; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; /** * Created by kigonyapa on 3/27/17. */ @RunWith(Parameterized.class) public class ImportTrialUtilsGetFullNameCtGovStyleTest { @Parameterized.Parameter(value = 0) public String firstName; @Parameterized.Parameter(value = 1) public String middleName; @Parameterized.Parameter(value = 2) public String lastName; @Parameterized.Parameter(value = 3) public String degrees; @Parameterized.Parameter(value = 4) public String expectedVal; @Parameterized.Parameters public static Collection<Object[]> data() { Collection<Object[]> params = new ArrayList<Object[]>(); params.add(new Object[] {"Andrew", "A", "Drew", "BSc Computer Science, Ms Medicine", "Andrew A Drew, BSc Computer Science, Ms Medicine"}); params.add(new Object[] {"", "A", "Drew", "BSc Computer Science, Ms Medicine", "A Drew, BSc Computer Science, Ms Medicine"}); return params; } @Test public void test() { Assert.assertEquals(ImportTrialUtils.getFullNameCtGovStyle(firstName, middleName, lastName, degrees), expectedVal); } }
package com.gsccs.sme.plat.svg.model; import java.text.SimpleDateFormat; import java.util.Date; public class AppealTraceT { private Long id; private Long itemid; private Long topicid; private Long corpid; private Long svgid; private String userid; private String tasktype; private Date addtime; private String addtimestr; private String content; private String status; private String corptitle; private String svgtitle; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getItemid() { return itemid; } public void setItemid(Long itemid) { this.itemid = itemid; } public Long getTopicid() { return topicid; } public void setTopicid(Long topicid) { this.topicid = topicid; } public Long getCorpid() { return corpid; } public void setCorpid(Long corpid) { this.corpid = corpid; } public Long getSvgid() { return svgid; } public void setSvgid(Long svgid) { this.svgid = svgid; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getTasktype() { return tasktype; } public void setTasktype(String tasktype) { this.tasktype = tasktype; } public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAddtimestr() { if (null != addtime){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); addtimestr = df.format(getAddtime()); } return addtimestr; } public void setAddtimestr(String addtimestr) { this.addtimestr = addtimestr; } public String getCorptitle() { return corptitle; } public void setCorptitle(String corptitle) { this.corptitle = corptitle; } public String getSvgtitle() { return svgtitle; } public void setSvgtitle(String svgtitle) { this.svgtitle = svgtitle; } }
/* * JBoss, a division of Red Hat * Copyright 2013, Red Hat Middleware, LLC, and individual * contributors as indicated by the @authors tag. See the * copyright.txt 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.impl.security; import org.gatein.wcm.api.model.security.WCMUser; import org.gatein.wcm.api.services.WCMSecurityService; import org.gatein.wcm.api.services.exceptions.WCMContentSecurityException; import org.gatein.wcm.impl.model.WCMContentFactory; import org.jboss.logging.Logger; /** * * Dummy Service facade to simulate an interaction with the Portal's authentication system. * <p> * In this case we are going to create the following users for testing: * <p> * <li>User/password: admin/admin Roles: admin <br> * <li>User/password: user1/gtn Roles: readwrite,europe <br> * <li>User/password: user2/gtn Roles: europe <br> * <li>User/password: user3/gtn Roles: readwrite,america <br> * <li>User/password: user4/gtn Roles: america <br> * <p> * ModeShape needs "admin" or "readwrite" roles to create a writable session. <br> * Other roles are used by WCM for fine grained ACL. <br> * <p> * This class will be replaced for another that connects to underlaying security subsystem. * <p> * * @author <a href="mailto:lponce@redhat.com">Lucas Ponce</a> * */ public class DummySecurityService implements WCMSecurityService { private static final Logger log = Logger.getLogger(DummySecurityService.class); public WCMUser authenticate(String idUser, String password) throws WCMContentSecurityException { log.debug("Authenticating user... " + idUser); WCMUser user = null; if ("admin".equals(idUser)) { if (!"admin".equals(password)) throw new WCMContentSecurityException("Bad password for user " + idUser); String[] roles = {"admin"}; user = WCMContentFactory.createUserInstance("admin", roles); user.setPassword(password); } if ("user1".equals(idUser)) { if (!"gtn".equals(password)) throw new WCMContentSecurityException("Bad password for user " + idUser); String[] roles = {"readwrite", "europe"}; user = WCMContentFactory.createUserInstance("user1", roles); user.setPassword(password); } if ("user2".equals(idUser)) { if (!"gtn".equals(password)) throw new WCMContentSecurityException("Bad password for user " + idUser); String[] roles = {"europe"}; user = WCMContentFactory.createUserInstance("user2", roles); user.setPassword(password); } if ("user3".equals(idUser)) { if (!"gtn".equals(password)) throw new WCMContentSecurityException("Bad password for user " + idUser); String[] roles = {"readwrite", "america"}; user = WCMContentFactory.createUserInstance("user3", roles); user.setPassword(password); } if ("user4".equals(idUser)) { if (!"gtn".equals(password)) throw new WCMContentSecurityException("Bad password for user " + idUser); String[] roles = {"america"}; user = WCMContentFactory.createUserInstance("user4", roles); user.setPassword(password); } if (user == null) throw new WCMContentSecurityException("User " + idUser + " doesn't found on DummySecurityService"); return user; } }
package escom.ipn.mx.appbecas; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; public class Login extends AppCompatActivity { Button btnEntrar, btnRegistrar; TextView txtBoleta, txtPassword; CheckBox remember; int REG = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btnEntrar = findViewById(R.id.btnEntrar); btnRegistrar = findViewById(R.id.btnRegistrar); remember = findViewById(R.id.chkRecordar); txtBoleta = findViewById(R.id.txtBoleta); txtPassword = findViewById(R.id.txtPassword); LoginProcess(); } @Override protected void onResume(){ super.onResume(); LoginProcess(); } @Override protected void onRestart(){ super.onRestart(); LoginProcess(); } public void LoginProcess(){ BaseDeDatos helper = new BaseDeDatos(this); final SQLiteDatabase db = helper.getWritableDatabase(); btnEntrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // BIENVENIDO // VERIFICANDO QUE NO ESTEN VACIOS LOS CAMPOS if(txtBoleta.getText().toString().isEmpty() || txtPassword.getText().toString().isEmpty()){ Toast.makeText(Login.this, "Ingresa los datos solicitados, por favor", Toast.LENGTH_LONG).show(); } else { // HACIENDO CONSULTA A LA BD String SQL = "SELECT * FROM Alumno WHERE boleta = '" + txtBoleta.getText().toString() + "' AND password = '" + txtPassword.getText().toString() + "'"; Cursor c = db.rawQuery(SQL, null); c.moveToFirst(); int filas = c.getCount(); // CONTADOR DE FILAS RESULTANTES DE LA CONSULTA A LA BD String boleta = ""; // CREANDO VARIABLE BOLETA if (filas > 0){ // SI EL USUARIO ES VALIDO boleta = c.getString(0); // OBTIENE EL NOMBRE DEL USUARIO } c.close(); System.out.println("FILAS: " + filas); // SHARED PREFERENCES SharedPreferences prefs = getSharedPreferences("MisPreferencias", Context.MODE_PRIVATE); // SI EL USUARIO ES VALIDO, ENTRA if (filas > 0) { if (remember.isChecked()) { // SI RECORDAR ESTÁ ACTIVO SharedPreferences.Editor editor = prefs.edit(); editor.putString("usuario", txtBoleta.getText().toString()); editor.putString("password", txtPassword.getText().toString()); editor.commit(); } else { SharedPreferences.Editor editor = prefs.edit(); editor.putString("usuario", ""); editor.putString("password", ""); editor.commit(); } Intent intent = new Intent(Login.this, Menu_Lobby.class); intent.putExtra("boleta", boleta); startActivity(intent); finish(); } else { Toast.makeText(Login.this, "Datos Incorrectos", Toast.LENGTH_SHORT).show(); } } } }); btnRegistrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // REGISTRARSE Intent intent = new Intent(Login.this, Registro.class); startActivityForResult(intent, REG); // REG ES UN IDENTIFICADOR PARA OBTENER UNA RESPUESTA DE LA OTRA CLASE } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent i){ if(requestCode == REG){ if(resultCode == RESULT_OK) { // EVERYTHING'S OK Toast.makeText(this,"Te has registrado correctamente!", Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this,"Registro cancelado", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this,"Código inesperado", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this,"Código inesperado", Toast.LENGTH_LONG).show(); } } }
package com.dengzhili.bookStore.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; @Entity @Table(name="t_user") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="user_id") private Integer userId; @Column(name="user_name") @NotBlank(message="用户名不能为空") private String username; @Column(name="true_name") private String trueName; @Column(name="user_pwd") @NotBlank(message="密码不能为空") private String password; @Column(name="user_email") private String email; @Column(name="address") private String address; @Column(name="register_date") private Date registerDate; @Column(name="image") private String imgUrl; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTrueName() { return trueName; } public void setTrueName(String trueName) { this.trueName = trueName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getRegisterDate() { return registerDate; } public void setRegisterDate(Date registerDate) { this.registerDate = registerDate; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (userId == null) { if (other.userId != null) return false; } else if (!userId.equals(other.userId)) return false; return true; } @Override public String toString() { return "User [userId=" + userId + ", username=" + username + ", password=" + password + "]"; } }
package de.tuberlin.dima.bdapro.solutions.gameoflife; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javafx.scene.SubScene; import org.apache.flink.api.common.functions.*; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.operators.IterativeDataSet; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.tuple.Tuple4; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.Collector; public class GameOfLifeTaskImpl implements GameOfLifeTask { static int n, m; @Override public int solve(String inputFile, int argN, int argM, int numSteps) throws Exception { //****************************** //*Implement your solution here* //****************************** n = argN; m = argM; final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<String> text = env.readTextFile(inputFile); DataSet<Tuple2<Cell, Integer>> firstGen = text.flatMap(new LineSplitter()); IterativeDataSet<Tuple2<Cell, Integer>> iteration = firstGen.iterate(numSteps); DataSet<Tuple2<Cell, Integer>> aliveCells = iteration.reduceGroup(new CountNeighboursAlive()) .filter(new DeathFilter()); DataSet<Tuple2<Cell, Integer>> bornCells = iteration.reduceGroup(new BornCells()) .reduceGroup(new CountNeighboursBorn()) .filter(new BornFilter()); DataSet<Tuple2<Cell, Integer>> newGen = aliveCells.union(bornCells); DataSet<Tuple2<Cell, Integer>> result = iteration.closeWith(newGen); System.out.println(result.collect().size()); return result.collect().size(); } public static final class LineSplitter implements FlatMapFunction<String, Tuple2<Cell, Integer>> { @Override public void flatMap(String value, Collector<Tuple2<Cell, Integer>> out) { // normalize and split the line String[] tokens = value.split("\\s+"); // System.out.println("token0 " + tokens[0]); // System.out.println("token1 " + tokens[1]); out.collect(new Tuple2<Cell, Integer>( new Cell(Long.parseLong(tokens[0]),Long.parseLong(tokens[1])), 0)); } } public class CountNeighboursAlive implements GroupReduceFunction<Tuple2<Cell, Integer>, Tuple2<Cell, Integer>> { @Override public void reduce(Iterable<Tuple2<Cell, Integer>> values, Collector<Tuple2<Cell, Integer>> out) { int neighbours; List<Cell> aliveCells = new ArrayList<>(); for (Tuple2<Cell, Integer> k : values){ aliveCells.add(k.f0); } List<Integer> normal = new ArrayList<>(Arrays.asList(-1,-0,1)); List<Integer> circularLeftX= new ArrayList<>(Arrays.asList(n-1,0,1)); List<Integer> circularRightX = new ArrayList<>(Arrays.asList(-1,0,1-n)); List<Integer> circularLeftY= new ArrayList<>(Arrays.asList(m-1,0,1)); List<Integer> circularRightY = new ArrayList<>(Arrays.asList(-1,0,1-m)); List<Integer> firstFor; List<Integer> secondFor; for(Cell k : aliveCells){ if(k.getRow() == 0) firstFor = circularLeftX; else if (k.getRow() == n-1) firstFor = circularRightX; else firstFor = normal; if(k.getColumn() == 0) secondFor = circularLeftY; else if (k.getColumn() == m-1) secondFor = circularRightY; else secondFor = normal; neighbours = 0; for(int i : firstFor){ for(int j : secondFor){ if(i == 0 && j == 0){ continue; } if(aliveCells.contains(new Cell(k.getRow()+i, k.getColumn()+j))){ neighbours++; } } } out.collect(new Tuple2<Cell, Integer>(k, neighbours)); } } } public class CountNeighboursBorn implements GroupReduceFunction<Tuple2<Cell, Integer>, Tuple2<Cell, Integer>> { @Override public void reduce(Iterable<Tuple2<Cell, Integer>> values, Collector<Tuple2<Cell, Integer>> out) { int neighbours; List<Cell> aliveCells = new ArrayList<>(); List<Cell> bornCells = new ArrayList<>(); for (Tuple2<Cell, Integer> k : values){ if (k.f0.getState() == true){ aliveCells.add(k.f0); } else { bornCells.add(k.f0); } } List<Integer> normal = new ArrayList<>(Arrays.asList(-1,-0,1)); List<Integer> circularLeftX= new ArrayList<>(Arrays.asList(n-1,0,1)); List<Integer> circularRightX = new ArrayList<>(Arrays.asList(-1,0,1-n)); List<Integer> circularLeftY= new ArrayList<>(Arrays.asList(m-1,0,1)); List<Integer> circularRightY = new ArrayList<>(Arrays.asList(-1,0,1-m)); List<Integer> firstFor; List<Integer> secondFor; for(Cell k : bornCells){ if(k.getRow() == 0) firstFor = circularLeftX; else if (k.getRow() == n-1) firstFor = circularRightX; else firstFor = normal; if(k.getColumn() == 0) secondFor = circularLeftY; else if (k.getColumn() == m-1) secondFor = circularRightY; else secondFor = normal; neighbours = 0; for(int i : firstFor){ for(int j : secondFor){ if(i == 0 && j == 0){ continue; } if(aliveCells.contains(new Cell(k.getRow()+i, k.getColumn()+j, true))){ neighbours++; } } } out.collect(new Tuple2<Cell, Integer>(k, neighbours)); } } } public class BornCells implements GroupReduceFunction<Tuple2<Cell, Integer>, Tuple2<Cell, Integer>> { @Override public void reduce(Iterable<Tuple2<Cell, Integer>> values, Collector<Tuple2<Cell, Integer>> out) { List<Cell> coordinates = new ArrayList<>(); List<Integer> normal = new ArrayList<>(Arrays.asList(-1,0,1)); List<Integer> circularLeftX= new ArrayList<>(Arrays.asList(n-1,0,1)); List<Integer> circularRightX = new ArrayList<>(Arrays.asList(-1,0,1-n)); List<Integer> circularLeftY= new ArrayList<>(Arrays.asList(m-1,0,1)); List<Integer> circularRightY = new ArrayList<>(Arrays.asList(-1,0,1-m)); List<Integer> firstFor; List<Integer> secondFor; for(Tuple2<Cell, Integer> k : values){ if(k.f0.getRow() == 0) firstFor = circularLeftX; else if (k.f0.getRow() == n-1) firstFor = circularRightX; else firstFor = normal; if(k.f0.getColumn() == 0) secondFor = circularLeftY; else if (k.f0.getColumn() == m-1) secondFor = circularRightY; else secondFor = normal; for(int i : firstFor) for(int j : secondFor){ if(i == 0 && j == 0){ coordinates.remove(new Cell(k.f0.getRow()+ i,k.f0.getColumn() + j,false)); coordinates.add(new Cell(k.f0.getRow()+ i,k.f0.getColumn() + j,true)); continue; } Cell c = new Cell(k.f0.getRow() + i,k.f0.getColumn() + j,false); if(!coordinates.contains(c) && !coordinates.contains(new Cell(k.f0.getRow() + i,k.f0.getColumn() + j,true))){ coordinates.add(c); } } } for (Cell cell: coordinates){ out.collect(new Tuple2<Cell, Integer>(cell, 0)); } } } public class DeathFilter implements FilterFunction<Tuple2<Cell, Integer>> { @Override public boolean filter(Tuple2<Cell, Integer> cell) { if (cell.f1 > 3 || cell.f1 < 2){ return false; } return true; } } public class BornFilter implements FilterFunction<Tuple2<Cell, Integer>> { @Override public boolean filter(Tuple2<Cell, Integer> cell) { return cell.f1 == 3; } } }
package com.sun.xml.bind.v2.runtime.property; import java.text.MessageFormat; import java.util.ResourceBundle; /** * Message resources */ enum Messages { UNSUBSTITUTABLE_TYPE, // 3 args UNEXPECTED_JAVA_TYPE, // 2 args ; private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName()); public String toString() { return format(); } public String format( Object... args ) { return MessageFormat.format( rb.getString(name()), args ); } }
package practise; public class AbstractClass extends Person1 { void definePerson() { System.out.println("this is student"); } void showage() { System.out.println("age is 16"); } public static void main(String[] args) { AbstractClass ac=new AbstractClass(); ac.definePerson(); ac.setavalue(12, 13); System.out.println(ac.getavalueb()); System.out.println(ac.getavaluea()); ac.show(); } } abstract class Person { private int a,b; void show() { System.out.println("hello world"); } void setavalue(int a,int b) { this.a=a; this.b=b; } int getavaluea() { return a; } int getavalueb() { return b; } abstract void definePerson(); } abstract class Person1 extends Person { abstract void definePerson(); abstract void showage(); }
package models.modules.mobile; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import play.Play; import play.db.jpa.GenericModel; import utils.jpa.SQLResult; @Entity @Table(name = "xjl_stamp_set") public class XjlStampSet extends GenericModel { @Id @Column(name = "SET_ID") public Long setId; @Column(name = "FILE_ID") public Long fileId; @Column(name = "COPIES") public String copies; @Column(name = "SCOPE") public String scope; @Column(name = "PAPER_TYPE") public String paperType; @Column(name = "COLOUR") public String colour; @Column(name = "FACE") public String face; @Column(name = "STATUS") public String status; @Column(name = "CREATE_TIME") public Date createTime; @Column(name = "WX_OPEN_ID") public String wxOpenId; @Column(name = "TOTAL_PRICE") public String totalPrice; @Column(name = "out_trade_no") public String outTradeNo; @Column(name = "pay_state") public String payState; @Transient public String filePath; /** * 根据主键得到打印设置 * @param setId * @return */ public static XjlStampSet queryXjlStampSetById(Long setId){ String sql="select * from xjl_stamp_set where SET_ID = [l:setId]"; Map<String, String> condition = new HashMap<String, String>(); condition.put("setId", String.valueOf(setId)); SQLResult ret = ModelUtils.createSQLResult(condition, sql); List<XjlStampSet> data = ModelUtils.queryData(1, -1, ret,XjlStampSet.class); if(data.isEmpty()){ return null; }else { return data.get(0); } } public static Map query(Map<String, String> condition, int pageIndex, int pageSize){ String sql = "select * from xjl_stamp_set where WX_OPEN_ID = '"+condition.get("wxOpenId")+"'and status='0AA' order by CREATE_TIME desc "; SQLResult ret = ModelUtils.createSQLResult(condition, sql); List<XjlStampSet> data = ModelUtils.queryData(pageIndex, pageSize, ret,XjlStampSet.class); if(!data.isEmpty()){ Calendar ca = Calendar.getInstance(); int year = ca.get(Calendar.YEAR); String savePath = Play.roots.get(0).child("public").child("tmp").child("QRcode").getRealFile().getAbsolutePath() +File.separator+year+File.separator; for (XjlStampSet xjlStampSet : data) { xjlStampSet.filePath = "/sp/public/tmp/QRcode/"+year+File.separator+xjlStampSet.wxOpenId+File.separator+xjlStampSet.outTradeNo+File.separator+xjlStampSet.outTradeNo+".png"; } } return ModelUtils.createResultMap(ret, data); } public static int modifyPayStatus(Long setId){ String sql ="update xjl_stamp_set set pay_state='1' where SET_ID = '"+setId+"'"; Map<String, String> condition = new HashMap<String, String>(); return ModelUtils.executeDelete(condition, sql); } }
package dbAssignment.opti_home_shop.data.repository; import dbAssignment.opti_home_shop.data.model.Customeraccount; public class CustomeraccountRepository extends GenericRep<Customeraccount, Integer>{ public CustomeraccountRepository() { super(Customeraccount.class); } }
package com.intel.realsense.librealsense; public interface ProcessingBlockInterface extends OptionsInterface{ void invoke(Frame original); void invoke(FrameSet original); }
/** * Schema generator. * * This package hosts the code that generates schemas from * {@link TypeInfoSet} (without the user interface.) */ package com.sun.xml.bind.v2.schemagen; import com.sun.xml.bind.v2.model.core.TypeInfoSet;
package video_storm.input; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; public class KeyInput { public boolean[] keys = new boolean[65536]; public KeyInput() throws LWJGLException { Keyboard.create(); } public void get() { while(Keyboard.next()) { if (Keyboard.getEventKeyState()) { keys[Keyboard.getEventKey()] = true; System.out.println( "*** " + Keyboard.getEventKey()); } else { keys[Keyboard.getEventKey()] = false; } } } public void close() { Keyboard.destroy(); } public boolean consume( int keySpace ) { boolean ans = keys[keySpace]; keys[keySpace] = false; return ans; } }
package day4; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class WindowHandlesTest extends BaseClass{ /* @Test public void testName(){ String url="http://the-internet.herokuapp.com/windows"; String expectedText="New Window"; String originalHandle=driver.getWindowHandle(); //navigateToUrl(url); driver.get("http://the-internet.herokuapp.com/windows"); clickOnTheLink(); switchOverToLatestWindow(originalHandle); assertThatTextIsPresented(expectedText); printOutAllTheTitles(); closeLastOpenWindow(); } */ }
package com.GestiondesClub.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Type; @Entity @Table(name="TypeClub") @NamedQuery(name="TypeClub.findAll", query="SELECT tc FROM TypeClub tc") public class TypeClub { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name="type", unique = true) private String type; public TypeClub() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package com.cs.promotion; import com.cs.avatar.Level; import com.cs.bonus.Bonus; import com.cs.user.User; import com.google.common.base.Objects; import org.hibernate.annotations.Type; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Set; import static javax.persistence.GenerationType.IDENTITY; import static javax.persistence.TemporalType.TIMESTAMP; /** * @author Omid Alaepour */ @Entity @Table(name = "promotions") public class Promotion implements Serializable { private static final long serialVersionUID = 1L; public static final Long CUSTOMER_SUPPORT_PROMOTION = 1L; public static final Long LEVEL_PROMOTION = 2L; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", nullable = false, unique = true) @Nonnull private Long id; @Column(name = "valid_from", nullable = false) @Temporal(TIMESTAMP) @Nonnull @NotNull(message = "promotion.validFrom.notNull") private Date validFrom; @Column(name = "valid_to", nullable = false) @Temporal(TIMESTAMP) @Nonnull @NotNull(message = "promotion.validFrom.notNull") private Date validTo; @Column(name = "name", nullable = false) @Nonnull @NotNull(message = "promotion.name.notNull") private String name; @Column(name = "promotion_type", nullable = false) @Type(type = "com.cs.promotion.PromotionTriggerType") @Nonnull @NotNull(message = "promotion.promotionTriggers.notNull") private Set<PromotionTrigger> promotionTriggers; @ManyToOne @JoinColumn(name = "created_by", nullable = false) @Nonnull @NotNull(message = "promotion.createdBy.notNull") private User createdBy; @Column(name = "created_date", nullable = false) @Temporal(TIMESTAMP) @Nonnull @NotNull(message = "promotion.createdDate.notNull") private Date createdDate; @ManyToOne @JoinColumn(name = "modified_by") @Nullable private User modifiedBy; @Column(name = "modified_date") @Temporal(TIMESTAMP) @Nullable private Date modifiedDate; @OneToMany(mappedBy = "promotion") @Nullable private List<Bonus> bonusList; @OneToMany(mappedBy = "pk.promotion") @Nullable private List<PlayerPromotion> playerPromotions; @ManyToOne @JoinColumn(name = "required_level", nullable = false) @Nonnull @NotNull(message = "promotion.level.notNull") private Level level; @Column(name = "auto_grant_bonuses", nullable = false) @Type(type = "org.hibernate.type.NumericBooleanType") @Nonnull private Boolean autoGrantBonuses; @Nonnull public Long getId() { return id; } public void setId(@Nonnull final Long id) { this.id = id; } @Nonnull public Date getValidFrom() { return validFrom; } public void setValidFrom(@Nonnull final Date validFrom) { this.validFrom = validFrom; } @Nonnull public Date getValidTo() { return validTo; } public void setValidTo(@Nonnull final Date validTo) { this.validTo = validTo; } @Nonnull public String getName() { return name; } public void setName(@Nonnull final String name) { this.name = name; } @Nonnull public User getCreatedBy() { return createdBy; } public void setCreatedBy(@Nonnull final User createdBy) { this.createdBy = createdBy; } @Nonnull public Date getCreatedDate() { return createdDate; } public void setCreatedDate(@Nonnull final Date createdDate) { this.createdDate = createdDate; } @Nullable public User getModifiedBy() { return modifiedBy; } public void setModifiedBy(@Nullable final User modifiedBy) { this.modifiedBy = modifiedBy; } @Nullable public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(@Nullable final Date modifiedDate) { this.modifiedDate = modifiedDate; } @Nullable public List<PlayerPromotion> getPlayerPromotions() { return playerPromotions; } public void setPlayerPromotions(@Nullable final List<PlayerPromotion> playerPromotions) { this.playerPromotions = playerPromotions; } @Nullable public List<Bonus> getBonusList() { return bonusList; } public void setBonusList(@Nullable final List<Bonus> bonusList) { this.bonusList = bonusList; } @Nonnull public Set<PromotionTrigger> getPromotionTriggers() { return promotionTriggers; } public void setPromotionTriggers(@Nonnull final Set<PromotionTrigger> promotionTriggers) { this.promotionTriggers = promotionTriggers; } @Nonnull public Level getLevel() { return level; } public void setLevel(@Nonnull final Level level) { this.level = level; } @Nonnull public Boolean isAutoGrantBonuses() { return autoGrantBonuses; } public void setAutoGrantBonuses(@Nonnull final Boolean autoGrantBonuses) { this.autoGrantBonuses = autoGrantBonuses; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Promotion that = (Promotion) o; return Objects.equal(id, that.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return Objects.toStringHelper(this) .addValue(id) .addValue(validFrom) .addValue(validTo) .addValue(name) .addValue(promotionTriggers) .addValue(createdBy) .addValue(createdDate) .addValue(modifiedBy) .addValue(modifiedDate) .addValue(level) .addValue(autoGrantBonuses) .toString(); } }
package com.crossover.trial.weather.model; import java.io.Serializable; import java.util.Optional; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Encapsulates sensor information for a particular location */ public class AtmosphericInformation implements Serializable { private static final long serialVersionUID = 4884101137188765237L; /** temperature in degrees celsius */ private DataPoint temperature; /** wind speed in km/h */ private DataPoint wind; /** humidity in percent */ private DataPoint humidity; /** precipitation in cm */ private DataPoint precipitation; /** pressure in mmHg */ private DataPoint pressure; /** cloud cover percent from 0 - 100 (integer) */ private DataPoint cloudCover; /** the last time this data was updated, in milliseconds since UTC epoch */ private long lastUpdateTime; private AtmosphericInformation(final Builder builder) { builder.temperature.ifPresent(value -> setTemperature(value)); builder.wind.ifPresent(value -> setWind(value)); builder.humidity.ifPresent(value -> setHumidity(value)); builder.precipitation.ifPresent(value -> setPrecipitation(value)); builder.pressure.ifPresent(value -> setPressure(value)); builder.cloudCover.ifPresent(value -> setCloudCover(value)); } public DataPoint getTemperature() { return temperature; } public void setTemperature(final DataPoint temperature) { this.temperature = temperature; } public DataPoint getWind() { return wind; } public void setWind(final DataPoint wind) { this.wind = wind; } public DataPoint getHumidity() { return humidity; } public void setHumidity(final DataPoint humidity) { this.humidity = humidity; } public DataPoint getPrecipitation() { return precipitation; } public void setPrecipitation(final DataPoint precipitation) { this.precipitation = precipitation; } public DataPoint getPressure() { return pressure; } public void setPressure(final DataPoint pressure) { this.pressure = pressure; } public DataPoint getCloudCover() { return cloudCover; } public void setCloudCover(final DataPoint cloudCover) { this.cloudCover = cloudCover; } public long getLastUpdateTime() { return this.lastUpdateTime; } public void setLastUpdateTime(final long lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.NO_CLASS_NAME_STYLE); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, false); } @Override public boolean equals(final Object that) { return EqualsBuilder.reflectionEquals(this, that, false); } public static class Builder { private Optional<DataPoint> temperature = Optional.empty(); private Optional<DataPoint> wind = Optional.empty(); private Optional<DataPoint> humidity = Optional.empty(); private Optional<DataPoint> precipitation = Optional.empty(); private Optional<DataPoint> pressure = Optional.empty(); private Optional<DataPoint> cloudCover = Optional.empty(); public Builder withTemperature(final DataPoint temperature) { if (temperature != null) { this.temperature = Optional.of(temperature); } return this; } public Builder withWind(final DataPoint wind) { if (wind != null) { this.wind = Optional.of(wind); } return this; } public Builder withHumidity(final DataPoint humidity) { if (humidity != null) { this.humidity = Optional.of(humidity); } return this; } public Builder withPrecipitation(final DataPoint precipitation) { if (precipitation != null) { this.precipitation = Optional.of(precipitation); } return this; } public Builder withPressure(final DataPoint pressure) { if (pressure != null) { this.pressure = Optional.of(pressure); } return this; } public Builder withCloudCover(final DataPoint cloudCover) { if (cloudCover != null) { this.cloudCover = Optional.of(cloudCover); } return this; } public AtmosphericInformation build() { return new AtmosphericInformation(this); } } }
package rso.dfs.model.dao.psql; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rso.dfs.model.File; import rso.dfs.model.Server; import rso.dfs.model.ServerRole; import rso.dfs.model.dao.DFSModelDAO; import rso.dfs.model.dao.DFSRepository; /** * @author Adam Papros <adam.papros@gmail.com> * */ public class DFSRepositoryImpl implements DFSRepository { final static Logger log = LoggerFactory.getLogger(DFSRepository.class); private DFSModelDAO modelDAO; private DFSDataSource dataSource; public DFSRepositoryImpl() { dataSource = new DFSDataSource(); modelDAO = new DFSModelDAOImpl(dataSource); } @Override public Server getMasterServer() { // fetch master List<Server> list = modelDAO.fetchServersByRole(ServerRole.MASTER); if (list.size() > 1) { // raise fatal error System.exit(-123); } else if (list.isEmpty()) { return null; } return list.get(0); } @Override public void saveMaster(Server server) { log.debug("Saving master:" + server.toString()); modelDAO.saveServer(server); } @Override public File getFileByFileName(String fileName) { log.debug("Fetching file: fileName=" + fileName); return modelDAO.fetchFileByFileName(fileName); } @Override public Server getSlaveByFile(File file) { log.debug("Fetching servers with file: " + file.getName()); List<Server> servers = modelDAO.fetchServersByFileId(file.getId()); // TODO :choose server ! if (servers == null || servers.isEmpty()) { // raise fatal error } return servers.get(0); } }
package com.how2java.tmall.comparator; public class ProductDateComparator { }
package Utility; public class Constant { public static final String URL = "http://www.store.demoqa.com"; public static final String Username = "testuser_1"; public static final String Password = "Test@123"; public static final String Path_TestData = "C://Users//user//workspace//POMDemo//src//testData//"; public static String File_TestData = "TestData.xlsx"; public static final String path_TestDat1="C://Users//user//workspace//POMDemo//"; public static final String File_TestDat1="SamsungLogIn-Valid TestData.xlsx"; }
package com.sims.bo.impl; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sims.bo.EmployeeBo; import com.sims.dao.EmployeeDao; import com.sims.model.Employee; @Service public class EmployeeBoImpl implements EmployeeBo { private final static Logger logger = Logger.getLogger(EmployeeBo.class); @Autowired EmployeeDao employeeDao; public void setEmployeeDao(EmployeeDao employeeDao){ this.employeeDao = employeeDao; } @Override @Transactional public boolean save(Employee entity) { entity.setCreatedOn(new java.sql.Timestamp(System.currentTimeMillis())); entity.setVersion(1); entity.setActive(true); logger.info("Save: " + entity.toString()); return employeeDao.save(entity); } @Override @Transactional public boolean update(Employee entity) { Employee model = employeeDao.findById(entity.getId()); //update the fields of the model model.setEmpType(entity.getEmpType()); model.setLastName(entity.getLastName()); model.setFirstName(entity.getFirstName()); model.setMiddleName(entity.getMiddleName()); model.setGender(entity.getGender()); model.setContactNo(entity.getContactNo()); model.setAddress(entity.getAddress()); model.setModifiedBy(entity.getModifiedBy()); model.setModifiedOn(new java.sql.Timestamp(System.currentTimeMillis())); model.setVersion(model.getVersion() + 1); logger.info("Update: " + model.toString()); return employeeDao.update(model); } @Override @Transactional public boolean delete(Employee entity) { entity.setActive(false); entity.setModifiedOn(new java.sql.Timestamp(System.currentTimeMillis())); entity.setVersion(entity.getVersion() + 1); logger.info("Delete: id = " + entity.getId()); return employeeDao.delete(entity); } @Override @Transactional public Map<Object, Object> findByLastName(Map<Object,Object> mapCriteria) { return employeeDao.findByLastName(mapCriteria); } @Override @Transactional public Employee findById(int criteria) { return employeeDao.findById(criteria); } @Override public List<Employee> getAllWithNoUserAccount() { return employeeDao.getAllWithNoUserAccount(); } }
package tech.liujin.drawable.state; import tech.liujin.drawable.PaintDrawable; import tech.liujin.drawable.StateConsumer; /** * @author wuxio 2018-05-25:7:11 */ public abstract class StateDrawable extends PaintDrawable implements StateConsumer { /** * 当前状态 */ protected int mState; public void setState ( int state ) { if( state != mState ) { mState = state; onStateChange( state ); } } public int getCurrentState ( ) { return mState; } /** * 当状态改变时,准备新状态下数据,之后重新绘制{@link #invalidateSelf()} * * @param state : 状态 */ @Override public abstract void onStateChange ( int state ); }
package kr.or.ddit.career.controller; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import kr.or.ddit.career.service.ICareerService; import kr.or.ddit.profile_file.service.IProfileFileService; import kr.or.ddit.project.service.IProjectService; import kr.or.ddit.successboard.service.ISuccessBoardService; import kr.or.ddit.vo.JoinVO; import kr.or.ddit.vo.ProfileFileVO; import kr.or.ddit.vo.ProjectVO; import kr.or.ddit.vo.SuccessBoardCommentVO; import kr.or.ddit.vo.SuccessBoardVO; import kr.or.ddit.vo.newsboardVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user/career/") public class CareerController { @Autowired private ICareerService careerService; @RequestMapping("selectCareer") @ResponseBody public List<Map<String, String>> selectCareer(String mem_id) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); return careerService.selectCareer(params); } @RequestMapping("insertCareer") @ResponseBody public Map<String, String> insertCareer(String mypage_no, String career_companyname, String career_department, String career_class, String career_startdate, String career_enddate) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("mypage_no", mypage_no); params.put("career_companyname", career_companyname); params.put("career_department", career_department); params.put("career_class", career_class); SimpleDateFormat wildFormat = new SimpleDateFormat("MM/dd/YYYY"); SimpleDateFormat wantFormat = new SimpleDateFormat("YYYY-MM-dd"); Date tempDate = null; tempDate = wildFormat.parse(career_startdate); career_startdate = wantFormat.format(tempDate); tempDate = wildFormat.parse(career_enddate); career_enddate = wantFormat.format(tempDate); params.put("career_startdate", career_startdate); params.put("career_enddate", career_enddate); int chk = careerService.insertCareer(params); Map<String, String> resultMap = new HashMap<String, String>(); if (chk > 0) { resultMap.put("result", "Y"); } else { resultMap.put("result", "N"); } return resultMap; } @RequestMapping("deleteCareer") @ResponseBody public Map<String, String> deleteCareer(String career_seq) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("career_seq", career_seq); int chk = careerService.deleteCareer(params); Map<String, String> resultMap = new HashMap<String, String>(); if (chk > 0) { resultMap.put("result", "Y"); } else { resultMap.put("result", "N"); } return resultMap; } }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.stdext.identity; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import pl.edu.icm.unity.MessageSource; import pl.edu.icm.unity.exceptions.IllegalIdentityValueException; import pl.edu.icm.unity.exceptions.IllegalTypeException; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.server.api.internal.LoginSession; import pl.edu.icm.unity.server.authn.InvocationContext; import pl.edu.icm.unity.stdext.identity.SessionIdentityModel.PerSessionEntry; import pl.edu.icm.unity.stdext.utils.Escaper; import pl.edu.icm.unity.types.basic.Attribute; import pl.edu.icm.unity.types.basic.AttributeType; import pl.edu.icm.unity.types.basic.IdentityParam; import pl.edu.icm.unity.types.basic.IdentityRepresentation; /** * Identity type which creates a different identifier for each target, which is valid only for a time span of a single * login session. * @author K. Benedyczak */ @Component public class TransientIdentity extends AbstractIdentityTypeProvider { public static final String ID = "transient"; private static final List<Attribute<?>> empty = Collections.unmodifiableList(new ArrayList<Attribute<?>>(0)); private ObjectMapper mapper; @Autowired public TransientIdentity(ObjectMapper mapper) { this.mapper = mapper; } /** * {@inheritDoc} */ @Override public String getId() { return ID; } /** * {@inheritDoc} */ @Override public String getDefaultDescription() { return "Transient targeted id"; } @Override public boolean isRemovable() { return false; } /** * {@inheritDoc} */ @Override public Set<AttributeType> getAttributesSupportedForExtraction() { return Collections.emptySet(); } /** * {@inheritDoc} */ @Override public void validate(String value) throws IllegalIdentityValueException { } /** * {@inheritDoc} */ @Override public String getComparableValue(String from, String realm, String target) { if (realm == null || target == null) return null; LoginSession ls; try { InvocationContext ctx = InvocationContext.getCurrent(); ls = ctx.getLoginSession(); if (ls == null) return null; } catch (InternalException e) { return null; } return getComparableValueInternal(from, realm, target, ls); } private String getComparableValueInternal(String from, String realm, String target, LoginSession ls) { return Escaper.encode(realm, target, ls.getId(), from); } /** * {@inheritDoc} */ @Override public List<Attribute<?>> extractAttributes(String from, Map<String, String> toExtract) { return empty; } /** * {@inheritDoc} */ @Override public String toPrettyStringNoPrefix(IdentityParam from) { return from.getValue(); } @Override public boolean isDynamic() { return true; } @Override public String toExternalForm(String realm, String target, String inDbValue) throws IllegalIdentityValueException { if (realm == null || target == null || inDbValue == null) throw new IllegalIdentityValueException("No enough arguments"); LoginSession ls; try { InvocationContext ctx = InvocationContext.getCurrent(); ls = ctx.getLoginSession(); if (ls == null) throw new IllegalIdentityValueException("No login session"); } catch (Exception e) { throw new IllegalIdentityValueException("Error getting invocation context", e); } return toExternalFormNoContext(inDbValue); } @Override public IdentityRepresentation createNewIdentity(String realm, String target, String value) throws IllegalTypeException { if (realm == null || target == null) throw new IllegalTypeException("Identity can be created only when target is defined"); if (value == null) value = UUID.randomUUID().toString(); try { InvocationContext ctx = InvocationContext.getCurrent(); LoginSession ls = ctx.getLoginSession(); if (ls == null) return null; SessionIdentityModel model = new SessionIdentityModel(mapper, ls, value); String contents = model.serialize(); String comparableValue = getComparableValueInternal(value, realm, target, ls); return new IdentityRepresentation(comparableValue, contents); } catch (Exception e) { throw new IllegalTypeException("Identity can be created only when login session is defined", e); } } @Override public boolean isExpired(IdentityRepresentation representation) { SessionIdentityModel model = new SessionIdentityModel(mapper, representation.getContents()); PerSessionEntry info = model.getEntry(); return info.isExpired(); } @Override public boolean isTargeted() { return true; } @Override public String toExternalFormNoContext(String inDbValue) { SessionIdentityModel model = new SessionIdentityModel(mapper, inDbValue); return model.getEntry().getValue(); } @Override public String toHumanFriendlyString(MessageSource msg, IdentityParam from) { return msg.getMessage("TransientIdentity.random"); } @Override public String getHumanFriendlyDescription(MessageSource msg) { return msg.getMessage("TransientIdentity.description"); } @Override public boolean isVerifiable() { return false; } @Override public String getHumanFriendlyName(MessageSource msg) { return msg.getMessage("TransientIdentity.name"); } }
//difficulty is considering careful of all the possible conditions //thougu solve the problem, I spent an hour to debug, which is terrible //the following version is the same efficiency, but easier to understand //by using a low and high pointer to record each head and rear of String, nice public class Solution { public static List<String> summaryRanges(int[] nums) { if (nums == null || nums.length == 0) return new ArrayList<String>(); List<String> result = new ArrayList<String>(); int len = nums.length, low = 0, high = 0; while (high < len) { if (high + 1 < len && nums[high] + 1 == nums[high + 1]) high++; else { if (low == high) { result.add(String.valueOf(nums[low])); } else { result.add(nums[low] + "->" + nums[high]); } high++; low = high; } } return result; } } public class Solution { public List<String> summaryRanges(int[] nums) { List<String> lst = new ArrayList<>(); if (nums.length == 0 || nums == null) return lst; if (nums.length == 1) { lst.add("" + nums[0]); return lst; } int count = 1; StringBuilder sb = new StringBuilder(); sb.append(nums[0]); for (int i = 1; i < nums.length; i++) { if (nums[i - 1] != nums[i] - 1) { if (count > 1) sb.append("->" + nums[i - 1]); lst.add(sb.toString()); sb.delete(0,sb.length()); sb.append(nums[i]); count = 0; } if (i == nums.length - 1) { if (nums[i - 1] == nums[i] - 1) sb.append("->" + nums[i]); lst.add(sb.toString()); } count++; } return lst; } }
package com.lms.model.database; public interface SQL { String DB_SOURCE = "java:comp/env/jdbc/thesis"; String INSERT_NEW_STUDENT_INFO = "INSERT into students(last_name, first_name, middle_initial, student_id, year_level, course_id)" +"VALUES (?,?,?,?,?,?)"; String INSERT_NEW_STUDENT_ACCOUNT = "INSERT into user_accounts(student_id,password, salt) VALUES(?,?,?)"; String INSERT_ADDRESS = "INSERT into address(street, barangay, city, province,student_id) VALUE(?,?,?,?,?)"; String SELECT_USER = "select * from user_accounts where account_id=(select account_id from students where student_id= :thisID)"; }
/* Chtobi perevesti chislo iz 10-i v 2-yu sistemu, nado chislo delit do teh por, poka ostatok ne stanet menshe 2 a zatem vse ostatki zapisat v obratnom poryadke */ package Methods; public class Example_Perevod_iz10v2sistemu { static void converter(int num) { int temp; temp = num % 2; if (num >= 2){ converter(num / 2); } System.out.print(temp); } public static void main(String[] args) { int n = 650; converter(n); } } //1010001010
package com.hotelbooking.equalexperts.steps; import com.hotelbooking.equalexperts.model.HotelBooking; import net.thucydides.core.annotations.Steps; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import java.util.*; import com.hotelbooking.equalexperts.steps.serenity.EndUserSteps; public class HotelBookingSteps { @Steps EndUserSteps user; @Given("I am on the hotel booking page") public void the_user_on_the_hotel_booking_page() { user.is_the_home_page(); } @When("^I enter the following details$") public void the_user_enters_the_following_details(List<HotelBooking> data) throws Throwable { HotelBooking booking = data.get(0); user.enters_booking_details(booking); } @When("^would like to make the hotel booking$") public void the_user_would_like_to_make_the_booking() throws Throwable { user.make_the_booking(); } @Then("^the booking should be added to the list$") public void the_booking_should_be_added_to_the_list() throws Throwable { user.booking_should_be_in_list(); } @When("^I delete that booking$") public void the_user_delete_that_booking() throws Throwable { user.delete_that_booking(); } @Then("^the booking should be deleted from the list$") public void the_booking_should_be_deleted_from_the_list() throws Throwable { user.booking_should_be_deleted_from_list(); } }
package gui; import javax.swing.JPanel; import logik.AbstractChat; import logik.ContactChat; public class DirectMessagePanel extends JPanel { private ContactChat chat; MessagePanel messagepanel; public DirectMessagePanel(AbstractChat chat, String user) { this.chat=(ContactChat)chat; this.messagepanel=new MessagePanel(chat.getHistory(),chat,user); this.add(messagepanel); } }
package apiAlquilerVideoJuegos.servicios; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import apiAlquilerVideoJuegos.basedatos.TituloBD; import apiAlquilerVideoJuegos.modelos.Titulo; @Service @Transactional public class TituloServicioImp implements TituloServicio { // Implementing Constructor based DI private TituloBD tituloBD; public TituloServicioImp() { } @Autowired public TituloServicioImp(TituloBD tituloBD) { super(); this.tituloBD = tituloBD; } @Override public List<Titulo> obtener() { List<Titulo> lista = new ArrayList<Titulo>(); tituloBD.findAll().forEach(e -> lista.add(e)); return lista; } @Override public Titulo obtenerTitulo(Long id) { Titulo Titulo = tituloBD.findById(id).get(); return Titulo; } @Override public boolean guardar(Titulo Titulo) { try { tituloBD.save(Titulo); return true; }catch(Exception ex) { return false; } } @Override public boolean eliminar(Long id) { try { tituloBD.deleteById(id); return true; }catch(Exception ex) { return false; } } }
package no.nav.vedtak.sikkerhet.pdp.xacml; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; public record XacmlRequest( @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) @JsonProperty("Request") Map<Category, List<Attributes>> request) { public static record Attributes( @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) @JsonProperty("Attribute") List<AttributeAssignment> attribute) { } public static record AttributeAssignment(@JsonProperty("AttributeId") String attributeId, @JsonProperty("Value") Object value) { } }
/* * 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.simp.broker; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.messaging.Message; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.support.GenericMessage; import org.springframework.messaging.support.MessageBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Unit tests for {@link org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler}. * * @author Rossen Stoyanchev */ public class BrokerMessageHandlerTests { private final TestBrokerMessageHandler handler = new TestBrokerMessageHandler(); @Test public void startShouldUpdateIsRunning() { assertThat(this.handler.isRunning()).isFalse(); this.handler.start(); assertThat(this.handler.isRunning()).isTrue(); } @Test public void stopShouldUpdateIsRunning() { this.handler.start(); assertThat(this.handler.isRunning()).isTrue(); this.handler.stop(); assertThat(this.handler.isRunning()).isFalse(); } @Test public void startAndStopShouldNotPublishBrokerAvailabilityEvents() { this.handler.start(); this.handler.stop(); assertThat(this.handler.availabilityEvents).isEqualTo(Collections.emptyList()); } @Test public void handleMessageWhenBrokerNotRunning() { this.handler.handleMessage(new GenericMessage<Object>("payload")); assertThat(this.handler.messages).isEqualTo(Collections.emptyList()); } @Test public void publishBrokerAvailableEvent() { assertThat(this.handler.isBrokerAvailable()).isFalse(); assertThat(this.handler.availabilityEvents).isEqualTo(Collections.emptyList()); this.handler.publishBrokerAvailableEvent(); assertThat(this.handler.isBrokerAvailable()).isTrue(); assertThat(this.handler.availabilityEvents).isEqualTo(Collections.singletonList(true)); } @Test public void publishBrokerAvailableEventWhenAlreadyAvailable() { this.handler.publishBrokerAvailableEvent(); this.handler.publishBrokerAvailableEvent(); assertThat(this.handler.availabilityEvents).isEqualTo(Collections.singletonList(true)); } @Test public void publishBrokerUnavailableEvent() { this.handler.publishBrokerAvailableEvent(); assertThat(this.handler.isBrokerAvailable()).isTrue(); this.handler.publishBrokerUnavailableEvent(); assertThat(this.handler.isBrokerAvailable()).isFalse(); assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true, false)); } @Test public void publishBrokerUnavailableEventWhenAlreadyUnavailable() { this.handler.publishBrokerAvailableEvent(); this.handler.publishBrokerUnavailableEvent(); this.handler.publishBrokerUnavailableEvent(); assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true, false)); } @Test public void checkDestination() { TestBrokerMessageHandler theHandler = new TestBrokerMessageHandler("/topic"); theHandler.start(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); accessor.setLeaveMutable(true); accessor.setDestination("/topic/foo"); theHandler.handleMessage(MessageBuilder.createMessage("p", accessor.toMessageHeaders())); accessor.setDestination("/app/foo"); theHandler.handleMessage(MessageBuilder.createMessage("p", accessor.toMessageHeaders())); accessor.setDestination(null); theHandler.handleMessage(MessageBuilder.createMessage("p", accessor.toMessageHeaders())); List<Message<?>> list = theHandler.messages; assertThat(list).hasSize(2); assertThat(list.get(0).getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER)).isEqualTo("/topic/foo"); assertThat(list.get(1).getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER)).isNull(); } @Test public void checkDestinationWithoutConfiguredPrefixes() { this.handler.setUserDestinationPredicate(destination -> destination.startsWith("/user/")); this.handler.start(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); accessor.setLeaveMutable(true); accessor.setDestination("/user/1/foo"); this.handler.handleMessage(MessageBuilder.createMessage("p", accessor.toMessageHeaders())); accessor.setDestination("/foo"); this.handler.handleMessage(MessageBuilder.createMessage("p", accessor.toMessageHeaders())); List<Message<?>> list = this.handler.messages; assertThat(list).hasSize(1); assertThat(list.get(0).getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER)).isEqualTo("/foo"); } private static class TestBrokerMessageHandler extends AbstractBrokerMessageHandler implements ApplicationEventPublisher { private final List<Message<?>> messages = new ArrayList<>(); private final List<Boolean> availabilityEvents = new ArrayList<>(); TestBrokerMessageHandler(String... destinationPrefixes) { super(mock(), mock(), mock(), Arrays.asList(destinationPrefixes)); setApplicationEventPublisher(this); } @Override protected void handleMessageInternal(Message<?> message) { String destination = (String) message.getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER); if (checkDestinationPrefix(destination)) { this.messages.add(message); } } @Override public void publishEvent(ApplicationEvent event) { publishEvent((Object) event); } @Override public void publishEvent(Object event) { if (event instanceof BrokerAvailabilityEvent) { this.availabilityEvents.add(((BrokerAvailabilityEvent) event).isBrokerAvailable()); } } } }
package com.lyl.mybatis; import com.lyl.core.dao.domain.Test; import com.lyl.core.dao.domain.TestExample; import com.lyl.core.dao.mapper.TestMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Created by lyl * Date 2018/12/7 * 只使用mybatis调用数据库 */ public class OnlyMybatisExecute { public static void main(String[] args) { String resource = "only_mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); TestMapper testMapper = sqlSession.getMapper(TestMapper.class); TestExample testExample = new TestExample(); TestExample.Criteria criteria = testExample.createCriteria(); criteria.andIdEqualTo(1); List<Test> list = testMapper.selectByExample(testExample); System.out.println(list); sqlSession.close(); } }
package slimeknights.tconstruct.gadgets.entity; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.init.SoundEvents; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.Explosion; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.List; public class ExplosionEFLN extends Explosion { protected ImmutableSet<BlockPos> affectedBlockPositions; @SideOnly(Side.CLIENT) public ExplosionEFLN(World worldIn, Entity entityIn, double x, double y, double z, float size, List<BlockPos> affectedPositions) { super(worldIn, entityIn, x, y, z, size, affectedPositions); } @SideOnly(Side.CLIENT) public ExplosionEFLN(World worldIn, Entity entityIn, double x, double y, double z, float size, boolean flaming, boolean smoking, List<BlockPos> affectedPositions) { super(worldIn, entityIn, x, y, z, size, flaming, smoking, affectedPositions); } public ExplosionEFLN(World worldIn, Entity entityIn, double x, double y, double z, float size, boolean flaming, boolean smoking) { super(worldIn, entityIn, x, y, z, size, flaming, smoking); } @Override public void doExplosionA() { ImmutableSet.Builder<BlockPos> builder = ImmutableSet.builder(); // we do a sphere of a certain radius, and check if the blockpos is inside the radius float r = size * size; int i = (int) r + 1; for(int j = -i; j < i; ++j) { for(int k = -i; k < i; ++k) { for(int l = -i; l < i; ++l) { int d = j * j + k * k + l * l; // inside the sphere? if(d <= r) { BlockPos blockpos = new BlockPos(j, k, l).add(x, y, z); // no air blocks if(world.isAirBlock(blockpos)) { continue; } // explosion "strength" at the current position float f = this.size * (1f - d / (r)); IBlockState iblockstate = this.world.getBlockState(blockpos); float f2 = this.exploder != null ? this.exploder.getExplosionResistance(this, this.world, blockpos, iblockstate) : iblockstate.getBlock().getExplosionResistance(world, blockpos, null, this); f -= (f2 + 0.3F) * 0.3F; if(f > 0.0F && (this.exploder == null || this.exploder.canExplosionDestroyBlock(this, this.world, blockpos, iblockstate, f))) { builder.add(blockpos); } } } } } this.affectedBlockPositions = builder.build(); } @Override public void doExplosionB(boolean spawnParticles) { this.world.playSound(null, this.x, this.y, this.z, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, (1.0F + (this.world.rand.nextFloat() - this.world.rand.nextFloat()) * 0.2F) * 0.7F); this.world.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); for(BlockPos blockpos : this.affectedBlockPositions) { IBlockState iblockstate = this.world.getBlockState(blockpos); Block block = iblockstate.getBlock(); /* if (spawnParticles) { double d0 = (double)((float)blockpos.getX() + this.world.rand.nextFloat()); double d1 = (double)((float)blockpos.getY() + this.world.rand.nextFloat()); double d2 = (double)((float)blockpos.getZ() + this.world.rand.nextFloat()); double d3 = d0 - this.explosionX; double d4 = d1 - this.explosionY; double d5 = d2 - this.explosionZ; double d6 = (double) MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5); d3 = d3 / d6; d4 = d4 / d6; d5 = d5 / d6; double d7 = 0.5D / (d6 / (double)this.explosionSize + 0.1D); d7 = d7 * (double)(this.world.rand.nextFloat() * this.world.rand.nextFloat() + 0.3F); d3 = d3 * d7; d4 = d4 * d7; d5 = d5 * d7; this.world.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, (d0 + this.explosionX) / 2.0D, (d1 + this.explosionY) / 2.0D, (d2 + this.explosionZ) / 2.0D, d3, d4, d5, new int[0]); this.world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0, d1, d2, d3, d4, d5, new int[0]); }*/ if(iblockstate.getMaterial() != Material.AIR) { if(block.canDropFromExplosion(this)) { block.dropBlockAsItemWithChance(this.world, blockpos, this.world.getBlockState(blockpos), 1.0F, 0); } block.onBlockExploded(this.world, blockpos, this); } } } }
package com.sirma.itt.javacourse.exceptions.task3.objectList; import com.sirma.itt.javacourse.InputUtils; /** * Class that represents a list of items * * @author simeon */ public class ObjectList { private int capacity = 10; private int index = 0; private Object[] array; /** * @param capacity * the capacity of the array. */ public ObjectList(int capacity) { this.capacity = capacity; array = new Object[capacity]; } /** * Basic constructor for object list. */ public ObjectList() { super(); array = new Object[capacity]; } /** * Adds an element at the last available index. * * @param obj * the object to be added. * @return true if the insert was successful. */ public boolean addElement(Object obj) { if (index > capacity - 1) { throw new OverFlodException(); } else { array[index] = obj; index++; return true; } } /** * Removes the last element of the array; */ public boolean removeElement() { index--; if (index < 0) { // Reset index value to Zero. index = 0; throw new NegativeIndexException(); } array[index] = null; return true; } /** * Removes an object at a specific index. * * @param index * the index of the object to be removed in the array. * @return true if the remove was successful. */ public boolean removeElementAtIndex(int index) { if (index < 0 || index > this.index) { throw new NegativeIndexException(); } array[index] = null; return true; } /** * Removes a specific object in the array. * * @param obj * the object to be removed from the array. * @return true if the object was found in the array. */ public boolean removeElementByObject(Object obj) { for (int i = 0; i < array.length; i++) { Object arrObj = array[i]; if (arrObj != null && arrObj.equals(obj)) { array[i] = null; return true; } } return false; } /** * Prints all the current elements in the array. */ public void printAllElements() { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < index; i++) { builder.append(" " + array[i]); } builder.append(" ]"); InputUtils.printConsoleMessage(builder.toString()); } }
package expr; import SemanticAnalysis.SemanticType; import slp.FuncArgsList; import slp.PropagatingVisitor; import slp.Visitor; public class CallExpr extends Expr { public final String funcName; public final FuncArgsList args_list; public final Expr e; public final Boolean isStatic; public final String classID; public CallExpr( Expr e, String n , FuncArgsList args, boolean is_static, String class_id , int line_num) { super( line_num ); this.funcName = n; this.args_list= args; this.e = e; isStatic = is_static; classID = class_id; this.type = new SemanticType("func" + n, false); } /** Accepts a visitor object as part of the visitor pattern. * @param visitor A visitor. */ @Override public Object accept(Visitor visitor) { return visitor.visit(this); } /** Accepts a propagating visitor parameterized by two types. * * @param <DownType> The type of the object holding the context. * @param <UpType> The type of the result object. * @param visitor A propagating visitor. * @param context An object holding context information. * @return The result of visiting this node. */ @Override public <DownType, UpType> UpType accept( PropagatingVisitor<DownType, UpType> visitor, DownType context) { return visitor.visit(this, context); } }
/* * Copyright 2002-2013 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.beans.factory.xml; import org.springframework.beans.testfixture.beans.FactoryMethods; import org.springframework.beans.testfixture.beans.TestBean; /** * Test class for Spring's ability to create objects using * static factory methods, rather than constructors. * * @author Rod Johnson */ public class InstanceFactory { protected static int count = 0; private String factoryBeanProperty; public InstanceFactory() { count++; } public void setFactoryBeanProperty(String s) { this.factoryBeanProperty = s; } public String getFactoryBeanProperty() { return this.factoryBeanProperty; } public FactoryMethods defaultInstance() { TestBean tb = new TestBean(); tb.setName(this.factoryBeanProperty); return FactoryMethods.newInstance(tb); } /** * Note that overloaded methods are supported. */ public FactoryMethods newInstance(TestBean tb) { return FactoryMethods.newInstance(tb); } public FactoryMethods newInstance(TestBean tb, int num, String name) { return FactoryMethods.newInstance(tb, num, name); } }
package modelo; import controlador.IngredienteView; public class Ingrediente { private float cantidad; private Producto producto; // Constructor de instancia ingrediente // ------------------------------------------------------------- public Ingrediente (Producto product, float cant){ this.producto = product; this.cantidad = cant; } // Metodo get que devuelve un IngredienteView para pasar a la vista // ------------------------------------------------------------- public IngredienteView getIngredienteView(){ IngredienteView iv = new IngredienteView(producto, cantidad); return iv; } // Metodos sets y Gets para los atributos de Ingrediente // ------------------------------------------------------------- public float getCantidad() { return cantidad; } public void setCantidad(float cuantiti) { this.cantidad = cuantiti; } public Producto getProducto() { return producto; } public void setProducto(Producto product) { this.producto = product; } // Metodos que operan con productos // ------------------------------------------------------------- // Revisa que la cantidad total de producto alcance para // preparar el total de platos o bebidas requeridos. public boolean esSuficiente(float cantidadTotal){ if (producto.getCantidad()>=cantidadTotal) return true; return false; } // Ordena al producto restarse la cantidad requerida para el plato-bebida public void usar(float cantidadTotal){ this.producto.setCantidad(producto.getCantidad()-cantidadTotal); } }
import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; /** * Rules allow very flexible addition or redefinition of the behavior of each test method in a test * class. Testers can reuse or extend one of the provided Rules below, or write their own. * * @author rollin * */ public class NameRuleTest { // The TestName Rule makes the current test name available inside test methods @Rule public TestName name = new TestName(); @Test public void testA() { assertEquals("testA", name.getMethodName()); } @Test public void testB() { assertEquals("testB", name.getMethodName()); } }
package ua.epam.provider.timer; public class Task implements Runnable { public void run() { System.out.println("task is run"); new Check().checkAllUsers(); } }
package org.jenkinsci.plugins.ghprb; import java.io.IOException; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Environment; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.listeners.RunListener; /** * @author janinko */ @Extension public class GhprbBuildListener extends RunListener<AbstractBuild<?, ?>> { @Override public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onStarted(build, listener); } } @Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onCompleted(build, listener); } } @Override public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onEnvironmentSetup(build, launcher, listener); } return new hudson.model.Environment(){}; } }