text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
package ggn.home.help.features.services; import ggn.home.help.web.Web; import ggn.home.help.web.response.BasicResponse; import io.reactivex.Observable; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; public interface ApiInterface { @Multipart @POST(Web.Path.ADD_MEMORY) Call<BasicResponse> addMemory(@Part MultipartBody.Part[] memories, @Part("details") RequestBody details); @Multipart @POST(Web.Path.ADD_POST) Call<BasicResponse> addPost(@Part MultipartBody.Part[] memories, @Part("details") RequestBody details); }
Java
CL
3a87bff78d8b30063a66e46db92b6a08deecb952e7e43f36deaefe00f98c2a61
// license-header java merge-point // // Attention: Generated code! Do not modify by hand! // Generated by: HibernateEntity.vsl in andromda-hibernate-cartridge. // package es.pode.adminusuarios.negocio.dominio; /** * */ public abstract class Rol implements java.io.Serializable { /** * The serial version UID of this class. Needed for serialization. */ private static final long serialVersionUID = 6092073140157700971L; private java.lang.String descripcion; /** * */ public java.lang.String getDescripcion() { return this.descripcion; } public void setDescripcion(java.lang.String descripcion) { this.descripcion = descripcion; } private java.lang.Long id; /** * */ public java.lang.Long getId() { return this.id; } public void setId(java.lang.Long id) { this.id = id; } /** * Returns <code>true</code> if the argument is an Rol instance and all identifiers for this entity * equal the identifiers of the argument entity. Returns <code>false</code> otherwise. */ public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof Rol)) { return false; } final Rol that = (Rol)object; if (this.id == null || that.id == null || !this.id.equals(that.id)) { return false; } return true; } /** * Returns a hash code based on this entity's identifiers. */ public int hashCode() { int hashCode = 0; hashCode = 29 * hashCode + (id == null ? 0 : id.hashCode()); return hashCode; } /** * Constructs new instances of {@link es.pode.adminusuarios.negocio.dominio.Rol}. */ public static final class Factory { /** * Constructs a new instance of {@link es.pode.adminusuarios.negocio.dominio.Rol}. */ public static es.pode.adminusuarios.negocio.dominio.Rol newInstance() { return new es.pode.adminusuarios.negocio.dominio.RolImpl(); } } // HibernateEntity.vsl merge-point }
Java
CL
a3559e50f30bcd784f4cce909b053ee504773aa60cdeb50c373384f1863f96dc
package com.c2c.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.DefaultMapContext; import org.geotools.map.MapContext; import org.geotools.map.MapLayer; import org.geotools.renderer.GTRenderer; import org.geotools.renderer.lite.StreamingRenderer; import org.geotools.styling.Style; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.c2c.geoutils.ReferenceEnvelopeFactory; /** * The Controller for handling compute requests. * <p/> * This class is registered as a bean in ws-servlet.xml. * * @author jeichar */ @Controller @RequestMapping("/getmap") public class GetMap extends AbstractQueryingController { @RequestMapping(method = RequestMethod.GET) public void getmap(HttpServletRequest request, HttpServletResponse response, @RequestParam("QUERYID") String queryId, @RequestParam("BBOX") String bbox, @RequestParam("WIDTH") int width, @RequestParam("HEIGHT") int height, @RequestParam(value = "STYLEID", required = false) String styleId, @RequestParam(value = "SRS", required = false) String srs, @RequestParam(value = "FORMAT", required = false) String format, @RequestParam(value = "FORMAT_OPTIONS", required = false) String format_options) throws Exception { if (format == null) { format = "image/png"; } int dpi = 90; if (format_options != null) { dpi = Util.getDpiFromFormat(format_options); } SimpleFeatureSource results = (SimpleFeatureSource) getCache().getResults(queryId).getFeatureSource(); response.setContentType(format); response.addHeader("Cache-Control", "no-cache"); response.addHeader("Expires", "-1"); ReferencedEnvelope bounds = ReferenceEnvelopeFactory.toReferencedEnvelope(bbox, srs == null ? "EPSG:4326" : srs); Rectangle imageSize = new Rectangle(width, height); Style sld = getCache().getStyle(styleId).getGtStyle(results.getFeatures()); //if(results.getSchema().getGeometryDescriptor() == null) renderMap(response, results, bounds, imageSize, sld, parseFormat(format), dpi); } private String parseFormat(String format) { if (format == null) { return "png"; } String[] parts = format.split("/"); if (parts.length == 1) { return format; } return parts[1]; } private void renderMap(HttpServletResponse response, SimpleFeatureSource results, ReferencedEnvelope bounds, Rectangle imageSize, Style sld, String format, int dpi) throws IOException { MapLayer[] layers = {new MapLayer(results, sld)}; MapContext map = new DefaultMapContext(layers, bounds .getCoordinateReferenceSystem()); try { GTRenderer renderer = new StreamingRenderer(); Map java2Dhints = new HashMap(); java2Dhints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.setJava2DHints(new RenderingHints(java2Dhints)); Map hints = new HashMap(); hints.put(StreamingRenderer.DPI_KEY, dpi); hints.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true); renderer.setRendererHints(hints); renderer.setContext(map); BufferedImage image = new BufferedImage(imageSize.width, imageSize.height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); try { if (results.getSchema().getGeometryDescriptor() == null) { graphics.setColor(Color.BLACK); int y = imageSize.height / 2; Font font = new Font(Font.SERIF, Font.BOLD, 14); graphics.setFont(font); graphics.drawString("Results have no geometries", 10, y - 14); } else { renderer.paint(graphics, imageSize, bounds); } ServletOutputStream output = response.getOutputStream(); try { ImageIO.write(image, format, output); } finally { output.close(); } } finally { graphics.dispose(); } } finally { map.dispose(); } } }
Java
CL
5366fefcf04c75efc8c3dcd053323e9220fefb45f0c1b50bb76e1f3366f2ec7a
package behaviours; import java.util.ArrayList; import agents.BaseAgent; import basicData.BatteryInfo; import basicData.FlexibilityData; import basicData.ResultPowerPrice; import database.DbAggregatorBattery; import database.DbBatteryInfo; import jade.core.behaviours.OneShotBehaviour; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.lang.acl.ACLMessage; import jade.lang.acl.UnreadableException; @SuppressWarnings("serial") public class DisaggregateBatteryBehaviour extends OneShotBehaviour { ACLMessage msg; ResultPowerPrice msgData; ArrayList<FlexibilityData> batteryChoices = new ArrayList<FlexibilityData>(); public DisaggregateBatteryBehaviour(ACLMessage msg) { this.msg = msg; try { msgData = (ResultPowerPrice)msg.getContentObject(); } catch (UnreadableException e) { e.printStackTrace(); } } @Override public void action() { /** * Get what the batteryAgents wanted to do for this hour and send them a message saying what to do * It should be as near as possible to what they wanted to do * * Linear Programming -> Operative Research */ //BatteryOutput -> powerRequested negative value //BatteryInput -> powerRequested positive value batteryChoices = new DbAggregatorBattery().getBatteriesChoice(this.myAgent.getName(), msgData.getDatetime()); DFAgentDescription[] batteryAgents = new BaseAgent().getAgentsbyServiceType(myAgent, "BatteryAgent"); if(batteryChoices.size() == batteryAgents.length) { if(msgData.getPowerRequested() < 0) //output from battery { takeFromMostConvenient(); } else if(msgData.getPowerRequested() > 0) //input in battery { giveWhatAsked(); } else if(msgData.getPowerRequested() == 0) { doNothing(); } } } private void takeFromMostConvenient() { double totalPowerRequested = msgData.getPowerRequested(); double batteryPowerRequested = 0; batteryChoices.sort((o1, o2) -> Double.compare(o1.getCostKwh(),o2.getCostKwh())); // the first battery is the one with lower CostKwh for(int i=0; i < batteryChoices.size(); i++) { batteryPowerRequested = totalPowerRequested < batteryChoices.get(i).getUpperLimit() ? batteryChoices.get(i).getUpperLimit() : totalPowerRequested; totalPowerRequested -= batteryPowerRequested; ResultPowerPrice batteryAction = new ResultPowerPrice(msgData.getDatetime(), batteryPowerRequested, msgData.getCostKwh()); sendMessage(batteryAction, i); } } /** * I try to give to all batteries what they asked * * batteriesChoice list is ordered by difference UpperLimit-DesiredChoice * why all of this? because some batteries can have the upperLimit equal to the desiredChoice, others maybe not. * So I take first the maximum (so the desidered choice) from the ones which requested the maximum, * then I apply the percentage to all the others. * * If some batteries desire to discharge then I'll charge them with the same quantity of kw * for the next slotTime */ private void giveWhatAsked() { // percentuale da aggiungere (o togliere, in base al segno) ad ogni scelta delle batterie //ATTENZIONE: passo i valori da negativi a positivi, alla fine li passo negativi di nuovo ArrayList<FlexibilityData> batteriesPositiveChoice = new DbAggregatorBattery() .getBatteriesChoiceByValue(this.myAgent.getName(), "positive", msgData.getDatetime()); double powerRequested = msgData.getPowerRequested(); double batteryPowerGiven = 0; //numero di batterie che vogliono caricarsi double batteriesDesiderCharge = batteryChoices.size() - batteriesPositiveChoice.size(); for(int i=0; i < batteryChoices.size(); i++) { batteryPowerGiven = 0; if(batteriesPositiveChoice.contains(batteryChoices.get(i))) { /** * le batterie che si vogliono scaricare sono alla fine della lista (diff maggiore), * quindi divido la parte rimanente tra loro */ if(powerRequested > 0) { if(powerRequested/batteriesDesiderCharge < batteryChoices.get(i).getLowerLimit()) { batteryPowerGiven = powerRequested/batteriesDesiderCharge; } else { batteryPowerGiven = batteryChoices.get(i).getLowerLimit(); } if(batteryPowerGiven > powerRequested) { batteryPowerGiven = powerRequested; } } } else if(powerRequested > 0) { batteryPowerGiven = powerRequested > batteryChoices.get(i).getLowerLimit() ? batteryChoices.get(i).getLowerLimit() : powerRequested; } powerRequested -= batteryPowerGiven; ResultPowerPrice batteryAction = new ResultPowerPrice(msgData.getDatetime(), batteryPowerGiven, msgData.getCostKwh()); sendMessage(batteryAction, i); } } /** * Send all the batteries 0 as value */ private void doNothing() { for(int i=0; i < batteryChoices.size(); i++) { ResultPowerPrice batteryAction = new ResultPowerPrice(msgData.getDatetime(), 0, msgData.getCostKwh()); BatteryInfo batteryInfo = new DbBatteryInfo().getBatteryInfoByIdBattery(batteryChoices.get(i).getIdAgent()); String shortName = new BaseAgent().getShortName(batteryInfo.getIdAgent()); new BaseAgent().sendMessageToAgentsByServiceType(this.myAgent, this.myAgent.getAID(shortName), "result", batteryAction); } } private void sendMessage(ResultPowerPrice batteryAction, int counter) { BatteryInfo batteryInfo = new DbBatteryInfo().getBatteryInfoByIdBattery(batteryChoices.get(counter).getIdAgent()); String shortName = new BaseAgent().getShortName(batteryInfo.getIdAgent()); new BaseAgent().sendMessageToAgentsByServiceType(this.myAgent, this.myAgent.getAID(shortName), "result", batteryAction); } }
Java
CL
a72de4f4e6f6f07296ec2df8a51b0ef0bff04e7259b1465274a798e6d552bfa2
package com.icupad.form.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.icupad.form.service.FormService; import com.icupad.form.model.FormTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; @RestController @RequestMapping("/form") public class FormController { private static final String FORM_ID = "form_domain"; private static final String FORM_NAME = "form_name"; private static final TypeReference<HashMap<String,Object>> MAP_REF = new TypeReference<HashMap<String,Object>>() {}; private final FormService formService; @Autowired public FormController(FormService formService) { this.formService = formService; } @RequestMapping(value = "/model/{module}/{modelName}", method = RequestMethod.GET) public ResponseEntity<?> getFormTemplate(@PathVariable("module") String module, @PathVariable("modelName") String modelName) { try { throwExceptionIfNotValid(module, modelName); return new ResponseEntity<>(Class.forName("com.icupad." + module + ".model." + modelName).getDeclaredFields(), HttpStatus.OK); } catch (ClassNotFoundException e) { return new ResponseEntity<Void>(HttpStatus.NOT_FOUND); } } @RequestMapping(value = "/{module}/{formId}", method = RequestMethod.GET) public ResponseEntity<String> getForm(@PathVariable("module") String module, @PathVariable("formId") String formId) { return new ResponseEntity<>(formService.findByModuleAndId(module, formId).getBody(), HttpStatus.OK); } @RequestMapping(value = "/{module}", method = RequestMethod.GET) public ResponseEntity<Map<String, String>> getModuleTemplates(@PathVariable("module") String module) { return new ResponseEntity<>(formService.findByModule(module).stream().collect(Collectors.toMap((FormTemplate t) -> t.getFormId(), t -> t.getFormName())), HttpStatus.OK); } @RequestMapping(value = "/{module}", method = RequestMethod.POST) public ResponseEntity<FormTemplate> addTemplate(@PathVariable("module") String module, @RequestBody String content) throws IOException { FormTemplate template = createTemplate(module, content); return new ResponseEntity<>(formService.saveTemplate(template), HttpStatus.CREATED); } private void throwExceptionIfNotValid(String... strings) { for (String string : strings) { if (!string.matches("[a-zA-Z_]+")) { throw new IllegalArgumentException("Invalid value: '" + string + "'"); } } } private FormTemplate createTemplate(String module, String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<String, String> extractedContent = mapper.readValue(content, MAP_REF); if (!extractedContent.containsKey(FORM_NAME) || !extractedContent.containsKey(FORM_ID)) { throw new IllegalArgumentException("Form model is not valid"); } FormTemplate template = new FormTemplate(); template.setFormId(extractedContent.get(FORM_ID)); template.setFormName(extractedContent.get(FORM_NAME)); template.setModuleName(module); template.setBody(content); return template; } }
Java
CL
a117a7f6309ea634769db9512e8e5e19dcbd36ba218cd9a7e29f05454eca4236
package com.path.dbmaps.vo; import com.path.lib.vo.BaseVO; import java.math.BigDecimal; public class TRS_CHARGES_REVERSAL_DETVOKey extends BaseVO { /** * This field corresponds to the database column TRS_CHARGES_REVERSAL_DET.BRANCH_CODE */ private BigDecimal BRANCH_CODE; /** * This field corresponds to the database column TRS_CHARGES_REVERSAL_DET.COMP_CODE */ private BigDecimal COMP_CODE; /** * This field corresponds to the database column TRS_CHARGES_REVERSAL_DET.LINE_NBR */ private BigDecimal LINE_NBR; /** * This field corresponds to the database column TRS_CHARGES_REVERSAL_DET.TRX_NBR */ private BigDecimal TRX_NBR; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TRS_CHARGES_REVERSAL_DET.BRANCH_CODE * * @return the value of TRS_CHARGES_REVERSAL_DET.BRANCH_CODE */ public BigDecimal getBRANCH_CODE() { return BRANCH_CODE; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TRS_CHARGES_REVERSAL_DET.BRANCH_CODE * * @param BRANCH_CODE the value for TRS_CHARGES_REVERSAL_DET.BRANCH_CODE */ public void setBRANCH_CODE(BigDecimal BRANCH_CODE) { this.BRANCH_CODE = BRANCH_CODE; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TRS_CHARGES_REVERSAL_DET.COMP_CODE * * @return the value of TRS_CHARGES_REVERSAL_DET.COMP_CODE */ public BigDecimal getCOMP_CODE() { return COMP_CODE; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TRS_CHARGES_REVERSAL_DET.COMP_CODE * * @param COMP_CODE the value for TRS_CHARGES_REVERSAL_DET.COMP_CODE */ public void setCOMP_CODE(BigDecimal COMP_CODE) { this.COMP_CODE = COMP_CODE; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TRS_CHARGES_REVERSAL_DET.LINE_NBR * * @return the value of TRS_CHARGES_REVERSAL_DET.LINE_NBR */ public BigDecimal getLINE_NBR() { return LINE_NBR; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TRS_CHARGES_REVERSAL_DET.LINE_NBR * * @param LINE_NBR the value for TRS_CHARGES_REVERSAL_DET.LINE_NBR */ public void setLINE_NBR(BigDecimal LINE_NBR) { this.LINE_NBR = LINE_NBR; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TRS_CHARGES_REVERSAL_DET.TRX_NBR * * @return the value of TRS_CHARGES_REVERSAL_DET.TRX_NBR */ public BigDecimal getTRX_NBR() { return TRX_NBR; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TRS_CHARGES_REVERSAL_DET.TRX_NBR * * @param TRX_NBR the value for TRS_CHARGES_REVERSAL_DET.TRX_NBR */ public void setTRX_NBR(BigDecimal TRX_NBR) { this.TRX_NBR = TRX_NBR; } }
Java
CL
d37d2a6569e4331d5428842206e39ab6da3485b0b5e2750cd52a9b6c5c93fa3d
package com.example.fangyi.mygame.map; import android.view.MotionEvent; import com.example.fangyi.mygame.R; import org.cocos2d.actions.base.CCRepeatForever; import org.cocos2d.actions.instant.CCCallFunc; import org.cocos2d.actions.interval.CCAnimate; import org.cocos2d.actions.interval.CCJumpBy; import org.cocos2d.actions.interval.CCMoveTo; import org.cocos2d.actions.interval.CCRotateBy; import org.cocos2d.actions.interval.CCSequence; import org.cocos2d.actions.interval.CCSpawn; import org.cocos2d.layers.CCLayer; import org.cocos2d.layers.CCTMXObjectGroup; import org.cocos2d.layers.CCTMXTiledMap; import org.cocos2d.nodes.CCAnimation; import org.cocos2d.nodes.CCDirector; import org.cocos2d.nodes.CCSprite; import org.cocos2d.nodes.CCSpriteFrame; import org.cocos2d.nodes.CCTextureCache; import org.cocos2d.particlesystem.CCParticleSnow; import org.cocos2d.particlesystem.CCParticleSystem; import org.cocos2d.sound.SoundEngine; import org.cocos2d.types.CGPoint; import org.cocos2d.types.CGRect; import org.cocos2d.types.CGSize; import org.cocos2d.types.util.CGPointUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by FANGYI on 2016/8/4. */ public class DemoLayer extends CCLayer { private CCTMXTiledMap map; private List<CGPoint> cgPointList;//地图中点的集合 int postion = 0;//僵尸要走的第一个点 private String filepath; private CCSprite sprite;//僵尸 private CCParticleSystem system; public DemoLayer() { this.setIsTouchEnabled(true);//打开触摸开发 init(); } private void init() { //加载地图 loadMap(); //解析地图 parserMap(); //粒子系统 loadParticle(); //需要一个僵尸 loadZombies(); } /** * 粒子系统 */ private void loadParticle() { //创建粒子系统 //创建的是雪花粒子系统 system = CCParticleSnow.node(); // CCParticleSystem system = CCParticleFire.node();//创建的是着火粒子系统 // CCParticleSystem system = CCParticleSmoke.node();//创建的是冒烟粒子系统 //设置雪花的样式 system.setTexture(CCTextureCache.sharedTextureCache().addImage("f.png")); this.addChild(system, 1); //自定义粒子系统 使用ParticleDesigner,导出的文件放里面 // CCParticleSystem ps = CCParticleSystemPoint.particleWithFile("f.plist"); // ps.setPosition(0, winSize.height); // addChild(ps); } /** * 展示僵尸 */ private void loadZombies() { sprite = CCSprite.sprite("z_1_01.png"); sprite.setPosition(cgPointList.get(0)); sprite.setAnchorPoint(0.4f, 0.1f); sprite.setScale(0.65f); sprite.setFlipX(true); map.addChild(sprite);//通过地图添加僵尸,如果地图随着手指移动,那么僵尸随着地图移动 animateZombies(); moveToNext(); } int speed = 40;//僵尸的速度 /** * 僵尸移动 */ public void moveToNext() { postion++; if (postion < cgPointList.size()) { CGPoint cgPoint = cgPointList.get(postion); float t = CGPointUtil.distance(cgPointList.get(postion - 1), cgPoint) / speed; CCMoveTo moveTo = CCMoveTo.action(t, cgPoint);//匀速 CCSequence ccSequence = CCSequence.actions(moveTo, CCCallFunc.action(this, "moveToNext"));//调用当前某一对象的方法,方法是公有,反射 sprite.runAction(ccSequence); } else { //雪停下来,移动完成了, system.stopSystem();//停止粒子系统 sprite.stopAllActions();//停止所有动作 //跳舞 dance(); //音乐 music(); } } /** * 声音引擎 */ private void music() { SoundEngine engine = SoundEngine.sharedEngine(); //1.上下文,2.音乐资源 3.是否循环播放 engine.playSound(CCDirector.theApp, R.raw.psy, true); } /** * 复杂的动作 */ private void dance() { sprite.setAnchorPoint(0.5f, 0.5f); CCJumpBy ccJumpBy = CCJumpBy.action(2, ccp(-20, 10), 10, 2); CCRotateBy ccRotateBy = CCRotateBy.action(1, 360); CCSpawn ccSpawn = CCSpawn.actions(ccJumpBy, ccRotateBy); CCSequence sequence = CCSequence.actions(ccSpawn, ccSpawn.reverse()); CCRepeatForever forver = CCRepeatForever.action(sequence); sprite.runAction(forver); } /** * 帧动画,僵尸行走的样子 */ private void animateZombies() { ArrayList<CCSpriteFrame> frames = new ArrayList<>(); filepath = "z_1_%02d.png";//02d占位符,可以表示两位的证书,如果不足两位前面可以用0补足 for (int i = 1; i <= 7; i++) { CCSpriteFrame ccSpriteFrame = CCSprite.sprite(String.format(filepath, i)).displayedFrame(); frames.add(ccSpriteFrame); } //序列帧的播放 //配置序列帧的信息 1:动作的名字(给程序员看的)2:每一帧播放的时间 单位秒 3:所有用到的帧 CCAnimation animation = CCAnimation.animation("走路", 0.2f, frames); CCAnimate animate = CCAnimate.action(animation); //序列帧动作默认是永不停止的循环 CCRepeatForever forever = CCRepeatForever.action(animate); sprite.runAction(forever); } /** * 加载地图 */ private void loadMap() { map = CCTMXTiledMap.tiledMap("map.tmx");//默认锚点0,0 map.setAnchorPoint(0.5f, 0.5f); //因为修改了锚点,所以坐标也需要修改 map.setPosition(map.getContentSize().width / 2, map.getContentSize().height / 2); this.addChild(map); } /** * 解析地图 */ private void parserMap() { cgPointList = new ArrayList<>(); CCTMXObjectGroup objectGroup = map.objectGroupNamed("road"); ArrayList<HashMap<String, String>> objects = objectGroup.objects; for (HashMap<String, String> object : objects) { int x = Integer.parseInt(object.get("x")); int y = Integer.parseInt(object.get("y")); CGPoint cgPoint = ccp(x, y); cgPointList.add(cgPoint); } } /** * 触摸事件 * * @param event * @return */ @Override public boolean ccTouchesMoved(MotionEvent event) { map.touchMove(event, map);//地图随着手指的移动而移动 如果该方法生效,必须保证地图的锚点在中间位置 return super.ccTouchesMoved(event); } @Override public boolean ccTouchesBegan(MotionEvent event) { //先把Android坐标系中的点 转换成 cocos2d坐标系中的点 CGPoint cgPoint = this.convertTouchToNodeSpace(event); CGRect boudingBox = sprite.getBoundingBox();//获取精灵的矩形 //判断点是否在矩形之中 //参数1:矩形 参数2:点 boolean containsPoint = CGRect.containsPoint(boudingBox, cgPoint); if (containsPoint) { this.onExit();//暂停 this.getParent().addChild(new PauseLayer());//让场景添加新的图层 } return super.ccTouchesBegan(event); } /** * 新的图层 */ private class PauseLayer extends CCLayer { private final CCSprite bilibili; public PauseLayer() { this.setIsTouchEnabled(true); bilibili = CCSprite.sprite("z_1_attack_01.png"); //获取屏幕的尺寸 CGSize winSize = CCDirector.sharedDirector().getWinSize(); bilibili.setPosition(winSize.width / 2, winSize.height / 2);//在屏幕的中间 this.addChild(bilibili); } @Override public boolean ccTouchesBegan(MotionEvent event) { //先把Android坐标系中的点 转换成 cocos2d坐标系中的点 CGPoint cgPoint = this.convertTouchToNodeSpace(event); CGRect boudingBox = bilibili.getBoundingBox();//获取精灵的矩形 //判断点是否在矩形之中 //参数1:矩形 参数2:点 boolean containsPoint = CGRect.containsPoint(boudingBox, cgPoint); if (containsPoint) { this.removeSelf();//收回当前图层 DemoLayer.this.onEnter();//游戏继续 } return super.ccTouchesBegan(event); } } }
Java
CL
e460e5a3795273d03b1c9c8e10bd3040953cba30791f1da8fdc3e94e885de826
package com.oracle.app.builtins; import com.oracle.app.GoException; import com.oracle.app.nodes.types.GoArray; import com.oracle.app.nodes.types.GoMap; import com.oracle.app.nodes.types.GoSlice; import com.oracle.app.runtime.GoNull; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; /** * Make builtin only for slices and maps. Missing channels because we do not implement channel types * Maps are made before make is called so just need to return the object itself. * Maps made with a capacity should only be called on new maps, but has the possibility of being called on * maps that are already defined. * @author Trevor * */ @NodeInfo(shortName = "make") public abstract class GoMakeBuiltin extends GoBuiltinNode{ @Specialization public GoSlice makeSliceWithCapacity(GoSlice slice, int len, int cap){ if(len > cap){ throw new GoException("len larger than cap in make()"); } return slice.make(len, cap); } @Specialization public GoSlice makeSlice(GoSlice slice, int len, GoNull x){ return slice.make(len, len); } @Specialization public GoMap makeMapWithCapacity(GoMap map, int len, GoNull x){ map.setNewMapCapacity(len); return map; } @Specialization public GoMap makeMap(GoMap map, GoNull x, GoNull y){ return map; } }
Java
CL
d8e101552dbf56e9f2a33f4076f48eaa77f28701faf5ad05d3330215fe45541d
package com.milo.libretrofit.http; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Title: * Describe: * Remark: * <p> * Created by Milo * E-Mail : 303767416@qq.com * 6/25/21 */ @Documented @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Query { /** The query parameter name. */ String value(); /** * Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded. */ boolean encoded() default false; }
Java
CL
621d2e6d7248cedb9c7166237277b8a2bf3c6e9b6c4e57a9030de9f7beaf68f3
package gumbo.engine.general.grouper.policies; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import gumbo.engine.general.grouper.structures.CalculationGroup; import gumbo.engine.general.grouper.structures.GuardedSemiJoinCalculation; /** * Abstract class used to create policies that group * based on a hash of the semijoin. * * @author Jonny Daenen * */ public abstract class AbstractHashGroupingPolicy implements GroupingPolicy { /** * Wraps all semijoin together in one group. */ @Override public List<CalculationGroup> group( CalculationGroup semijoins) { // hash the semijoins HashMap<String,CalculationGroup> hashmap = hash(semijoins); // each bucket becomes one group LinkedList<CalculationGroup> groupedResult = new LinkedList<CalculationGroup>(); for (String key : hashmap.keySet()) { CalculationGroup group = new CalculationGroup(semijoins.getRelevantExpressions()); group.addAll(hashmap.get(key)); groupedResult.add(group); } return groupedResult; } private HashMap<String, CalculationGroup> hash( CalculationGroup semijoins) { HashMap<String, CalculationGroup> hashmap = new HashMap<String, CalculationGroup>(); for (GuardedSemiJoinCalculation semijoin : semijoins.getAll()) { String hashVal = hash(semijoin); if (!hashmap.containsKey(hashVal)) { hashmap.put(hashVal, new CalculationGroup(semijoins.getRelevantExpressions())); } hashmap.get(hashVal).add(semijoin); } return hashmap; } protected abstract String hash(GuardedSemiJoinCalculation semijoin); }
Java
CL
2a9ae414c21e0fbf48da92fc58ac0be31b4d9160dff65521284b16996d0a6610
/* * * * Copyright 2019 Symphony Communication Services, LLC. * * 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.symphony.oss.allegro.api; import com.symphony.oss.fugue.pipeline.FatalConsumerException; import com.symphony.oss.fugue.pipeline.RetryableConsumerException; import com.symphony.oss.fugue.trace.ITraceContext; import com.symphony.oss.models.allegro.canon.facade.IReceivedChatMessage; import com.symphony.oss.models.allegro.canon.facade.IReceivedMaestroMessage; import com.symphony.oss.models.allegro.canon.facade.IReceivedSocialMessage; /** * A consumer adaptor for ReceivedChatMessages. * * Various typed onTYPENAME methods are defined and called when messages of each type are consumed. * The default implementations are NO-OPs so if some message types are to be ignored simply * do not override those handler methods. * * @author Bruce Skingle * */ public class ReceivedChatMessageAdaptor extends AbstractAdaptor<IReceivedChatMessage> { /** * Constructor. */ public ReceivedChatMessageAdaptor() { super(IReceivedChatMessage.class); } @Override public final void consume(IReceivedChatMessage message, ITraceContext trace) throws RetryableConsumerException, FatalConsumerException { if(message instanceof IReceivedSocialMessage) { onSocialMessage((IReceivedSocialMessage) message, trace); } else if(message instanceof IReceivedMaestroMessage) { onMaestroMessage((IReceivedMaestroMessage) message, trace); } else { defaultConsumer_.consume(message, trace); } } @Override public void close() { } /** * Handle a ReceivedSocialMessage (an actual chat message) * * @param message The message to be consumed. * @param trace A trace context. */ public void onSocialMessage(IReceivedSocialMessage message, ITraceContext trace) { } /** * Handle a ReceivedMaestroMessage (a notification of some meta-event) * * @param message The message to be consumed. * @param trace A trace context. */ public void onMaestroMessage(IReceivedMaestroMessage message, ITraceContext trace) { } }
Java
CL
3546e28a9c4461f226d47a3f5f119e7b06a9e943c8cfb0823dc2761f34201507
package com.yc.springmvc.web; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yc.damai.bean.DmOrders; @RestController @RequestMapping("demo") public class FormatAction { /** * Field error in object 'dmOrders' on field 'date': * rejected value [2020-09-09]; codes * [typeMismatch.dmOrders.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; * arguments [org.springframework.context.support.DefaultMessageSourceResolvable: * codes [dmOrders.date,date]; arguments []; default message [date]]; * default message [Failed to convert property value of type * 'java.lang.String' to required type 'java.util.Date' for property 'date'; * nested exception is org.springframework.core.convert.ConversionFailedException: * Failed to convert from type [java.lang.String] to type [java.util.Date] for value * '2020-09-09'; nested exception is java.lang.IllegalArgumentException]] */ @RequestMapping("addOrder") public DmOrders addOrder(DmOrders dos) { System.out.println(dos.getDate()); return dos; } }
Java
CL
badcc93e57f99bd4670ec59b7ba0a969fbd68edd8d0080b144c5a76c861ea6e3
package com.xwguan.autofund.service.mapper.tactic; import com.xwguan.autofund.entity.plan.tactic.MATactic; import com.xwguan.autofund.service.mapper.rule.CleanCopyPeriodConditionMapper; import com.xwguan.autofund.service.mapper.rule.CleanCopyRuleMapper; import javax.annotation.Generated; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2019-01-30T10:49:11+0800", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 1.1.0.v20150122-0735, environment: Java 1.8.0_151 (Oracle Corporation)" ) @Component public class CleanCopyMATacticMapperImpl implements CleanCopyMATacticMapper { @Autowired private CleanCopyRuleMapper cleanCopyRuleMapper; @Autowired private CleanCopyPeriodConditionMapper cleanCopyPeriodConditionMapper; @Override public MATactic cleanCopy(MATactic source) { if ( source == null ) { return null; } MATactic mATactic = new MATactic(); mATactic.setPeriodCondition( cleanCopyPeriodConditionMapper.cleanCopy( source.getPeriodCondition() ) ); mATactic.setRuleList( cleanCopyRuleMapper.cleanCopyList( source.getRuleList() ) ); mATactic.setMa( source.getMa() ); mATactic.setPlanId( Long.parseLong( "-1" ) ); mATactic.setId( Long.parseLong( "-1" ) ); mATactic.setActivated( Boolean.parseBoolean( "true" ) ); return mATactic; } }
Java
CL
8f86a0f200910e0575bf4eeb3554cd7a7028099ef490b4e0557e074c7929eabe
package com.example.providerexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import com.example.providerexample.database.DatabaseHandler; import com.example.providerexample.database.Item; /** * A fragment representing a single Item detail screen. This fragment is either * contained in a {@link ItemListActivity} in two-pane mode (on tablets) or a * {@link ItemDetailActivity} on handsets. */ public class ItemDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; /** * The Item this fragment is presenting. (Item is my addition, mItem was there */ private Item mItem; /** * The UI elements showing the details of the Person */ private TextView textTitle; private CheckBox checkboxComplete; private TextView textDesc; public ItemDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Should use the content provider here ideally. mItem = DatabaseHandler.getInstance(getActivity()) .getItem(getArguments().getLong(ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false); if (mItem != null) { textTitle = ((TextView) rootView.findViewById(R.id.textItemTitle)); textTitle.setText(mItem.title); checkboxComplete = ((CheckBox) rootView.findViewById(R.id.fragmentDetailComplete)); checkboxComplete.setChecked(mItem.complete); textDesc = ((TextView) rootView.findViewById(R.id.textDescription)); textDesc.setText(mItem.description); } return rootView; } //Saves changes onPause @Override public void onPause() { super.onPause(); updateItemFromUI(); } private void updateItemFromUI() { if (mItem != null) { mItem.complete = checkboxComplete.isChecked(); mItem.title = textTitle.getText().toString(); mItem.description = textDesc.getText().toString(); DatabaseHandler.getInstance(getActivity()).putItem(mItem); } } }
Java
CL
0e88161f0b95e9d4849cccc2549a27f174f0fe9b3fb1e426b06f4d0b1886facd
/* * Copyright (C) 2018, Google LLC. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.transport; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Set; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.annotations.Nullable; import org.eclipse.jgit.lib.ObjectId; /** * Common fields between v0/v1/v2 fetch requests. */ abstract class FetchRequest { final Set<ObjectId> wantIds; final int depth; final Set<ObjectId> clientShallowCommits; final FilterSpec filterSpec; final Set<String> clientCapabilities; final int deepenSince; final List<String> deepenNotRefs; @Nullable final String agent; /** * Initialize the common fields of a fetch request. * * @param wantIds * list of want ids * @param depth * how deep to go in the tree * @param clientShallowCommits * commits the client has without history * @param filterSpec * the filter spec * @param clientCapabilities * capabilities sent in the request * @param deepenNotRefs * Requests that the shallow clone/fetch should be cut at these * specific revisions instead of a depth. * @param deepenSince * Requests that the shallow clone/fetch should be cut at a * specific time, instead of depth * @param agent * agent as reported by the client in the request body */ FetchRequest(@NonNull Set<ObjectId> wantIds, int depth, @NonNull Set<ObjectId> clientShallowCommits, @NonNull FilterSpec filterSpec, @NonNull Set<String> clientCapabilities, int deepenSince, @NonNull List<String> deepenNotRefs, @Nullable String agent) { this.wantIds = requireNonNull(wantIds); this.depth = depth; this.clientShallowCommits = requireNonNull(clientShallowCommits); this.filterSpec = requireNonNull(filterSpec); this.clientCapabilities = requireNonNull(clientCapabilities); this.deepenSince = deepenSince; this.deepenNotRefs = requireNonNull(deepenNotRefs); this.agent = agent; } /** * @return object ids in the "want" (and "want-ref") lines of the request */ @NonNull Set<ObjectId> getWantIds() { return wantIds; } /** * @return the depth set in a "deepen" line. 0 by default. */ int getDepth() { return depth; } /** * Shallow commits the client already has. * * These are sent by the client in "shallow" request lines. * * @return set of commits the client has declared as shallow. */ @NonNull Set<ObjectId> getClientShallowCommits() { return clientShallowCommits; } /** * @return the filter spec given in a "filter" line */ @NonNull FilterSpec getFilterSpec() { return filterSpec; } /** * Capabilities that the client wants enabled from the server. * * Capabilities are options that tune the expected response from the server, * like "thin-pack", "no-progress" or "ofs-delta". This list should be a * subset of the capabilities announced by the server in its first response. * * These options are listed and well-defined in the git protocol * specification. * * The agent capability is not included in this set. It can be retrieved via * {@link #getAgent()}. * * @return capabilities sent by the client (excluding the "agent" * capability) */ @NonNull Set<String> getClientCapabilities() { return clientCapabilities; } /** * The value in a "deepen-since" line in the request, indicating the * timestamp where to stop fetching/cloning. * * @return timestamp in seconds since the epoch, where to stop the shallow * fetch/clone. Defaults to 0 if not set in the request. */ int getDeepenSince() { return deepenSince; } /** * @return refs received in "deepen-not" lines. */ @NonNull List<String> getDeepenNotRefs() { return deepenNotRefs; } /** * @return string identifying the agent (as sent in the request body by the * client) */ @Nullable String getAgent() { return agent; } }
Java
CL
941706c3e08d9943844a129801054ae7e5fb2ab1aebea487468adc3d39943653
package mapsted.com.myapplication.model; import org.json.JSONException; import org.json.JSONObject; import mapsted.com.myapplication.provider.IBuildingProvider; /* Nested within the root object: AnalyticsData has an Array of Objects there is an Object,"session_infos", which is Array of Objects(which it also contains array of objects) it-self Purchase class is defined to gain access to the lowest(last) level of objects in this array of objects. */ public class Purchase { private int buildingId; private int itemId; private int categoryId; private double cost; private Building building; public int getBuildingId() { return buildingId; } public int getItemId() { return itemId; } public int getCategoryId() { return categoryId; } public double getCost() { return cost; } public Building getBuilding() { return building; } public void setBuilding(IBuildingProvider<Building> buildingProvider) { this.building = buildingProvider.getById(this.buildingId); } public Purchase(int buildingId, int itemId, int categoryId, double cost) { this.buildingId = buildingId; this.itemId = itemId; this.categoryId = categoryId; this.cost = cost; } //Returns an object of this class, is used in Device class (part of its objects) public static Purchase parse(JSONObject jsonObject, int buildingId) throws JSONException{ return new Purchase( buildingId, jsonObject.getInt("item_id"), jsonObject.getInt("item_category_id"), jsonObject.getDouble("cost") ); } }
Java
CL
2ab58db871514dfe794aee92daaee89fd1075c99142a2d3c762b2234ce07bd3e
// -------------------------------------------------------------------------------- // Copyright 2002-2023 Echo Three, LLC // // 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.echothree.control.user.term.server.command; import com.echothree.control.user.term.common.edit.PartyCreditLimitEdit; import com.echothree.control.user.term.common.edit.TermEditFactory; import com.echothree.control.user.term.common.form.EditPartyCreditLimitForm; import com.echothree.control.user.term.common.result.EditPartyCreditLimitResult; import com.echothree.control.user.term.common.result.TermResultFactory; import com.echothree.control.user.term.common.spec.PartyCreditLimitSpec; import com.echothree.model.control.accounting.server.control.AccountingControl; import com.echothree.model.control.party.common.PartyTypes; import com.echothree.model.control.party.server.control.PartyControl; import com.echothree.model.control.party.server.logic.PartyChainLogic; import com.echothree.model.control.term.server.control.TermControl; import com.echothree.model.data.accounting.server.entity.Currency; import com.echothree.model.data.party.common.pk.PartyPK; import com.echothree.model.data.party.server.entity.Party; import com.echothree.model.data.term.server.entity.PartyCreditLimit; import com.echothree.model.data.term.server.value.PartyCreditLimitValue; import com.echothree.model.data.user.common.pk.UserVisitPK; import com.echothree.util.common.message.ExecutionErrors; import com.echothree.util.common.validation.FieldDefinition; import com.echothree.util.common.validation.FieldType; import com.echothree.util.common.command.BaseResult; import com.echothree.util.common.command.EditMode; import com.echothree.util.common.form.BaseForm; import com.echothree.util.server.control.BaseEditCommand; import com.echothree.util.server.persistence.Session; import com.echothree.util.server.string.AmountUtils; import com.echothree.util.server.validation.Validator; import java.util.Arrays; import java.util.Collections; import java.util.List; public class EditPartyCreditLimitCommand extends BaseEditCommand<PartyCreditLimitSpec, PartyCreditLimitEdit> { private final static List<FieldDefinition> SPEC_FIELD_DEFINITIONS; private final static List<FieldDefinition> EDIT_FIELD_DEFINITIONS; static { SPEC_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList( new FieldDefinition("PartyName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("CurrencyIsoName", FieldType.ENTITY_NAME, true, null, null) )); EDIT_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList( new FieldDefinition("CreditLimit", FieldType.UNSIGNED_PRICE_LINE, false, null, null), new FieldDefinition("PotentialCreditLimit", FieldType.UNSIGNED_PRICE_LINE, false, null, null) )); } /** Creates a new instance of EditPartyCreditLimitCommand */ public EditPartyCreditLimitCommand(UserVisitPK userVisitPK, EditPartyCreditLimitForm form) { super(userVisitPK, form, null, SPEC_FIELD_DEFINITIONS, EDIT_FIELD_DEFINITIONS); } @Override protected void setupValidatorForEdit(Validator validator, BaseForm specForm) { var accountingControl = Session.getModelController(AccountingControl.class); String currencyIsoName = spec.getCurrencyIsoName(); validator.setCurrency(accountingControl.getCurrencyByIsoName(currencyIsoName)); } @Override protected BaseResult execute() { var partyControl = Session.getModelController(PartyControl.class); EditPartyCreditLimitResult result = TermResultFactory.getEditPartyCreditLimitResult(); String partyName = spec.getPartyName(); Party party = partyControl.getPartyByName(partyName); if(party != null) { var accountingControl = Session.getModelController(AccountingControl.class); String currencyIsoName = spec.getCurrencyIsoName(); Currency currency = accountingControl.getCurrencyByIsoName(currencyIsoName); if(currency != null) { var termControl = Session.getModelController(TermControl.class); if(editMode.equals(EditMode.LOCK)) { PartyCreditLimit partyCreditLimit = termControl.getPartyCreditLimit(party, currency); if(partyCreditLimit != null) { result.setPartyCreditLimit(termControl.getPartyCreditLimitTransfer(getUserVisit(), partyCreditLimit)); if(lockEntity(party)) { PartyCreditLimitEdit edit = TermEditFactory.getPartyCreditLimitEdit(); result.setEdit(edit); edit.setCreditLimit(AmountUtils.getInstance().formatPriceLine(currency, partyCreditLimit.getCreditLimit())); edit.setPotentialCreditLimit(AmountUtils.getInstance().formatPriceLine(currency, partyCreditLimit.getPotentialCreditLimit())); } else { addExecutionError(ExecutionErrors.EntityLockFailed.name()); } result.setEntityLock(getEntityLockTransfer(party)); } else { addExecutionError(ExecutionErrors.UnknownPartyCreditLimit.name()); } } else if(editMode.equals(EditMode.UPDATE)) { PartyCreditLimitValue partyCreditLimitValue = termControl.getPartyCreditLimitValueForUpdate(party, currency); if(partyCreditLimitValue != null) { if(lockEntityForUpdate(party)) { String strCreditLimit = edit.getCreditLimit(); Long creditLimit = strCreditLimit == null? null: Long.valueOf(strCreditLimit); String strPotentialCreditLimit = edit.getPotentialCreditLimit(); Long potentialCreditLimit = strPotentialCreditLimit == null? null: Long.valueOf(strPotentialCreditLimit); try { partyCreditLimitValue.setCreditLimit(creditLimit); partyCreditLimitValue.setPotentialCreditLimit(potentialCreditLimit); if(partyCreditLimitValue.hasBeenModified()) { String partyTypeName = party.getLastDetail().getPartyType().getPartyTypeName(); PartyPK updatedBy = getPartyPK(); termControl.updatePartyCreditLimitFromValue(partyCreditLimitValue, updatedBy); if(partyTypeName.equals(PartyTypes.CUSTOMER.name())) { // ExecutionErrorAccumulator is passed in as null so that an Exception will be thrown if there is an error. PartyChainLogic.getInstance().createPartyCreditLimitChangedChainInstance(null, party, updatedBy); } } } finally { unlockEntity(party); } } else { addExecutionError(ExecutionErrors.EntityLockStale.name()); } } else { addExecutionError(ExecutionErrors.UnknownPartyCreditLimit.name()); } } } else { addExecutionError(ExecutionErrors.UnknownCurrencyIsoName.name(), currencyIsoName); } } else { addExecutionError(ExecutionErrors.UnknownPartyName.name(), partyName); } return result; } }
Java
CL
a79ae2db54506530a77770ac6a00114d93927adfb91021987867d845b6c0f621
package nl.d2n.controller; import nl.d2n.model.ApplicationException; import nl.d2n.model.D2NErrorCode; import nl.d2n.model.GameClock; import org.hibernate.StaleStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.orm.jpa.JpaOptimisticLockingFailureException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AbstractController { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractController.class); @Autowired private GameClock gameClock; @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleApplicationException(ApplicationException err, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!err.getError().isSkipLogging()) { ControllerUtils.logParameters(err, LOGGER, request); } writeJsonStringToResponse(err.getError().toJson(err.getDescription()), response); } @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleMissingParameterException(TypeMismatchException err, HttpServletRequest request, HttpServletResponse response) throws IOException { ControllerUtils.logParameters(D2NErrorCode.WRONG_VALUE.toString()+": "+err.getMessage(), LOGGER, request); writeJsonStringToResponse(D2NErrorCode.WRONG_VALUE.toJson(err.getValue().toString()), response); } @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleMissingParameterException(MissingServletRequestParameterException err, HttpServletRequest request, HttpServletResponse response) throws IOException { ControllerUtils.logParameters(D2NErrorCode.MISSING_PARAMETER.toString()+": "+err.getMessage(), LOGGER, request); writeJsonStringToResponse(D2NErrorCode.MISSING_PARAMETER.toJson(err.getParameterName()), response); } @ExceptionHandler({StaleStateException.class, JpaOptimisticLockingFailureException.class}) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleOptimisticLockingException(HttpServletRequest request, HttpServletResponse response) throws IOException { ControllerUtils.logParameters("Optimistic Locking Failure exception", LOGGER, request); writeJsonStringToResponse(D2NErrorCode.SYSTEM_ERROR.toJson(), response); } @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleUnspecifiedExceptions(Throwable err, HttpServletRequest request, HttpServletResponse response) throws IOException { ControllerUtils.logParameters(err.getMessage(), LOGGER, request); LOGGER.error("", err); writeJsonStringToResponse(D2NErrorCode.SYSTEM_ERROR.toJson(), response); } protected void writeJsonStringToResponse(String json, HttpServletResponse response) throws IOException { response.setContentType("application/j-son"); response.setHeader("Date", gameClock.isInitialized() ? gameClock.getJavaScriptDate() : ""); response.setCharacterEncoding("UTF-8"); response.getWriter().print(json); } }
Java
CL
9f6de5b155ecfb28ee96db324b74a289af7844ebea49d555e47c88741a5de6c2
package cn.cnic.component.process.service.Impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import cn.cnic.base.utils.JsonUtils; import cn.cnic.base.utils.PageHelperUtils; import cn.cnic.base.utils.ReturnMapUtils; import cn.cnic.component.process.entity.Process; import cn.cnic.component.process.entity.ProcessGroup; import cn.cnic.component.process.mapper.ProcessAndProcessGroupMapper; import cn.cnic.component.process.mapper.ProcessGroupMapper; import cn.cnic.component.process.mapper.ProcessMapper; import cn.cnic.component.process.service.IProcessAndProcessGroupService; import cn.cnic.component.process.utils.ProcessGroupUtils; import cn.cnic.component.process.utils.ProcessUtils; import cn.cnic.component.process.vo.ProcessGroupVo; import cn.cnic.component.process.vo.ProcessVo; @Service public class ProcessAndProcessGroupServiceImpl implements IProcessAndProcessGroupService { @Autowired private ProcessAndProcessGroupMapper processAndProcessGroupMapper; @Autowired private ProcessGroupMapper processGroupMapper; @Autowired private ProcessMapper processMapper; /** * Query ProcessAndProcessGroupList (parameter space-time non-paging) * * @param offset Number of pages * @param limit Number each page * @param param Search content * @return json */ @Override public String getProcessAndProcessGroupListPage(String username, boolean isAdmin, Integer offset, Integer limit, String param) { if (null == offset || null == limit) { return ReturnMapUtils.setFailedMsgRtnJsonStr(ReturnMapUtils.ERROR_MSG); } Page<Process> page = PageHelper.startPage(offset, limit,"crt_dttm desc"); if (isAdmin) { processAndProcessGroupMapper.getProcessAndProcessGroupList(param); } else { processAndProcessGroupMapper.getProcessAndProcessGroupListByUser(param, username); } Map<String, Object> rtnMap = ReturnMapUtils.setSucceededMsg(ReturnMapUtils.SUCCEEDED_MSG); rtnMap = PageHelperUtils.setLayTableParam(page, rtnMap); return JsonUtils.toJsonNoException(rtnMap); } /** * getAppInfoList * * @param taskAppIds task appId array * @param groupAppIds group appId array * @return json */ public String getAppInfoList(String[] taskAppIds, String[] groupAppIds) { if ((null == taskAppIds || taskAppIds.length <= 0) && (null == groupAppIds || groupAppIds.length <= 0)) { return ReturnMapUtils.setFailedMsgRtnJsonStr("Incoming parameter is null"); } Map<String, Object> rtnMap = ReturnMapUtils.setSucceededMsg(ReturnMapUtils.SUCCEEDED_MSG); if (null != taskAppIds && taskAppIds.length > 0) { Map<String, Object> taskAppInfoMap = new HashMap<>(); List<Process> processListByAppIDs = processMapper.getProcessListByAppIDs(taskAppIds); if (CollectionUtils.isNotEmpty(processListByAppIDs)){ for (Process process : processListByAppIDs) { ProcessVo processVo = ProcessUtils.processPoToVo(process); if (null == processVo) { continue; } taskAppInfoMap.put(processVo.getAppId(), processVo); } } rtnMap.put("taskAppInfo",taskAppInfoMap); } if (null != groupAppIds && groupAppIds.length > 0) { Map<String, Object> groupAppInfoMap = new HashMap<>(); List<ProcessGroup> processGroupListByAppIDs = processGroupMapper.getProcessGroupListByAppIDs(groupAppIds); if (CollectionUtils.isNotEmpty(processGroupListByAppIDs)) { for (ProcessGroup processGroup : processGroupListByAppIDs) { ProcessGroupVo processGroupVo = ProcessGroupUtils.processGroupPoToVo(processGroup); if (null == processGroupVo) { continue; } groupAppInfoMap.put(processGroupVo.getAppId(), processGroupVo); } } rtnMap.put("groupAppInfo",groupAppInfoMap); } return JsonUtils.toJsonNoException(rtnMap); } }
Java
CL
26188e4e18885fa6b29752992295c66841c243b919cb60fddd7a615abe76e0f6
/* Copyright (c) 2000-2022, Board of Trustees of Leland Stanford Jr. University Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lockss.plugin.ojs2; import java.io.InputStream; import org.htmlparser.NodeFilter; import org.htmlparser.filters.*; import org.lockss.daemon.PluginException; import org.lockss.filter.html.*; import org.lockss.plugin.*; public class OJS2HtmlCrawlFilterFactory implements FilterFactory { @Override public InputStream createFilteredInputStream(ArchivalUnit au, InputStream in, String encoding) throws PluginException { NodeFilter[] keepers = new NodeFilter[] { HtmlNodeFilters.tagWithAttribute("div", "id", "content"), HtmlNodeFilters.tag("img"), HtmlNodeFilters.tagWithAttribute("div", "id", "sidebarRTArticleTools") }; NodeFilter[] filters = new NodeFilter[] { // Some sidebars contain links to all other issue TOCs // e.g. http://ojs.statsbiblioteket.dk/index.php/bras/issue/view/1049 // Keep sidebar images (important logos) and article toolbox (printer-friendly link, etc.) HtmlNodeFilters.allExceptSubtree(HtmlNodeFilters.tagWithAttribute("div", "id", "sidebar"), new OrFilter(keepers)), // do not get links from navbar HtmlNodeFilters.tagWithAttribute("div", "id", "navbar"), // nor breadcrumbs HtmlNodeFilters.tagWithAttribute("div", "id", "breadcrumb"), // do not get links from references section HtmlNodeFilters.tagWithAttribute("div", "id", "articleCitations"), // do not get links that contain https?%25... HtmlNodeFilters.tagWithAttributeRegex("a", "href", "https?[%]25"), //Athabasca is now putting ALL issue volumes on the manifest page in the footer // see http://jrp.icaap.org/index.php/jrp/gateway/lockss?year=2018 HtmlNodeFilters.tagWithAttribute("div", "id", "pageFooter"), // ignore the setLocale urls, we dont want the other languages until they stop redirecting to the landing pages. HtmlNodeFilters.tagWithAttributeRegex("a", "href", "/user/setLocale") }; return new HtmlFilterInputStream(in, encoding, HtmlNodeFilterTransform.exclude(new OrFilter(filters))); } }
Java
CL
a9152f3fdcecc82daa79eef140ed2069822a764457758b7794b833dfbcd02911
package control; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.swing.Timer; import entity.actor.Monster; import entity.actor.Player; /** * Controller class to trigger actor events. * @author Milo * @since 7 April 2013 */ public class ActorController implements ActionListener { /** The player to control **/ private Player player; /** The monsters to control **/ private List<Monster> monsters = new LinkedList<Monster>(); /** The game to interact with **/ private final Game game; /** * The base time unit to tick, in milliseconds. * Actor speeds are in multiples of this. **/ private final int rate = 100; /** The timer to trigger actor events **/ private final Timer actorTimer = new Timer(rate, this); /** If the game is paused **/ public boolean paused = false; /** * Incremented every time the timer fires and triggers the correct actors. * In theory this could overflow if the game is left on for a very long time (i.e. 6 years at the current timer rate). **/ private int tickCount = 0; /** * Creates a new actor controller and starts the timer. * @param game - The game to interact with. */ public ActorController(Game game) { this.game = game; actorTimer.start(); } /** * Sets the player. * @param player - The player to control * @return this instance */ public ActorController withPlayer(Player player) { this.player = player; return this; } /** * Adds monsters to the control list * @param monsters - Monsters to control * @return this instance */ public ActorController withMonsters(Collection<Monster> monsters) { this.monsters.addAll(monsters); return this; } /** * Refreshes actor positions and checks if any actors should act. */ public void actionPerformed(ActionEvent event) { if (!paused) { if (tickCount % player.getSpeed() == 0) { player.act(); game.refreshActors(); } for (Monster monster : monsters) { if (monster.isActive() && tickCount % monster.getSpeed() == 0) { monster.act(); game.refreshActors(); } } tickCount++; } } /** * Prevents actors from acting until game is resumed. * @see resume() */ public void pause() { paused = true; } /** * Allows actors to act. * @see pause() */ public void resume() { paused = false; } }
Java
CL
976ba6273921f603148d191aaf5466817123dfe2a73c600f37965a9f14de351a
/** * Copyright 2016 LinkedIn Corp. All rights reserved. * * 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. */ package com.github.ambry.router; import com.github.ambry.clustermap.PartitionId; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.clustermap.ReplicaState; import com.github.ambry.commons.BlobId; import com.github.ambry.config.RouterConfig; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A implementation of {@link OperationTracker}. It internally maintains the status of a * corresponding operation, and returns information that decides if the operation should * continue or terminate. * * This implementation simplifies such that it unifies parallelism. That is, a single parallelism * parameter controls the maximum number of total allowed in-flight requests to both local and remote * replicas. This simplification is valid for PUT operation, yet a mature implementation will take * a more sophisticated control of parallelism in the future. * * This class assumes a request will be {@code succeeded, failed, or timedout} (which means failed). * So a deterministic response will be received in a definite time, and no request will pend forever. * When a request is timed out, it is considered as failed. * * A typical usage of an {@code SimpleOperationTracker} would be: *<pre> *{@code * * SimpleOperationTracker operationTracker = new SimpleOperationTracker(datacenterName, * partitionId, crossColoEnabled, successTarget, parallelism); * //... * Iterator<ReplicaId> itr = operationTracker.getReplicaIterator(); * while (itr.hasNext()) { * ReplicaId nextReplica = itr.next(); * //determine request can be sent to the replica, i.e., connection available. * if(true) { * itr.remove(); * } * } *} *</pre> * */ class SimpleOperationTracker implements OperationTracker { private static final Logger logger = LoggerFactory.getLogger(SimpleOperationTracker.class); private static final int NOT_FOUND_THRESHOLD_INVALID_VALUE = -1; protected final String datacenterName; protected final String originatingDcName; protected final int replicaSuccessTarget; protected final int replicaParallelism; // How many NotFound responses from originating dc will terminate the operation. protected int originatingDcNotFoundFailureThreshold = NOT_FOUND_THRESHOLD_INVALID_VALUE; protected final int totalReplicaCount; protected final LinkedList<ReplicaId> replicaPool = new LinkedList<>(); protected final NonBlockingRouterMetrics routerMetrics; private final OpTrackerIterator otIterator; private final RouterOperation routerOperation; private final PartitionId partitionId; private final RouterConfig routerConfig; protected int inflightCount = 0; protected int replicaSuccessCount = 0; protected List<ReplicaId> successReplica = new ArrayList<>(); protected int replicaInPoolOrFlightCount = 0; protected int failedCount = 0; protected int disabledCount = 0; protected int originatingDcNotFoundCount = 0; protected int totalNotFoundCount = 0; protected ReplicaId lastReturnedByIterator = null; private Iterator<ReplicaId> replicaIterator; private final Set<ReplicaId> originatingDcLeaderOrStandbyReplicas; private final int originatingDcTotalReplicaCount; private final Map<ReplicaState, List<ReplicaId>> allDcReplicasByState; private final BlobId blobId; // is that possible to run the offline repair? private boolean possibleRunOfflineRepair; /** * Constructor for an {@code SimpleOperationTracker}. In constructor, there is a config allowing operation tracker to * use eligible replicas to populate replica pool. ("eligible" replicas are those in required states for specific * operation) * Following are different types of operation and their eligible replica states: * --------------------------------------------------------- * | Operation Type | Eligible Replica State | * --------------------------------------------------------- * | PUT | STANDBY, LEADER | * | GET | STANDBY, LEADER, BOOTSTRAP, INACTIVE | * | DELETE | STANDBY, LEADER, BOOTSTRAP | * | TTLUpdate | STANDBY, LEADER, BOOTSTRAP | * | UNDELETE | STANDBY, LEADER, BOOTSTRAP | * --------------------------------------------------------- * Following are dynamic configs when replica state is taken into consideration: (N is number of eligible replicas) * ----------------------------------------------------------------------- * | Operation Type | Parallelism | Success Target | * ----------------------------------------------------------------------- * | GET | 1~2 decided by adaptive tracker | 1 | * | PUT | N | N - 1 | * | DELETE | 3~N | 2 | * | TTLUpdate | 3~N | 2 | * | UNDELETE | 3~N | Global Quorum | * ----------------------------------------------------------------------- * Note: for now, we still use 3 as parallelism for DELETE/TTLUpdate/UNDELETE even though there are N eligible replicas, this * can be adjusted to any number between 3 and N (inclusive) * For Undelete, it needs to reach global quorum to succeed. A dedicated operation tracker is created to check that. * @param routerConfig The {@link RouterConfig} containing the configs for operation tracker. * @param routerOperation The {@link RouterOperation} which {@link SimpleOperationTracker} is associated with. * @param partitionId The partition on which the operation is performed. * @param originatingDcName The original DC where blob was put. * @param shuffleReplicas Indicates if the replicas need to be shuffled. * @param routerMetrics The {@link NonBlockingRouterMetrics} to use. */ SimpleOperationTracker(RouterConfig routerConfig, RouterOperation routerOperation, PartitionId partitionId, String originatingDcName, boolean shuffleReplicas, NonBlockingRouterMetrics routerMetrics) { this(routerConfig, routerOperation, partitionId, originatingDcName, shuffleReplicas, routerMetrics, null); } /** * Constructor for an {@code SimpleOperationTracker}. In constructor, there is a config allowing operation tracker to * use eligible replicas to populate replica pool. ("eligible" replicas are those in required states for specific * operation) * Following are different types of operation and their eligible replica states: * --------------------------------------------------------- * | Operation Type | Eligible Replica State | * --------------------------------------------------------- * | PUT | STANDBY, LEADER | * | GET | STANDBY, LEADER, BOOTSTRAP, INACTIVE | * | DELETE | STANDBY, LEADER, BOOTSTRAP | * | TTLUpdate | STANDBY, LEADER, BOOTSTRAP | * | UNDELETE | STANDBY, LEADER, BOOTSTRAP | * --------------------------------------------------------- * Following are dynamic configs when replica state is taken into consideration: (N is number of eligible replicas) * ----------------------------------------------------------------------- * | Operation Type | Parallelism | Success Target | * ----------------------------------------------------------------------- * | GET | 1~2 decided by adaptive tracker | 1 | * | PUT | N | N - 1 | * | DELETE | 3~N | 2 | * | TTLUpdate | 3~N | 2 | * | UNDELETE | 3~N | Global Quorum | * ----------------------------------------------------------------------- * Note: for now, we still use 3 as parallelism for DELETE/TTLUpdate/UNDELETE even though there are N eligible replicas, this * can be adjusted to any number between 3 and N (inclusive) * For Undelete, it needs to reach global quorum to succeed. A dedicated operation tracker is created to check that. * @param routerConfig The {@link RouterConfig} containing the configs for operation tracker. * @param routerOperation The {@link RouterOperation} which {@link SimpleOperationTracker} is associated with. * @param partitionId The partition on which the operation is performed. * @param originatingDcName The original DC where blob was put. * @param shuffleReplicas Indicates if the replicas need to be shuffled. * @param routerMetrics The {@link NonBlockingRouterMetrics} to use. * @param blobId The {@link BlobId}, if available, for the operation. */ SimpleOperationTracker(RouterConfig routerConfig, RouterOperation routerOperation, PartitionId partitionId, String originatingDcName, boolean shuffleReplicas, NonBlockingRouterMetrics routerMetrics, BlobId blobId) { // populate tracker parameters based on operation type this.routerConfig = routerConfig; this.routerOperation = routerOperation; this.originatingDcName = originatingDcName; this.partitionId = partitionId; this.routerMetrics = routerMetrics; this.blobId = blobId; datacenterName = routerConfig.routerDatacenterName; // Note that we get a snapshot of replicas by state only once in this class, and use the same snapshot everywhere // to avoid the case where a replica state might change in between an operation. allDcReplicasByState = (Map<ReplicaState, List<ReplicaId>>) partitionId.getReplicaIdsByStates(EnumSet.allOf(ReplicaState.class), null); List<ReplicaId> eligibleReplicas; List<ReplicaId> offlineReplicas = new ArrayList<>(); // This is a list of all replicas for this partition. This comes from replica information updated by us in helix // Data node configs via bootstrap tool and not external view. This would be same as ideal view. List<ReplicaId> allReplicas = new ArrayList<>(partitionId.getReplicaIds()); boolean crossColoEnabled; switch (routerOperation) { case GetBlobOperation: case GetBlobInfoOperation: replicaSuccessTarget = routerConfig.routerGetSuccessTarget; replicaParallelism = routerConfig.routerGetRequestParallelism; crossColoEnabled = routerConfig.routerGetCrossDcEnabled; Map<ReplicaState, List<ReplicaId>> replicasByState = getReplicasByState(null, EnumSet.of(ReplicaState.BOOTSTRAP, ReplicaState.STANDBY, ReplicaState.LEADER, ReplicaState.INACTIVE, ReplicaState.OFFLINE)); offlineReplicas = replicasByState.getOrDefault(ReplicaState.OFFLINE, new ArrayList<>()); eligibleReplicas = new ArrayList<>(); replicasByState.values().forEach(eligibleReplicas::addAll); // Whether to add offline replicas to replica pool is controlled by "routerOperationTrackerIncludeDownReplicas" // config. For now, we remove them from eligible replica list. eligibleReplicas.removeAll(offlineReplicas); break; case PutOperation: eligibleReplicas = getEligibleReplicas(datacenterName, EnumSet.of(ReplicaState.STANDBY, ReplicaState.LEADER)); replicaSuccessTarget = routerConfig.routerGetEligibleReplicasByStateEnabled ? Math.max(eligibleReplicas.size() - 1, routerConfig.routerPutSuccessTarget) : routerConfig.routerPutSuccessTarget; replicaParallelism = routerConfig.routerGetEligibleReplicasByStateEnabled ? Math.min(eligibleReplicas.size(), routerConfig.routerPutRequestParallelism) : routerConfig.routerPutRequestParallelism; crossColoEnabled = false; break; case DeleteOperation: replicaSuccessTarget = routerConfig.routerDeleteSuccessTarget; replicaParallelism = routerConfig.routerDeleteRequestParallelism; crossColoEnabled = true; eligibleReplicas = getEligibleReplicas(null, EnumSet.of(ReplicaState.BOOTSTRAP, ReplicaState.STANDBY, ReplicaState.LEADER)); break; case TtlUpdateOperation: replicaSuccessTarget = routerConfig.routerTtlUpdateSuccessTarget; replicaParallelism = routerConfig.routerTtlUpdateRequestParallelism; crossColoEnabled = true; eligibleReplicas = getEligibleReplicas(null, EnumSet.of(ReplicaState.BOOTSTRAP, ReplicaState.STANDBY, ReplicaState.LEADER)); break; case UndeleteOperation: replicaParallelism = routerConfig.routerUndeleteRequestParallelism; crossColoEnabled = true; eligibleReplicas = getEligibleReplicas(null, EnumSet.of(ReplicaState.BOOTSTRAP, ReplicaState.STANDBY, ReplicaState.LEADER)); replicaSuccessTarget = routerConfig.routerUndeleteSuccessTarget; break; case ReplicateBlobOperation: // Replicate one blob. Unlike PutBlob, crossColoEnabled is true. // ON_DEMAND_REPLICATION_TODO: may tune the order of the replica pool. Currently still local first and then remote. // a. right now we pick local replicas first for simplicity. // b. Among the remote replicas, we randomly pick one. We don't pick the replication leader. eligibleReplicas = getEligibleReplicas(null, EnumSet.of(ReplicaState.STANDBY, ReplicaState.LEADER, ReplicaState.BOOTSTRAP)); replicaSuccessTarget = routerConfig.routerReplicateBlobSuccessTarget; replicaParallelism = routerConfig.routerReplicateBlobRequestParallelism; crossColoEnabled = true; break; default: throw new IllegalArgumentException("Unsupported operation: " + routerOperation); } if (replicaParallelism < 1) { throw new IllegalArgumentException( "Parallelism has to be > 0. Parallelism=" + replicaParallelism + ", routerOperation=" + routerOperation); } // Order the replicas so that local healthy replicas are ordered and returned first, // then the remote healthy ones, and finally the possibly down ones. List<? extends ReplicaId> replicas = routerConfig.routerGetEligibleReplicasByStateEnabled ? eligibleReplicas : new ArrayList<>(partitionId.getReplicaIds()); // In a case where a certain dc is decommissioned and blobs previously uploaded to this dc now have a unrecognizable // dc id. Current clustermap code will treat originating dc as null if dc id is not identifiable. To improve success // rate of cross-colo requests(GET/DELETE/TTLUpdate), operation tracker should be allowed to try remote dc with most // replicas first. This is useful in cluster with "unbalanced" replica distribution (i.e. 3 replicas in local dc and // 1 replica per remote dc) String reassignedOriginDc = null; if (originatingDcName == null && routerConfig.routerCrossColoRequestToDcWithMostReplicas) { Map<String, Long> dcToReplicaCnt = replicas.stream() .collect(Collectors.groupingBy(e -> e.getDataNodeId().getDatacenterName(), Collectors.counting())); List<Map.Entry<String, Long>> entryList = new ArrayList<>(dcToReplicaCnt.entrySet()); entryList.sort(Map.Entry.comparingByValue()); // we assign a dc with most replicas to "originatingDcName", which only takes effect when populating replica pool // (replicas in that colo have higher priority than other remote colos). Note that, "this.originatingDcName" still // keeps the actual originating dc name (which is null). This value forces operation tracker to go through replicas // in all dc(s) rather than terminating on not found in originating dc. reassignedOriginDc = entryList.get(entryList.size() - 1).getKey(); logger.debug("Originating dc name is null and has been re-assigned to {}", reassignedOriginDc); } LinkedList<ReplicaId> backupReplicas = new LinkedList<>(); LinkedList<ReplicaId> downReplicas = new LinkedList<>(); if (shuffleReplicas) { Collections.shuffle(replicas); } // The priority here is local dc replicas, originating dc replicas, other dc replicas, down replicas. // To improve read-after-write performance across DC, we prefer to take local and originating replicas only, // which can be done by setting includeNonOriginatingDcReplicas False. List<ReplicaId> examinedReplicas = new ArrayList<>(); originatingDcName = originatingDcName == null ? reassignedOriginDc : originatingDcName; int numLocalAndLiveReplicas = 0; for (ReplicaId replicaId : replicas) { examinedReplicas.add(replicaId); String replicaDcName = replicaId.getDataNodeId().getDatacenterName(); boolean isLocalDcReplica = replicaDcName.equals(datacenterName); boolean isOriginatingDcReplica = replicaDcName.equals(originatingDcName); if (!replicaId.isDown()) { if (isLocalDcReplica) { numLocalAndLiveReplicas++; addToBeginningOfPool(replicaId); } else if (crossColoEnabled && isOriginatingDcReplica) { addToEndOfPool(replicaId); } else if (crossColoEnabled) { backupReplicas.addFirst(replicaId); } } else { if (isLocalDcReplica) { downReplicas.addFirst(replicaId); } else if (crossColoEnabled) { downReplicas.addLast(replicaId); } } } List<ReplicaId> backupReplicasToCheck = new ArrayList<>(backupReplicas); List<ReplicaId> downReplicasToCheck = new ArrayList<>(downReplicas); // Add replicas that are neither in local dc nor in originating dc. backupReplicas.forEach(this::addToEndOfPool); if (routerConfig.routerOperationTrackerIncludeDownReplicas) { // Add those replicas deemed by native failure detector to be down downReplicas.forEach(this::addToEndOfPool); // Add those replicas deemed by Helix to be down (offline). This only applies to GET operation. // Adding this logic to mitigate situation where one or more Zookeeper clusters are suddenly unavailable while // ambry servers are still up. if (routerOperation == RouterOperation.GetBlobOperation || routerOperation == RouterOperation.GetBlobInfoOperation) { List<ReplicaId> remoteOfflineReplicas = new ArrayList<>(); for (ReplicaId replica : offlineReplicas) { if (replica.getDataNodeId().getDatacenterName().equals(datacenterName)) { addToEndOfPool(replica); } else { remoteOfflineReplicas.add(replica); } } remoteOfflineReplicas.forEach(this::addToEndOfPool); } } maybeDeprioritizeLocalBootstrapReplicas(numLocalAndLiveReplicas); totalReplicaCount = replicaPool.size(); // MockPartitionId.getReplicaIds() is returning a shared reference which may cause race condition. // Please report the test failure if you run into this exception. Supplier<IllegalArgumentException> notEnoughReplicasException = () -> new IllegalArgumentException( generateErrorMessage(partitionId, examinedReplicas, replicaPool, backupReplicasToCheck, downReplicasToCheck, routerOperation)); possibleRunOfflineRepair = possibleRunOfflineRepair(totalReplicaCount); if (totalReplicaCount < getSuccessTarget()) { if (possibleRunOfflineRepair) { logger.info("RepairRequest: Not enough quorum for delete but give it a try since offline repair is enabled {}", blobId); } else { throw notEnoughReplicasException.get(); } } originatingDcTotalReplicaCount = (int) allReplicas.stream() .filter(replicaId -> replicaId.getDataNodeId().getDatacenterName().equals(this.originatingDcName)) .count(); originatingDcLeaderOrStandbyReplicas = new HashSet<>( getEligibleReplicas(this.originatingDcName, EnumSet.of(ReplicaState.STANDBY, ReplicaState.LEADER))); originatingDcNotFoundFailureThreshold = routerConfig.routerOperationTrackerCheckAllOriginatingReplicasForNotFound ? originatingDcTotalReplicaCount : Math.max(originatingDcTotalReplicaCount - routerConfig.routerPutSuccessTarget + 1, 0); this.otIterator = new OpTrackerIterator(); logger.debug( "Router operation type: {}, successTarget = {}, parallelism = {}, originatingDcNotFoundFailureThreshold = {}, replicaPool = {}, originatingDC = {}", routerOperation, replicaSuccessTarget, replicaParallelism, originatingDcNotFoundFailureThreshold, replicaPool, originatingDcName); } /** * @param eligibleReplicaCount eligible replicas to send Delete Requests. * @return true if it's possible to run offline repair for the Delete */ public boolean possibleRunOfflineRepair(int eligibleReplicaCount) { // LOCAL_CONSISTENCY_TODO: after enabled TtlUpdate offline repair in TtlUpdateOperation, add the condition here. return (eligibleReplicaCount >= 1 && routerOperation == RouterOperation.DeleteOperation && routerConfig.routerDeleteOfflineRepairEnabled); } /** * The dynamic success target is introduced mainly for following use case: * In the intermediate state of "move replica", when decommission of old replicas is initiated(but hasn't transited to * INACTIVE yet), the PUT requests should be rejected on old replicas. For frontends, they are seeing both old and new * replicas(lets say 3 old and 3 new) and the success target should be 6 - 1 = 5. In the aforementioned scenario, PUT * request failed on 3 old replicas. It seems we should fail whole PUT operation because number of remaining requests * is already less than success target. * From another point of view, however, PUT request is highly likely to succeed on 3 new replicas and we actually * could consider it success without generating "slip put" (which makes PUT latency worse). The reason is, if new PUTs * already succeeded on at least 2 new replicas, read-after-write should always succeed because frontends are always * able to see new replicas and subsequent READ/DELETE/TtlUpdate request should succeed on at least 2 aforementioned * new replicas. */ @Override public boolean hasSucceeded() { boolean hasSucceeded; if (routerOperation == RouterOperation.PutOperation && routerConfig.routerPutUseDynamicSuccessTarget) { // this logic only applies to replicas where the quorum can change during replica movement int dynamicSuccessTarget = Math.max(totalReplicaCount - disabledCount - 1, routerConfig.routerPutSuccessTarget); hasSucceeded = replicaSuccessCount >= dynamicSuccessTarget; } else { hasSucceeded = replicaSuccessCount >= replicaSuccessTarget; } return hasSucceeded; } @Override public boolean hasFailedOnNotFound() { if (routerOperation == RouterOperation.PutOperation) { return false; } if (originatingDcName == null || replicaSuccessCount > 0) { return false; } if (originatingDcNotFoundFailureThreshold > 0 && originatingDcNotFoundCount >= originatingDcNotFoundFailureThreshold) { // If we get sufficient not found responses in originating DC, we can confirm that blob is not present in Ambry. logger.info("Terminating {} on {} due to Not_Found failure in originating DC {}, " + "NotFoundCount: {}, FailureThreshold: {}, TotalReplicaCount: {}, LeaderStandbyCount: {}, {}", routerOperation.name(), partitionId, originatingDcName, originatingDcNotFoundCount, originatingDcNotFoundFailureThreshold, originatingDcTotalReplicaCount, originatingDcLeaderOrStandbyReplicas.size(), getBlobIdLog()); routerMetrics.failedOnTotalNotFoundCount.inc(); return true; } return false; } @Override public boolean hasSomeUnavailability() { if (originatingDcName != null && originatingDcLeaderOrStandbyReplicas.size() < originatingDcTotalReplicaCount) { logger.info("{} on {} has some replicas unavailable in originating DC {}, TotalReplicaCount: {}," + "LeaderStandbyCount: {}, ReplicasByState: {}, {}", routerOperation.name(), partitionId, originatingDcName, originatingDcTotalReplicaCount, originatingDcLeaderOrStandbyReplicas.size(), allDcReplicasByState, getBlobIdLog()); routerMetrics.failedMaybeDueToUnavailableReplicasCount.inc(); return true; } return false; } @Override public boolean hasNotFound() { return totalNotFoundCount > 0; } @Override public List<ReplicaId> getSuccessReplica() { return successReplica; } @Override public int getSuccessCount() { return replicaSuccessCount; } @Override public boolean isDone() { return hasSucceeded() || hasFailed(); } @Override public void onResponse(ReplicaId replicaId, TrackedRequestFinalState trackedRequestFinalState) { inflightCount--; // once a response has been received, a replica is no longer in the pool or currently in flight. modifyReplicasInPoolOrInFlightCount(-1); switch (trackedRequestFinalState) { case SUCCESS: successReplica.add(replicaId); replicaSuccessCount++; break; // Request disabled may happen when PUT/DELETE/TTLUpdate requests attempt to perform on replicas that are being // decommissioned (i.e STANDBY -> INACTIVE). This is because decommission may take some time and frontends still // hold old view. Aforementioned requests are rejected by server with Temporarily_Disabled error. For DELETE/TTLUpdate, // even though we may receive such errors, the success target is still same(=2). For PUT, we have to adjust the // success target (quorum) to let some PUT operations (with at least 2 requests succeeded on new replicas) succeed. // Currently, disabledCount only applies to PUT operation. case REQUEST_DISABLED: disabledCount++; break; default: failedCount++; // NOT_FOUND is a special error. When tracker sees >= numReplicasInOriginatingDc - 1 "NOT_FOUND" from the // originating DC, we can be sure the operation will end up with a NOT_FOUND error. if (trackedRequestFinalState == TrackedRequestFinalState.NOT_FOUND) { totalNotFoundCount++; if (replicaId.getDataNodeId().getDatacenterName().equals(originatingDcName)) { if (originatingDcLeaderOrStandbyReplicas.contains(replicaId)) { // Since bootstrap replicas could still be catching up, treat NotFound responses only from leader or // standby replicas as valid. originatingDcNotFoundCount++; } } } } } @Override public Iterator<ReplicaId> getReplicaIterator() { replicaIterator = replicaPool.iterator(); return otIterator; } private class OpTrackerIterator implements Iterator<ReplicaId> { @Override public boolean hasNext() { return inflightCount < getCurrentParallelism() && replicaIterator.hasNext(); } @Override public void remove() { replicaIterator.remove(); inflightCount++; } @Override public ReplicaId next() { if (!hasNext()) { throw new NoSuchElementException(); } lastReturnedByIterator = replicaIterator.next(); return lastReturnedByIterator; } } /** * Get eligible replicas by states for the specified data center. If dcName is null, it gets all eligible * replicas from all data centers. * @param dcName the name of data center from which the replicas should come from. This can be {@code null}. * @param states a set of {@link ReplicaState}(s) that replicas should match. * @return a list of eligible replicas that are in specified states. */ private List<ReplicaId> getEligibleReplicas(String dcName, EnumSet<ReplicaState> states) { Map<ReplicaState, List<ReplicaId>> replicasByState = getReplicasByState(dcName, states); List<ReplicaId> eligibleReplicas = new ArrayList<>(); for (List<ReplicaId> replicas : replicasByState.values()) { eligibleReplicas.addAll(replicas); } return eligibleReplicas; } /** * Get replicas in required states for the specified datacenter. * @param dcName the name of data center from which the replicas should come from. This can be {@code null}. * @param states a set of {@link ReplicaState}(s) that replicas should match. * @return a map whose key is {@link ReplicaState} and value is a list of {@link ReplicaId}(s) in that state. */ Map<ReplicaState, List<ReplicaId>> getReplicasByState(String dcName, EnumSet<ReplicaState> states) { Map<ReplicaState, List<ReplicaId>> map = new HashMap<>(); for (ReplicaState replicaState : states) { if (allDcReplicasByState.containsKey(replicaState)) { for (ReplicaId replicaId : allDcReplicasByState.get(replicaState)) { if (dcName == null || replicaId.getDataNodeId().getDatacenterName().equals(dcName)) { map.putIfAbsent(replicaState, new ArrayList<>()); map.get(replicaState).add(replicaId); } } } } return map; } /** * Deprioritize bootstrap replicas in local dc if all conditions are satisfied. * @param numLocalAndLiveReplicas The number of live replicas in local dc. */ void maybeDeprioritizeLocalBootstrapReplicas(int numLocalAndLiveReplicas) { // we know local and live replicas are going to be put in frontend of the pool if (isGetOperation() && numLocalAndLiveReplicas > 1 && routerConfig.routerGetOperationDeprioritizeBootstrapReplicas) { List<ReplicaId> localAndLiveReplicas = new ArrayList<>(); localAndLiveReplicas.addAll(replicaPool.subList(0, numLocalAndLiveReplicas)); // Sort local and live replicas based on the replica state, bootstrap replicas // are going to be pushed back localAndLiveReplicas.sort((r1, r2) -> { ReplicaState rs1 = getReplicaState(r1); ReplicaState rs2 = getReplicaState(r2); if (rs1 == ReplicaState.BOOTSTRAP && rs2 == ReplicaState.BOOTSTRAP) { return 0; } else if (rs1 == ReplicaState.BOOTSTRAP || rs2 == ReplicaState.BOOTSTRAP) { // if rs1 is bootstrap, which means rs2 is not, then r2 should be smaller than r1 // so it can be prioritized. return rs1 == ReplicaState.BOOTSTRAP ? 1 : -1; } else { return 0; } }); ListIterator<ReplicaId> iter = replicaPool.listIterator(); for (ReplicaId replicaId : localAndLiveReplicas) { iter.next(); iter.set(replicaId); } } } public boolean hasFailed() { if (routerOperation == RouterOperation.PutOperation && routerConfig.routerPutUseDynamicSuccessTarget) { return totalReplicaCount - failedCount < Math.max(totalReplicaCount - 1, routerConfig.routerPutSuccessTarget + disabledCount); } else { // If blob is not found in originating DC, we can terminate the operation early. Adding // routerConfig.routerOperationTrackerTerminateOnNotFoundEnabled as a safe guard to search replicas in all colos // before terminating the operation. if (routerConfig.routerOperationTrackerTerminateOnNotFoundEnabled && hasFailedOnNotFound()) { return true; } // if there is no possible way to use the remaining replicas to meet the success target, // deem the operation a failure. // For Delete, even there is not enough quorum, if offline repair is enabled, continue to run it. if (possibleRunOfflineRepair) { logger.trace("RepairRequest: continue to run as long as we have replicas {}", blobId); return replicaInPoolOrFlightCount <= 0; } else { return replicaInPoolOrFlightCount + replicaSuccessCount < replicaSuccessTarget; } } } /** * Exposed for testing only. * @return the number of replicas in current replica pool. */ int getReplicaPoolSize() { return replicaPool.size(); } /** * Add a replica to the beginning of the replica pool linked list. * @param replicaId the replica to add. */ private void addToBeginningOfPool(ReplicaId replicaId) { modifyReplicasInPoolOrInFlightCount(1); replicaPool.addFirst(replicaId); } /** * Add a replica to the end of the replica pool linked list. * @param replicaId the replica to add. */ private void addToEndOfPool(ReplicaId replicaId) { modifyReplicasInPoolOrInFlightCount(1); replicaPool.addLast(replicaId); } /** * Add {@code delta} to a replicas in pool or in flight counter. * @param delta the value to add to the counter. */ private void modifyReplicasInPoolOrInFlightCount(int delta) { replicaInPoolOrFlightCount += delta; } /** * @return the success target number of this operation tracker for the provided replica type. */ int getSuccessTarget() { return replicaSuccessTarget; } /** * This method determines the current number of parallel requests to send, based on the last request sent out or the * first replica in the pool if this is the first request sent. * @return the parallelism setting to honor. */ int getCurrentParallelism() { return replicaParallelism; } /** * @return the number of requests that are temporarily disabled on certain replicas. */ int getDisabledCount() { return disabledCount; } /** * @return current failed count in this tracker */ int getFailedCount() { return failedCount; } /** * Returns string to for logging {@code BlobId}, if the blob id if not {@code null}. * @return string to for logging {@code BlobId}. Returns empty string if the blob id is {@code null}. */ private final String getBlobIdLog() { return (blobId == null) ? "" : String.format(", BlobId: %s", blobId.toString()); } /** * Helper function to catch a potential race condition in * {@link SimpleOperationTracker#SimpleOperationTracker(RouterConfig, RouterOperation, PartitionId, String, boolean, NonBlockingRouterMetrics)}. * @param partitionId The partition on which the operation is performed. * @param examinedReplicas All replicas examined. * @param replicaPool Replicas added to replicaPool. * @param backupReplicas Replicas added to backupReplicas. * @param downReplicas Replicas added to downReplicas. * @param routerOperation The operation type associated with current operation tracker. */ private static String generateErrorMessage(PartitionId partitionId, List<ReplicaId> examinedReplicas, List<ReplicaId> replicaPool, List<ReplicaId> backupReplicas, List<ReplicaId> downReplicas, RouterOperation routerOperation) { StringBuilder errMsg = new StringBuilder("Total Replica count ").append(replicaPool.size()) .append(" is less than success target. ") .append("Router operation is ") .append(routerOperation) .append(". Partition is ") .append(partitionId) .append(", partition class is ") .append(partitionId.getPartitionClass()) .append(" and associated resources are ") .append(partitionId.getResourceNames()) .append(". examinedReplicas: "); for (ReplicaId replicaId : examinedReplicas) { errMsg.append(replicaId.getDataNodeId()).append(":").append(replicaId.isDown()).append(" "); } errMsg.append("replicaPool: "); for (ReplicaId replicaId : replicaPool) { errMsg.append(replicaId.getDataNodeId()).append(":").append(replicaId.isDown()).append(" "); } errMsg.append("backupReplicas: "); for (ReplicaId replicaId : backupReplicas) { errMsg.append(replicaId.getDataNodeId()).append(":").append(replicaId.isDown()).append(" "); } errMsg.append("downReplicas: "); for (ReplicaId replicaId : downReplicas) { errMsg.append(replicaId.getDataNodeId()).append(":").append(replicaId.isDown()).append(" "); } return errMsg.toString(); } /** * @return True when router operation is a get operation */ private boolean isGetOperation() { return routerOperation == RouterOperation.GetBlobOperation || routerOperation == RouterOperation.GetBlobInfoOperation; } /** * Return the replica state for given replica id. * @param replicaId The replica id * @return Replica state for replica id. */ private ReplicaState getReplicaState(ReplicaId replicaId) { for (Map.Entry<ReplicaState, List<ReplicaId>> entry : allDcReplicasByState.entrySet()) { if (entry.getValue().contains(replicaId)) { return entry.getKey(); } } throw new IllegalStateException("ReplicaId " + replicaId + " can't find state in " + allDcReplicasByState); } }
Java
CL
8155d21df593815b10eda2af459a0856ac46567e5a556a5658830c144b45d3be
package fi.vm.sade.varda.rekisterointi.service; import com.github.kagkarlsson.scheduler.SchedulerClient; import com.github.kagkarlsson.scheduler.task.Task; import fi.vm.sade.varda.rekisterointi.model.*; import fi.vm.sade.varda.rekisterointi.repository.RekisterointiRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import java.util.Optional; import java.util.Set; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) public class RekisterointiFinalizerTest { private static final Kayttaja TESTI_KAYTTAJA = Kayttaja.builder() .asiointikieli("fi") .etunimi("Testi") .sukunimi("Henkilo") .sahkoposti("testi.henkilo@osoite.foo") .build(); @TestConfiguration static class Configuration { @Bean public RekisterointiFinalizer rekisterointiFinalizer(RekisterointiRepository rekisterointiRepository, RekisterointiOrganisaatioFinalizer rekisterointiOrgFinalizer, OrganisaatioKayttajaFinalizer kayttajaFinalizer, SchedulerClient schedulerClient, Task<Long> kutsuKayttajaTask, Task<Long> paatosEmailTask) { return new RekisterointiFinalizer(rekisterointiRepository, rekisterointiOrgFinalizer, kayttajaFinalizer, schedulerClient, kutsuKayttajaTask, paatosEmailTask); } } @MockBean private RekisterointiRepository rekisterointiRepository; @MockBean private RekisterointiOrganisaatioFinalizer rekisterointiOrgFinalizer; @MockBean private OrganisaatioKayttajaFinalizer kayttajaFinalizer; @MockBean private SchedulerClient schedulerClient; @MockBean(name = "kutsuKayttajaTask") private Task<Long> kutsuKayttajaTask; @MockBean(name = "paatosEmailTask") private Task<Long> paatosEmailTask; @Autowired private RekisterointiFinalizer rekisterointiFinalizer; @Test public void luoTaiPaivitaOrganisaatioTallentaaOidinJaAjastaaKutsun() { Organisaatio organisaatio = TestiOrganisaatio.organisaatio(null); Rekisterointi rekisterointi = Rekisterointi.of( organisaatio, "varda", "vardatoimintamuoto_tm01", Set.of("kunta_123"), Set.of("testi@osoite.foo"), TESTI_KAYTTAJA); when(rekisterointiRepository.findById(anyLong())).thenReturn(Optional.of(rekisterointi)); when(rekisterointiOrgFinalizer.luoTaiPaivitaOrganisaatio(any(Rekisterointi.class))).thenReturn("1.23.456"); rekisterointiFinalizer.luoTaiPaivitaOrganisaatio(1L); verify(rekisterointiRepository).save(any(Rekisterointi.class)); verify(kutsuKayttajaTask).instance(anyString(), anyLong()); verify(schedulerClient).schedule(any(), any()); } @Test public void luoTaiPaivitaOrganisaatioAjastaaKutsun() { Organisaatio organisaatio = TestiOrganisaatio.organisaatio("1.23.456"); Rekisterointi rekisterointi = Rekisterointi.of( organisaatio, "varda", "vardatoimintamuoto_tm01", Set.of("kunta_123"), Set.of("testi@osoite.foo"), TESTI_KAYTTAJA); when(rekisterointiRepository.findById(anyLong())).thenReturn(Optional.of(rekisterointi)); when(rekisterointiOrgFinalizer.luoTaiPaivitaOrganisaatio(any(Rekisterointi.class))) .thenReturn(organisaatio.oid); rekisterointiFinalizer.luoTaiPaivitaOrganisaatio(1L); verify(rekisterointiRepository, never()).save(any(Rekisterointi.class)); verify(kutsuKayttajaTask).instance(anyString(), anyLong()); verify(schedulerClient).schedule(any(), any()); } @Test public void kutsuKayttajaAjastaaEmailin() { Organisaatio organisaatio = TestiOrganisaatio.organisaatio(null); Rekisterointi rekisterointi = Rekisterointi.of( organisaatio, "varda", "vardatoimintamuoto_tm01", Set.of("kunta_123"), Set.of("testi@osoite.foo"), TESTI_KAYTTAJA); when(rekisterointiRepository.findById(anyLong())).thenReturn(Optional.of(rekisterointi)); rekisterointiFinalizer.kutsuKayttaja(1L); verify(kayttajaFinalizer).kutsuKayttaja(rekisterointi); verify(paatosEmailTask).instance(anyString(), anyLong()); verify(schedulerClient).schedule(any(), any()); } }
Java
CL
9e3827d8414f5ddc4e97f545df34f898f2657d2764da1cb627ff6573ece14e61
package com.wxplatform.controller; import com.wxplatform.pojo.GroupMember; import com.wxplatform.service.WxMemberInfoService; import common.beans.ResultBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /*后台控制器*/ @RestController @RequestMapping("/wxbackstage") public class InfoController { @Autowired WxMemberInfoService wxMemberInfoService; /** * @ClassName:selectMember * @Description: 遍历用户个人信息 * @Author: zhijie * @CreateDate: 2018/11/24 15:11 * @RequestMethod:get * @Param [currentPage] * @Return [groupMember] */ @RequestMapping(value="selectmemberlist", method = RequestMethod.GET) public ResultBean selectMember(@RequestParam("currentPage") Integer currentPage) { return new ResultBean(wxMemberInfoService.selectAllMember(currentPage)); } @RequestMapping(value="selectmemberlistbydepartment", method = RequestMethod.POST) public ResultBean selectMemberByDepartment(@RequestParam("department") Integer department) { return new ResultBean(wxMemberInfoService.selectMemberInfoByDepartment(department)); } /** * @ClassName:updateMemberStatus * @Description: 若审核通过,则改变用户的状态 * @Author: zhijie * @CreateDate: 2018/11/24 15:3 * @RequestMethod:post * @Param [openid] * @Return [code] */ @RequestMapping(value = "updatamemberstatus", method = RequestMethod.POST) public ResultBean<Integer> updateMemberStatus(GroupMember groupMember, @RequestParam("openid") String openid) { return new ResultBean<Integer>(wxMemberInfoService.updataMemberInfoByPrimaryKey(groupMember, openid)); } /** * @ClassName:deleteMemberInfo * @Description: 删除用户个人信息 * @Author: zhijie * @CreateDate: 2018/11/24 15:15 * @RequestMethod:post * @Param [openid] * @Return [code] */ @RequestMapping(value = "deletemembermnfo", method = RequestMethod.POST) public ResultBean<Integer> deleteMemberInfo(@RequestParam("openid") String openid) { return new ResultBean<Integer>(wxMemberInfoService.intdeleteMemberInfoByPrimaryKey(openid)); } }
Java
CL
14ef0ff5e9760c28c65c3f8e47407f4e2ad07cf51d064457c281f3c0af15c386
/* * The MIT License * * Copyright 2020 Y.K. Chan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jacobi.core.spatial.rtree; import java.util.Arrays; import java.util.List; /** * Data object for a serialized siblings layer in a R-Tree. * * <p>A layer consists of a cuts array and a bounds array. The cuts array is the sequence of * the ending index for each node in the underlying layer. The bounds array is the sequence of * axis-aligned bounding boxes for each node, with a minimum and maximum for each dimension.</p> * * @author Y.K Chan * */ public class RLayer { /** * Construct a layer by combining nodes in an another layer * @param cover Array of number of nodes in each groups * @param layer Underlying layer * @return Combined layer */ public static RLayer coverOf(int[] cover, RLayer layer){ int width = 0; for(int i = 0; i < cover.length; i++){ if(cover[i] < 1){ throw new IllegalArgumentException("Invalid cover #" + i + ": " + cover[i]); } width += cover[i]; } if(width != layer.length()){ throw new IllegalArgumentException("Grouping " + Arrays.toString(cover) + " is not a cover of the layer " + Arrays.toString(layer.cuts)); } int[] cuts = new int[cover.length]; int aabbLen = 2 * layer.dim(); double[] bounds = new double[aabbLen * cover.length]; int index = 0; for(int i = 0; i < cover.length; i++){ double[] aabb = layer.mbbOf(index, cover[i]); System.arraycopy(aabb, 0, bounds, i * aabbLen, aabbLen); index += cover[i]; cuts[i] = index; } return new RLayer(cuts, bounds); } /** * Construct a layer by combining spatial vectors * @param cover Array of number of nodes in each groups * @param vectors List of vectors * @return R-Layer */ public static RLayer coverOf(int[] cover, List<double[]> vectors) { if(vectors.isEmpty()){ return new RLayer(cover, new double[0]); } int numDim = vectors.get(0).length; int[] cuts = new int[cover.length]; double[] bounds = new double[2 * numDim * cover.length]; int begin = 0; for(int i = 0; i < cover.length; i++){ if(cover[i] < 1){ throw new IllegalArgumentException("Invalid span " + cover[i] + " at #" + i); } double[] mbb = RLayer.mbbOf(vectors.subList(begin, begin + cover[i])); if(mbb.length != 2 * numDim){ throw new IllegalArgumentException("Dimension mismatch"); } System.arraycopy(mbb, 0, bounds, i * mbb.length, mbb.length); begin += cover[i]; cuts[i] = begin; } return new RLayer(cuts, bounds); } /** * Span array */ public final int[] cuts; /** * Bound array. */ public final double[] bounds; /** * Constructor * @param cuts Array of spans * @param bounds Array of bounds */ protected RLayer(int[] cuts, double[] bounds) { this.cuts = cuts; this.bounds = bounds; } /** * Get the number of dimensions of the axis-aligned bounded boxes * @return Number of dimensions */ public int dim() { return this.bounds.length / 2 / this.cuts.length; } /** * Get the number of nodes of this layer * @return Number of nodes */ public int length() { return this.cuts.length; } /** * Compute the minimum axis-aligned bounded box of a range of aabbs. * @param layer R-Layer * @param index Starting index of aabb * @param span Number of aabb to be included * @return Mbb of the range of aabbs */ public double[] mbbOf(int index, int span) { int mbbLen = 2 * this.dim(); double[] mbb = Arrays.copyOfRange(this.bounds, index * mbbLen, (index + 1) * mbbLen); for(int i = 1; i < span; i++){ int begin = (index + i) * mbbLen; for(int j = 0; j < mbbLen; j += 2){ if(mbb[j] > this.bounds[begin + j]){ mbb[j] = this.bounds[begin + j]; } if(mbb[j + 1] < this.bounds[begin + j + 1]){ mbb[j + 1] = this.bounds[begin + j + 1]; } } } return mbb; } /** * Compute the minimum axis-aligned bounded box of a list of vectors. * @param vectors List of vectors * @return Mbb of a list of vectors */ private static double[] mbbOf(List<double[]> vectors) { double[] first = vectors.get(0); int numDim = first.length; double[] mbb = new double[2 * numDim]; for(int i = 0; i < mbb.length; i++){ mbb[i] = first[i / 2]; } for(int i = 1; i < vectors.size(); i++){ double[] vector = vectors.get(i); if(vector.length != numDim){ throw new IllegalArgumentException("Dimension mismatch."); } for(int j = 0; j < vector.length; j++){ double x = vector[j]; if(mbb[2 * j] > x){ mbb[2 * j] = x; } if(mbb[2 * j + 1] < x){ mbb[2 * j + 1] = x; } } } return mbb; } }
Java
CL
ef29dc77a427b7a4a78c26045fd7f75638ce375663229d738b71e5f690aee948
package heuristic; import java.util.function.ToDoubleFunction; import javax.annotation.Nonnull; import optimization.algorithm.IOptimizationAlgorithm; import optimization.decoder.IDecoder; import optimization.fittnesEvaluator.IFitnessEvaluator; import optimization.solution.ISolution; import optimization.solution.neighborhood.INeighborGenerator; import optimization.stopper.IOptimisationStopper; /** * Generic greedy algorithm implementation. </br> * This can be used for a iterative greedy search. </br> * */ public class GreedyAlgorithm<I,T extends ISolution<T>> implements IOptimizationAlgorithm<T> { private final @Nonnull IDecoder<T,I> decoder; private final @Nonnull IFitnessEvaluator<T> evaluator; private final @Nonnull INeighborGenerator<T> neighborhood; private final @Nonnull T startSolution; private final @Nonnull ToDoubleFunction<I> function; private final @Nonnull IOptimisationStopper<T> stopper; public GreedyAlgorithm(IDecoder<T,I> decoder, INeighborGenerator<T> neighborhood, IFitnessEvaluator<T> evaluator, IOptimisationStopper<T> stopper,ToDoubleFunction<I> function, T startSolution) { this.decoder = decoder; this.evaluator = evaluator; this.neighborhood = neighborhood; this.stopper = stopper; this.startSolution = startSolution; this.function = function; } @Override public @Nonnull T run() { T solution = startSolution; double solutionValue = function.applyAsDouble(decoder.decode(solution)); double solutionFitness = evaluator.evaluate(solution, solutionValue); T neighbor = solution.clone(); do{ neighborhood.randomNeighbor(solution,neighbor); double neighborValue = function.applyAsDouble(decoder.decode(neighbor)); double neighborFitness = evaluator.evaluate(neighbor, neighborValue); if(neighborFitness>=solutionFitness){ T solutionSwapHelp = solution; solution = neighbor; solutionValue = neighborValue; solutionFitness = neighborFitness; neighbor = solutionSwapHelp; } //neighbor was changed (mutated or is solution) and should be reset neighbor.copy(solution); }while(!stopper.shouldStop(solution, solutionFitness, solutionValue)); return solution; } }
Java
CL
ed337983946172f9ba7a6607180b7c230dd21a49670f252bdb3878a1d62f4b19
package com.demo.bankingapi.service; import com.demo.bankingapi.entity.Account; import com.demo.bankingapi.entity.Currency; import com.demo.bankingapi.entity.Transaction; import com.demo.bankingapi.repository.TransactionRepository; import com.demo.bankingapi.resource.TransactionResource; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class TransactionServiceTest { @InjectMocks private TransactionService transactionService; @Mock private TransactionRepository transactionRepository; @Mock private ConversionService conversionService; private final EasyRandom generator = new EasyRandom(); @Test void getTransactions() { Long accountNumber = 1L; Transaction.Type type = Transaction.Type.TRANSFER; LocalDateTime from = LocalDateTime.MIN; LocalDateTime to = LocalDateTime.MAX; Pageable pageable = PageRequest.of(5, 10, Sort.Direction.ASC, "createdAt"); // given List<Transaction> transactions = generator.objects(Transaction.class, 5).collect(Collectors.toUnmodifiableList()); when(transactionRepository.findAllByAccount_AccountNumberAndTypeAndCreatedAtBetween( accountNumber, type, from, to, pageable)) .thenReturn(new PageImpl<>(transactions)); // when transactionService.getTransactions(accountNumber, type, from, to, pageable); // then verify(conversionService, times(5)).convert(any(Transaction.class), eq(TransactionResource.class)); } @Test void createDepositTransactions() { // given Account account = generator.nextObject(Account.class); ArgumentCaptor<Transaction> transactionArgumentCaptor = ArgumentCaptor.forClass(Transaction.class); // when transactionService.createDepositTransactions(account, new BigDecimal("100.00"), Currency.GBP); // then verify(transactionRepository).save(transactionArgumentCaptor.capture()); Transaction transaction = transactionArgumentCaptor.getValue(); assertEquals(new BigDecimal("100.00"), transaction.getBalance()); assertEquals(Currency.GBP, transaction.getCurrency()); assertEquals(account, transaction.getAccount()); } @Test void createTransferTransactions() { // given Account from = generator.nextObject(Account.class); from.setBalance(new BigDecimal("3.00")); Account to = generator.nextObject(Account.class); to.setBalance(new BigDecimal("30.00")); ArgumentCaptor<Transaction> transactionArgumentCaptor = ArgumentCaptor.forClass(Transaction.class); // when transactionService.createTransferTransactions(from, to, new BigDecimal("100.00"), Currency.GBP); // then verify(transactionRepository, times(2)).save(transactionArgumentCaptor.capture()); List<Transaction> transactions = transactionArgumentCaptor.getAllValues(); assertEquals(new BigDecimal("3.00"), transactions.get(0).getBalance()); assertEquals(Currency.GBP, transactions.get(0).getCurrency()); assertEquals(from, transactions.get(0).getAccount()); assertEquals(BigDecimal.ZERO, transactions.get(0).getInAmount()); assertEquals(new BigDecimal("100.00"), transactions.get(0).getOutAmount()); assertEquals(new BigDecimal("30.00"), transactions.get(1).getBalance()); assertEquals(Currency.GBP, transactions.get(1).getCurrency()); assertEquals(to, transactions.get(1).getAccount()); assertEquals(new BigDecimal("100.00"), transactions.get(1).getInAmount()); assertEquals(BigDecimal.ZERO, transactions.get(1).getOutAmount()); } }
Java
CL
8f95538ea2f132bb99cc50019e03497839d1ba28a63fd08a2b983181c2743c0f
/* * 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.apache.camel.examples; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CamelConfiguration extends RouteBuilder { private static final Logger log = LoggerFactory.getLogger(CamelConfiguration.class); @Autowired private ApiProperties apiProperties; @Override public void configure() throws Exception { fromF("cxfrs:%s?bindingStyle=SimpleConsumer&resourceClasses=org.apache.camel.examples.api.PetApi,org.apache.camel.examples.api.StoreApi,org.apache.camel.examples.api.UserApi&features=#cxfFeatures&providers=#cxfProviders", apiProperties.getBasePath()) .description("petStoreApi", "Swagger Pet Store API", null) .routingSlip(simple("direct:${headers[operationName]}")) ; from("direct:getPetById") .log(LoggingLevel.INFO, log, "Getting pet by ID: [${headers[petId]}]") .to("sql:select * from PET, CATEGORY, PET_TAG_ASS, TAG, PET_PHOTO_ASS, PHOTO where PET.ID=:#petId and PET.CATEGORY_ID=CATEGORY.ID and PET.ID=PET_TAG_ASS.PET_ID and PET_TAG_ASS.TAG_ID=TAG.ID and PET.ID=PET_PHOTO_ASS.PET_ID and PET_PHOTO_ASS.PHOTO_ID=PHOTO.ID?dataSource=#dataSource&outputType=SelectList") .filter() .simple("${body} == ${null} || ${body.empty}") .log("Pet [${headers[petId]}] not found") .setHeader(Exchange.HTTP_RESPONSE_CODE).constant("404") .setHeader(Exchange.HTTP_RESPONSE_TEXT).constant("Pet not found") .stop() .end() .log("Pet [${headers[petId]}] found") .transform().groovy("resource:classpath:/META-INF/groovy/SqlResultToPet.groovy") ; from("direct:findPetsByTags") .log(LoggingLevel.INFO, log, "Getting pet by tags: [${headers[tags]}]") .filter() .simple("${headers[tags]} == ${null} || ${headers[tags].empty} || ${headers[tags]} == ''") .log("No tags provided") .setHeader(Exchange.HTTP_RESPONSE_CODE).constant("400") .setHeader(Exchange.HTTP_RESPONSE_TEXT).constant("Invalid tag value") .stop() .end() .setHeader("tags").groovy("request.headers['tags'].collect() { it.toLowerCase() }") .to("sql:select * from PET, CATEGORY, PET_TAG_ASS, TAG, PET_PHOTO_ASS, PHOTO where TAG.LTAG_NAME in (:#in:tags) and PET.CATEGORY_ID=CATEGORY.ID and PET.ID=PET_TAG_ASS.PET_ID and PET_TAG_ASS.TAG_ID=TAG.ID and PET.ID=PET_PHOTO_ASS.PET_ID and PET_PHOTO_ASS.PHOTO_ID=PHOTO.ID?dataSource=#dataSource&outputType=SelectList") .filter() .simple("${body} == ${null} || ${body.empty}") .log("Pets with tags [${headers[tags]}] not found") .setHeader(Exchange.HTTP_RESPONSE_TEXT).constant(null) .stop() .end() .log("Pets with tags [${headers[tags]}] found") .transform().groovy("request.body.groupBy() { it['ID'] }.values()") .split(body()).aggregationStrategyRef("listOfPetAggregationStrategy") .transform().groovy("resource:classpath:/META-INF/groovy/SqlResultToPet.groovy") .end() ; from("direct:findPetsByStatus") .log(LoggingLevel.INFO, log, "Getting pet by status: [${headers[status]}]") .filter() .simple("${headers[status]} == ${null} || ${headers[status].empty} || ${headers[status]} == ''") .log("No status provided") .setHeader(Exchange.HTTP_RESPONSE_CODE).constant("400") .setHeader(Exchange.HTTP_RESPONSE_TEXT).constant("Invalid status value") .stop() .end() .setHeader("status") .groovy("request.headers['status'].collect() { it.toLowerCase() }") .to("sql:select * from PET, CATEGORY, PET_TAG_ASS, TAG, PET_PHOTO_ASS, PHOTO where PET.STATUS in (:#in:status) and PET.CATEGORY_ID=CATEGORY.ID and PET.ID=PET_TAG_ASS.PET_ID and PET_TAG_ASS.TAG_ID=TAG.ID and PET.ID=PET_PHOTO_ASS.PET_ID and PET_PHOTO_ASS.PHOTO_ID=PHOTO.ID?dataSource=#dataSource&outputType=SelectList") .filter() .simple("${body} == ${null} || ${body.empty}") .log("Pets with status [${headers[status]}] not found") .setHeader(Exchange.HTTP_RESPONSE_TEXT).constant(null) .stop() .end() .log("Pets with status [${headers[status]}] found") .transform().groovy("request.body.groupBy() { it['ID'] }.values()") .split(body()).aggregationStrategyRef("listOfPetAggregationStrategy") .transform().groovy("resource:classpath:/META-INF/groovy/SqlResultToPet.groovy") .end() ; } }
Java
CL
0d15f2e234795c6bba4f6469cd453e1910da3072a55aa5ec21071fa156a00fa1
package com.example.recyclerview; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.example.recyclerview.DAO.BookViewModel; import com.example.recyclerview.recycleAdapters.GoogleBookAdapter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FavoritesFragment extends Fragment { BookViewModel bookViewModel; private static final String LOG = FavoritesFragment.class.getSimpleName(); private static final int LOADER_ID = 3; private RecyclerView mRecyclerView; private ArrayList<Book> mBooksData; View rootView; GoogleBookAdapter googleBookAdapter; RelativeLayout emptyViews; public FavoritesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_favorites, container, false); emptyViews = rootView.findViewById(R.id.empty_view); mRecyclerView = rootView.findViewById(R.id.favorites); // Set the Layout Manager. mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); rootView.findViewById((R.id.empty_view)).setVisibility(View.VISIBLE); bookViewModel = ViewModelProviders.of(this).get(BookViewModel.class); bookViewModel.getmAllBooks().observe(getActivity(), new Observer<List<Book>>() { @Override public void onChanged(@Nullable List<Book> books) { if (books != null) { rootView.findViewById((R.id.empty_view)).setVisibility(View.GONE); } mBooksData = (ArrayList<Book>) books; googleBookAdapter = new GoogleBookAdapter(getContext(), (ArrayList<Book>) books); mRecyclerView.setAdapter(googleBookAdapter); } }); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(( new ItemTouchHelper.SimpleCallback(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.DOWN | ItemTouchHelper.UP, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int from = viewHolder.getAdapterPosition(); int to = target.getAdapterPosition(); Collections.swap(mBooksData, from, to); googleBookAdapter.notifyItemMoved(from, to); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) { bookViewModel.delete(mBooksData.get(viewHolder.getAdapterPosition())); mBooksData.remove(viewHolder.getAdapterPosition()); //to allow the RecyclerView to animate the deletion properly, you must also call notifyItemRemoved() googleBookAdapter.notifyItemRemoved(viewHolder.getAdapterPosition()); } })); itemTouchHelper.attachToRecyclerView(mRecyclerView); setHasOptionsMenu(true); return rootView; } @Override // This method initialize the contents of the Activity's options menu public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.search, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_search) { Intent intent = new Intent(getContext(), GoogleBookActivity.class); this.startActivity(intent); } return super.onOptionsItemSelected(item); } }
Java
CL
78c520ddbdbd32add813cf81f59d0901c4b2b94c15bccab0035058904ee211e0
package life.qbic.infrastructure.event.deserialization; import life.qbic.domain.sample.SampleEvent; /** * Provides factory methods for event deserializers. * * @since 2.0.0 */ public class EventDeserializerFactory { public static EventDeserializer<SampleEvent> sampleEventDeserializer() { return new SampleEventDeserializer(); } }
Java
CL
c6c8c6fc60cffcdc2045524294f5d0cdf1d2e1ab02559e2ef750b6b4076632b0
package com.free.fasttools.service.formatTool.serviceImpl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.free.fasttools.dto.formatTool.FormatToolDTO; import com.free.fasttools.global.Global; import com.free.fasttools.global.TradeCode; import com.free.fasttools.service.formatTool.service.FormatService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.StringWriter; /** * @Auther: zhengwei * @Date: 2018/12/3 21:28 * @Description: 格式转化service */ @Service public class FormatServiceImpl implements FormatService { private static final Logger logger= LoggerFactory.getLogger(FormatServiceImpl.class); @Override public JSONObject getFormatResult(FormatToolDTO dto) { String formatJson= Global.EMPTY; JSONObject json=null; try{ if(Global.TYPE_JSON.equalsIgnoreCase(dto.getType())){ formatJson=toPrettyFormat(dto.getInputVal()); }else if(Global.TYPE_XML.equalsIgnoreCase(dto.getType())){ formatJson=xmlFormat(dto.getInputVal()); } dto.setErrMsg(TradeCode.TRADE_SUCCESS.getMessage()); dto.setResultVal(formatJson); json=(JSONObject)JSON.toJSON(dto); json.put(Global.SUCCESS,true); }catch (Exception e){ logger.error("格式化出错:{}",e.getMessage()); dto.setResultVal(e.getMessage()); dto.setErrMsg(TradeCode.TRADE_FORMAT_ERROR.getMessage()); json=(JSONObject)JSON.toJSON(dto); json.put(Global.SUCCESS,false); } return json; } /** * 使用gson进行json格式化 * @param json * @return */ private String toPrettyFormat(String json)throws Exception{ JsonParser jsonParser = new JsonParser(); json=json.replaceAll("\\\\\"","").replaceAll("\r|\n", ""); if(json.startsWith("\"")&&json.endsWith("\"")){ json=json.substring(1,json.length()-1); } JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(jsonObject); } private String xmlFormat(String json)throws Exception{ Document document = null; document = DocumentHelper.parseText(json); /** * 格式化输出格式 */ OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(Global.UTF8); StringWriter writer = new StringWriter(); /** * 格式化输出流 */ XMLWriter xmlWriter = new XMLWriter(writer, format); /** * 将document写入到输出流 */ xmlWriter.write(document); xmlWriter.close(); return writer.toString(); } }
Java
CL
51a675f790068dbc28e2800aa549d69dcd65a2fe3b342807a8c107cc62139426
package mobile.che.com.oddymobstar.chemobile.util; import android.database.Cursor; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import mobile.che.com.oddymobstar.chemobile.database.DBHelper; import mobile.che.com.oddymobstar.chemobile.model.Config; /** * Created by root on 27/02/15. */ public class Configuration implements Serializable { /* we hold the static configs here. we hold them in database as there values can change */ public final static String PORT = "PORT"; public final static String URL = "URL"; public final static String PLAYER_KEY = "PLAYER_KEY"; public final static String PLAYER_NAME = "PLAYER_NAME"; public final static String UUID_ALGORITHM = "UUID_ALGO"; public final static String SSL_ALGORITHM = "SSL_ALGO"; public final static String CURRENT_UTM_LONG = "CURRENT_UTM_LONG"; public final static String CURRENT_SUBUTM_LONG = "CURRENT_SUBUTM_LONG"; public final static String CURRENT_UTM_LAT = "CURRENT_UTM_LAT"; public final static String CURRENT_SUBUTM_LAT = "CURRENT_SUBUTM_LAT"; public final static String CURRENT_LATITUTDE = "CURRENT_LATITUDE"; public final static String CURRENT_LONGITUDE = "CURRENT_LONGITUDE"; //need to actuall glamourize this so its in minutes, not milliseconds. public final static String GPS_UPDATE_INTERVAL = "GPS_UPDATE_INTERVAL"; //technically we do not need these in the database...but we may add them. //also need mappers to control the values....some are checkboxes. but we need to store settings public final static String SERVER_LOCATION_HIDE = "LOCATION_HIDE"; public final static String RESET_SOCKET = "RESET_SOCKET"; public final static String CLEAR_BACKLOG = "CLEAR_BACKLOG"; public final static String START_PURCHASE_INFA = "FREE_INFRA"; public final static String START_PURCHASE_LAND = "FREE_LAND"; public final static String START_PURCHASE_AIR = "FREE_AIR"; public final static String START_PURCHASE_MISSILE = "FREE_MISSILE"; public final static String START_PURCHASE_SEA = "FREE_SEA"; //Need last server contact. public final static String CURRENT_SUBUTM = "CURRENT_SUBUTM"; /* we will also need other configs, ie security types...enough to get going tho. */ private Map<String, Config> configs = new HashMap<String, Config>(); public Configuration(Cursor cursor) { /* load whatever configs we have. we need to add in some base ones on the create method. */ while (cursor.moveToNext()) { Config config = new Config(cursor); configs.put(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.CONFIG_NAME)), config); } cursor.close(); } public Map<String, Config> getConfigs() { return configs; } public Config getConfig(String key) { return configs.get(key); } }
Java
CL
aee9f4ddd2fec4b098dcb89e4fe40cae33162bd1790eb61c4b33ab4bcf4e4d14
package hostileworlds; import hostileworlds.ai.WorldDirectorMultiDim; import hostileworlds.commands.CommandHW; import hostileworlds.config.ModConfigFields; import hostileworlds.dimension.HWDimensionManager; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import modconfig.ConfigMod; import net.minecraft.block.Block; import net.minecraft.command.ServerCommandManager; import net.minecraft.entity.Entity; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.MinecraftForge; import CoroUtil.IChunkLoader; import CoroUtil.util.CoroUtilFile; import com.google.common.collect.Lists; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerAboutToStartEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStoppedEvent; import cpw.mods.fml.common.network.FMLEventChannel; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.relauncher.Side; @Mod(modid = "HostileWorlds", name="Hostile Worlds", version="0.5.0", useMetadata=false) public class HostileWorlds { @Mod.Instance( value = "HostileWorlds" ) public static HostileWorlds instance; public static String modID = "hostileworlds"; @SidedProxy(clientSide = "hostileworlds.ClientProxy", serverSide = "hostileworlds.CommonProxy") public static CommonProxy proxy; public static Block blockAuraCurse; public static Block blockSourceInvasion; public static Block blockBloodyCobblestone; public static Block blockSourceStructure; //public static BlockHWPortal blockPortal; //public static Block blockRaidingLadder; //public static Block blockRaidingLadderBase; //public static Block blockItemTurret; //public static Block blockFactory; public static List<Block> blocksList = new ArrayList<Block>(); //public static Block blockRtsBuilding; //public static Item itemLaserBeam; public static int texBloodCobble; public static boolean initProperNeededForWorld = true; public static String eventChannelName = "hostileworlds"; public static final FMLEventChannel eventChannel = NetworkRegistry.INSTANCE.newEventDrivenChannel(eventChannelName); @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { ConfigMod.addConfigFile(event, "hw", new ModConfigFields()); //ConfigMod.addConfigFile(event, "hwblocks", new ModConfigBlockFields(), false); //config.init(event); //generateConfigFile(); //updateSaveFile(); //test(); } @Mod.EventHandler public void load(FMLInitializationEvent event) { eventChannel.register(new EventHandlerPacket()); MinecraftForge.EVENT_BUS.register(new HWEventHandler()); FMLCommonHandler.instance().bus().register(new EventHandlerFML()); //NetworkRegistry.instance().registerConnectionHandler(new ConnectionHandler()); //NetworkRegistry.instance().registerGuiHandler(this, new GuiHandler()); /*dimIDCatacombs = DimensionManager.getNextFreeDimId(); DimensionManager.registerProviderType(dimIDCatacombs, HWWorldProvider.class, false); DimensionManager.registerDimension(dimIDCatacombs, dimIDCatacombs);*/ proxy.init(this); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { ForgeChunkManager.setForcedChunkLoadingCallback(instance, new PortalChunkloadCallback()); } public class PortalChunkloadCallback implements ForgeChunkManager.OrderedLoadingCallback { @Override public void ticketsLoaded(List<Ticket> tickets, World world) { for (Ticket ticket : tickets) { Entity ent = ticket.getEntity(); if (ent == null) { int portalX = ticket.getModData().getInteger("portalX"); int portalY = ticket.getModData().getInteger("portalY"); int portalZ = ticket.getModData().getInteger("portalZ"); if (portalY >= 0) { TileEntity te = world.getTileEntity(portalX, portalY, portalZ); if (te instanceof IChunkLoader) { ((IChunkLoader) te).setChunkTicket(ticket); ((IChunkLoader) te).forceChunkLoading(portalX/16, portalZ/16); } } } else if (ent instanceof IChunkLoader) { dbg("world load readd IChunkLoader chunkloader"); ((IChunkLoader) ent).setChunkTicket(ticket); ((IChunkLoader) ent).forceChunkLoading(ent.chunkCoordX, ent.chunkCoordZ); } } } @Override public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount) { List<Ticket> validTickets = Lists.newArrayList(); for (Ticket ticket : tickets) { Entity ent = ticket.getEntity(); if (ent == null) { int portalX = ticket.getModData().getInteger("portalX"); int portalY = ticket.getModData().getInteger("portalY"); int portalZ = ticket.getModData().getInteger("portalZ"); TileEntity te = world.getTileEntity(portalX, portalY, portalZ); if (te instanceof IChunkLoader) { validTickets.add(ticket); } /*int blId = world.getBlockId(portalX, portalY, portalZ); if (blId == blockPortal.blockID) { validTickets.add(ticket); }*/ } else if (ent instanceof IChunkLoader) { validTickets.add(ticket); } } return validTickets; } } public HostileWorlds() { int hm = 0; //TickRegistry.registerTickHandler(new ServerTickHandler(this), Side.SERVER); } @Mod.EventHandler public void serverAboutToStart(FMLServerAboutToStartEvent event) { //so it inits before entity nbt does } @Mod.EventHandler public void serverStart(FMLServerStartedEvent event) { ((ServerCommandManager)FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager()).registerCommand(new CommandHW()); //proper command adding //((ServerCommandManager) MinecraftServer.getServer().getCommandManager()).registerCommand(new commandAddOwner()); } @Mod.EventHandler public void serverStop(FMLServerStoppedEvent event) { writeGameNBT(); //HWDimensionManager.unregisterDimensionsAndSave(); //ServerTickHandler.rts.writeToFile(true); initProperNeededForWorld = true; } public static void initTry() { if (initProperNeededForWorld) { initProperNeededForWorld = false; //if (ServerTickHandler.rts == null) ServerTickHandler.rts = new RtsEngine(); //ServerTickHandler.rts.readFromFile(); CoroUtilFile.getWorldFolderName(); //make it cache the lastWorldFolder, lucky that it was cached before, as serverStop method cant update the cache, issue arrised due to new use of FMLServerAboutToStartEvent HWDimensionManager.loadAndRegisterDimensions(); } } /*public static String lastWorldFolder = ""; public static String getWorldFolderName() { World world = DimensionManager.getWorld(0); if (world != null) { lastWorldFolder = ((WorldServer)world).getChunkSaveLocation().getName(); return lastWorldFolder + File.separator; } return lastWorldFolder + File.separator; } public static String getSaveFolderPath() { if (MinecraftServer.getServer() == null || MinecraftServer.getServer().isSinglePlayer()) { return getClientSidePath() + File.separator; } else { return new File(".").getAbsolutePath() + File.separator; } } public static String getWorldSaveFolderPath() { if (MinecraftServer.getServer() == null || MinecraftServer.getServer().isSinglePlayer()) { return getClientSidePath() + File.separator + "saves" + File.separator; } else { return new File(".").getAbsolutePath() + File.separator; } } @SideOnly(Side.CLIENT) public static String getClientSidePath() { return FMLClientHandler.instance().getClient().mcDataDir.getPath(); }*/ public static void writeGameNBT() { if (FMLCommonHandler.instance().getEffectiveSide() != Side.SERVER) return; dbg("Saving Hostile Worlds data"); NBTTagCompound gameData = new NBTTagCompound(); try { HWDimensionManager.writeNBT(gameData); String saveFolder = CoroUtilFile.getWorldSaveFolderPath() + CoroUtilFile.getWorldFolderName(); //Write out to file FileOutputStream fos = new FileOutputStream(saveFolder + "HostileWorlds.dat"); CompressedStreamTools.writeCompressed(gameData, fos); fos.close(); WorldDirectorMultiDim.writeAllPlayerNBT(); } catch (Exception ex) { ex.printStackTrace(); } } public static void readGameNBT() { dbg("Reading Hostile Worlds data"); NBTTagCompound gameData = null; HWDimensionManager.registeredDimensions.clear(); try { String saveFolder = CoroUtilFile.getWorldSaveFolderPath() + CoroUtilFile.getWorldFolderName(); if ((new File(saveFolder + "HostileWorlds.dat")).exists()) { gameData = CompressedStreamTools.readCompressed(new FileInputStream(saveFolder + "HostileWorlds.dat")); //NBTTagList var14 = gameData.getTagList("playerData"); HWDimensionManager.readNBT(gameData); } //dont read in player nbt, its read in on demand } catch (Exception ex) { ex.printStackTrace(); } } public static void writeChunkCoords(String prefix, ChunkCoordinates coords, NBTTagCompound nbt) { nbt.setInteger(prefix + "X", coords.posX); nbt.setInteger(prefix + "Y", coords.posY); nbt.setInteger(prefix + "Z", coords.posZ); } public static ChunkCoordinates readChunkCoords(String prefix, NBTTagCompound nbt) { return new ChunkCoordinates(nbt.getInteger(prefix + "X"), nbt.getInteger(prefix + "Y"), nbt.getInteger(prefix + "Z")); } public static void dbg(Object obj) { if (ModConfigFields.debugConsoleOutput) { //MinecraftServer.getServer().getLogAgent().logInfo(String.valueOf(obj)); System.out.println(obj); } } }
Java
CL
07ba1fa285182879acd8b5b27bf8f7a2426164a19d6ba9fc98f2e5dd8e43204e
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.api.component; import org.mule.api.MuleEvent; import org.mule.api.MuleException; import org.mule.api.MuleMessage; import org.mule.api.lifecycle.Lifecycle; import org.mule.api.routing.InboundRouterCollection; import org.mule.api.service.Service; import org.mule.management.stats.ComponentStatistics; /** * A <code>Component</code> is a invoked by a {@link Service} for each incoming * {@link MuleEvent} routed on by the {@link InboundRouterCollection}. A component * processes a {@link MuleEvent} by invoking the component instance that has been * configured, optionally returning a result. <p/> Implementations of * <code>Component</code> can use different types of component implementation, * implement component instance pooling or implement <em>bindings</em> which allow * for service composition. */ public interface Component extends Lifecycle { /** * Invokes the component * * @param event the event used to invoke the component * @return the return event from the component * @throws MuleException if the call fails */ MuleMessage invoke(MuleEvent event) throws MuleException; /** * Component statistics are used to gather component statistics such as * sync/async invocation counts and total and average execution time. */ ComponentStatistics getStatistics(); void setService(Service service); Service getService(); }
Java
CL
65764a9cc44a4c1a0270bbf57212d3122f78a825a05313a293d6f949e791e7e6
package com.cuketest.reporting.cukeframework.steps; import com.cuketest.reporting.cukeframework.fixtures.ClientFixture; import com.google.inject.Inject; public class ClientSteps { private ClientFixture clientFixture; @Inject public ClientSteps(ClientFixture fixture) { clientFixture = fixture; } // @When("^\"(.*?)\" requests the \"(.*?)\" report to be run with values$") // public void requests_the_report_be_run_with_values(String user, String reportName, DataTable arg3) throws Throwable { // throw new PendingException(); // } // // @Then("^the response should be a unique report id \"(.*?)\"$") // public void the_response_should_be_a_unique_report_id(String internalReportRef) throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } // // @When("^\"(.*?)\" requests report \"(.*?)\"$") // public void requests_report(String userName, String reportName) throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } // // @Then("^the response will indicate it is \"(.*?)\"$") // public void the_response_will_indicate_it_is(String expectedResponse) throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } // // @Then("^the response will contain the report body$") // public void the_response_will_contain_the_report_body() throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } // // @Given("^that report \"(.*?)\" has been requested by user \"(.*?)\"$") // public void that_report_has_been_requested_by_user(String reportName, String arg2) throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } // // @Then("^the response message will be \"(.*?)\"$") // public void the_response_message_will_be(String arg1) throws Throwable { // // Write code here that turns the phrase above into concrete actions // throw new PendingException(); // } }
Java
CL
c11c9b66d4335ebcbda15ff1b000e57be93d213f6d74af31827a3f53ab866902
package com.msucil.hadoop.wordcount.v1; import com.msucil.hadoop.wordcount.WordCountReducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * Created by msucil on 4/21/18. */ public class WordCountTest { @Test public void processWordCount() throws IOException { MapReduceDriver<LongWritable, Text, Text, IntWritable, Text, IntWritable> mapReduceDriver = MapReduceDriver.newMapReduceDriver(new WordCountMapper(), new WordCountReducer()); Text input = new Text("Hello BigData Hadoop"); mapReduceDriver.withInput(new LongWritable(0), input) .withAllOutput(Arrays.asList( new Pair<>(new Text("BigData"), new IntWritable(1)), new Pair<>(new Text("Hadoop"), new IntWritable(1)), new Pair<>(new Text("Hello"), new IntWritable(1))) ) .runTest(); } @Test public void processWordCountOnLocalData() throws Exception { final Configuration config = new Configuration(); config.set("fs.defaultFS", "local"); config.set("mapreduce.framework.name", "local"); config.setInt("mapreduce.task.io.sort.mb", 1); final Path input = new Path("input/wordcount/wordcount.txt"); final Path outout = new Path("output"); final FileSystem fs = FileSystem.getLocal(config); fs.delete(outout, true); final WordCount wordCount = new WordCount(); wordCount.setConf(config); int exitCode = wordCount.run(new String[]{input.toString(), outout.toString()}); assertEquals(exitCode, 0); } }
Java
CL
8915cdec1efe541a32e4ddc3ab7b163f716e80c7779ee90c4c3b542707271cc3
package uk.co.resilientdatasystems.thtkya.config; import java.sql.SQLException; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.jdbc.datasource.init.ScriptException; import org.springframework.stereotype.Component; @Component public class SampleDatabasePopulator { private final static Logger log = LoggerFactory.getLogger(SampleDatabasePopulator.class); private final DataSource dataSource; @Autowired public SampleDatabasePopulator(DataSource dataSource) { this.dataSource = dataSource; } @PostConstruct public void populateData() throws ScriptException, SQLException { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(new ClassPathResource("quotes.sql")); populator.addScript(new ClassPathResource("stats.sql")); populator.populate(dataSource.getConnection()); log.info("Populated DB with sample data"); } }
Java
CL
0a46c85938b282a411c64b0c554d8bade4cdf36db0d4067d12377fe91d23d1bf
/* * This file is part of BlueMap, licensed under the MIT License (MIT). * * Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.bluecolored.bluemap.core.resourcepack.blockmodel; import com.flowpowered.math.vector.Vector2f; import de.bluecolored.bluemap.core.util.math.MatrixM3f; public class TransformedBlockModelResource { private final Vector2f rotation; private final boolean uvLock; private final BlockModelResource model; private final boolean hasRotation; private final MatrixM3f rotationMatrix; public TransformedBlockModelResource(Vector2f rotation, boolean uvLock, BlockModelResource model) { this.model = model; this.rotation = rotation; this.uvLock = uvLock; this.hasRotation = !rotation.equals(Vector2f.ZERO); this.rotationMatrix = new MatrixM3f() .rotate( -rotation.getX(), -rotation.getY(), 0 ); } public Vector2f getRotation() { return rotation; } public boolean hasRotation() { return hasRotation; } public MatrixM3f getRotationMatrix() { return rotationMatrix; } public boolean isUVLock() { return uvLock; } public BlockModelResource getModel() { return model; } }
Java
CL
28dcbd1fef3dbd28d6f725134a0bf1ccf2247d5af6cfb50e2abfc02fcf81583b
package com.nedap.archie.archetypevalidator.validations; import com.nedap.archie.aom.AuthoredArchetype; import com.nedap.archie.aom.ResourceDescriptionItem; import com.nedap.archie.aom.TranslationDetails; import com.nedap.archie.archetypevalidator.ArchetypeValidationBase; import com.nedap.archie.archetypevalidator.ErrorType; import org.openehr.utils.message.I18n; import java.util.Objects; public class AuthoredArchetypeMetadataChecks extends ArchetypeValidationBase { public AuthoredArchetypeMetadataChecks() { super(); } @Override public void validate() { if(archetype instanceof AuthoredArchetype) { AuthoredArchetype authoredArchetype = (AuthoredArchetype) archetype; checkOriginalLanguagePresent(); checkAdlRmVersionIdFormats(); validateDescription(); if(this.hasPassed()) { checkLanguagesInTranslationAreInTerminology(); } } } private void validateDescription() { if(archetype.getDescription().getDetails() != null) { for(String language:archetype.getDescription().getDetails().keySet()) { ResourceDescriptionItem resourceDescriptionItem = archetype.getDescription().getDetails().get(language); if(resourceDescriptionItem.getLanguage() == null || !Objects.equals(language, resourceDescriptionItem.getLanguage().getCodeString())){ addMessage(ErrorType.VRDLA, I18n.t("Resource description language {0} has an incorrect key: {1}", language, resourceDescriptionItem.getLanguage() == null ? null : resourceDescriptionItem.getLanguage().getCodeString())); } } } } private void checkLanguagesInTranslationAreInTerminology() { if(archetype.getTranslations() != null) { for(String language:archetype.getTranslations().keySet()) { TranslationDetails translationDetails = archetype.getTranslations().get(language); if(translationDetails.getLanguage() == null || !language.equals(translationDetails.getLanguage().getCodeString())) { addMessage(ErrorType.VTRLA, I18n.t("Translation details language {0} has an incorrect key: {1}", language, translationDetails.getLanguage().getCodeString())); } //check if also defined in terminology if(archetype.getTerminology() == null || archetype.getTerminology().getTermDefinitions() == null || archetype.getTerminology().getTermDefinitions().get(language) == null) { addMessage(ErrorType.VOTM, I18n.t("Language {0} is defined in the translations, but is not present in the terminology", language)); } } } } private void checkAdlRmVersionIdFormats() { if(!isValidVersion(archetype.getAdlVersion())) { addMessage(ErrorType.VARAV, I18n.t("ADL version {0} is an invalid format for a version, should be x.x.x-(rc|alpha(x)?)?", archetype.getAdlVersion())); } if(!isValidVersion(archetype.getRmRelease())) { addMessage(ErrorType.VARRV, I18n.t("RM Release version {0} is an invalid format for a version, should be x.x.x-(rc|alpha(x)?)?", archetype.getRmRelease())); } } private void checkOriginalLanguagePresent() { if(archetype.getOriginalLanguage() != null) { String languageCode = archetype.getOriginalLanguage().getCodeString();; if(languageCode != null) { if(archetype.getTerminology().getTermDefinitions().get(languageCode) == null) { addMessage(ErrorType.VOLT, I18n.t("Original language {0} is not defined in the terminology", languageCode)); } } } else { addMessage(ErrorType.VDEOL, I18n.t("Original language is missing in archetype")); } } private boolean isValidVersion(String version) { //from grammar: DIGIT+ '.' DIGIT+ '.' DIGIT+ ( ( '-rc' | '-alpha' ) ( '.' DIGIT+ )? )? ; return version != null && version.matches("\\d+\\.\\d+\\.\\d+((-rc|-alpha)(\\.\\d+)?)?"); } }
Java
CL
6671618769915effbb6db725e87d8ae73fedfd39a337916483ec5a65122a6f7e
package com.wp.wpqa_81_check_for_Ad_units_TOH; import org.apache.log4j.Logger; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.wp.genericLib.ConfigFileReader; import com.wp.genericLib.Constant; import com.wp.genericLib.Driver; import com.wp.genericLib.ExcelLibrary; import com.wp.genericLib.WebDriverCommonLib; import com.wp.pageObjectRepo.GlobalFunctions; public class VerifyAdUnitsIn_TOH_HomePage extends Driver { //Initialize object using page factory method ConfigFileReader configFileReader; public Logger APPLICATION_LOGS = Logger.getLogger("AppLogger"); //Test Data String url=Constant.TOH_HomePage+"?showads=1"; String adStackID=ExcelLibrary.getExcelData("AdUnits", 1, 3); String platform=ExcelLibrary.getExcelData("AdUnits", 1, 4); String template=ExcelLibrary.getExcelData("AdUnits", 1, 5); @BeforeClass public void navigateToRequiredURL() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Step:1 Navigate required URL globalPage.navigateToRequiredSite(url); //Step: 2 Scroll to the end of page globalPage.scrollDownPage(); //Step:3 switch to iFrame //globalPage.switchToFrame(); } @Test public void Verify_Prearticle_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 6); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_oop_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 9); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } /*@Test public void Verify_rail_1_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 26); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_rail_2_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 27); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_rail_3_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 28); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_rail_4_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 29); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_rail_5_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 30); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_rail_6_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 31); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } */ @Test public void Verify_content_1_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 11); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_content_2_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 12); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } /*@Test public void Verify_content_3_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 13); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_content_4_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 14); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_content_5_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 15); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); } @Test public void Verify_content_6_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Data: String adUnit=ExcelLibrary.getExcelData("AdUnits", 1, 16); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verifyAdUnitsInAdSlots(url, adStackID, platform, template, adUnit); }*/ @Test public void Verify_Duplicate_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.Verify_Duplicate_Adunits(url); } @Test public void Verify_Incorrect_Order_AdUnit_In_TOH_HomePage() throws Exception{ //Object Initialization GlobalFunctions globalPage=PageFactory.initElements(driver, GlobalFunctions.class); //Test Steps: //Step:3 Verify Key Value attribute present globalPage.verify_InCorrect_Order_AdUnits(url); } }
Java
CL
f2aa8f7e48fa66811eedbf63a324db48b622c890b554efc543f3bfb6b0bd7fed
package io.flutter.plugins; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin; public final class MyPluginRegistrant{ /*public static void registerWith(PluginRegistry registry) { if (alreadyRegisteredWith(registry)) { return; } FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")); } private static boolean alreadyRegisteredWith(PluginRegistry registry) { final String key = FirebaseMessagingPlugin.class.getCanonicalName(); if (registry.hasPlugin(key)) { return true; } registry.registrarFor(key); return false; }*/ public static void registerWith(PluginRegistry registry){ io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin")); io.flutter.plugins.firebaseauth.FirebaseAuthPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebaseauth.FirebaseAuthPlugin")); io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin.registerWith(registry.registrarFor("io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin")); com.baseflow.geolocator.GeolocatorPlugin.registerWith(registry.registrarFor("com.baseflow.geolocator.GeolocatorPlugin")); com.baseflow.googleapiavailability.GoogleApiAvailabilityPlugin.registerWith(registry.registrarFor("com.baseflow.googleapiavailability.GoogleApiAvailabilityPlugin")); io.flutter.plugins.googlemaps.GoogleMapsPlugin.registerWith(registry.registrarFor("io.flutter.plugins.googlemaps.GoogleMapsPlugin")); com.lyokone.location.LocationPlugin.registerWith(registry.registrarFor("com.lyokone.location.LocationPlugin")); com.baseflow.location_permissions.LocationPermissionsPlugin.registerWith(registry.registrarFor("com.baseflow.location_permissions.LocationPermissionsPlugin")); io.flutter.plugins.firebase.core.FirebaseCorePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.core.FirebaseCorePlugin")); io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")); io.flutter.plugins.firebasemlvision.FirebaseMlVisionPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemlvision.FirebaseMlVisionPlugin")); io.flutter.plugins.firebase.storage.FirebaseStoragePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.storage.FirebaseStoragePlugin")); io.flutter.plugins.imagepicker.ImagePickerPlugin.registerWith(registry.registrarFor("io.flutter.plugins.imagepicker.ImagePickerPlugin")); io.flutter.plugins.pathprovider.PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin")); io.flutter.plugins.urllauncher.UrlLauncherPlugin.registerWith(registry.registrarFor("io.flutter.plugins.urllauncher.UrlLauncherPlugin")); } }
Java
CL
ab1c0c881360f98d1b8de121c8fb9fe5b06b63586f7685431702878b4e3fb196
/* * Copyright 2019 Jonathan Chang, Chun-yien <ccy@musicapoetica.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 tech.metacontext.ocnhfa.cf_composer.enums; import java.util.function.Predicate; import tech.metacontext.ocnhfa.cf_composer.ex.UnexpectedMusicNodeException; import tech.metacontext.ocnhfa.cf_composer.ex.UnexpectedMusicThoughtException; import tech.metacontext.ocnhfa.cf_composer.model.MusicThread; import tech.metacontext.ocnhfa.cf_composer.model.x.MusicNode; import tech.metacontext.ocnhfa.cf_composer.model.y.PitchPath; /** * * @author Jonathan Chang, Chun-yien <ccy@musicapoetica.org> */ public enum MusicThought { Directional_Conjunct, Directional_Disjunct, Complemental_ShortTerm, Complemental_LongTerm, NULL; public static final MusicNode START = new MusicNode("Start"); public static final MusicNode DIRECTIONAL = new MusicNode("Directional"); public static final MusicNode COMPLEMENTAL = new MusicNode("Complemental"); public static final MusicNode CONJUNCT = new MusicNode("Conjunct"); public static final MusicNode DISJUNCT = new MusicNode("Disjunct"); public static final MusicNode SHORTTERM = new MusicNode("ShortTerm"); public static final MusicNode LONGTERM = new MusicNode("LongTerm"); public static MusicNode getNode(String name) { return switch (name) { case "Start"-> START; case "Directional"-> DIRECTIONAL; case "Complemental"-> COMPLEMENTAL; case "Conjunct"-> CONJUNCT; case "Disjunct"-> DISJUNCT; case "ShortTerm"-> SHORTTERM; case "LongTerm"-> LONGTERM; default-> throw new UnexpectedMusicThoughtException(name); }; } public Predicate<PitchPath> getPredicate(MusicThread thread) { return path -> thread.getCf().size() > 1 ? switch (this) { case Directional_Conjunct: yield (thread.lastPitchDirection() > 0 && Pitch.diff(path) == 2) || (thread.lastPitchDirection() < 0 && Pitch.diff(path) == -2); case Directional_Disjunct: yield (thread.lastPitchDirection() > 0 && Pitch.diff(path) > 2) || (thread.lastPitchDirection() < 0 && Pitch.diff(path) < -2); case Complemental_LongTerm: if (thread.lastPitchLevel() != 0) yield (thread.lastPitchLevel() > 0 && Pitch.diff(path) < 0) || (thread.lastPitchLevel() < 0 && Pitch.diff(path) > 0); case Complemental_ShortTerm: yield (thread.lastPitchDirection() > 0 && Pitch.diff(path) < 0) || (thread.lastPitchDirection() < 0 && Pitch.diff(path) > 0); default: yield true; } : switch (this) { case Directional_Conjunct-> Pitch.diff(path) == 2 || Pitch.diff(path) == -2; case Directional_Disjunct-> Pitch.diff(path) > 2 || Pitch.diff(path) < -2; default-> true; }; } public static MusicThought getInstance(MusicNode node1, MusicNode node2) throws UnexpectedMusicNodeException { switch (node1.getName()) { case "Directional": switch (node2.getName()) { case "Conjunct": return Directional_Conjunct; case "Disjunct": return Directional_Disjunct; } case "Complemental": switch (node2.getName()) { case "ShortTerm": return Complemental_ShortTerm; case "LongTerm": return Complemental_LongTerm; } } throw new UnexpectedMusicNodeException(node1, node2); } }
Java
CL
237a007b1c1c6c4dca36d5cad34b0489b44cc549c183bd21c4981a17d7f8f10f
package org.russianpost.operationhistory; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.8 * Generated source version: 2.2 * */ @WebServiceClient(name = "OperationHistory12", targetNamespace = "http://russianpost.org/operationhistory", wsdlLocation = "https://tracking.russianpost.ru/rtm34?wsdl") public class OperationHistory12_Service extends Service { private final static URL OPERATIONHISTORY12_WSDL_LOCATION; private final static WebServiceException OPERATIONHISTORY12_EXCEPTION; private final static QName OPERATIONHISTORY12_QNAME = new QName("http://russianpost.org/operationhistory", "OperationHistory12"); static { URL url = null; WebServiceException e = null; try { url = new URL("https://tracking.russianpost.ru/rtm34?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } OPERATIONHISTORY12_WSDL_LOCATION = url; OPERATIONHISTORY12_EXCEPTION = e; } public OperationHistory12_Service() { super(__getWsdlLocation(), OPERATIONHISTORY12_QNAME); } public OperationHistory12_Service(WebServiceFeature... features) { super(__getWsdlLocation(), OPERATIONHISTORY12_QNAME, features); } public OperationHistory12_Service(URL wsdlLocation) { super(wsdlLocation, OPERATIONHISTORY12_QNAME); } public OperationHistory12_Service(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, OPERATIONHISTORY12_QNAME, features); } public OperationHistory12_Service(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public OperationHistory12_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns OperationHistory12 */ @WebEndpoint(name = "OperationHistory12Port") public OperationHistory12 getOperationHistory12Port() { return super.getPort(new QName("http://russianpost.org/operationhistory", "OperationHistory12Port"), OperationHistory12.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns OperationHistory12 */ @WebEndpoint(name = "OperationHistory12Port") public OperationHistory12 getOperationHistory12Port(WebServiceFeature... features) { return super.getPort(new QName("http://russianpost.org/operationhistory", "OperationHistory12Port"), OperationHistory12.class, features); } private static URL __getWsdlLocation() { if (OPERATIONHISTORY12_EXCEPTION!= null) { throw OPERATIONHISTORY12_EXCEPTION; } return OPERATIONHISTORY12_WSDL_LOCATION; } }
Java
CL
57725c39c450fbee6daff49616a308bf8bc87da43f3aaeb78991b5ce9519d7ac
package tonegod.emitter.influencers; import com.jme3.util.SafeArrayList; import org.jetbrains.annotations.NotNull; import tonegod.emitter.interpolation.Interpolation; /** * The interface for implementing interpolated particle influencers. * * @author JavaSaBr */ public interface InterpolatedParticleInfluencer<D> extends ParticleInfluencer<D> { /** * Get the count of interpolation steps. * * @return the count of interpolation steps. */ int getStepCount(); /** * Get an interpolation for the step. * * @param index the index of the step. * @return the interpolation for the step. * @throws RuntimeException if the index is invalid. */ @NotNull Interpolation getInterpolation(int index) throws RuntimeException; /** * Update a interpolation for the index. * * @param interpolation the new interpolation. * @param index the index. * @throws RuntimeException if the index is invalid. */ void updateInterpolation(@NotNull Interpolation interpolation, int index) throws RuntimeException; /** * Get the list of all exists interpolations. * * @return the list of interpolations. */ @NotNull SafeArrayList<Interpolation> getInterpolations(); /** * Is cycle boolean. * * @return true if using cycle changing. */ boolean isCycle(); /** * Returns the current duration used between frames for cycled animation * * @return the fixed duration */ float getFixedDuration(); /** * Animated texture should cycle and use the provided duration between frames (0 diables * cycling) * * @param fixedDuration duration between frame updates */ void setFixedDuration(float fixedDuration); }
Java
CL
6dd16d0b1240db0a22447c1c4bfe760921bdc4291681e3ed1de8565e509b5566
package com.example.proyectopdm.Audio; import android.app.Activity; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.proyectopdm.R; import java.io.IOException; public class ReproducirAudio extends AppCompatActivity { private Context mContext; private Activity mActivity; private Button mButtonPlay; private Button mButtonStop; private SeekBar mSeekBar; private TextView mPass; private TextView mDuration; private TextView mDue; private MediaPlayer mPlayer; private Handler mHandler; private Runnable mRunnable; Uri videoUri; String uri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.reproduciraudio); // Get the application context mContext = getApplicationContext(); mActivity = ReproducirAudio.this; uri = getIntent().getStringExtra("Aduio"); videoUri = Uri.parse(uri); // Get the widget reference from xml layout mButtonPlay = findViewById(R.id.btn_play); mButtonStop = findViewById(R.id.btn_stop); mSeekBar = findViewById(R.id.seek_bar); mPass = findViewById(R.id.tv_pass); mDuration = findViewById(R.id.tv_duration); mDue = findViewById(R.id.tv_due); // Initialize the handler mHandler = new Handler(); // Click listener for playing button mButtonPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // If media player another instance already running then stop it first Reproducir(view); } }); // Set a click listener for top playing button mButtonStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stopPlaying(); } }); /* SeekBar.OnSeekBarChangeListener A callback that notifies clients when the progress level has been changed. This includes changes that were initiated by the user through a touch gesture or arrow key/trackball as well as changes that were initiated programmatically. */ // Set a change listener for seek bar mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { /* void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) Notification that the progress level has changed. Clients can use the fromUser parameter to distinguish user-initiated changes from those that occurred programmatically. Parameters seekBar SeekBar : The SeekBar whose progress has changed progress int : The current progress level. This will be in the range min..max where min and max were set by setMin(int) and setMax(int), respectively. (The default values for min is 0 and max is 100.) fromUser boolean : True if the progress change was initiated by the user. */ @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if(mPlayer!=null && b){ /* void seekTo (int msec) Seeks to specified time position. Same as seekTo(long, int) with mode = SEEK_PREVIOUS_SYNC. Parameters msec int: the offset in milliseconds from the start to seek to Throws IllegalStateException : if the internal player engine has not been initialized */ mPlayer.seekTo(i*1000); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } /* ----------------------------------------------------------------------------* Función:Reproducir* Paràmetros:view, y videoUri Descripción:Se reproduce el Audio que se ha indicado en el file explorer * -------------------------------------------------------------------------*/ public void Reproducir(View view) { MediaPlayer mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(this,videoUri); mediaPlayer.prepare(); } catch (IOException e){ } mediaPlayer.start(); Toast.makeText(getApplicationContext(), "Reproduciendo audio", Toast.LENGTH_SHORT).show(); } /* ----------------------------------------------------------------------------* Función:stopPlaying* Paràmetros: Descripción:Se para la reproduccion indicada si la el audio no es null * -------------------------------------------------------------------------*/ protected void stopPlaying(){ // If media player is not null then try to stop it if(mPlayer!=null){ mPlayer.stop(); mPlayer.release(); mPlayer = null; Toast.makeText(mContext,"Stop playing.",Toast.LENGTH_SHORT).show(); if(mHandler!=null){ mHandler.removeCallbacks(mRunnable); } } } /* ----------------------------------------------------------------------------* Función:getAudioStats* Paràmetros: Descripción:Se obtiene los datos del audio para ponerlo en los textviews indicado dando informacion al usuario. * -------------------------------------------------------------------------*/ protected void getAudioStats(){ int duration = mPlayer.getDuration()/1000; // In milliseconds int due = (mPlayer.getDuration() - mPlayer.getCurrentPosition())/1000; int pass = duration - due; mPass.setText("" + pass + " seconds"); mDuration.setText("" + duration + " seconds"); mDue.setText("" + due + " seconds"); } /* ----------------------------------------------------------------------------* Función:initializeSeekBar* Paràmetros: Descripción:Inicializa la barra Seek con los datos obtenidos de la funcion getAudioStats();, No esta puesta ya que si la pongo la pantalla de reproducior no funciona * -------------------------------------------------------------------------*/ protected void initializeSeekBar(){ mSeekBar.setMax(mPlayer.getDuration()/1000); mRunnable = new Runnable() { @Override public void run() { if(mPlayer!=null){ int mCurrentPosition = mPlayer.getCurrentPosition()/1000; // In milliseconds mSeekBar.setProgress(mCurrentPosition); getAudioStats(); } mHandler.postDelayed(mRunnable,1000); } }; mHandler.postDelayed(mRunnable,1000); } }
Java
CL
775762a65545046409cde094794c26c9a845cdaad6c4b7df8d0540919bf7fc19
package com.bfly.cms.content.dao; import com.bfly.cms.content.entity.Article; import com.bfly.cms.content.entity.dto.ArticleLuceneDTO; import com.bfly.core.base.dao.IBaseDao; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.math.BigInteger; import java.util.Date; import java.util.List; import java.util.Map; /** * @author andy_hulibo@163.com * @date 2019/8/1 13:45 */ public interface IArticleDao extends IBaseDao<Article, Integer> { /** * 清除文章和会员组之间的浏览关系权限 * * @param articleId 文章ID * @return 受影响行数 * @author andy_hulibo@163.com * @date 2019/8/7 15:23 */ @Modifying @Query(value = "delete from article_group_view where article_id=:articleId", nativeQuery = true) int removeArticleGroupViewShip(@Param("articleId") int articleId); /** * 清除文章的评分数据 * * @param articleId 文章ID * @return 受影响行数 * @author andy_hulibo@163.com * @date 2019/8/7 16:05 */ @Modifying @Query(value = "delete from article_score where article_id=:articleId", nativeQuery = true) int removeArticleScore(@Param("articleId") int articleId); /** * 审核文章 * * @param articleIds 文章ID * @param status 状态 * @author andy_hulibo@163.com * @date 2018/12/12 11:44 */ @Modifying @Query("update Article set status=:status where id in (:articleId)") void verifyArticle(int status, @Param("articleId") Integer... articleIds); /** * 修改文章推荐级别 * * @param recommend 是否推荐 * @param articleIds 文章Id * @param recommendLevel 推荐级别 * @author andy_hulibo@163.com * @date 2019/8/7 16:14 */ @Modifying @Query("update Article set recommend=:recommend,recommendLevel=:recommendLevel where id in (:articleId)") void recommendArticle(@Param("recommend") boolean recommend, @Param("recommendLevel") int recommendLevel, @Param("articleId") Integer... articleIds); /** * 修改文章置顶 * * @param articleId 文章Id * @param topLevel 置顶级别 * @param expired 置顶有效期 * @author andy_hulibo@163.com * @date 2019/8/7 16:13 */ @Modifying @Query("update Article set topLevel=:topLevel,topExpired=:expired where id=:articleId") void editArticleTop(@Param("articleId") int articleId, @Param("topLevel") int topLevel, @Param("expired") Date expired); /** * 文章和专题关联 * * @param articleId 文章ID * @param topicId 专题ID * @author andy_hulibo@163.com * @date 2019/8/8 16:11 */ @Modifying @Query(value = "insert into special_topic_article_ship(article_id,topic_id) values(:articleId,:topicId)", nativeQuery = true) void saveSpecialTopicArticleShip(@Param("articleId") int articleId, @Param("topicId") int topicId); /** * 删除文章和专题的关联 * * @param articleId 文章ID * @param topicId 专题ID * @author andy_hulibo@163.com * @date 2019/8/8 16:12 */ @Modifying @Query(value = "delete from special_topic_article_ship where article_id=:articleId and topic_id=:topicId ", nativeQuery = true) void removeSpecialTopicArticleShip(@Param("articleId") int articleId, @Param("topicId") int topicId); /** * 清空文章和专题的所有关联 * * @param articleId 文章ID * @author andy_hulibo@163.com * @date 2019/8/8 16:12 */ @Modifying @Query(value = "delete from special_topic_article_ship where article_id=:articleId", nativeQuery = true) void clearSpecialTopicArticleShip(@Param("articleId") int articleId); /** * 查询是否存在关联 * * @param articleId 文章ID * @param topicId 专题ID * @return true存在关联 反之 * @author andy_hulibo@163.com * @date 2019/8/8 16:53 */ @Query(value = "select CAST(count(1)>0 AS CHAR)as flag from special_topic_article_ship where article_id=:articleId and topic_id=:topicId ", nativeQuery = true) boolean isExistSpecialTopicArticleShip(@Param("articleId") int articleId, @Param("topicId") int topicId); /** * 删除文章图片集 * * @param picId 图片ID * @author andy_hulibo@163.com * @date 2019/8/13 10:36 */ @Modifying @Query(value = "delete from article_picture where id=:picId", nativeQuery = true) void delArticlePicture(@Param("picId") int picId); /** * 删除文章附件集 * * @param attachmentId 附件ID * @author andy_hulibo@163.com * @date 2019/8/13 10:37 */ @Modifying @Query(value = "delete from article_attachment where id=:attachmentId", nativeQuery = true) void delArticleAttachment(@Param("attachmentId") int attachmentId); /** * 统计今天发布和总数的文章 * * @return Map today 今日发布数 total 发布总数 * @author andy_hulibo@163.com * @date 2019/8/14 19:26 */ @Query(value = "select count(1) as total,temp.today FROM article,(select count(1) as today from article_ext as ar_ext INNER JOIN article as ar on ar.id=ar_ext.article_id where date_format(post_date, '%Y-%m-%d')=date_format(NOW(), '%Y-%m-%d') AND ar.status!=0) as temp where status!=0", nativeQuery = true) Map<String, BigInteger> getTodayAndTotalArticle(); /** * 点击率头几名的文章信息 * * @param limit * @return Map * @author andy_hulibo@163.com * @date 2019/8/15 12:46 */ @Query(value = "select a.id,a_ext.title,a.views from article as a LEFT JOIN article_ext as a_ext on a.id=a_ext.article_id WHERE a.`status`=2 order by views desc limit 0,:limit", nativeQuery = true) List<Map<String, Object>> getClickTopArticle(@Param("limit") int limit); /** * 评论数头几名的文章信息 * * @param limit * @return Map * @author andy_hulibo@163.com * @date 2019/8/15 12:47 */ @Query(value = "select a.id,a_ext.title,a.comments from article as a LEFT JOIN article_ext as a_ext on a.id=a_ext.article_id WHERE a.`status`=2 order by comments desc limit 0,:limit", nativeQuery = true) List<Map<String, Object>> getCommentsTopArticle(@Param("limit") int limit); /** * 下一篇文章 * * @param currentArticleId 当前文章ID * @param channelId 栏目ID * @param status 状态 * @return Map 部分字段 * @author andy_hulibo@163.com * @date 2019/9/4 22:54 */ @Query(value = "select ar.id,title,ch.channel_path as path,title_img as titleImg from article as ar INNER JOIN article_ext on ar.id=article_id INNER JOIN channel as ch ON ar.channel_id=ch.id where ar.id>:currentArticleId and (ar.status=:status or :status is null) and (ar.channel_id=:channelId or :channelId is null) limit 0,1", nativeQuery = true) Map<String, Object> getNext(@Param("currentArticleId") int currentArticleId, @Param("channelId") Integer channelId, @Param("status") Integer status); /** * 上一篇文章 * * @param currentArticleId 当前文章ID * @param channelId 栏目ID * @param status 状态 * @return Map 部分字段 * @author andy_hulibo@163.com * @date 2019/9/4 22:54 */ @Query(value = "select ar.id,title,ch.channel_path as path,title_img as titleImg from article as ar INNER JOIN article_ext on ar.id=article_id INNER JOIN channel as ch ON ar.channel_id=ch.id where ar.id<:currentArticleId and (ar.status=:status or :status is null) and (ar.channel_id=:channelId or :channelId is null) order by ar.id desc limit 0,1", nativeQuery = true) Map<String, Object> getPrev(int currentArticleId, @Param("channelId") Integer channelId, @Param("status") Integer status); /** * 文章评论数增长 * * @param articleId 文章ID * @param setup 增长数 * @return * @author andy_hulibo@163.com * @date 2019/9/6 16:44 */ @Modifying @Query("update Article set comments=comments+ :setup where id=:articleId") int editArticleComments(@Param("articleId") int articleId, @Param("setup") int setup); /** * 修改文章的浏览量 * * @param articleId 文章ID * @param setup 增长数 * @return * @author andy_hulibo@163.com * @date 2019/9/6 17:45 */ @Modifying @Query("update Article set views=views+ :setup where id=:articleId") int editArticleViews(@Param("articleId") int articleId, @Param("setup") int setup); /** * 修改文章文件下载量 * * @param articleId 文章ID * @param setup 增长数 * @return * @author andy_hulibo@163.com * @date 2019/9/7 18:36 */ @Modifying @Query("update Article set downloads=downloads+ :setup where id=:articleId") int editArticleDownloads(@Param("articleId") int articleId, @Param("setup") int setup); /** * 修改文章评分 * * @param articleId 文章ID * @param scoreItemId 评分项ID * @return * @author andy_hulibo@163.com * @date 2019/9/7 18:37 */ @Modifying @Query(value = "update article set scores=scores+(select score from score_item WHERE id=:scoreItemId) WHERE id=:articleId", nativeQuery = true) int editArticleScores(@Param("articleId") int articleId, @Param("scoreItemId") int scoreItemId); /** * 踩文章 * * @param articleId 文章Id * @return * @author andy_hulibo@163.com * @date 2019/9/6 18:18 */ @Modifying @Query("update Article set downs=downs+1 where id=:articleId") int editArticleDowns(@Param("articleId") int articleId); /** * 顶文章 * * @param articleId 文章Id * @return * @author andy_hulibo@163.com * @date 2019/9/6 18:18 */ @Modifying @Query("update Article set ups=ups+1 where id=:articleId") int editArticleUps(@Param("articleId") int articleId); /** * 清空置顶过期的文章把置顶级别设置为0 * * @param date 日期 * @return * @author andy_hulibo@163.com * @date 2019/9/14 11:22 */ @Modifying @Query("update Article set topLevel=0,topExpired=null where topExpired<:date and topExpired is not null") int resetArticleTopLevelForExpired(@Param("date") Date date); /** * 自动发布文章 * * @param passingStatus * @param passStatus * @return * @author andy_hulibo@163.com * @date 2019/9/14 13:23 */ @Modifying @Query(value = "UPDATE article set `status`=:passStatus WHERE exists(select article_id from article_ext WHERE `status`=:passingStatus and post_date<now())", nativeQuery = true) int autoPublishArticle(@Param("passStatus") int passStatus, @Param("passingStatus") int passingStatus); /** * 得到ArticleLuceneDTO * * @param limit * @param from * @return * @author andy_hulibo@163.com * @date 2019/10/28 12:09 */ @Query(value = "select ar.id,ar.status,ch.channel_path as channelPath,ar_ext.title,ar_ext.post_date as postDate,ar_ext.title_img as titleImg,ar_ext.summary,ar_txt.txt from article as ar LEFT JOIN article_ext as ar_ext on ar.id=ar_ext.article_id LEFT JOIN article_txt as ar_txt on ar.id=ar_txt.article_id LEFT JOIN channel as ch on ar.channel_id=ch.id limit :from,:limit", nativeQuery = true) List<Map<String,Object>> getArticleLuceneDTO(@Param("from") int from, @Param("limit") int limit); }
Java
CL
c8df611425015f0d3427263efbabc72e91c1a1d9abae86249ed41103c9071224
package com.geeboo.dyna.server.service.topic; import com.geeboo.common.msg.BaseResponse; import com.geeboo.common.msg.ObjectResponse; import com.geeboo.common.msg.TableResultResponse; import com.geeboo.common.page.Page; import com.geeboo.dyna.server.client.dto.topic.DynaTopicFavorDTO; public interface IDynaTopicFavorService { /** * 增加动态_话题点赞表 * * @param dto * @return */ BaseResponse add(DynaTopicFavorDTO dto); /** * 修改动态_话题点赞表 * * @param dto * @return */ BaseResponse update(DynaTopicFavorDTO dto); /** * 删除动态_话题点赞表 * * @param id 系统主键 * @return */ BaseResponse delete(Integer id); /** * 分页查询 * * @param dto 查询条件 * @param page 当前页,每页显示的条数 * @return */ TableResultResponse<DynaTopicFavorDTO> page(DynaTopicFavorDTO dto, Page<DynaTopicFavorDTO> page); /** * 通过ID获取动态_话题点赞表实体 * * @param id 主键id * @return */ ObjectResponse findById(Integer id); /** * 通过条件获取动态_话题点赞表实体 * * @param dto 查询条件 * @return */ ObjectResponse findByCondition(DynaTopicFavorDTO dto); }
Java
CL
eca9b8d354a414350e76617bde9d59f9c27d5894a436b8819d1436e891607e16
package com.yj.dal.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.yj.dal.model.FrCardType; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * <p> * 卡类型表 Mapper 接口 * </p> * * @author MP自动生成 * @since 2018-09-12 */ public interface FrCardTypeMapper extends BaseMapper<FrCardType> { List<FrCardType> selectCardTypetByIdAndName(@Param("shopId") String shopId, @Param("cardTypeId") String cardTypeId , @Param("cardTypeName")String cardTypeName, @Param("pId")String pId, @Param("typeSetState")Integer typeSetState); Integer selectCardTypetCount(@Param("shopId") String shopId, @Param("cardTypeId") String cardTypeId , @Param("cardTypeName")String cardTypeName, @Param("pId")String pId, @Param("typeSetState")Integer typeSetState); List<FrCardType> queryByShopIdList(Map<String,Object> map); /** * 根据会员卡ID 获取卡类型 * @param cardId * @param CustomerCode * @return */ FrCardType queryByCardId(@Param("cardId") String cardId , @Param("CustomerCode")String CustomerCode); List<FrCardType> getAllShopIdList(Map<String,Object> map); List<Map<String,Object>> getCardTypeByShopIdList(Map<String,Object> map); /** * 根据会员卡名称 门店id查询会员卡类型 * @param cardCardTypeMap * @return */ FrCardType selectByCardTypeName(Map<String, Object> cardCardTypeMap); /** * 根据会员卡名称 门店id为0(门店id值是0为连锁店 ) * @param cardTypeName * @return */ FrCardType selectByShopId(String cardTypeName); List<FrCardType> queryByShopIdList2(Map<String,Object> map); }
Java
CL
8393b1ab2da99ca9028dc79b482a010d1badf9465041c5b619fe325f371bf409
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.02.15 at 01:36:40 PM CST // package com.ibm.ws.jpa.diagnostics.tools.appscanner.report.pascanresult.v10; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PersistenceParseResultType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PersistenceParseResultType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="originalHash" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="scannedHash" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="persistenceUnitDocument" type="{PersistentArchiveScanResult_1.0}PersistenceUnitType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="version"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]+(\.[0-9]+)*"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PersistenceParseResultType", propOrder = { "originalHash", "scannedHash", "persistenceUnitDocument" }) public class PersistenceParseResultType { @XmlElement(required = true) protected String originalHash; @XmlElement(required = true) protected String scannedHash; protected List<PersistenceUnitType> persistenceUnitDocument; @XmlAttribute(name = "version") protected String version; /** * Gets the value of the originalHash property. * * @return * possible object is * {@link String } * */ public String getOriginalHash() { return originalHash; } /** * Sets the value of the originalHash property. * * @param value * allowed object is * {@link String } * */ public void setOriginalHash(String value) { this.originalHash = value; } /** * Gets the value of the scannedHash property. * * @return * possible object is * {@link String } * */ public String getScannedHash() { return scannedHash; } /** * Sets the value of the scannedHash property. * * @param value * allowed object is * {@link String } * */ public void setScannedHash(String value) { this.scannedHash = value; } /** * Gets the value of the persistenceUnitDocument property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the persistenceUnitDocument property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPersistenceUnitDocument().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PersistenceUnitType } * * */ public List<PersistenceUnitType> getPersistenceUnitDocument() { if (persistenceUnitDocument == null) { persistenceUnitDocument = new ArrayList<PersistenceUnitType>(); } return this.persistenceUnitDocument; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } }
Java
CL
26316e9d2e1f5fa632ec655d2950699525deedce5186c22d6ccb336573347c44
package com.mvvm.lux.framework.base; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mvvm.lux.framework.utils.Utils; import com.mvvm.lux.widget.swipeback.SwipeBackActivityBase; import com.mvvm.lux.widget.swipeback.SwipeBackActivityHelper; import com.mvvm.lux.widget.swipeback.SwipeBackLayout; /** * @Description 1、想要实现向右滑动删除Activity效果只需要继承SwipeBackActivity即可,如果当前页面含有ViewPager * 只需要调用SwipeBackLayout的setViewPager()方法即可 * 2、设置activity的主题为android:theme="@style/CustomTransparent * @Author luxiao418 * @Email luxiao418@pingan.com.cn * @Date 2017/1/4 15:02 * @Version */ public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase { private SwipeBackActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SwipeBackActivityHelper(this); mHelper.onActivityCreate(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(); } @Override public View findViewById(int id) { View v = super.findViewById(id); if (v == null && mHelper != null) return mHelper.findViewById(id); return v; } @Override public SwipeBackLayout getSwipeBackLayout() { return mHelper.getSwipeBackLayout(); } @Override public void setSwipeBackEnable(boolean enable) { getSwipeBackLayout().setEnableGesture(enable); } public void setEdge(int edgeFlags) { getSwipeBackLayout().setEdgeTrackingEnabled(edgeFlags); } @Override public void scrollToFinishActivity() { Utils.convertActivityToTranslucent(this); getSwipeBackLayout().scrollToFinishActivity(); } }
Java
CL
b01f3ca283b3667d3617737c87f91bdb60f68d92efc412fd3fece96d8f420223
package networkZ; import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.JTextField; import javax.swing.JSeparator; import javax.swing.JOptionPane; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.UIManager; import javax.swing.border.*; import javax.swing.ListSelectionModel; import javax.swing.DefaultListModel; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import java.awt.Color; import java.awt.Font; import java.awt.Toolkit; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.util.ArrayList; /** * The GUI class sets up the GUI and controls the application logic, * using the data structures defined in Network, Edge and Node. * * @author James Roberts * @since 2017-12-01 * */ public class GUI { private JFrame frame; int currentNetwork = 0; ArrayList<Network> networks = new ArrayList<Network>(); ArrayList<String> networkNames = new ArrayList<String>(); /** * Launch the application. */ public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { //if unsuccessful, do nothing and use default Metal appearance } EventQueue.invokeLater(new Runnable() { public void run() { try { GUI window = new GUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public GUI() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame("NetworkZ Analysis"); frame.setSize(new Dimension(490, 300)); frame.setMaximumSize(new Dimension(490, 2147483647)); frame.setPreferredSize(new Dimension(490, 300)); frame.setMinimumSize(new Dimension(490, 300)); frame.setBounds(100, 100, 490, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { frame.setIconImage(Toolkit.getDefaultToolkit().getImage("networkZ_icon.png")); } catch (Exception ex) { //if not found, use default java icon } //main frame components - created before menu items so they can be referred to in event handlers JScrollPane scrollPane = new JScrollPane(); scrollPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); scrollPane.setViewportBorder(null); JTextPane txtPane = new JTextPane(); scrollPane.setViewportView(txtPane); txtPane.setBorder(new EmptyBorder(0, 20, 0, 10)); txtPane.setFont(new Font("Segoe UI", Font.PLAIN, 12)); JSeparator separator = new JSeparator(JSeparator.VERTICAL); separator.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); JLabel lblMessage = new JLabel(" "); lblMessage.setFont(new Font("Segoe UI", Font.PLAIN, 12)); lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setPreferredSize(new Dimension(450, 15)); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "Networks:", TitledBorder.LEADING, TitledBorder.TOP, null, null)); DefaultListModel<String> listContents = new DefaultListModel<String>(); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setViewportBorder(null); scrollPane_1.setPreferredSize(new Dimension(124, 173)); panel.add(scrollPane_1); JList<String> list = new JList<String>(); scrollPane_1.setViewportView(list); list.setFont(new Font("Segoe UI", Font.PLAIN, 12)); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { if(list.getValueIsAdjusting()) { return; } try { currentNetwork = list.getSelectedIndex(); txtPane.setText("\n"+networkNames.get(currentNetwork)+networks.get(currentNetwork).networkSummary()); txtPane.setCaretPosition(1); } catch (Exception ex) { //if not changing to a valid index, do nothing txtPane.setText(ex.toString()); } } }); list.setModel(listContents); list.setSize(new Dimension(125, 175)); list.setBorder(null); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); networks.add(new Network()); networkNames.add("Network1"); listContents.addElement("Network1"); //introductory prompt txtPane.setText("\r\nCreate a network from a tab-delimited .txt file of interactions to begin, or manually add interactions to a blank network.\n\nAn empty network has been started automatically."); //menu bar JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); //Network dropdown menu JMenu mnNetwork = new JMenu("Network"); menuBar.add(mnNetwork); //Network/new from file JMenuItem mntmNewNetwork = new JMenuItem("Create new network from file"); mntmNewNetwork.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmNewNetwork.setPreferredSize(new Dimension(180,22)); //reverses jmenuitem height shrinking to item height mnNetwork.add(mntmNewNetwork); mntmNewNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); JTextField networkName = new JTextField(); networkName.setText(file.getName().replaceAll(".txt","")); Object[] message = { "Network name: ",networkName }; int option = JOptionPane.showConfirmDialog(null, message, "New network from file", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (networkName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name was left blank. Please provide a network name."); } else if (networkNames.contains(networkName.getText())) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name is already in use. Please provide a unique name."); } else { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Network created: "+networkName.getText()); networks.add(new Network(file.getAbsolutePath())); networkNames.add(networkName.getText()); listContents.addElement(networkName.getText()); } } } } }); //network/new blank JMenuItem mntmBlankNetwork = new JMenuItem("Create new blank network"); mntmBlankNetwork.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmBlankNetwork.setPreferredSize(new Dimension(180,22)); mnNetwork.add(mntmBlankNetwork); mntmBlankNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField networkName = new JTextField(); Object[] message = { "Network name: ",networkName }; int option = JOptionPane.showConfirmDialog(null, message, "New blank network", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (networkName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name was left blank. Please provide a network name."); } else if (networkNames.contains(networkName.getText())) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name is already in use. Please provide a unique name."); } else { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Network created: "+networkName.getText()); networks.add(new Network()); networkNames.add(networkName.getText()); listContents.addElement(networkName.getText()); } } } }); //network/separator mnNetwork.addSeparator(); //network/export degrees JMenuItem mntmExportDegreeDistribution = new JMenuItem("Export degree distribution"); mntmExportDegreeDistribution.setMinimumSize(new Dimension(0, 22)); mntmExportDegreeDistribution.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmExportDegreeDistribution.setPreferredSize(new Dimension(180,22)); mnNetwork.add(mntmExportDegreeDistribution); mntmExportDegreeDistribution.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { final JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(networkNames.get(currentNetwork)+"_degrees.txt")); int returnVal = fc.showSaveDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); networks.get(currentNetwork).saveDegrees(file.getAbsolutePath()); lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Degree distribution for "+networkNames.get(currentNetwork)+" saved to: " + file.getName()); } } }); //network/export network JMenuItem mntmExportNetwork = new JMenuItem("Export network as file"); mnNetwork.add(mntmExportNetwork); mntmExportNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { final JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(networkNames.get(currentNetwork)+".txt")); int returnVal = fc.showSaveDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); networks.get(currentNetwork).exportNetwork(file.getAbsolutePath()); lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText(networkNames.get(currentNetwork)+" saved to: " + file.getName()); } } }); //network/export network JMenuItem mntmDisplayNetwork = new JMenuItem("Display network interactions"); mnNetwork.add(mntmDisplayNetwork); mntmDisplayNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String interactions = networks.get(currentNetwork).writeInteractions(); if (interactions.equals("")) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Empty network selected."); } else { txtPane.setText(String.format("\nInteractions in network %s:\n\n%s",networkNames.get(currentNetwork),interactions)); lblMessage.setText(""); } } }); //network/separator2 mnNetwork.addSeparator(); //network/rename JMenuItem mntmRenameNetwork = new JMenuItem("Rename current network"); mnNetwork.add(mntmRenameNetwork); mntmRenameNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField networkName = new JTextField(); networkName.setText(networkNames.get(currentNetwork)); String oldName = networkNames.get(currentNetwork); Object[] message = { "Network name: ", networkName }; int option = JOptionPane.showConfirmDialog(null, message, "Rename network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (networkName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name was left blank. Please provide a network name."); } else if (networkNames.contains(networkName.getText())) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name is already in use. Please provide a unique name."); } else { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Network renamed from "+ oldName + " to "+networkName.getText()); networkNames.set(currentNetwork,networkName.getText()); listContents.setElementAt(networkName.getText(), currentNetwork); //list.setSelectedIndex(currentNetwork); do I need this? } } } }); //network/duplicate JMenuItem mntmDuplicateNetwork = new JMenuItem("Duplicate current network"); mnNetwork.add(mntmDuplicateNetwork); mntmDuplicateNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField networkName = new JTextField(); networkName.setText(networkNames.get(currentNetwork)+"_copy"); Object[] message = { "Network name: ",networkName }; int option = JOptionPane.showConfirmDialog(null, message, "Copy of network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (networkName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name was left blank. Please provide a network name."); } else if (networkNames.contains(networkName.getText())) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Network name is already in use. Please provide a unique name."); } else { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Duplicate network created: "+networkName.getText()); networks.add(new Network(networks.get(currentNetwork))); networkNames.add(networkName.getText()); listContents.addElement(networkName.getText()); } } } }); //network/delete JMenuItem mntmDeleteNetwork = new JMenuItem("Delete current network"); mnNetwork.add(mntmDeleteNetwork); mntmDeleteNetwork.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Object[] message = { "Deleted networks cannot be recovered.\nWould you like to proceed?" }; int option = JOptionPane.showConfirmDialog(null, message, "Delete network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Deleted network: "+networkNames.get(currentNetwork)); String removedName = networkNames.get(currentNetwork); networks.remove(networks.get(currentNetwork)); listContents.removeElement(removedName); networkNames.remove(removedName); //if no remaining networks, create blank network if (networkNames.size()==0) { networks.add(new Network()); networkNames.add("Network1"); listContents.addElement("Network1"); lblMessage.setText(lblMessage.getText()+". Blank network Network1 created."); } currentNetwork = 0; list.setSelectedIndex(0); } } }); //edit menu JMenu mnEdit = new JMenu("Edit"); menuBar.add(mnEdit); //edit/add JMenuItem mntmAddNewInteraction = new JMenuItem("Add new interaction"); mntmAddNewInteraction.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmAddNewInteraction.setPreferredSize(new Dimension(180,22)); mnEdit.add(mntmAddNewInteraction); mntmAddNewInteraction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField node1 = new JTextField(); JTextField node2 = new JTextField(); Object[] message = { "Node #1:", node1, "Node #2:", node2 }; int option = JOptionPane.showConfirmDialog(null, message, "Add interaction to: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (node1.getText().isEmpty() || node2.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Insufficient arguments: two nodes needed."); } else { networks.get(currentNetwork).addInteraction(new Node(node1.getText()), new Node(node2.getText())); lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Interaction added to "+networkNames.get(currentNetwork)+": "+node1.getText()+" to "+node2.getText()); } } } }); //edit/remove JMenuItem mntmRemoveExistingInteraction = new JMenuItem("Remove existing interaction"); mnEdit.add(mntmRemoveExistingInteraction); mntmRemoveExistingInteraction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField node1 = new JTextField(); JTextField node2 = new JTextField(); Object[] message = { "Node #1:", node1, "Node #2:", node2 }; int option = JOptionPane.showConfirmDialog(null, message, "Remove interaction from: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (node1.getText().isEmpty() || node2.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Insufficient arguments: two nodes needed."); } else { ArrayList<Node> removedNodes = networks.get(currentNetwork).removeInteraction(new Node(node1.getText()), new Node(node2.getText())); if (removedNodes.size()>0) { txtPane.setText("\nThe following nodes were disconnected from the rest of the network and have been removed:\n"); for (Node node : removedNodes) { txtPane.setText(txtPane.getText()+"\n"+node); } } lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText("Interaction removed from "+networkNames.get(currentNetwork)+": "+node1.getText()+" to "+node2.getText()); } } } }); //edit/remove node JMenuItem mntmRemoveNode = new JMenuItem("Remove node"); mnEdit.add(mntmRemoveNode); mntmRemoveNode.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField nodeName = new JTextField(); Object[] message = { "The selected node will be removed from the network.\nAny resulting nodes with degree 0 will also be removed.\nWould you like to proceed?", "Node name:", nodeName }; int option = JOptionPane.showConfirmDialog(null, message, "Remove node from: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (nodeName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Node name was left blank. Please provide a node name."); } else { ArrayList<Node> removedNodes = networks.get(currentNetwork).removeNode(nodeName.getText()); if (removedNodes.size()>0) { txtPane.setText("\nThe following nodes were disconnected from the rest of the network and have been removed:\n"); for (Node node : removedNodes) { txtPane.setText(txtPane.getText()+"\n"+node); } lblMessage.setText(""); } else { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Node "+nodeName.getText()+ " was not found in "+networkNames.get(currentNetwork)); } } } } }); //search menu JMenu mnSearch = new JMenu("Search"); menuBar.add(mnSearch); //search/lookup JMenuItem mntmLookupNodeDegree = new JMenuItem("Look up node degree"); mntmLookupNodeDegree.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmLookupNodeDegree.setPreferredSize(new Dimension(180,22)); mnSearch.add(mntmLookupNodeDegree); mntmLookupNodeDegree.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField nodeName = new JTextField(); Object[] message = { "Node name: ",nodeName }; int option = JOptionPane.showConfirmDialog(null, message, "Look up node in network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (nodeName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Node name was left blank. Please provide a node name."); } else { int nodeD = networks.get(currentNetwork).getDegree(nodeName.getText()); if (nodeD != 0) { txtPane.setText("\nNode: "+nodeName.getText()+"\n\nDegree: "+nodeD); lblMessage.setText(""); } else { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Node: "+nodeName.getText()+" not found in network "+networkNames.get(currentNetwork)); } } } } }); //search/hubs JMenuItem mntmGetNetworkHubs = new JMenuItem("Get network hubs"); mntmGetNetworkHubs.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmGetNetworkHubs.setPreferredSize(new Dimension(180,22)); mnSearch.add(mntmGetNetworkHubs); mntmGetNetworkHubs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ArrayList<Node> networkHubs = networks.get(currentNetwork).getHubs(); if (networkHubs.size() > 0) { txtPane.setText("\nNetwork hubs:\n"); String hubNode = ""; for (Node counter : networkHubs) { txtPane.setText(txtPane.getText()+"\n"+counter.nodeName); hubNode = counter.nodeName; } int nodeD = networks.get(currentNetwork).getDegree(hubNode); txtPane.setText(txtPane.getText()+"\n\nHub degree: "+nodeD); lblMessage.setText(""); } else { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Empty network selected."); } } }); //search/average JMenuItem mntmGetAverageDegree = new JMenuItem("Get average degree"); mntmGetAverageDegree.setIcon(new ImageIcon(GUI.class.getResource("/javax/swing/plaf/metal/icons/sortDown.png"))); mntmGetAverageDegree.setPreferredSize(new Dimension(180,22)); mnSearch.add(mntmGetAverageDegree); mntmGetAverageDegree.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { double averageDegree = networks.get(currentNetwork).getAverageDegree(); if (Double.isNaN(averageDegree)) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Empty network selected."); } else { txtPane.setText(String.format("\nAverage Degree: %.2f",averageDegree)); lblMessage.setText(""); } } }); //search/separator mnSearch.addSeparator(); //search/degree search JMenuItem mntmNodesByDegree = new JMenuItem("Find nodes by degree"); mnSearch.add(mntmNodesByDegree); mntmNodesByDegree.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField nodeDegree = new JTextField(); Object[] message = { "Degree: ", nodeDegree }; int option = JOptionPane.showConfirmDialog(null, message, "Look up nodes in network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (nodeDegree.getText().isEmpty() || ! nodeDegree.getText().matches("^[0-9]*$")) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Invalid degree given. Please provide an integer degree."); } else { ArrayList<Node> degreeNodes = networks.get(currentNetwork).getNodesByDegree(Integer.parseInt(nodeDegree.getText())); txtPane.setText("\nNodes with degree "+nodeDegree.getText()+":\n"); for (Node counter : degreeNodes) { txtPane.setText(txtPane.getText()+"\n"+counter.nodeName); } lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText(""); } } } }); //search/node summary JMenuItem mntmNodeSummary = new JMenuItem("Node summary"); mnSearch.add(mntmNodeSummary); mntmNodeSummary.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTextField nodeName = new JTextField(); Object[] message = { "Node name: ",nodeName }; int option = JOptionPane.showConfirmDialog(null, message, "Node summary from network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (nodeName.getText().isEmpty()) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Node name was left blank. Please provide a node name."); } else { txtPane.setText(networks.get(currentNetwork).nodeSummary(nodeName.getText())); lblMessage.setText(""); } } } }); //search/subnetworks JMenuItem mntmSubNetworks = new JMenuItem("Find sub-networks"); mnSearch.add(mntmSubNetworks); mntmSubNetworks.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ArrayList<ArrayList<Node>> subNetworks = networks.get(currentNetwork).subNetworks(); if (subNetworks.size() == 0) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Empty network selected."); } else if (subNetworks.size() == 1) { txtPane.setText("\nNo sub-networks found.\nAll nodes form one connected network."); } else if (subNetworks.size() > 10) { JTextField groupMinSize = new JTextField(); groupMinSize.setText("2"); Object[] message = { subNetworks.size()+" unconnected sub-networks were found." + "\nSave each component as a new network?"+ "\n\nOptional: Save only groups of N nodes or greater", groupMinSize }; int option = JOptionPane.showConfirmDialog(null, message, "Disconnected network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { if (groupMinSize.getText().isEmpty() || ! groupMinSize.getText().matches("^[0-9]*$")) { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("Invalid group size given. Please provide an integer greater than or equal to 2."); return; } //constructor based on list of nodes and parent network - pull out relevant edges int j = 0; int k = 0; int minSize = Integer.parseInt(groupMinSize.getText()); for (ArrayList<Node> group : subNetworks) { if (group.size() < minSize) { k++; continue; } j++; networks.add(new Network(group,networks.get(currentNetwork))); networkNames.add(networkNames.get(currentNetwork)+"_sub"+j); listContents.addElement(networkNames.get(currentNetwork)+"_sub"+j); } if (k > 0 && j > 0) { lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText(String.format("%d sub-networks below size threshold, %d sub-networks saved.",k,j)); } else if (j > 0){ lblMessage.setForeground(new Color(0, 100, 0)); lblMessage.setText(String.format("%d subnetworks saved.",j)); } else { lblMessage.setForeground(new Color(255, 0, 0)); lblMessage.setText("No sub-networks found above size threshold."); } } } else { StringBuilder groups = new StringBuilder(); int i = 0; for (ArrayList<Node> group : subNetworks) { i++; groups.append("\nGroup "+i+": "+group.size()+" nodes"); } Object[] message = { "Multiple unconnected sub-networks were found:"+groups.toString()+"\nSave each component as a new network?" }; int option = JOptionPane.showConfirmDialog(null, message, "Disconnected network: "+networkNames.get(currentNetwork), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { //constructor based on list of nodes and parent network - pull out relevant edges int j = 0; for (ArrayList<Node> group : subNetworks) { j++; networks.add(new Network(group,networks.get(currentNetwork))); networkNames.add(networkNames.get(currentNetwork)+"_sub"+j); listContents.addElement(networkNames.get(currentNetwork)+"_sub"+j); } } lblMessage.setText(""); } } }); //help menu JMenu mnAbout = new JMenu("About"); menuBar.add(mnAbout); JMenuItem mntmHelp = new JMenuItem("Help"); mnAbout.add(mntmHelp); mntmHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { //included as string due to assignment file upload limitations, would otherwise be imported from .txt as needed String helpText = "\n" + "Creating Networks\n--------------------\n" + "Networks consist of undirected interactions between nodes. Node names are case-sensitive; Node1 and node1 would be added to the network separately.\n\n" + "Self interactions can be included in the network. The resulting loops increase the node's degree by two.\n\n" + "Exporting Networks\n--------------------\n" + "A summary of the network degree distribution can be saved as a tab-delimited .txt file.\n\n" + "The network can also be exported as a tab-delimited .txt file of pairs of interactions, allowing networks to be saved and reloaded later.\n\n" + "Modifying Networks\n--------------------\n" + "Networks can be modified by adding or removing interactions between nodes. Single nodes can also be deleted along with all of their interactions, e.g. to simulate gene knockout or protein inhibition.\n\n" + "Modifying networks may result in disconnected networks, in which all nodes do not form a continuous network. The selected network can be checked for sub-networks and all detected components saved as new networks. " + "The contents of the sub-networks can be checked by exporting them as .txt files or by viewing them in the GUI window.\n\n" + "Single nodes that are no longer connected to any other nodes (with degree 0) are removed from the network automatically.\n\n" + "Comparing Networks\n--------------------\n" + "Networks can be copied. Any changes made to the resulting copy will not affect the original, allowing quick comparison of the effects of any changes on the network characteristics.\n\n" + "A network summary is displayed when it is selected from the list of open networks.\n"; txtPane.setText(helpText); txtPane.setCaretPosition(1); } }); //layout handler GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) .addGap(10) .addComponent(separator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE) .addGap(10) .addComponent(panel, GroupLayout.PREFERRED_SIZE, 128, GroupLayout.PREFERRED_SIZE)) .addComponent(lblMessage, GroupLayout.PREFERRED_SIZE, 450, GroupLayout.PREFERRED_SIZE)) .addGap(14)) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGap(10) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(panel, GroupLayout.PREFERRED_SIZE, 195, GroupLayout.PREFERRED_SIZE) .addComponent(separator, GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)) .addGap(10) .addComponent(lblMessage, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(10)) ); frame.getContentPane().setLayout(groupLayout); } }
Java
CL
a9a496179f6cf8614b8127aa84679b6b747f2ee3fca767eadbe294c51bf1bb20
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.IOException; import java.util.concurrent.TimeUnit; public class MainClass { static WebDriver driver; public static void main(String[] args) throws IOException { // много комменчу, даже самые очевидные вещи, чтобы не ломать голову, что для чего и откуда // обратить на путь к драйверу gecko System.setProperty("webdriver.gecko.driver", "C:\\java_exercises\\ideaProjects\\ZakupkiGovRu\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.zakupki.gov.ru"); // задаем начальные значения для фильтра (только драйвер и цена от, до) ExtendedFilter extendedFilter = new ExtendedFilter(driver, "100000000", "300000000"); // использование метода в классе для применения фильтра extendedFilter.useExtendedFilters(); // создаем объект для класса получения имени подписанта и кода электронной подписи CryptoSignCheck crSing = new CryptoSignCheck(driver); // получение имени подписанта и кода электронной подписи crSing.getCryptoSign(); // полчучаем нужные данные по открытии каждого пункта из сформированного списка закупок GetPurchaseInfo purchaseInfo = new GetPurchaseInfo(driver); purchaseInfo.getUsePurchaseInfo(); // закрыть браузер и выход driver.quit(); } }
Java
CL
1ecd863529d4ba944fe9e2e09b647b3a71bd755673262ee13e0b2375f6a2d790
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package image; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; /** * * @author Wouter */ public interface ImgComponent { /** * Prints a formatted representation of the component to output. */ public void printFormatted(); /** * Get the position of where to find this data in the actual file. * @return position in the file */ public long getPositionOffset(); /** * Get the size (in bytes) of this component * @return the size (in bytes) */ public long getSize(); public void writeToFile(OutputStream os)throws IOException; }
Java
CL
0181c62e674091672bd55193230c82527c840bdd433bc1a4cc989c2cfd8f92e1
package com.mznerp.model; import java.io.Serializable; /** * 用户信息表Model * @author John Kenrinus Lee */ public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; /** 用户代码 */ public String userID; /** 用户图片 */ public String userImage; /** 手机号 */ public String phoneNumber; /** 用户邮箱 */ public String email; /** 用户名称 */ public String username; /** 用户密码 */ public String password; /** 单位代码 */ public String companyID; /** 单位名称 */ public String companyName; /** 部门代码 */ public String departmentID; /** 部门名称 */ public String departmentName; /** 最后登录时间 */ public String lastLoginTime; /** 会话代码 */ public String sessionID; /** 是否自动登录 */ public String isAutoLogin; }
Java
CL
911253c6b2fb622775253d0a30ac24719cb9095c6110d268a4791ecf68cd5ac7
/* * Copyright 2017 AppDirect, Inc. and/or its affiliates * 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.appdirect.sdk.appmarket.events; import static com.appdirect.sdk.appmarket.events.APIResult.success; import static com.appdirect.sdk.appmarket.events.EventHandlingContexts.eventContext; import static com.appdirect.sdk.support.QueryParameters.oneQueryParam; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.http.HttpStatus.OK; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import org.springframework.http.ResponseEntity; import com.appdirect.sdk.web.oauth.BasicAuthUserExtractor; import com.appdirect.sdk.web.oauth.OAuthKeyExtractor; public class AppmarketEventControllerTest { private AppmarketEventService service; private AppmarketEventController controller; private OAuthKeyExtractor keyExtractor; @Before public void setup() throws Exception { service = mock(AppmarketEventService.class); keyExtractor = mock(OAuthKeyExtractor.class); controller = new AppmarketEventController(service, keyExtractor); when(service.processEvent(anyString(), any())).thenReturn(aHugeSuccess()); } @Test public void processEvent_sendsTheRequestToTheKeyExtractor_andSendsTheRightContextToTheService() throws Exception { Map<String, String[]> someParams = oneQueryParam("some", "params"); HttpServletRequest someRequest = mock(HttpServletRequest.class); when(someRequest.getParameterMap()).thenReturn(someParams); when(keyExtractor.extractFrom(someRequest)).thenReturn("the-key-from-the-request"); controller.processEvent(someRequest, "some-event-url"); verify(service).processEvent("some-event-url", eventContext("the-key-from-the-request", someParams)); } @Test public void processEvent_sendsTheEventToTheService_andReturnsItsResults() throws Exception { when(keyExtractor.extractFrom(any())).thenReturn("da-key"); APIResult aHugeSuccess = aHugeSuccess(); when(service.processEvent(eq("some-event-url"), any())).thenReturn(aHugeSuccess); ResponseEntity<APIResult> response = controller.processEvent(anyRequest(), "some-event-url"); assertThat(response.getBody()).isEqualTo(aHugeSuccess); assertThat(response.getStatusCode()).isEqualTo(OK); } @Test public void process_OAuth2_Event_sendsTheEventToTheService_andReturnsItsResults() throws Exception { APIResult aHugeSuccess = aHugeSuccess(); when(service.processEvent(eq("some-event-url"), any(), any())).thenReturn(aHugeSuccess); ResponseEntity<APIResult> response = controller.processEvent(anyRequest(), "some-event-url", "applicationUuid"); assertThat(response.getBody()).isEqualTo(aHugeSuccess); assertThat(response.getStatusCode()).isEqualTo(OK); } private HttpServletRequest aRequestContainingHeader(String key, String value) { HttpServletRequest request = anyRequest(); when(request.getHeader(key)).thenReturn(value); return request; } private HttpServletRequest anyRequest() { return mock(HttpServletRequest.class); } private APIResult aHugeSuccess() { return success("HUGE SUCCESS!"); } }
Java
CL
c69fd7e68b1c886e7d553db222b8749ca14ef9509508347dd7b70fa2e499d702
package com.blakgeek.cordova.plugin.amazonmobileads; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.amazon.device.ads.*; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; // TODO: add separate methods for loading and displaying interstitial // TODO: add callback javascript callbacks // TODO: add support for controlling the ad sizes public class AmazonMobileAdsPlugin extends CordovaPlugin { private static final String LOGTAG = "[AmazonMobileAdsPlugin]"; private boolean bannerAtTop = true; private AdLayout bannerAdView = null; private InterstitialAd interstitialAd = null; private CallbackEnabledInterstitialAdListener interstitialAdListener; private CallbackEnabledAdListener bannerAdListener; private ViewGroup blender; private ViewGroup webViewContainer; private View webView; @Override protected void pluginInitialize() { // look for the smoothie parent view if(super.webView instanceof View) { webView = (View) super.webView; } else { webView = (View) super.webView.getView().getParent(); } webViewContainer = (ViewGroup) webView.getParent(); bannerAdView = new AdLayout(AmazonMobileAdsPlugin.this.cordova.getActivity(), AdSize.SIZE_320x50); float scale = this.cordova.getActivity().getApplicationContext().getResources().getDisplayMetrics().density; bannerAdView.setLayoutParams(new FrameLayout.LayoutParams( (int) (320 * scale),(int) (50 * scale), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL)); bannerAdListener = new CallbackEnabledAdListener(); bannerAdView.setListener(bannerAdListener); // create banner view cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { plugInBlender(); bannerAdView.setVisibility(View.INVISIBLE); blender.addView(bannerAdView); } }); // create interstitial interstitialAd = new InterstitialAd(cordova.getActivity()); interstitialAdListener = new CallbackEnabledInterstitialAdListener(interstitialAd); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { Log.i(LOGTAG, action); if (action.equals("setAppKey")) { AdRegistration.setAppKey(args.getString(0)); callbackContext.success(); } else if (action.equals("enableTestMode")) { AdRegistration.enableTesting(args.getBoolean(0)); callbackContext.success(); } else if (action.equals("enableLogging")) { AdRegistration.enableLogging(args.getBoolean(0)); callbackContext.success(); } else if (action.equals("showBannerAd")) { showBannerAd(args, callbackContext); } else if (action.equals("hideBannerAd")) { hideBannerAd(args, callbackContext); } else if (action.equals("showInterstitialAd")) { showInterstitialAd(callbackContext); } else if ("claimBannerAdSpace".equals(action)) { // TODO: implement code to claim space } else if ("releaseBannerAdSpace".equals(action)) { // TODO: implement code to release space } else { callbackContext.error("Unknown Action"); return false; } return true; } catch (JSONException e) { Log.e("AmazonMobileAdsPlugin", e.getMessage()); callbackContext.error("AmazonMobileAdsPlugin: " + e.getMessage()); return false; } } private void showInterstitialAd(CallbackContext callbackContext) { interstitialAdListener.setCallbackContext(callbackContext); if (!interstitialAd.loadAd()) { callbackContext.error("Unable to load interstitial ad"); } } private void hideBannerAd(JSONArray args, final CallbackContext callbackContext) throws JSONException { final boolean releaseAdSpace = args.getBoolean(0); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (releaseAdSpace) { blender.setVisibility(View.GONE); } bannerAdView.setVisibility(View.INVISIBLE); callbackContext.success(); } }); } protected void showBannerAd(JSONArray args, CallbackContext callbackContext) throws JSONException { final boolean showAtTop = args.getBoolean(0); // TODO: figure out how to claim and not claim space final boolean claimAdSpace = args.getBoolean(1); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (showAtTop != bannerAtTop) { bannerAtTop = showAtTop; webViewContainer.removeView(blender); webViewContainer.addView(blender, bannerAtTop ? 0 : webViewContainer.getChildCount()); } blender.setVisibility(View.VISIBLE); } }); bannerAdListener.setCallbackContext(callbackContext); if (!bannerAdView.loadAd()) { callbackContext.error("Unable to load banner ad"); } } private void plugInBlender() { blender = (ViewGroup) webViewContainer.findViewWithTag("SMOOTHIE_BLENDER"); if (blender == null) { // make the webView stretchy webView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 1f)); blender = new FrameLayout(cordova.getActivity()); blender.setTag("SMOOTHIE_BLENDER"); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); float density = cordova.getActivity().getResources().getDisplayMetrics().density; params.height = Math.round(50 * density); blender.setLayoutParams(params); blender.setVisibility(View.GONE); webViewContainer.addView(blender, bannerAtTop ? 0 : webViewContainer.getChildCount()); } } private class CallbackEnabledInterstitialAdListener extends DefaultAdListener { CallbackContext callbackContext; InterstitialAd interstitialAd; public CallbackEnabledInterstitialAdListener(InterstitialAd interstitialAd) { this.interstitialAd = interstitialAd; this.interstitialAd.setListener(this); } public void setCallbackContext(CallbackContext callbackContext) { if (this.callbackContext != null && !this.callbackContext.isFinished()) { callbackContext.error("Too slow. Your request got stomped on by a newer one"); } this.callbackContext = callbackContext; } @Override public void onAdLoaded(Ad ad, AdProperties adProperties) { interstitialAd.showAd(); callbackContext.success(); } @Override public void onAdFailedToLoad(Ad ad, AdError error) { callbackContext.error(error.getMessage()); } } private class CallbackEnabledAdListener extends DefaultAdListener { CallbackContext callbackContext; public void setCallbackContext(CallbackContext callbackContext) { if (this.callbackContext != null && !this.callbackContext.isFinished()) { callbackContext.error("Too slow. Your request got stomped on by a newer one"); } this.callbackContext = callbackContext; } @Override public void onAdLoaded(Ad ad, AdProperties adProperties) { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { bannerAdView.setVisibility(View.VISIBLE); bannerAdView.bringToFront(); } }); callbackContext.success(); } @Override public void onAdFailedToLoad(Ad ad, AdError error) { callbackContext.error(error.getMessage()); } } }
Java
CL
a453d8369dd60c986e3f55b2670ffe2e074816fdd78d887f37f44a09b4b8b061
package com.lxw.videoworld.app.api; import com.lxw.videoworld.app.model.ConfigModel; import com.lxw.videoworld.app.model.SearchResultModel; import com.lxw.videoworld.app.model.SourceDetailModel; import com.lxw.videoworld.app.model.SourceListModel; import com.lxw.videoworld.framework.http.BaseResponse; import io.reactivex.Observable; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by lxw9047 on 2016/10/20. */ public interface HttpService { @FormUrlEncoded @POST("config") Observable<BaseResponse<ConfigModel>> getConfig(@Field("id") String id); @FormUrlEncoded @POST("list") Observable<BaseResponse<SourceListModel>> getList(@Field("sourceType") String sourceType, @Field("category") String category, @Field("type") String type, @Field("start") String start, @Field("limit") String limit); @FormUrlEncoded @POST("search") Observable<BaseResponse<String>> getSearch(@Field("uid") String uid, @Field("url") String url, @Field("keyword") String keyword, @Field("searchType") String searchType); @FormUrlEncoded @POST("searchResult") Observable<BaseResponse<SearchResultModel>> getSearchResult(@Field("uid") String uid, @Field("url") String url); @FormUrlEncoded @POST("feedback") Observable<BaseResponse<String>> addFeedback(@Field("uid") String uid, @Field("feedback") String feedback); @FormUrlEncoded @POST("detail") Observable<BaseResponse<SourceDetailModel>> getDetail(@Field("url") String url, @Field("sourceType") String sourceType); @FormUrlEncoded @POST("userInfo") Observable<BaseResponse<String>> addUserInfo(@Field("uid") String uid, @Field("sms") String sms, @Field("contact") String contact, @Field("address") String address, @Field("history") String history); }
Java
CL
8d85767163d7bd0c8a5f42f37be5a5b038f4ddc2c222cad0824b205133cd8181
package vladbrown.turing_machine; import java.io.File; import java.io.FileNotFoundException; import java.sql.SQLException; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; /** * Класс {@link TuringMachine} * симулирует работу абстрактной машины Тьюринга, * включает в себя вложенные классы {@link Head}, {@link Tape} и {@link Box}, * имитирующие внутреннее строение машины Тьюринга и базовый абстрактный класс {@link State}, * от которого наследуются дочерние классы, реализующие состояния машины Тьюринга * * @author Бурый Владислав * @version 1.1 */ public class TuringMachine { private static DataBase dataBase; private boolean wasLogGiven = false; private String textFolder; /** * Конуструктор класса {@link TuringMachine} создает объект класса {@link DataBase} * инциализирует private поля textFolder и wasLogGiven параметрами, * переданными программе при консольном запуске приложения. * * @param args Аргументы командной строки, первым из которых должен быть путь к файлу с начальным машины тьюринга, а вторым специальная команда * @see DataBase */ public TuringMachine(String[] args) throws ClassNotFoundException { dataBase = new DataBase("jdbc:mysql://localhost:3306/turing_machine_rules?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "9098"); this.textFolder = args[0]; if (args[1].equals("-log")) { this.wasLogGiven = true; } } /** * Метод Start реализует интерфейс взаимодействия с машиной Тьюринга */ public void start() throws SQLException { int menuIndex; outer: while (true) { System.out.println( "1 - start machine\n" + "2 - view rules\n" + "3 - add rule\n" + "4 - change rule\n" + "5 - delete rule\n" + "6 - show tape\n" + "7 - exit\n" ); Scanner in = new Scanner(System.in); menuIndex = in.nextInt(); switch (menuIndex) { case 1: { Tape tape = new Tape(textFolder); tape.showTape(); Head head = new Head(tape); State currentState = new State_0(); while (currentState != null) { if (this.wasLogGiven) { System.out.println(currentState.toString()); } currentState = currentState.executeRules(head, currentState.toString()); } tape.showTape(); break; } case 2: { dataBase.showRules(); break; } case 3: { dataBase.insertRule(); break; } case 4: { dataBase.showRules(); System.out.println("Enter number of rule that must be changed"); int numberOfRule = in.nextInt(); System.out.println("Enter new current state. For example \"q1\" means state 1"); String newCurrentState = in.next(); System.out.println("Enter new current symbol. For example \"(\""); String newCurrentSymbol = in.next(); System.out.println("Enter new next state. For example \"q2\" means state 2"); String newNextState = in.next(); System.out.println("Enter new direction. \"Right\" - to move head right, \"Left\" - to move head left, \"Stay\" - to not move head"); String newDirection = in.next(); dataBase.changeRule(numberOfRule, newCurrentState, newCurrentSymbol, newNextState, newDirection); System.out.println("Rule was changed\n"); break; } case 5: { dataBase.showRules(); System.out.println("Enter number of rule that must be changed"); int numberOfRule = in.nextInt(); dataBase.removeRule(numberOfRule); break; } case 6: { Tape tape = new Tape(textFolder); tape.showTape(); break; } case 7: { break outer; } } } } /** * Абстрактный класс {@link State} показывает поведение состояний; * {@link State_0}, * {@link State_1}, * {@link State_2}, * {@link State_3}, * и является базовым для всех состояний */ static abstract class State { /** * Метод execute_rules выполняет необходимые действия для данного состояния: * 1. Манипуляции с данными головной ячейки (изменение, удаление, игнорирование). * 2. Перемещение каретки, исходя из правил интерпретации машины Тьюринга. * 3. Переход в следующее состояние, исходя из правил интерпретации машины Тьюринга. * * @param head объект класса Head {@code ...} для взаимодействия с лентой * @param currentState текущее состояние машины Тьюринга * @return {@code State} следующее состояние машины Тьюринга, исходя из правил интерпретации машины Тьюринга */ public abstract State executeRules(Head head, String currentState) throws SQLException; /** * @return текущее состояние в строковом формате для взаимодействия с базой данный */ @Override public abstract String toString(); } /** * {@link State} * * @see vladbrown.turing_machine.TuringMachine.State */ static class State_0 extends State { /** * @see State#executeRules(Head, String) */ @Override public State executeRules(Head head, String currentState) { if (head.currentElement == null && head.it.hasNext()) { head.move("Right"); return this; } if (head.currentElement != null) { if (head.currentElement.getValue().equals("A") && head.it.hasNext()) { head.move("Right"); return new State_1(); } else { return null; } } else { System.out.println("Null founded in Tape"); return null; } } /** * @return Текущее состояние в строковом формате для взаимодействия с базой данный. */ @Override public String toString() { return "q0"; } } /** * {@link State} * * @see vladbrown.turing_machine.TuringMachine.State */ static class State_1 extends State { /** * @see State#executeRules(Head, String) */ @Override public State executeRules(Head head, String currentState) throws SQLException { String currentElement = head.currentElement.getValue(); head.move(dataBase.getDirection(this.toString(), head.currentElement.getValue())); return dataBase.getNextState(this.toString(), currentElement); } /** * @return Текущее состояние в строковом формате для взаимодействия с базой данный. */ @Override public String toString() { return "q1"; } } /** * {@link State} * * @see vladbrown.turing_machine.TuringMachine.State */ static class State_2 extends State { /** * @see State#executeRules(Head, String) */ @Override public State executeRules(Head head, String currentState) throws SQLException { String currentElement = head.currentElement.getValue(); head.move(dataBase.getDirection(this.toString(), head.currentElement.getValue())); return dataBase.getNextState(this.toString(), currentElement); } /** * @return Текущее состояние в строковом формате для взаимодействия с базой данный. */ @Override public String toString() { return "q2"; } } /** * {@link State} * * @see vladbrown.turing_machine.TuringMachine.State */ static class State_3 extends State { /** * Метод для манипуляции с данными текущей ячейки. */ private void specialRules(Head head) { head.clear(); head.move("Right"); head.move("Right"); head.clear(); head.move("Right"); } /** * @see State#executeRules(Head, String) */ @Override public State executeRules(Head head, String currentState) throws SQLException { specialRules(head); return dataBase.getNextState(this.toString(), head.currentElement.getValue()); } /** * @return Текущее состояние в строковом формате для взаимодействия с базой данный. */ @Override public String toString() { return "q3"; } } /** * Класс {@link Box} - это ячейка "ленты" {@link Tape}, в которой хранятся данные. * Содержит поле symbol для хранения значение ячейки. */ static class Box { private String symbol; /** * Конструктор класса {@link Box} инициализирует поле symbol строковым значением. * * @param symbol Значение, которым инициализируется поле класса {@link Box} */ Box(String symbol) { this.symbol = symbol; } public String getValue() { return this.symbol; } public void setValue(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } } /** * Класс Tape {@link Tape} - это "лента" машины Тьюринга, по которой перемещается каретка {@link Head}. * Содержит поле tape - список объектов класса {@link Box} и поле * it - интератор, перемещающийся по "ленте", передаваемый в другие классы для сохранения позиции каретки. */ static class Tape { private LinkedList<Box> tape; private ListIterator<Box> it; /** * Конструктор класса {@link Tape} создает "ленту" и заполняет её значениями, которые прописаны в текстовом файле * * @param path Директория текстового файла с "начальным" машины Тьюринга. */ Tape(String path) { this.tape = new LinkedList<>(); this.it = tape.listIterator(0); File file; Scanner scanner = null; String rawTape = ""; try { file = new File(path); scanner = new Scanner(file); while (scanner.hasNext()) { rawTape = scanner.nextLine(); } for (String x : rawTape.split("", rawTape.length())) { this.tape.add(new Box(x)); } } catch (FileNotFoundException e) { System.err.println(e); } finally { if (scanner != null) { scanner.close(); } } this.it = tape.listIterator(0); } /** * Выводит на экран "ленту." */ void showTape() { for (Box x : this.tape) { System.out.print(x); } System.out.println("\n"); } } /** * Класс {@link Head} это "каретка" машины Тьюринга. * Содержит поле it, которое хранит положение "каретки", поле current_element, для доступа к значению текущей ячейки * и методы, для перемещения "каретки" и манипуляции данными. */ static class Head { private ListIterator<Box> it; private Box currentElement; private Tape currentTape; /** * Конструктор класса Head{@code Head} * * @param objectTape Объект "ленты" с которой должна взаимодействовать каретка. */ Head(Tape objectTape) { this.currentTape = objectTape; this.it = objectTape.it; } /** * Перемещает каретку на одно положение влево или вправо(или оставляет на месте). * * @param direction Направление по которому необходимо переместить каретку */ void move(String direction) { if ("error".equals(direction)) { System.out.println("Program hasn't enough instructions to work correctly and will be stopped!"); return; } if ("Left".equals(direction)) { if (this.it.hasPrevious()) { this.currentElement = this.it.previous(); this.currentElement = this.it.previous(); } else System.out.println("Head in the extreme left position!"); } if ("Right".equals(direction)) { if (this.it.hasNext()) { this.currentElement = this.it.next(); } else System.out.println("Head in the extreme right position!"); } if ("Stay".equals(direction)) { System.out.println("Head didn't move!\n"); } } /** * Заменяет значение текущей ячейки на новое, переданно как параметр метода. * * @param newSymbol новое значение ячейки, на которое заменяется текущее */ void change(String newSymbol) { this.it.set(new Box(newSymbol)); } /** * Зачищает текущую ячейку. */ void clear() { change("."); } /** * @return Значение текущей ячейки. */ public String getCurrentValue() { return this.currentElement.getValue(); } /** * Возвращает каретку в начальную позициую и обновляет значения ленты. * Этот метод должен быть вызван, если вы собираетесь работать с лентой после изменения её значений. */ void updateTape() { this.it = currentTape.tape.listIterator(0); } } }
Java
CL
3e99328508df068e74e27eaf2cf1ac4dfeaf6c1d161447f49f1cf6a51e74475e
package com.pltfm.app.dao; import com.pltfm.app.vobject.HealthYgenericInfo; import com.pltfm.app.vobject.HealthYgenericInfoExample; import java.sql.SQLException; import java.util.List; /** * 健康信息处理接口 * * @author cjm * @since 2013-7-18 */ public interface HealthYgenericInfoDAO { /** * 记录分布信息的总数 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ int countByExample(HealthYgenericInfoExample example) throws SQLException; /** * 删除健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ int deleteByExample(HealthYgenericInfoExample example) throws SQLException; /** * 跟据主键删除健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ public int deleteHealthYgenericId(Integer n_HealthYgenericId) throws SQLException; /** * 跟据id删除健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ int deleteByPrimaryKey(int nHealthYgenericId) throws SQLException; /** * 添加健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ void insert(HealthYgenericInfo record) throws SQLException; /** * 添加健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ void insertSelective(HealthYgenericInfo record) throws SQLException; /** * 健康信息列表 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ List selectByExample(HealthYgenericInfoExample example) throws SQLException; /** * 查询健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ HealthYgenericInfo selectByPrimaryKey(int nHealthYgenericId) throws SQLException; /** * 跟据登录id查询健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ HealthYgenericInfo selectByPrimaryFk(int nLoginId) throws SQLException; /** * 修改健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ int updateByPrimaryKeySelective(HealthYgenericInfo record) throws SQLException; int insertHealthInfo(HealthYgenericInfo record) throws SQLException; /** * 修改健康信息 * * @param userLevel 健康实体 * @return 返回值 * @throws SQLException sql异常 */ int updateByPrimaryKey(HealthYgenericInfo record) throws SQLException; }
Java
CL
ed6eef9738de5b3fd445952f9887545799a1950711ae898317a09ce7d982dbe0
package website.magyar.muservice.bootstrap; import website.magyar.muservice.configuration.VersionTitleProvider; import website.magyar.muservice.initialize.EngineConfigurationAccess; import website.magyar.muservice.initialize.PropertyDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Logs the startup message. */ @Component public class StartUpMessageGenerator { private final Logger logger = LoggerFactory.getLogger(StartUpMessageGenerator.class); @Value("#{startMessage}") private String startMessage; @Autowired private EngineConfigurationAccess configurationAccess; @Autowired private VersionTitleProvider versionTitleProvider; /** * Logs the startup message. */ public void logStartUpMessage() { PropertyDto properties = configurationAccess.getProperties(); Integer port = properties.getPort(); String startUpMessage = String.format(startMessage, versionTitleProvider.getVersionTitle(), port); logger.info(startUpMessage); } }
Java
CL
b98963c6c1d1d1b735bc24aab547b3a6f33841202973fc62d336203db008ef12
package com.appsmith.server.configurations; import com.appsmith.server.configurations.mongo.SoftDeleteMongoRepositoryFactoryBean; import com.appsmith.server.repositories.BaseRepositoryImpl; import com.github.cloudyrock.mongock.SpringBootMongock; import com.github.cloudyrock.mongock.SpringBootMongockBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.EnableMongoAuditing; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; /** * This configures the JPA Mongo repositories. The default base implementation is defined in {@link BaseRepositoryImpl}. * This is required to add default clauses for default JPA queries defined by Spring Data. * <p> * The factoryBean class is also custom defined in order to add default clauses for soft delete for all custom JPA queries. * {@link SoftDeleteMongoRepositoryFactoryBean} for details. */ @Slf4j @Configuration @EnableMongoAuditing @EnableReactiveMongoRepositories(repositoryFactoryBeanClass = SoftDeleteMongoRepositoryFactoryBean.class, basePackages = "com.appsmith.server.repositories", repositoryBaseClass = BaseRepositoryImpl.class ) public class MongoConfig { @Bean public SpringBootMongock mongock(ApplicationContext springContext, MongoTemplate mongoTemplate) { return new SpringBootMongockBuilder( mongoTemplate, getClass().getPackageName().replaceFirst("\\.[^.]+$", ".migrations") ) .setApplicationContext(springContext) .setLockQuickConfig() .build(); } }
Java
CL
61d6b13deab3119b284f36bc107c02a5dfe6a3255d911ce7578302e3b74f137d
/* ** This file is part of the emx370 emulator. ** ** This software is provided "as is" in the hope that it will be useful, ** with no promise, commitment or even warranty (explicit or implicit) ** to be suited or usable for any particular purpose. ** Using this software is at your own risk! ** ** Written by Dr. Hans-Walter Latz, Berlin (Germany), 2015 ** Released to the public domain. */ package dev.hawala.vm370.vm.device; /** * Definition of the relevant status flag generated at channel level by the CCW-processor. * * (most flags defined by the PrincOps are not relevant as unsupported like Program controlled Interrupt * or related to hardware failures not simulated here) * * @author Dr. Hans-Walter Latz, Berlin/Germany, 2015 * */ public final class iDeviceChannelStatus { /** * All channel status bits set to zero. */ public final static int OK = 0; /** Long/short block on input or output data transfer between memory and device. * */ public final static int INCORRECT_LENGTH = 0x40; /** CCW programming error, with the relevant variants: * - invalid CCW address specification (not a double-word address in CAW or transfer-in-channel) * - invalid command code (4 low-order zeroes) * - invalid count (count = 0) * - invalid IDAW address specification (first IDAW not on a word boundary) * - invalid IDAW specification (bits 0-7 not zero, subsequent IDAW not a page boundary) * - invalid CAW format (required zero bits not zero) * - invalid CCW format (required zero bits not zero) * - invalid sequence (CAW specifies a transfer-in-channel or 2 consecutive transfer-in-channel) */ public final static int PROGRAM_CHECK = 0x20; /* * not available status flags: * - Program-Controlled Interruption: not supported (as an interrupt can occur only after the complete chain is processed) * - Protection-Check: not relevant (no protection available) * - Channel Data Check: not relevant (no machine parity errors when transferring data) * - Channel Control Check: not relevant (no detectable machine malfunctions or damages) * - Interface Control Check: not relevant (no detectable I/O device malfunctioning) * - Chaining Check: not relevant (no data rate mismatches provoking channel overruns) */ }
Java
CL
82995ca447a07acf7ae19a7aa358cd6d0aeb7e8e1cf8f4d77553f9198cb06eb5
package org.poormanscastle.products.hit2ass.renderer.domain.table; import com.ctc.wstx.util.StringUtil; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.poormanscastle.products.hit2ass.renderer.VelocityHelper; import java.io.StringWriter; public class TableColumnImpl implements TableColumn { private int width; /** * this factor shall help calculate the width of a column in cm which is stated in characters between tab stops. * first guess is a 12th of an inch (12cpi) => 0.212 cm * 0.212 still appears to narrow, setting it to 0.27 and get feedback from the customer */ private final static double factorCharacterToCm = 0.27; TableColumnImpl(int width) { this.width = width; } @Override public void setWidth(int width) { this.width = width; } @Override public int getWidth() { return width; } @Override public String getTranslatedWidth() { return StringUtils.join(Math.round(100 * TableColumnImpl.factorCharacterToCm * width) / 100.0, " cm"); } @Override public String getContent() { VelocityContext context = VelocityHelper.getVelocityContext(); context.put("columnWidth", getTranslatedWidth()); Template template = Velocity.getTemplate("/velocity/tables/TemplateColumn.vlt"); StringWriter stringWriter = new StringWriter(); template.merge(context, stringWriter); return stringWriter.toString(); } @Override public String toString() { return "TableColumnImpl{" + "width=" + width + '}'; } }
Java
CL
235aee946107a765ba71996fd4f70c8d36f06caa9ba47772a9d189cf25a9ca95
package org.sfm.jdbc.impl; import org.sfm.jdbc.MultiIndexFieldMapper; import org.sfm.jdbc.impl.setter.PreparedStatementIndexSetter; import org.sfm.reflect.Getter; import org.sfm.reflect.IndexedGetter; import org.sfm.reflect.primitive.IntGetter; import org.sfm.utils.ErrorHelper; import java.sql.PreparedStatement; public class CollectionIndexFieldMapper<T, C, P> implements MultiIndexFieldMapper<T> { private final PreparedStatementIndexSetter<P> setter; private final Getter<T, C> collectionGetter; private final IntGetter<? super C> sizeGetter; private final IndexedGetter<C, P> indexedGetter; public CollectionIndexFieldMapper(PreparedStatementIndexSetter<P> setter, Getter<T, C> collectionGetter, IntGetter<? super C> sizeGetter, IndexedGetter<C, P> indexedGetter) { this.setter = setter; this.collectionGetter = collectionGetter; this.sizeGetter = sizeGetter; this.indexedGetter = indexedGetter; } @Override public int map(PreparedStatement ps, T value, int columnIndex) throws Exception { C collection = collectionGetter.get(value); int size = sizeGetter.getInt(collection); for(int i = 0; i < size; i++) { setter.set(ps, indexedGetter.get(collection, i), columnIndex + i + 1); } return size; } @Override public int getSize(T value) { try { return sizeGetter.getInt(collectionGetter.get(value)); } catch (Exception e) { ErrorHelper.rethrow(e); return 1; } } }
Java
CL
e874859f12612306d1f726b49f4a9aadd5389c55b10cfa5dbfb8d208c39a8897
/** * Este paquete contiene las clases necesarias para representar los objetos de * dominio de una manera tal que puedan ser enviados a la capa de presentación <br> * Estas representaciones toman la forma de DTOs (Data Transfer Objects). */ package zinbig.item.util.dto; import java.io.Serializable; /** * Las instancias de esta clase se utilizan pare representar la información * relevante de las descripciones de los enlaces del workflows.<br> * Esta clase implementa la interface Serializable ya que debe ser mantenida en * memoria y eventualmente se la puede enviar a otros servidores.<br> * * * @author Javier Bazzocco javier.bazzocco@zinbig.com * */ public class WorkflowLinkDescriptionDTO extends ItemAbstractDTO implements Serializable { /** * UID por defecto. */ private static final long serialVersionUID = 5899214378296150368L; /** * Es el título de la descripción de nodo representada por este dto. */ public String title; /** * Es el oid de la descripción de nodo representada por este dto. */ public String oid; /** * Es una referencia al dto que representa al nodo inicial del enlace. */ public WorkflowNodeDescriptionDTO initialNode; /** * Es una referencia al dto que representa al nodo final del enlace. */ public WorkflowNodeDescriptionDTO finalNode; /** * Constructor. * * @param aTitle * es el título de la descripción de enlace. * * @param anOid * es el oid de la descripción de enlace. */ public WorkflowLinkDescriptionDTO(String aTitle, String anOid, WorkflowNodeDescriptionDTO initialNode, WorkflowNodeDescriptionDTO finalNode) { this.setTitle(aTitle); this.setFinalNode(finalNode); this.setInitialNode(initialNode); this.setOid(anOid); } /** * Getter. * * @return el título de la descripción de nodo. */ public String getTitle() { return this.title; } /** * Setter. * * @param aTitle * es el título de la descripción de nodo. */ public void setTitle(String aTitle) { this.title = aTitle; } /** * Getter. * * @return el oid de la descripción de nodo. */ public String getOid() { return this.oid; } /** * Setter. * * @param anOid * es el oid de la descripción de nodo. */ public void setOid(String anOid) { this.oid = anOid; } /** * Getter. * * @return el dto que representa al nodo inicial. */ public WorkflowNodeDescriptionDTO getInitialNode() { return this.initialNode; } /** * Setter. * * @param aNodeDTO * es un dto que representa al nodo inicial. */ public void setInitialNode(WorkflowNodeDescriptionDTO aNodeDTO) { this.initialNode = aNodeDTO; } /** * Getter. * * @return el dto que representa al nodo final. */ public WorkflowNodeDescriptionDTO getFinalNode() { return this.finalNode; } /** * Setter. * * @param aNodeDTO * es el dto que representa al nodo final. */ public void setFinalNode(WorkflowNodeDescriptionDTO aNodeDTO) { this.finalNode = aNodeDTO; } }
Java
CL
b8eb226683aac18a2a290c9bd7ea29992a31cf9c35be5e8518a3266b850fa256
package server.handlers.games; import com.sun.net.httpserver.HttpExchange; import server.Server; import server.handlers.Handler; import shared.request.game.SaveGameRequest; import java.io.IOException; /** * For handling requests to /games/save */ public class SaveHandler extends Handler { /** * Expects request body to contain a serialized SaveRequest object. * Saves the current state of the specified game to a file. * @param exchange * @throws IOException */ @Override public void handle(HttpExchange exchange) throws IOException { logger.info("SaveHandler Called"); String body = getRequestBody(exchange); SaveGameRequest request = gson.fromJson(body, SaveGameRequest.class); Server.facade.save(request); exchange.sendResponseHeaders(200, -1); exchange.close(); } }
Java
CL
1e6fab7d002842a19771969f650151c4930026ae911cf213137a7ff53dd961ff
package ws.slink.mine.info; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import ws.slink.mine.info.model.MinerInfo; import ws.slink.mine.info.conf.MinerInfoLoader; import java.util.List; @Component @EnableScheduling public class Updater { private static final Logger logger = LoggerFactory.getLogger(Updater.class); @Autowired private RigUpdater rigUpdater; @Autowired private PoolUpdater poolUpdater; @Autowired private MinerInfoLoader minerInfoLoader; private List<MinerInfo> minerInfoList; @Scheduled(initialDelay = 1000, fixedRate = 60000) // reload config once in a minute private void readConfig() { synchronized (this) { logger.trace("running miners config update task"); minerInfoList = minerInfoLoader.get(); } } @Scheduled(initialDelay = 5000, fixedRateString = "${schedule.timeout.rig}") public void updateRigInfo() { try { logger.trace("rig update attempt"); if (null != minerInfoList && !minerInfoList.isEmpty()) rigUpdater.update(minerInfoList); else logger.trace("empty input commands"); } catch (Exception ex) { logger.error("Exception processing rig information: " + ex.getMessage()); // ex.printStackTrace(); } } @Scheduled(initialDelay = 5000, fixedRateString = "${schedule.timeout.pool}") public void updatePoolInfo() { try { logger.trace("pool update attempt"); if (null != minerInfoList && !minerInfoList.isEmpty()) poolUpdater.update(minerInfoList); else logger.trace("empty input commands"); } catch (Exception ex) { logger.error("Exception processing pool information: " + ex.getMessage()); ex.printStackTrace(); } } }
Java
CL
b3277b8ad4267386e844f11a69fb184df9f3934e6765fe139b9c01182f6f9f97
package com.kaitusoft.ratel.core.handler; import com.kaitusoft.ratel.core.model.Target; import com.kaitusoft.ratel.util.StringUtils; import io.vertx.core.http.Cookie; import io.vertx.ext.web.RoutingContext; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * @author frog.w * @version 1.0.0, 2018/8/20 * <p> * write description here */ public abstract class ProxyPolicy { protected Target[] targets; protected Set<Target> deadTargets = new HashSet<>(); protected boolean keepSession = false; private Map<Object, Target> sessionMap; public static ProxyPolicy create(LoadBalance loadBalance, Target[] targets) { return create(loadBalance, false, targets); } public static ProxyPolicy create(LoadBalance loadBalance, boolean keepSession, Target[] targets) { ProxyPolicy proxyPolicy = null; if (loadBalance == LoadBalance.POLLING_AVAILABLE) { proxyPolicy = new WeightPollingProxyPolicy(); } else if (loadBalance == LoadBalance.RANDOM) { proxyPolicy = new RandomProxyPolicy(); } else if (loadBalance == LoadBalance.IP_HASH) { proxyPolicy = new IpHashProxyPolicy(); } else { throw new IllegalStateException("not support yet"); } proxyPolicy.targets = new Target[targets.length]; System.arraycopy(targets, 0, proxyPolicy.targets, 0, targets.length); proxyPolicy.keepSession = keepSession; if(keepSession) proxyPolicy.sessionMap = new ConcurrentHashMap<Object, Target>(65535, 0.75f, 16); proxyPolicy.init(); return proxyPolicy; } // protected String[] status; protected void init() { } protected synchronized void dead(String target) { if (StringUtils.isEmpty(target) || targets.length == 0) return; Target[] newTargets = new Target[targets.length - 1]; for (int i = 0, j = 0; i < targets.length; i++) { if (targets[i].getUrl().equals(target)) { deadTargets.add(targets[i]); i++; continue; } newTargets[j] = targets[i]; j++; } targets = newTargets; // 上报给 t 重试任务 } protected void dead(Target target) { dead(target.getUrl()); } public Set<Target> dead() { return deadTargets; } public void rebirth(Target target) { rebirth(target.getUrl()); } public synchronized void rebirth(String host) { if (StringUtils.isEmpty(host)) return; Target target = null; for (Target t : deadTargets) { if (t.getUrl().equals(host)) { target = t; break; } } /** * 移除 */ if (target == null || !deadTargets.remove(target)) return; Target[] newTargets = new Target[targets.length + 1]; System.arraycopy(targets, 0, newTargets, 0, targets.length); newTargets[targets.length] = target; targets = newTargets; } public Target next(Object client) { if (targets == null || targets.length == 0) return null; Target t = null; if(keepSession && client != null) { t = sessionMap.get(client); if(t == null) { t = choseNext(client); sessionMap.put(client, t); } }else{ t = choseNext(client); } return t; } public abstract Target choseNext(Object client); public enum LoadBalance { /** * 随机 */ RANDOM, /** * 轮询可用 */ POLLING_AVAILABLE, /** * ip哈希化 */ IP_HASH, /** * 最小活跃数 */ LEAST_ACTIVE, } }
Java
CL
de4d99ecc17b224dae74f2063ce55ae287d7c6cbbf51a0b782a06fcee4538e9e
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.supertribe; import org.junit.Assert; import org.junit.Test; import io.churchkey.Key; import io.churchkey.Keys; import java.security.interfaces.RSAPublicKey; public class ExampleTest { @Test public void read() throws Exception { final String pemFile = "" + "-----BEGIN PUBLIC KEY-----\n" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyzNurU19lqnYhx5QI72sIX1lh\n" + "8cTehTmboC+DLG7UuaUHqs096M754HtP2IiHFcIQqwYNzHgKmjmfGdbk9JBkz/DN\n" + "eDVsA5nc7qTnsSgULXTxwHSF286IJdco5kasaJm4Xurlm3V+2oiTugraBsi1J0Ht\n" + "0OtHgJIlIaGxK7mY/QIDAQAB\n" + "-----END PUBLIC KEY-----\n"; final Key key = Keys.decode(pemFile.getBytes()); Assert.assertEquals(Key.Algorithm.RSA, key.getAlgorithm()); Assert.assertEquals(Key.Format.PEM, key.getFormat()); Assert.assertEquals(Key.Type.PUBLIC, key.getType()); Assert.assertTrue(key.getKey() instanceof RSAPublicKey); } }
Java
CL
783a040d403d3dc3cc59a438da50326ffb982226051e7fa413c75e15d8f92c36
package com.google.android.gms.fitness.request; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import com.google.android.gms.common.internal.zzw; import com.google.android.gms.common.internal.zzx; import com.google.android.gms.fitness.data.Bucket; import com.google.android.gms.fitness.data.DataSource; import com.google.android.gms.fitness.data.DataType; import com.google.android.gms.fitness.data.Device; import com.google.android.gms.internal.zznu; import com.google.android.gms.internal.zznu.zza; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; public class DataReadRequest implements SafeParcelable { public static final Parcelable.Creator<DataReadRequest> CREATOR = new zzf(); public static final int NO_LIMIT = 0; private final int mVersionCode; private final long zzNY; private final long zzapN; private final List<DataType> zzapW; private final int zzapZ; private final List<DataSource> zzasd; private final List<DataType> zzasi; private final List<DataSource> zzasj; private final long zzask; private final DataSource zzasl; private final int zzasm; private final boolean zzasn; private final boolean zzaso; private final zznu zzasp; private final List<Device> zzasq; DataReadRequest(int paramInt1, List<DataType> paramList1, List<DataSource> paramList2, long paramLong1, long paramLong2, List<DataType> paramList3, List<DataSource> paramList4, int paramInt2, long paramLong3, DataSource paramDataSource, int paramInt3, boolean paramBoolean1, boolean paramBoolean2, IBinder paramIBinder, List<Device> paramList) { this.mVersionCode = paramInt1; this.zzapW = paramList1; this.zzasd = paramList2; this.zzNY = paramLong1; this.zzapN = paramLong2; this.zzasi = paramList3; this.zzasj = paramList4; this.zzapZ = paramInt2; this.zzask = paramLong3; this.zzasl = paramDataSource; this.zzasm = paramInt3; this.zzasn = paramBoolean1; this.zzaso = paramBoolean2; if (paramIBinder == null) {} for (paramList1 = null;; paramList1 = zznu.zza.zzbu(paramIBinder)) { this.zzasp = paramList1; paramList1 = paramList; if (paramList == null) { paramList1 = Collections.EMPTY_LIST; } this.zzasq = paramList1; return; } } private DataReadRequest(Builder paramBuilder) { this(Builder.zza(paramBuilder), Builder.zzb(paramBuilder), Builder.zzc(paramBuilder), Builder.zzd(paramBuilder), Builder.zze(paramBuilder), Builder.zzf(paramBuilder), Builder.zzg(paramBuilder), Builder.zzh(paramBuilder), Builder.zzi(paramBuilder), Builder.zzj(paramBuilder), Builder.zzk(paramBuilder), Builder.zzl(paramBuilder), null, Builder.zzm(paramBuilder)); } public DataReadRequest(DataReadRequest paramDataReadRequest, zznu paramzznu) { this(paramDataReadRequest.zzapW, paramDataReadRequest.zzasd, paramDataReadRequest.zzNY, paramDataReadRequest.zzapN, paramDataReadRequest.zzasi, paramDataReadRequest.zzasj, paramDataReadRequest.zzapZ, paramDataReadRequest.zzask, paramDataReadRequest.zzasl, paramDataReadRequest.zzasm, paramDataReadRequest.zzasn, paramDataReadRequest.zzaso, paramzznu, paramDataReadRequest.zzasq); } public DataReadRequest(List<DataType> paramList1, List<DataSource> paramList2, long paramLong1, long paramLong2, List<DataType> paramList3, List<DataSource> paramList4, int paramInt1, long paramLong3, DataSource paramDataSource, int paramInt2, boolean paramBoolean1, boolean paramBoolean2, zznu paramzznu, List<Device> paramList) {} private boolean zzb(DataReadRequest paramDataReadRequest) { return (this.zzapW.equals(paramDataReadRequest.zzapW)) && (this.zzasd.equals(paramDataReadRequest.zzasd)) && (this.zzNY == paramDataReadRequest.zzNY) && (this.zzapN == paramDataReadRequest.zzapN) && (this.zzapZ == paramDataReadRequest.zzapZ) && (this.zzasj.equals(paramDataReadRequest.zzasj)) && (this.zzasi.equals(paramDataReadRequest.zzasi)) && (zzw.equal(this.zzasl, paramDataReadRequest.zzasl)) && (this.zzask == paramDataReadRequest.zzask) && (this.zzaso == paramDataReadRequest.zzaso); } public int describeContents() { return 0; } public boolean equals(Object paramObject) { return (this == paramObject) || (((paramObject instanceof DataReadRequest)) && (zzb((DataReadRequest)paramObject))); } public DataSource getActivityDataSource() { return this.zzasl; } public List<DataSource> getAggregatedDataSources() { return this.zzasj; } public List<DataType> getAggregatedDataTypes() { return this.zzasi; } public long getBucketDuration(TimeUnit paramTimeUnit) { return paramTimeUnit.convert(this.zzask, TimeUnit.MILLISECONDS); } public int getBucketType() { return this.zzapZ; } public List<DataSource> getDataSources() { return this.zzasd; } public List<DataType> getDataTypes() { return this.zzapW; } public long getEndTime(TimeUnit paramTimeUnit) { return paramTimeUnit.convert(this.zzapN, TimeUnit.MILLISECONDS); } public int getLimit() { return this.zzasm; } public long getStartTime(TimeUnit paramTimeUnit) { return paramTimeUnit.convert(this.zzNY, TimeUnit.MILLISECONDS); } int getVersionCode() { return this.mVersionCode; } public int hashCode() { return zzw.hashCode(new Object[] { Integer.valueOf(this.zzapZ), Long.valueOf(this.zzNY), Long.valueOf(this.zzapN) }); } public String toString() { StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("DataReadRequest{"); Iterator localIterator; if (!this.zzapW.isEmpty()) { localIterator = this.zzapW.iterator(); while (localIterator.hasNext()) { localStringBuilder.append(((DataType)localIterator.next()).zzst()).append(" "); } } if (!this.zzasd.isEmpty()) { localIterator = this.zzasd.iterator(); while (localIterator.hasNext()) { localStringBuilder.append(((DataSource)localIterator.next()).toDebugString()).append(" "); } } if (this.zzapZ != 0) { localStringBuilder.append("bucket by ").append(Bucket.zzeu(this.zzapZ)); if (this.zzask > 0L) { localStringBuilder.append(" >").append(this.zzask).append("ms"); } localStringBuilder.append(": "); } if (!this.zzasi.isEmpty()) { localIterator = this.zzasi.iterator(); while (localIterator.hasNext()) { localStringBuilder.append(((DataType)localIterator.next()).zzst()).append(" "); } } if (!this.zzasj.isEmpty()) { localIterator = this.zzasj.iterator(); while (localIterator.hasNext()) { localStringBuilder.append(((DataSource)localIterator.next()).toDebugString()).append(" "); } } localStringBuilder.append(String.format("(%tF %tT - %tF %tT)", new Object[] { Long.valueOf(this.zzNY), Long.valueOf(this.zzNY), Long.valueOf(this.zzapN), Long.valueOf(this.zzapN) })); if (this.zzasl != null) { localStringBuilder.append("activities: ").append(this.zzasl.toDebugString()); } if (this.zzaso) { localStringBuilder.append(" +server"); } localStringBuilder.append("}"); return localStringBuilder.toString(); } public void writeToParcel(Parcel paramParcel, int paramInt) { zzf.zza(this, paramParcel, paramInt); } public long zzkX() { return this.zzNY; } public IBinder zzsO() { if (this.zzasp == null) { return null; } return this.zzasp.asBinder(); } public boolean zzsT() { return this.zzaso; } public boolean zzsU() { return this.zzasn; } public long zzsV() { return this.zzask; } public List<Device> zzsW() { return this.zzasq; } public long zzsi() { return this.zzapN; } public static class Builder { private long zzNY; private long zzapN; private List<DataType> zzapW = new ArrayList(); private int zzapZ = 0; private List<DataSource> zzasd = new ArrayList(); private List<DataType> zzasi = new ArrayList(); private List<DataSource> zzasj = new ArrayList(); private long zzask = 0L; private DataSource zzasl; private int zzasm = 0; private boolean zzasn = false; private boolean zzaso = false; private List<Device> zzasq = new ArrayList(); public Builder aggregate(DataSource paramDataSource, DataType paramDataType) { zzx.zzb(paramDataSource, "Attempting to add a null data source"); if (!this.zzasd.contains(paramDataSource)) {} for (boolean bool = true;; bool = false) { zzx.zza(bool, "Cannot add the same data source for aggregated and detailed"); DataType localDataType = paramDataSource.getDataType(); zzx.zzb(DataType.AGGREGATE_INPUT_TYPES.contains(localDataType), "Unsupported input data type specified for aggregation: %s", new Object[] { localDataType }); zzx.zzb(DataType.getAggregatesForInput(localDataType).contains(paramDataType), "Invalid output aggregate data type specified: %s -> %s", new Object[] { localDataType, paramDataType }); if (!this.zzasj.contains(paramDataSource)) { this.zzasj.add(paramDataSource); } return this; } } public Builder aggregate(DataType paramDataType1, DataType paramDataType2) { zzx.zzb(paramDataType1, "Attempting to use a null data type"); if (!this.zzapW.contains(paramDataType1)) {} for (boolean bool = true;; bool = false) { zzx.zza(bool, "Cannot add the same data type as aggregated and detailed"); zzx.zzb(DataType.AGGREGATE_INPUT_TYPES.contains(paramDataType1), "Unsupported input data type specified for aggregation: %s", new Object[] { paramDataType1 }); zzx.zzb(DataType.getAggregatesForInput(paramDataType1).contains(paramDataType2), "Invalid output aggregate data type specified: %s -> %s", new Object[] { paramDataType1, paramDataType2 }); if (!this.zzasi.contains(paramDataType1)) { this.zzasi.add(paramDataType1); } return this; } } public Builder bucketByActivitySegment(int paramInt, TimeUnit paramTimeUnit) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label74; } } label74: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); this.zzapZ = 4; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; } } public Builder bucketByActivitySegment(int paramInt, TimeUnit paramTimeUnit, DataSource paramDataSource) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label121; } bool = true; label38: zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); if (paramDataSource == null) { break label127; } } label121: label127: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Invalid activity data source specified"); zzx.zzb(paramDataSource.getDataType().equals(DataType.TYPE_ACTIVITY_SEGMENT), "Invalid activity data source specified: %s", new Object[] { paramDataSource }); this.zzasl = paramDataSource; this.zzapZ = 4; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; bool = false; break label38; } } public Builder bucketByActivityType(int paramInt, TimeUnit paramTimeUnit) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label74; } } label74: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); this.zzapZ = 3; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; } } public Builder bucketByActivityType(int paramInt, TimeUnit paramTimeUnit, DataSource paramDataSource) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label121; } bool = true; label38: zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); if (paramDataSource == null) { break label127; } } label121: label127: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Invalid activity data source specified"); zzx.zzb(paramDataSource.getDataType().equals(DataType.TYPE_ACTIVITY_SEGMENT), "Invalid activity data source specified: %s", new Object[] { paramDataSource }); this.zzasl = paramDataSource; this.zzapZ = 3; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; bool = false; break label38; } } public Builder bucketBySession(int paramInt, TimeUnit paramTimeUnit) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label74; } } label74: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); this.zzapZ = 2; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; } } public Builder bucketByTime(int paramInt, TimeUnit paramTimeUnit) { if (this.zzapZ == 0) { bool = true; zzx.zzb(bool, "Bucketing strategy already set to %s", new Object[] { Integer.valueOf(this.zzapZ) }); if (paramInt <= 0) { break label74; } } label74: for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Must specify a valid minimum duration for an activity segment: %d", new Object[] { Integer.valueOf(paramInt) }); this.zzapZ = 1; this.zzask = paramTimeUnit.toMillis(paramInt); return this; bool = false; break; } } public DataReadRequest build() { boolean bool2 = true; label69: label112: int i; if ((!this.zzasd.isEmpty()) || (!this.zzapW.isEmpty()) || (!this.zzasj.isEmpty()) || (!this.zzasi.isEmpty())) { bool1 = true; zzx.zza(bool1, "Must add at least one data source (aggregated or detailed)"); if (this.zzNY <= 0L) { break label205; } bool1 = true; zzx.zza(bool1, "Invalid start time: %s", new Object[] { Long.valueOf(this.zzNY) }); if ((this.zzapN <= 0L) || (this.zzapN <= this.zzNY)) { break label210; } bool1 = true; zzx.zza(bool1, "Invalid end time: %s", new Object[] { Long.valueOf(this.zzapN) }); if ((!this.zzasj.isEmpty()) || (!this.zzasi.isEmpty())) { break label215; } i = 1; label158: if (i != 0) { bool1 = bool2; if (this.zzapZ == 0) {} } else { if ((i != 0) || (this.zzapZ == 0)) { break label220; } } } label205: label210: label215: label220: for (boolean bool1 = bool2;; bool1 = false) { zzx.zza(bool1, "Must specify a valid bucketing strategy while requesting aggregation"); return new DataReadRequest(this, null); bool1 = false; break; bool1 = false; break label69; bool1 = false; break label112; i = 0; break label158; } } public Builder enableServerQueries() { this.zzaso = true; return this; } public Builder read(DataSource paramDataSource) { zzx.zzb(paramDataSource, "Attempting to add a null data source"); if (!this.zzasj.contains(paramDataSource)) {} for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Cannot add the same data source as aggregated and detailed"); if (!this.zzasd.contains(paramDataSource)) { this.zzasd.add(paramDataSource); } return this; } } public Builder read(DataType paramDataType) { zzx.zzb(paramDataType, "Attempting to use a null data type"); if (!this.zzasi.contains(paramDataType)) {} for (boolean bool = true;; bool = false) { zzx.zza(bool, "Cannot add the same data type as aggregated and detailed"); if (!this.zzapW.contains(paramDataType)) { this.zzapW.add(paramDataType); } return this; } } public Builder setLimit(int paramInt) { if (paramInt > 0) {} for (boolean bool = true;; bool = false) { zzx.zzb(bool, "Invalid limit %d is specified", new Object[] { Integer.valueOf(paramInt) }); this.zzasm = paramInt; return this; } } public Builder setTimeRange(long paramLong1, long paramLong2, TimeUnit paramTimeUnit) { this.zzNY = paramTimeUnit.toMillis(paramLong1); this.zzapN = paramTimeUnit.toMillis(paramLong2); return this; } } } /* Location: C:\Users\julian\Downloads\Veryfit 2 0_vV2.0.28_apkpure.com-dex2jar.jar!\com\google\android\gms\fitness\request\DataReadRequest.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
Java
CL
6bba506355387141ff222059f32b978f76d3eb1c97412a4637ff0d4e920ec5b0
/** */ package rover; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see rover.RoverPackage * @generated */ public interface RoverFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ RoverFactory eINSTANCE = rover.impl.RoverFactoryImpl.init(); /** * Returns a new object of class '<em>Rover</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Rover</em>'. * @generated */ Rover createRover(); /** * Returns a new object of class '<em>Sensor</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Sensor</em>'. * @generated */ Sensor createSensor(); /** * Returns a new object of class '<em>Actuator</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Actuator</em>'. * @generated */ Actuator createActuator(); /** * Returns a new object of class '<em>GPS</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>GPS</em>'. * @generated */ GPS createGPS(); /** * Returns a new object of class '<em>Distance Sensor</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Distance Sensor</em>'. * @generated */ DistanceSensor createDistanceSensor(); /** * Returns a new object of class '<em>direction Facing</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>direction Facing</em>'. * @generated */ directionFacing createdirectionFacing(); /** * Returns a new object of class '<em>Motor</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Motor</em>'. * @generated */ Motor createMotor(); /** * Returns a new object of class '<em>Light</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Light</em>'. * @generated */ Light createLight(); /** * Returns a new object of class '<em>Program</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Program</em>'. * @generated */ Program createProgram(); /** * Returns a new object of class '<em>Block</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Block</em>'. * @generated */ Block createBlock(); /** * Returns a new object of class '<em>Command</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Command</em>'. * @generated */ Command createCommand(); /** * Returns a new object of class '<em>Tansition</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Tansition</em>'. * @generated */ Tansition createTansition(); /** * Returns a new object of class '<em>Set Light Color</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Set Light Color</em>'. * @generated */ SetLightColor createSetLightColor(); /** * Returns a new object of class '<em>Wait</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Wait</em>'. * @generated */ Wait createWait(); /** * Returns a new object of class '<em>Move</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Move</em>'. * @generated */ Move createMove(); /** * Returns a new object of class '<em>Rotate</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Rotate</em>'. * @generated */ Rotate createRotate(); /** * Returns a new object of class '<em>Terminate</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Terminate</em>'. * @generated */ Terminate createTerminate(); /** * Returns a new object of class '<em>Repeate</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Repeate</em>'. * @generated */ Repeate createRepeate(); /** * Returns a new object of class '<em>Start</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Start</em>'. * @generated */ Start createStart(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ RoverPackage getRoverPackage(); } //RoverFactory
Java
CL
12617d1a03fa3d6cab5219990249cd5b1521abba9441fb9cfcfe6ea4956028e1
/* * Copyright 2016 charl. * * 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.atf.hybird.server.pageobj; import com.atf.hybird.Element; import com.atf.hybird.AppDriver; import com.atf.hybird.annotations.FindBy; /** * * @author charl */ public class TestPageForFramework { AppDriver driver; @FindBy(className="userName") Element userName; @FindBy(className="password") Element password; @FindBy(className="btnLogin") Element btnLogin; @FindBy(className="btnCancel") Element btnCancel; public TestPageForFramework(AppDriver driver){ this.driver=driver; } public void inputUserName(String id){ System.out.println(userName.getLocateScript()); userName.input(id,50000); } public void inputPassword(String password){ System.out.println(this.password.getLocateScript()); this.password.input(password,10000); } public void login(){ System.out.println(btnLogin.getLocateScript()); btnLogin.click(15000); } public String getTestScript(){ return this.driver.getTestScript(); } }
Java
CL
f49b5c0d074a55a87b0cc81711e7796b8b3c8af10316e6dda7a6f479e3bd9fcd
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * 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.caffinitas.ohc; import java.io.IOError; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import com.google.common.cache.CacheStats; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.caffinitas.ohc.Constants.*; public final class SegmentedCacheImpl<K, V> implements OHCache<K, V> { private static final Logger LOGGER = LoggerFactory.getLogger(SegmentedCacheImpl.class); public static final int ONE_GIGABYTE = 1024 * 1024 * 1024; private final CacheSerializer<K> keySerializer; private final CacheSerializer<V> valueSerializer; private final OffHeapMap[] maps; private final long segmentMask; private final int segmentShift; private final long maxEntrySize; private boolean statisticsEnabled; private volatile long hitCount; private volatile long missCount; private volatile long loadSuccessCount; private volatile long loadExceptionCount; private volatile long totalLoadTime; private volatile long putFailCount; private volatile long putAddCount; private volatile long putReplaceCount; private volatile long removeCount; public SegmentedCacheImpl(OHCacheBuilder<K, V> builder) { long capacity = builder.getCapacity(); // calculate trigger for cleanup/eviction/replacement double cuTrigger = builder.getCleanUpTriggerFree(); long cleanUpTriggerFree; if (cuTrigger < 0d) { // auto-sizing // 12.5% if capacity less than 8GB // 10% if capacity less than 16 GB // 5% if capacity is higher than 16GB if (capacity < 8L * ONE_GIGABYTE) cleanUpTriggerFree = (long) (.125d * capacity); else if (capacity < 16L * ONE_GIGABYTE) cleanUpTriggerFree = (long) (.10d * capacity); else cleanUpTriggerFree = (long) (.05d * capacity); } else { if (cuTrigger >= 1d) throw new IllegalArgumentException("Invalid clean-up percentage trigger value " + String.format("%.2f", cuTrigger)); cuTrigger *= capacity; cleanUpTriggerFree = (long) cuTrigger; } // build segments int segments = builder.getSegmentCount(); if (segments <= 0) segments = Runtime.getRuntime().availableProcessors() * 2; segments = OffHeapMap.roundUpToPowerOf2(segments); maps = new OffHeapMap[segments]; for (int i = 0; i < segments; i++) maps[i] = new OffHeapMap(builder, capacity / segments, cleanUpTriggerFree / segments ); // bit-mask for segment part of hash int bitNum = bitNum(segments) - 1; this.segmentShift = 64 - bitNum; this.segmentMask = ((long) segments - 1) << segmentShift; // calculate max entry size double mes = builder.getMaxEntrySize(); long maxEntrySize; if (mes <= 0d || mes >= 1d) maxEntrySize = capacity / segments / 128; else maxEntrySize = (long) (mes * capacity / segments); this.maxEntrySize = maxEntrySize; this.statisticsEnabled = builder.isStatisticsEnabled(); this.keySerializer = builder.getKeySerializer(); this.valueSerializer = builder.getValueSerializer(); } private static int bitNum(long val) { int bit = 0; for (; val != 0L; bit++) val >>>= 1; return bit; } // // map stuff // public V getIfPresent(Object key) { KeyBuffer keySource = keySource((K) key); long hashEntryAdr = segment(keySource.hash()).getEntry(keySource); if (hashEntryAdr == 0L) { if (statisticsEnabled) missCount++; return null; } if (statisticsEnabled) hitCount++; try { return valueSerializer.deserialize(HashEntries.readValueFrom(hashEntryAdr)); } catch (IOException e) { throw new IOError(e); } finally { dereference(hashEntryAdr); } } public void put(K k, V v) { KeyBuffer key = keySource(k); long keyLen = key.size(); long valueLen = valueSerializer.serializedSize(v); long hash = key.hash(); long bytes = allocLen(keyLen, valueLen); long hashEntryAdr; if (bytes > maxEntrySize || (hashEntryAdr = Uns.allocate(bytes))==0L) { // entry too large to be inserted or OS is not able to provide enough memory if (statisticsEnabled) putFailCount++; removeInternal(key); return; } // initialize hash entry HashEntries.init(hash, keyLen, valueLen, hashEntryAdr); HashEntries.toOffHeap(key, hashEntryAdr, ENTRY_OFF_DATA); try { valueSerializer.serialize(v, new HashEntryOutput(hashEntryAdr, key.size(), valueLen)); } catch (VirtualMachineError e) { Uns.free(hashEntryAdr); throw e; } catch (Throwable e) { Uns.free(hashEntryAdr); throw new IOError(e); } if (segment(hash).putEntry(key, hashEntryAdr, bytes)) { if (statisticsEnabled) putAddCount++; return; } if (statisticsEnabled) putReplaceCount++; } public void invalidate(Object k) { KeyBuffer key = keySource((K) k); if (removeInternal(key) && statisticsEnabled) removeCount++; } private boolean removeInternal(KeyBuffer key) { return segment(key.hash()).removeEntry(key); } private OffHeapMap segment(long hash) { int seg = (int) ((hash & segmentMask) >>> segmentShift); return maps[seg]; } private KeyBuffer keySource(K o) { if (keySerializer == null) throw new NullPointerException("no keySerializer configured"); int size = keySerializer.serializedSize(o); KeyBuffer key = new KeyBuffer(size); try { keySerializer.serialize(o, key); } catch (IOException e) { throw new IOError(e); } return key.finish(); } // // maintenance // public Iterator<K> hotN(int n) { // hotN implementation does only return a (good) approximation - not necessarily the exact hotN // since it iterates over the all segments and takes a fraction of 'n' from them. // This implementation may also return more results than expected just to keep it simple // (it does not really matter if you request 5000 keys and e.g. get 5015). final int perMap = n / maps.length + 1; return new AbstractIterator<K>() { int mapIndex; long[] hotPerMap; int subIndex; protected K computeNext() { while (true) { if (hotPerMap != null && subIndex < hotPerMap.length) { long hashEntryAdr = hotPerMap[subIndex++]; if (hashEntryAdr != 0L) try { return keySerializer.deserialize(HashEntries.readKeyFrom(hashEntryAdr)); } catch (IOException e) { LOGGER.error("Key serializer failed to deserialize", e); continue; } finally { dereference(hashEntryAdr); } } if (mapIndex == maps.length) return endOfData(); hotPerMap = maps[mapIndex++].hotN(perMap); subIndex = 0; } } }; } public void invalidateAll() { for (OffHeapMap map : maps) map.clear(); } public void cleanUp() { for (OffHeapMap map : maps) map.cleanUp(); } // // state // public void close() throws IOException { invalidateAll(); for (OffHeapMap map : maps) map.release(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Closing OHC instance"); } // // statistics and related stuff // public boolean isStatisticsEnabled() { return statisticsEnabled; } public void setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; } public void resetStatistics() { for (OffHeapMap map : maps) map.resetStatistics(); putAddCount = 0; putReplaceCount = 0; putFailCount = 0; removeCount = 0; hitCount = 0; missCount = 0; loadSuccessCount = 0; loadExceptionCount = 0; totalLoadTime = 0; } public OHCacheStats extendedStats() { long[] mapSizes = new long[maps.length]; long rehashes = 0L; for (int i = 0; i < maps.length; i++) { OffHeapMap map = maps[i]; rehashes += map.rehashes(); mapSizes[i] = map.size(); } return new OHCacheStats(stats(), mapSizes, size(), getCapacity(), freeCapacity(), cleanUpCount(), rehashes, putAddCount, putReplaceCount, putFailCount, removeCount); } public CacheStats stats() { return new CacheStats( hitCount, missCount, loadSuccessCount, loadExceptionCount, totalLoadTime, evictedEntries() ); } public long getCapacity() { long capacity = 0L; for (OffHeapMap map : maps) capacity += map.capacity(); return capacity; } public long freeCapacity() { long capacity = 0L; for (OffHeapMap map : maps) capacity += map.freeCapacity(); return capacity; } public long cleanUpCount() { long cleanUpCount = 0L; for (OffHeapMap map : maps) cleanUpCount += map.cleanUpCount(); return cleanUpCount; } public long evictedEntries() { long evictedEntries = 0L; for (OffHeapMap map : maps) evictedEntries += map.evictedEntries(); return evictedEntries; } public long size() { long size = 0L; for (OffHeapMap map : maps) size += map.size(); return size; } public int getSegments() { return maps.length; } public double getLoadFactor() { return maps[0].loadFactor(); } public int[] getHashTableSizes() { int[] r = new int[maps.length]; for (int i = 0; i < maps.length; i++) r[i] = maps[i].hashTableSize(); return r; } // // convenience methods // public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException { V v = getIfPresent(key); if (v == null) { long t0 = System.currentTimeMillis(); try { v = valueLoader.call(); loadSuccessCount++; } catch (Exception e) { loadExceptionCount++; throw new ExecutionException(e); } finally { totalLoadTime += System.currentTimeMillis() - t0; } put(key, v); } return v; } public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) { // TODO implement return null; } public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) put(entry.getKey(), entry.getValue()); } public void invalidateAll(Iterable<?> iterable) { for (Object o : iterable) invalidate(o); } public long getMemUsed() { return getCapacity() - freeCapacity(); } // // methods that don't make sense in this implementation // public ConcurrentMap<K, V> asMap() { throw new UnsupportedOperationException(); } // // alloc/free // private void dereference(long hashEntryAdr) { if (HashEntries.dereference(hashEntryAdr)) free(hashEntryAdr); } long free(long hashEntryAdr) { if (hashEntryAdr == 0L) throw new NullPointerException(); long bytes = HashEntries.getAllocLen(hashEntryAdr); if (bytes == 0L) throw new IllegalStateException(); long hash = HashEntries.getHash(hashEntryAdr); Uns.free(hashEntryAdr); segment(hash).freed(bytes); return bytes; } }
Java
CL
e1c5069fc413df68bd9a9d98b71548ab0a845ec6769a8182a91f28f0927cf6f4
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2011, Geomatys * * This library 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotoolkit.ncwms; import org.geotoolkit.client.Request; /** * Interface for GetMetadata requests * * @author Olivier Terral (Geomatys) * @module */ public interface NcGetMetadataRequest extends Request { /** * Returns the layer name. */ String getLayerName(); /** * Sets the layer name. */ void setLayerName(final String name); /** * Returns an id representing which informations you want. */ String getItem(); /** * Sets the type of the GetMetadata request. * * @param item The type of the GetMetadata request. Possible values * are 'menu', 'layerDetails', 'timesteps', 'minmax', 'animationTimesteps' */ void setItem(final String item); /** * Returns the day in ISO8601 format. */ String getDay(); /** * Sets the day in ISO8601 format. */ void setDay(final String day); /** * Returns the start date of an animation in ISO8601 format. */ String getStart(); /** * Sets the start date of an animation in ISO8601 format. */ void setStart(final String start); /** * Returns the end date of an animation in ISO8601 format. */ String getEnd(); /** * Sets the end date of an animation in ISO8601 format. */ void setEnd(final String end); /** * Returns the Time in ISO8601 format. */ String getTime(); /** * Sets the Time in ISO8601 format. */ void setTime(final String time); /** * Gets the Elevation. */ public String getElevation(); /** * Sets the Elevation. */ public void setElevation(final String elevation); }
Java
CL
85ffad3ee56a0d9cf4c2697640d79616dc9143e16bf28b0a7b5e6402fadf0a57
package com.at.ac.tuwien.sepm.ss15.edulium.gui; import com.at.ac.tuwien.sepm.ss15.edulium.domain.MenuEntry; import com.at.ac.tuwien.sepm.ss15.edulium.domain.validation.ValidationException; import com.at.ac.tuwien.sepm.ss15.edulium.domain.validation.Validator; import com.at.ac.tuwien.sepm.ss15.edulium.service.MenuService; import com.at.ac.tuwien.sepm.ss15.edulium.service.ServiceException; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.annotation.Resource; import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; @Controller public class MenuEntryViewController implements Initializable { private static final Logger LOGGER = LogManager.getLogger(MenuEntryViewController.class); @FXML private TableView<MenuEntry> tableViewMenuEntry; @FXML private TableColumn<MenuEntry,Long> tableColMenuEntryId; @FXML private TableColumn<MenuEntry,String> tableColMenuEntryName; @FXML private TableColumn<MenuEntry,BigDecimal> tableColMenuEntryPrice; @FXML private TableColumn<MenuEntry, String> tableColMenuEntryCategory; @FXML private TableColumn<MenuEntry, Boolean> tableColMenuEntryAvailable; @FXML private Button buttonMenuEntryUpdate; @FXML private Button buttonMenuEntryRemove; @FXML private Button buttonMenuEntryAvailable; @Autowired private MenuService menuService; @Autowired private Validator<MenuEntry> menuEntryValidator; @Resource(name = "menuEntryDialogPane") private FXMLPane menuEntryDialogPane; private MenuEntryDialogController menuEntryDialogController; private final ObservableList<MenuEntry> menuEntries = FXCollections.observableArrayList(); @Override public void initialize(URL location, ResourceBundle resources) { menuEntryDialogController = menuEntryDialogPane.getController(); tableViewMenuEntry.setItems(menuEntries); tableViewMenuEntry.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); tableColMenuEntryId.setCellValueFactory(new PropertyValueFactory<>("identity")); tableColMenuEntryName.setCellValueFactory(new PropertyValueFactory<>("name")); tableColMenuEntryPrice.setCellValueFactory(new PropertyValueFactory<>("price")); tableColMenuEntryAvailable.setCellValueFactory(new PropertyValueFactory<>("available")); tableColMenuEntryCategory.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getCategory().getName())); tableViewMenuEntry.getSelectionModel().selectedIndexProperty().addListener(event -> { final boolean hasSelection = tableViewMenuEntry.getSelectionModel().getSelectedIndex() >= 0; buttonMenuEntryUpdate.setDisable(!hasSelection); buttonMenuEntryRemove.setDisable(!hasSelection); buttonMenuEntryAvailable.setDisable(!hasSelection); }); loadAllMenuEntries(); } @FXML public void buttonMenuEntryRemoveClicked() { List<MenuEntry> selectedMenuEntries = tableViewMenuEntry.getSelectionModel().getSelectedItems(); for (MenuEntry menuEntry : selectedMenuEntries) { try { menuService.removeMenuEntry(menuEntry); } catch (ValidationException | ServiceException e) { LOGGER.error("Could not delete menu entry " + menuEntry, e); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error while deleting menu entry"); alert.setHeaderText("Could not delete menu entry '" + menuEntry.getName() + "'"); alert.setContentText(e.getMessage()); alert.showAndWait(); } } menuEntries.removeAll(selectedMenuEntries); } @FXML public void buttonMenuEntrySearchClicked() { SearchInputDialog<MenuEntry> menuEntrySearchDialog = new SearchInputDialog<>("menu entries"); menuEntrySearchDialog.setContent(menuEntryDialogPane); menuEntrySearchDialog.setController(menuEntryDialogController); menuEntrySearchDialog.showAndWait().ifPresent(menuEntryMatcher -> { try { menuEntries.setAll(menuService.findMenuEntry(menuEntryMatcher)); } catch (ServiceException e) { LOGGER.error("Could not search for menu entries with matcher " + menuEntryMatcher, e); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error while searching for menu entries"); alert.setHeaderText("Could not search for menu entries"); alert.setContentText(e.getMessage()); alert.showAndWait(); } }); } @FXML public void buttonMenuEntryUpdateClicked() { MenuEntry selectedMenuEntry = tableViewMenuEntry.getSelectionModel().getSelectedItem(); if (selectedMenuEntry != null) { UpdateInputDialog<MenuEntry> menuEntryInputDialog = new UpdateInputDialog<>("menu entry", selectedMenuEntry); menuEntryInputDialog.setValidator(menuEntryValidator); menuEntryInputDialog.setContent(menuEntryDialogPane); menuEntryInputDialog.setController(menuEntryDialogController); menuEntryInputDialog.showAndWait().ifPresent(editedMenuEntry -> { try { menuService.updateMenuEntry(editedMenuEntry); menuEntries.remove(selectedMenuEntry); menuEntries.add(editedMenuEntry); } catch (ValidationException | ServiceException e) { LOGGER.error("Could not change menu entry " + editedMenuEntry, e); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error while updating menu entry"); alert.setHeaderText("Could not update menu entry '" + selectedMenuEntry.getName() + "'"); alert.setContentText(e.getMessage()); alert.showAndWait(); } }); } } @FXML public void buttonMenuEntryAddClicked() { CreateInputDialog<MenuEntry> menuEntryInputDialog = new CreateInputDialog<>("menu entry"); menuEntryInputDialog.setValidator(menuEntryValidator); menuEntryInputDialog.setContent(menuEntryDialogPane); menuEntryInputDialog.setController(menuEntryDialogController); menuEntryInputDialog.showAndWait().ifPresent(menuEntry -> { try { menuService.addMenuEntry(menuEntry); menuEntries.add(menuEntry); } catch (ValidationException | ServiceException e) { LOGGER.error("Could not add menu entry " + menuEntry, e); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error while adding menu entry"); alert.setHeaderText("Could not add menu entry '" + menuEntry.getName() + "'"); alert.setContentText(e.getMessage()); alert.showAndWait(); } }); } @FXML public void buttonMenuEntryAvailableClicked() { List<MenuEntry> selectedMenuEntries = tableViewMenuEntry.getSelectionModel().getSelectedItems(); List<MenuEntry> addMenuEntries = new ArrayList<>(); for (MenuEntry menuEntry : selectedMenuEntries) { try { MenuEntry editedMenuEntry = menuEntry.clone(); editedMenuEntry.setAvailable(true); menuService.updateMenuEntry(editedMenuEntry); addMenuEntries.add(editedMenuEntry); } catch (ValidationException | ServiceException e) { LOGGER.error("Could not reset availability of menu entry " + menuEntry, e); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error while resetting the availability a menu entry"); alert.setHeaderText("Could not reset the availability of the menu entry '" + menuEntry.getName() + "'"); alert.setContentText(e.getMessage()); alert.showAndWait(); } } menuEntries.removeAll(selectedMenuEntries); menuEntries.addAll(addMenuEntries); } @FXML public void buttonShowAllMenuEntryClicked() { loadAllMenuEntries(); } private void loadAllMenuEntries() { try { menuEntries.setAll(menuService.getAllMenuEntries()); } catch (ServiceException e){ LOGGER.error("Could not load all menu entries", e); } } }
Java
CL
4239ed06248a57fbc42f62edc771bbaecbbcff962ce7cbe32fbcb407db0fbdf8
package com.vcat.module.ec.web; import com.vcat.common.easyui.DataGrid; import com.vcat.common.persistence.Page; import com.vcat.common.utils.DateUtils; import com.vcat.common.utils.StringUtils; import com.vcat.common.web.BaseController; import com.vcat.module.core.utils.excel.ExportExcel; import com.vcat.module.ec.entity.*; import com.vcat.module.ec.service.*; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * 供货商Controller */ @Controller @RequestMapping(value = "${adminPath}/ec/supplier") public class SupplierController extends BaseController { @Autowired private SupplierService supplierService; @Autowired private BrandService brandService; @Autowired private GatewayService gatewayService; @Autowired private ReconciliationDetailService reconciliationDetailService; @Autowired private ProductReconciliationService productReconciliationService; @Autowired private AccountingService accountingService; @Autowired private ReconciliationFreightService reconciliationFreightService; @RequiresPermissions("ec:supplier:list") @RequestMapping(value = "list") public String list(Supplier supplier, HttpServletRequest request, HttpServletResponse response, Model model) { model.addAttribute("page", supplierService.findPage(new Page<>(request, response), supplier)); return "module/ec/supplier/list"; } @RequiresPermissions("ec:supplier:edit") @RequestMapping(value = "form") public String form(Supplier supplier, Model model) { if(StringUtils.isNotEmpty(supplier.getId())){ supplier = supplierService.get(supplier); } model.addAttribute("supplier",supplier); return "module/ec/supplier/form"; } @RequiresPermissions("ec:supplier:edit") @RequestMapping(value = "save") public String save(Supplier supplier, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, supplier)){ return form(supplier, model); } supplierService.save(supplier); addMessage(redirectAttributes, "保存供货商'" + StringUtils.abbr(supplier.getName(), 100) + "'成功"); return "redirect:" + adminPath + "/ec/supplier/list"; } @RequiresPermissions("ec:finance:supplier:statementOfAccount") @RequestMapping(value = "statementOfAccount") public String statementOfAccount(Supplier supplier,@RequestParam(value = "init" ,defaultValue = "false")boolean init, HttpServletRequest request, HttpServletResponse response, Model model) { model.addAttribute("supplierList", supplierService.findList(new Supplier())); model.addAttribute("brandList", brandService.findList(new Brand())); if (!init) { model.addAttribute("page", supplierService.statementOfAccount(new Page<>(request, response), supplier)); model.addAttribute("totalList", supplierService.statementOfAccountTotal(supplier)); } return "module/ec/supplier/statementOfAccount"; } @RequiresPermissions("ec:finance:supplier:statementOfAccount") @RequestMapping(value = "exportStatementOfAccount", method= RequestMethod.POST) public void exportStatementOfAccount(Supplier supplier, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "供应商对账单"+ DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; Page<StatementOfAccount> page = supplierService.statementOfAccount(new Page<>(request, response, -1), supplier); page.getList().addAll(supplierService.statementOfAccountTotal(supplier)); new ExportExcel("V猫小店对账单", StatementOfAccount.class).setDataList(page.getList()).write(response, fileName).dispose(); } catch (Exception e) { logger.error("导出V猫小店供应商对账单失败!失败信息:" + e.getMessage()); } } @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "statementOfFinancial") public String statementOfFinancial(Supplier supplier,Model model) { model.addAttribute("supplier", supplier); model.addAttribute("supplierList", supplierService.findList(new Supplier())); model.addAttribute("brandList", brandService.findList(new Brand())); model.addAttribute("gatewayList", gatewayService.findList(new Gateway())); return "module/ec/supplier/statementOfFinancial"; } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "statementOfFinancialData") public DataGrid statementOfFinancialData(Supplier supplier, HttpServletRequest request, HttpServletResponse response) { DataGrid dataGrid = DataGrid.parse(supplierService.statementOfFinancial(new Page<>(request, response), supplier)); dataGrid.setFooter(supplierService.statementOfFinancialTotal(supplier)); return dataGrid; } @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "exportStatementOfFinancial", method= RequestMethod.POST) public void exportStatementOfFinancial(Supplier supplier, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "财务对账单"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; supplier.getSqlMap().put("mode","export"); Page<StatementOfFinancial> page = supplierService.statementOfFinancial(new Page<>(request, response, -1), supplier); page.getList().addAll(supplierService.statementOfFinancialTotal(supplier)); new ExportExcel("V猫小店对账单", StatementOfFinancial.class).setDataList(page.getList()).write(response, fileName).dispose(); } catch (Exception e) { logger.error("导出V猫小店财务对账单失败!失败信息:"+e.getMessage()); } } @ResponseBody @RequestMapping(value = "getSupplierList") public List<Supplier> getSupplierList() { return supplierService.findList(new Supplier()); } @ResponseBody @RequestMapping(value = "getBrandList") public List<Brand> getBrandList() { return brandService.findList(new Brand()); } @RequiresPermissions("ec:brand:list") @RequestMapping(value = "brandList") public String brandList(Brand brand, HttpServletRequest request, HttpServletResponse response, Model model) { model.addAttribute("supplierList", supplierService.findList(new Supplier())); model.addAttribute("page", brandService.findPage(new Page<>(request, response), brand)); return "module/ec/brand/list"; } @RequiresPermissions("ec:brand:edit") @RequestMapping(value = "brandForm") public String brandForm(Brand brand, Model model) { if(StringUtils.isNotEmpty(brand.getId())){ brand = brandService.get(brand); } model.addAttribute("brand", brand); model.addAttribute("supplierList", supplierService.findList(new Supplier())); return "module/ec/brand/form"; } @RequiresPermissions("ec:brand:edit") @RequestMapping(value = "saveBrand") public String brandSave(Brand brand, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, brand)){ return brandForm(brand, model); } brandService.save(brand); addMessage(redirectAttributes, "保存品牌'" + StringUtils.abbr(brand.getName(), 100) + "'成功"); return "redirect:" + adminPath + "/ec/supplier/brandList"; } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationOrder") public void reconciliationOrder(ReconciliationDetail reconciliationDetail) { reconciliationDetailService.reconciliationByOrder(reconciliationDetail); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationItem") public void reconciliationItem(ReconciliationDetail reconciliationDetail) { reconciliationDetailService.reconciliationByItem(reconciliationDetail); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "batchReconciliationOrder") public int batchReconciliationOrder(String[] orderIdArray) { return reconciliationDetailService.batchReconciliationOrder(orderIdArray); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationByQueryConditions") public int reconciliationByQueryConditions(Supplier supplier) { return reconciliationDetailService.reconciliationByQueryConditions(supplier); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "getReconciliationDetailList") public List<ReconciliationDetail> getReconciliationDetailList(ReconciliationDetail reconciliationDetail) { return reconciliationDetailService.findList(reconciliationDetail); } @RequiresPermissions("ec:supplier:productReconciliation") @RequestMapping(value = "productReconciliation") public String productReconciliation(ProductReconciliation productReconciliation,HttpServletRequest request, HttpServletResponse response, Model model) { model.addAttribute("page", productReconciliationService.findPage(new Page<>(request, response), productReconciliation)); model.addAttribute("productReconciliation",productReconciliation); model.addAttribute("brandList", brandService.findList(new Brand())); return "module/ec/supplier/productReconciliation"; } @ResponseBody @RequiresPermissions("ec:supplier:productReconciliation") @RequestMapping(value = "saveProductReconciliation") public void saveProductReconciliation(@RequestParam(value = "itemIdArray")String[] itemIdArray, @RequestParam(value = "productIdArray")String[] productIdArray, @RequestParam(value = "surplusQuantityArray")int[] surplusQuantityArray) { productReconciliationService.saveList(itemIdArray, productIdArray, surplusQuantityArray); } @ResponseBody @RequiresPermissions("ec:supplier:productReconciliation") @RequestMapping(value = "addProductReconciliation") public void addProductReconciliation(@RequestParam(value = "itemIdArray")String[] itemIdArray, @RequestParam(value = "surplusQuantityArray")int[] surplusQuantityArray) { productReconciliationService.addReconciliation(itemIdArray, surplusQuantityArray); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "accountingOrder") public void accountingOrder(Accounting accounting) { accountingService.accountingByOrder(accounting); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "batchAccountingOrder") public int batchAccountingOrder(@RequestParam(required = false, value = "orderIdArray") String[] orderIdArray) { return accountingService.batchAccountingOrder(orderIdArray); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "accountingByQueryConditions") public int accountingByQueryConditions(Supplier supplier) { return accountingService.accountingByQueryConditions(supplier); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationFreight") public void reconciliationFreightOrder(ReconciliationFreight reconciliationFreight) { reconciliationFreightService.reconciliationFreightByOrder(reconciliationFreight); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "batchReconciliationFreight") public int batchReconciliationFreightOrder(@RequestParam(required = false, value = "orderIdArray") String[] orderIdArray) { return reconciliationFreightService.batchReconciliationFreight(orderIdArray); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationFreightByQueryConditions") public int reconciliationFreightByQueryConditions(Supplier supplier) { return reconciliationFreightService.reconciliationFreightByQueryConditions(supplier); } @ResponseBody @RequiresPermissions("ec:finance:supplier:statementOfFinancial") @RequestMapping(value = "reconciliationFreightAndOrder") public void reconciliationFreightAndOrder(Order order) { ReconciliationDetail reconciliationDetail = new ReconciliationDetail(); ReconciliationFreight reconciliationFreight = new ReconciliationFreight(); reconciliationDetail.setOrder(order); reconciliationFreight.setOrder(order); reconciliationDetailService.reconciliationByOrder(reconciliationDetail); reconciliationFreightService.reconciliationFreightByOrder(reconciliationFreight); } }
Java
CL
de1f373315fa3c1b963563b2fc1ca5e5aa9b0a8c6eb6823cbd4e4fbb614dc46c
package org.cache2k.config; /*- * #%L * cache2k API * %% * Copyright (C) 2000 - 2022 headissue GmbH, Munich * %% * 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. * #L% */ import org.cache2k.annotation.Nullable; /** * Configuration options for a cache manager. The options can only be changed if an * XML file is provided. This bean is in the API artifact for documentation purposes. * * @author Jens Wilke */ public class Cache2kManagerConfig implements ConfigBean<Cache2kManagerConfig, Cache2kManagerConfig.Builder> { private @Nullable String version = null; private @Nullable String defaultManagerName = null; private boolean ignoreMissingCacheConfiguration = false; private boolean skipCheckOnStartup = false; private boolean ignoreAnonymousCache = false; public boolean isIgnoreMissingCacheConfiguration() { return ignoreMissingCacheConfiguration; } /** * Configure a cache with default parameters if configuration has no specific section for it. */ public void setIgnoreMissingCacheConfiguration(boolean f) { ignoreMissingCacheConfiguration = f; } public @Nullable String getDefaultManagerName() { return defaultManagerName; } /** * Replace the default name of the default cache manager. */ public void setDefaultManagerName(String v) { defaultManagerName = v; } public @Nullable String getVersion() { return version; } /** * Version of the configuration. Mandatory in every cache configuration. The version affects * how the configuration XML file is interpreted. */ public void setVersion(String v) { version = v; } public boolean isSkipCheckOnStartup() { return skipCheckOnStartup; } /** * The configuration for each cache is parsed and checked as soon as the cache manager is created. */ public void setSkipCheckOnStartup(boolean f) { skipCheckOnStartup = f; } public boolean isIgnoreAnonymousCache() { return ignoreAnonymousCache; } /** * When a configuration is present, every cache needs a cache name so that the configuration * can be applied. */ public void setIgnoreAnonymousCache(boolean f) { ignoreAnonymousCache = f; } /** * Not supported, but will eventually get one. */ @Override public Builder builder() { throw new UnsupportedOperationException(); } public static class Builder implements ConfigBuilder<Builder, Cache2kManagerConfig> { @Override public Cache2kManagerConfig config() { throw new UnsupportedOperationException(); } } }
Java
CL
b0f85c5cfb093322653e32ad53b3cec8b737942420c9ed44cef9dee89f7631f5
package no.forsen.skisenter; //import skisenter.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.LinkedList; import java.util.Objects; import java.net.URL; /** * Skiresert is the class with the main-method. * Skiresort creates the Personlist, Cardlist and List of Validations. * * @author Erik Haider Forsén * @author Ole Hansen * @author Julie Hill Roa * @version 0.9 */ public class Skiresort { private static String message = null; private static Personlist registry; private static Cardlist cardregistry; private static List<Validations> validations; private static RandomData r; public static Salesclerk s; public static Info i; public static Admin a; public static Control lift1; public static Control lift2; public static Lift chLift; public static Lift tLift; public static boolean unsaved; /** * main-method to run the program. * Creates the Control-Windows, Salesclerk-Window, Admin-Window and the Info-Window. */ public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); Toolkit verktoykasse = Toolkit.getDefaultToolkit(); URL bildefil = Skiresort.class.getResource("img/offpist_logo.png"); final Image ikon = verktoykasse.getImage(bildefil); unsaved = false; Skiresort test = new Skiresort(); test.readFile(); chLift = new Chairlift(validations, registry, "Eventyrheisen", 2000, 3 ); tLift = new Tcuplift( validations, registry, "Lårgnagern", 1433 ); EventQueue.invokeLater( new Runnable() { public void run() { /* Uncomment this code if you want to auto-generate some demo data. int yn = JOptionPane.showOptionDialog(null, "Vil du få litt tilfeldig data?", "Random stash", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null ); if( yn == JOptionPane.YES_OPTION ) r = new RandomData( registry, cardregistry, validations ); */ s = new Salesclerk(registry, cardregistry, message); s.setJMenuBar( new MenuBar().createMenu() ); s.setVisible( true ); s.setIconImage(ikon); s.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); s.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { if( checkForUnsaved()) System.exit( 0 ); } }); i = new Info(); i.setJMenuBar( new MenuBar().createMenu() ); i.setVisible(false); a = new Admin( registry,validations, cardregistry); a.setLocation(0,425); a.setJMenuBar( new MenuBar().createMenu() ); a.setIconImage(ikon); a.setVisible( false ); lift1 = new Control( registry, chLift, cardregistry ); lift1.setJMenuBar( new MenuBar().createMenu() ); lift1.setLocation(700,625); lift1.setIconImage(ikon); lift1.setVisible(false); lift2 = new Control( registry, tLift, cardregistry ); lift2.setJMenuBar( new MenuBar().createMenu() ); lift2.setLocation(200,625); lift2.setIconImage(ikon); lift2.setVisible(false); } } ); } /** *This method reads the objects from file and puts them into Personlist, Cardlist and a list of Validations. */ private static void readFile() { try( ObjectInputStream input = new ObjectInputStream( new FileInputStream( "data/data.dta" ) ) ) { registry = (Personlist) input.readObject(); validations = (List<Validations>) input.readObject(); cardregistry = (Cardlist) input.readObject(); Person.setNext( input.readInt() ); Card.setNext( input.readInt() ); } catch( ClassNotFoundException cnfe ) { message = "Ingen personliste funnet, oppretter ny"; registry = new Personlist(); validations = new LinkedList<>(); cardregistry = new Cardlist(); } catch( FileNotFoundException fnfe ) { message = "Finner ikke datafilen, oppretter ny datafil"; registry = new Personlist(); validations = new LinkedList<>(); cardregistry = new Cardlist(); } catch( IOException ioe ) { message = "Feil med lesing fra fil, oppretter ny datafil"; registry = new Personlist(); validations = new LinkedList<>(); cardregistry = new Cardlist(); } } /** *This method saves the objects from Personlist, Cardlist and a list of Validations onto a file */ public static void saveFile() { try( ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream( "data/data.dta" ) ) ) { output.writeObject( registry ); output.writeObject( validations ); output.writeObject(cardregistry); output.writeInt( Person.readNext() ); output.writeInt( Card.readNext() ); s.statusTxt.setText( "alt ble lagret" ); unsaved = false; } catch( NotSerializableException nse ) { JOptionPane.showMessageDialog(null, "Objektet er ikke serialisert", "Feil!", JOptionPane.ERROR_MESSAGE ); nse.printStackTrace( System.out ); } catch( IOException ioe ) { JOptionPane.showMessageDialog(null, "Feil ved skriving til fil", "Feil!", JOptionPane.ERROR_MESSAGE ); } } /** * Checks if you have unsaved objects when you exit the program. * if you do, this method displays a dialogbox asking if you want to save or not. * @return Returns true if the user didn't have anything unsaved, pressed option YES and NO. False if they chose CANCEL */ public static boolean checkForUnsaved() { if( !unsaved ) return true; String[] options = {"Lagre", "Ikke lagre", "Avbryt"}; int n = JOptionPane.showOptionDialog(null, "Du har ulagrete endringer.", "Lagringsdialog", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); switch( n ) { case JOptionPane.YES_OPTION: saveFile(); return true; case JOptionPane.NO_OPTION: return true; case JOptionPane.CANCEL_OPTION: return false; } return false; } }
Java
CL
1e8a795cce6b74de0585491a31502ec5646353c6b39410104da712ac346661c3
// -*- mode: java; indent-tabs-mode: nil; tab-width: 4; -*- // vim: set shiftwidth=4 softtabstop=4 expandtab: /* ******************************************************************** ** ISFS: NCAR Integrated Surface Flux System software ** ** 2016, Copyright University Corporation for Atmospheric Research ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** The LICENSE.txt file accompanying this software contains ** a copy of the GNU General Public License. If it is not found, ** write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** ******************************************************************** */ package edu.ucar.nidas.apps.cockpit.ui; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.util.ArrayList; import java.util.List; import com.trolltech.qt.core.QPoint; import com.trolltech.qt.core.QRect; import com.trolltech.qt.core.QSize; import com.trolltech.qt.core.QTimer; import com.trolltech.qt.core.Qt; import com.trolltech.qt.core.Qt.MouseButton; import com.trolltech.qt.gui.QColor; import com.trolltech.qt.gui.QAction; import com.trolltech.qt.gui.QInputDialog; import com.trolltech.qt.gui.QColorDialog; import com.trolltech.qt.gui.QFont; import com.trolltech.qt.gui.QFontMetrics; import com.trolltech.qt.gui.QMenu; import com.trolltech.qt.gui.QMouseEvent; import com.trolltech.qt.gui.QPaintEvent; import com.trolltech.qt.gui.QPainter; import com.trolltech.qt.gui.QPen; import com.trolltech.qt.gui.QPixmap; import com.trolltech.qt.gui.QResizeEvent; import com.trolltech.qt.gui.QWidget; import com.trolltech.qt.gui.QPainter.CompositionMode; import com.trolltech.qt.gui.QSizePolicy.Policy; import edu.ucar.nidas.model.FloatSample; import edu.ucar.nidas.model.DataClient; import edu.ucar.nidas.model.QProxyDataClient; import edu.ucar.nidas.model.Var; import edu.ucar.nidas.model.Log; import edu.ucar.nidas.apps.cockpit.ui.Cockpit.QMenuActionWithToolTip; /** * Gauge class is a plot unit of cockpit. * It draws the current data in the plot. * The time-span in a plot is 2 minutes be default. * When the new data's time-tag is out of the range, it draws the current data into different color * as history. and Clear the plot to draw new data. * * Its main members are: * the variable whose data is plotted. * gauge-width in milli-seconds * history image * _painter to draw the data-line * */ public class Gauge extends QWidget { /* * gauge's parent page */ GaugePage _gaugePage; private Gauge.GaugeDataClient _client; private DataClient _proxyClient; /** * data reduction time of minMaxer, milli-seconds */ int _statisticsPeriod = 1000; /** * pixels/sec in Int */ // int _PixelSecInt; /** * If it does not receive the data for the max-time-out, it will put no-data-image to the plot */ int _timeoutSec = 300; /** * represent the no-data-time-out */ boolean _noDataPaint = false; /** * timetag of last sample with non-nan data. */ long _lastTm =-1; /** * previous ttag */ long _prevTtag=-1; /** * previous x-pixel, the previous xp */ int _prevXp= -1; /** * timer to track the no-data-time-out */ QTimer _tm ; /** * Whether to force a plot rescale. */ boolean _forceRescale = true; /** * data-pair for current plot span */ List<QPoint> _pts = new ArrayList<QPoint>(); /** * Y maximum and minimum values in current trace, used when auto-scaling. */ float[] _yminmax = new float[2]; /** * current image */ QPixmap _pixmap; /** * history image */ QPixmap _historyPixmap; /** * no-data image */ QPixmap _noDataPixmap; /** * painter for current data */ QPainter _painter; QPainter _historyPainter; /** * painter for history data */ /** * plot label */ public String _name; /** * plot units */ String _units; /** * create it dynamically or not */ boolean _dynamic; /** * Minimum value in y range */ float _yRangeMin; /** * Maximum value in y range */ float _yRangeMax; /** * Current time in milliseconds of start of plot. */ long _xmin; /** * Width of plot in milliseconds. */ int _xwidth; /** * x-position for the newest data */ //int _xp =-1; //x-position /** * pix/msec in x-axis */ float _xscale = 1.0f; /** * pix/1.0 in y-axis */ float _yscale = 1.0f; /** * ticDelta */ float _ticDelta; /** * x and y locate when a mouse is clicked */ QPoint _mousePoint = null; /** * plot width and height in pix */ int _pwidth, _pheight; //plot-height-in-pix //color QColor _traceColor= Cockpit.defTraceColor; QColor _historyColor = Cockpit.defHistoryColor; QColor _bgColor = Cockpit.defBGColors.get(0); static QColor _red = new QColor(Qt.GlobalColor.red); private Log _log; /** * @param parent * @param size Initial widget QSize * @param gaugeWidthMsec - gauge-width in milli-seconds * @param var - variable whose data is plotted */ public Gauge(GaugePage p, QSize size, int gaugeWidthMsec, Var var, QColor tc, QColor hc, QColor bg) { super(p); _gaugePage = p; _log = p.getLog(); _xmin = 0; //plot-start-tm-in-sec _xwidth = gaugeWidthMsec; //in-milli-seconds _statisticsPeriod = p.getStatisticsPeriod(); _traceColor = tc; _historyColor = hc; _bgColor = bg; setMinimumSize(0,0); // resize(size); _name = var.getNameWithStn(); _units = var.getUnits(); _dynamic = var.getDynamic(); _pwidth = size.width(); _pheight = size.height(); calTics(var.getMax(), var.getMin()); rescale(size()); initPixmaps(); //show(); _lastTm = System.currentTimeMillis(); _tm = new QTimer(); _tm.timeout.connect(this, "timeout()"); // wakeup more often than the _timeoutSec so that we // detect a timeout quicker. 10th of timeoutSec int tmlen = (_timeoutSec*1000)/10; _tm.start(tmlen); /* System.out.printf("new Gauge %s: w=%d,h=%d\n", getName(),size.width(),size.height()); */ _client = this.new GaugeDataClient(); _proxyClient = QProxyDataClient.getProxy(_client); } DataClient getDataClient() { return _proxyClient; } public int heightForWidth(int w) { /* System.out.printf("Gauge heightForWidth %s: w=%d,h=%d\n", getName(),w,w*2/3); */ return w * 2 / 3; } /** * @ param x milliseconds into plot */ private int xpixel(long x) { return Math.round(x * _xscale); } /** * @ param y value in data units */ private int ypixel(float y) { return Math.round((_yRangeMax - y) * _yscale); } /** * get the parent of the plot * @return */ public GaugePage getPage() { return _gaugePage; } /* public void autoResize(){ synchronized(this) { QSize qs = size(); resize(qs); } } */ public void setWidthMsec(int msec) { if (msec == _xwidth) return; synchronized(this) { _xwidth = msec; QSize qs = size(); resize(qs); rescale(qs); initPixmaps(); _pts.clear(); _yminmax[0] = Float.MAX_VALUE; _yminmax[1] = -Float.MAX_VALUE; } } public void setDataTimeoutSec() { int timeout = QInputDialog.getInt(this,tr("Data Timeout"), tr("Seconds"),_timeoutSec,1,3600); if (timeout <= 0) return; setDataTimeoutSec(timeout); } public void setDataTimeoutSec(int sec) { if (_timeoutSec == sec) return; _timeoutSec = sec; _tm.stop(); _tm.start(sec * 1000 / 6); _noDataPaint = false; parentWidget().repaint(); } /** * recalculate the scale of the x and y * x-axis -- pix/msec * y-axis -- pix /1.0 * @param qs */ private void rescale(QSize qs) { synchronized(this) { _pheight = qs.height(); _pwidth = qs.width(); _xscale = _pwidth / (float)_xwidth; _yscale = getYScale(); //pheight changed _prevTtag = -1; _prevXp = -1; } } /** * Paint the current data line */ private void paintLines() { synchronized(this) { if (_painter != null) { _painter.drawLinesFromPoints(_pts); drawOutliners(_pts); update(); } } } /** * Clean up the data-history */ public void clearHistory () { initPixmaps(); paintLines(); // repaint(); } /** * Color the current data with the new color * @param */ public void changeTraceColor(QColor c) { _traceColor = c; resetPainter(); paintLines(); //repaint(); } /** * Color the history data-line with the new color. * This method will clean up history, and make a new image * @param c */ public void changeHistoryColor(QColor c) { _historyColor = c; initPixmaps(); paintLines(); //repaint(); } /** * /** * Color the back-ground of a plot with the new color * @param */ public void changeBGColor(QColor c) { _bgColor = c; initPixmaps(); paintLines(); // repaint(); } public void resizeEvent(QResizeEvent ent) { synchronized(this) { rescale(ent.size()); initPixmaps(); _pts.clear(); _yminmax[0] = Float.MAX_VALUE; _yminmax[1] = -Float.MAX_VALUE; } } /** * timer to check the no-data-time-out */ private void timeout() { long c = System.currentTimeMillis(); if ((c - _lastTm) / 1000 < _timeoutSec) return; _noDataPaint = true; repaint(); } public void paintEvent(QPaintEvent e) { QPainter p = null; if (! _pixmap.isNull()) { p = new QPainter(this); p.drawPixmap(0,0, _pixmap); if (_noDataPaint) { p.setPen(new QColor(Qt.GlobalColor.lightGray)); p.drawText(width() / 2, height() / 2, tr("RIP")); } } /* if (!_noDataPixmap.isNull()) { CompositionMode cpmode = p.compositionMode();//QPainter::CompositionMode_Clear; p.setCompositionMode(QPainter.CompositionMode.CompositionMode_Destination); p.drawPixmap(0,0,_noDataPixmap); } else { if (! _pixmap.isNull()) p.drawPixmap(0,0, _pixmap); } */ if (p!=null) p.end(); } public void mouseReleaseEvent(QMouseEvent event) { if (event.button() == MouseButton.RightButton) { QMenu menu = new QMenu(tr("Plot Options")); if (_gaugePage.frozenPlotSizes()) { QAction action = new QMenuActionWithToolTip( tr("&Unfreeze &Plot Sizes"), tr("Allow plot sizes on this page to vary, losing history shadow"), menu); action.triggered.connect(_gaugePage, "unfreezePlotSizes()"); menu.addAction(action); } else { QAction action = new QMenuActionWithToolTip( tr("Freeze &Plot Sizes"), tr("Fix plot sizes on this page"), menu); action.triggered.connect(_gaugePage, "freezePlotSizes()"); menu.addAction(action); } if (_gaugePage.frozenGridLayout()) { QAction action = new QMenuActionWithToolTip( tr("Unfreeze &Grid Layout"), tr("Allow grid layout on this page to change"), menu); action.triggered.connect(_gaugePage, "unfreezeGridLayout()"); menu.addAction(action); } else { QAction action = new QMenuActionWithToolTip( tr("Freeze &Grid Layout"), tr("Fix grid layout on this page"), menu); action.triggered.connect(_gaugePage, "freezeGridLayout()"); menu.addAction(action); } QAction action = new QMenuActionWithToolTip(tr("Clear &History"), tr("Clear history shadow on this plot"), menu); action.triggered.connect(this, "clearHistory()"); menu.addAction(action); QMenu color = menu.addMenu(tr("&Color")); action = new QMenuActionWithToolTip(tr("&Trace Color"), tr("Change trace color on this plot"), color); action.triggered.connect(this, "changeTraceColor()"); color.addAction(action); action = new QMenuActionWithToolTip(tr("&History Color"), tr("Change color of history shadow on this plot"), color); action.triggered.connect(this, "changeHistoryColor()"); color.addAction(action); action = new QMenuActionWithToolTip(tr("&Background Color"), tr("Change background color on this plot"), color); action.triggered.connect(this, "changeBGColor()"); color.addAction(action); QMenu scale = menu.addMenu(tr("&Scale")); action = new QMenuActionWithToolTip(tr("&Manual Scale Plot"), tr("Fix Y scale on this plot"), scale); action.triggered.connect(this, "changeYMaxMin()"); scale.addAction(action); action = new QMenuActionWithToolTip(tr("&Auto Scale Plot"), tr("Allow Y scale to vary on this plot"), scale); action.triggered.connect(this, "forceAutoScalePlot()"); scale.addAction(action); menu.addAction(tr("Set Data &Timeout"), this, "setDataTimeoutSec()"); // menu.addAction(tr("&Auto Resize"), this, "autoResize()"); menu.addAction(tr("&Delete Plot"), this, "deletePlot()"); _mousePoint = event.globalPos(); menu.popup(_mousePoint); } } private void deletePlot() { hide(); _gaugePage.remove(this) ; } /** * paint the history image with new data */ private void drawHistData() { synchronized(this) { if (_historyPainter!=null) _historyPainter.drawLinesFromPoints(_pts); } } /** * Make a new history image based on the plot-size, paint the label, unit, and scale on the new image * Redraw the no-data-image based on the history image, * get the copy of history image for current data drawing */ public void initPixmaps() { _historyPixmap = new QPixmap(size().width(),size().height()); _historyPixmap.fill(_bgColor); _noDataPixmap = _historyPixmap.copy(); resetHistoryPainter(); resetPainter(); QPainter p = new QPainter(_noDataPixmap); QPen qp = p.pen(); p.setPen(new QColor(Qt.GlobalColor.lightGray)); p.drawText(width()/2, height()/2, tr("RIP")); p.setPen(qp); paintText(p); p.end(); } /** * Color the plot with new color */ private void changeTraceColor() { QColor cc = QColorDialog.getColor(_traceColor); if (cc.value()==0) return; _traceColor = cc; changeTraceColor(_traceColor); } /** * Color the history data with new color, discard the previous histroy image */ private void changeHistoryColor() { QColor cc = QColorDialog.getColor(_historyColor); if (cc.value()==0) return; _historyColor = cc; changeHistoryColor(_historyColor); } /** * Color the plot back-ground with new color. */ private void changeBGColor() { QColor cc = QColorDialog.getColor(_bgColor); if (cc.value()==0) return; _bgColor = cc; changeBGColor(_bgColor); } /** * Rescale y-axis (pix/1.0data-value) */ private void changeYMaxMin() { RescaleDialog rd = new RescaleDialog(_yRangeMax, _yRangeMin, _mousePoint.x(), _mousePoint.y()) ; if (!rd.getOk()) return; if (rd.getMax() <=rd.getMin()) { _log.error(tr("Y axis max is smaller than Y axis min")); return; } changeYMaxMin(rd.getMax(), rd.getMin()); } /** * Rescale y-axis , based on given ymax and ymin */ public void changeYMaxMin(float ymax, float ymin) { if (ymax == _yRangeMax && ymin == _yRangeMin) return; synchronized(this) { _yscale = getYScale(ymax, ymin); _pts.clear(); _yminmax[0] = Float.MAX_VALUE; _yminmax[1] = -Float.MAX_VALUE; initPixmaps(); } repaint(); } /** * forced auto-scale from the plot's drop-down menu */ public void forceAutoScalePlot() { autoScalePlot(true); } /** * Rescale the plot. * If the g is false, it means (local-rescale) forced rescale. * Otherwise, it will check to see yf is in the range. * @param g */ public void autoScalePlot(boolean force) { _forceRescale = force; autoScalePlot(); _forceRescale = true; } /** * Rescale the plot. * If the g is false, it means (local-rescale) forced rescale. * Otherwise, it will check to see yf is in the range. */ private void autoScalePlot() { synchronized(this) { if (_pts == null || _pts.isEmpty()){ _noDataPaint = true; repaint(); return; } if (_yminmax[0] == Float.MAX_VALUE) return; float ymin = _yminmax[0]; float ymax = _yminmax[1]; //check the old ones with 2% margin float oldmargin = Math.abs(_yRangeMax - _yRangeMin) * (float).02; boolean check = !_forceRescale && ymin > (_yRangeMin + oldmargin) && ymax < (_yRangeMax - oldmargin); if (check) return; //in range // add range if the range is small float range = Math.abs(ymax - ymin); if (range < 1.0 ) { ymax = ymax + 5; ymin = ymin - 5; check = !_forceRescale && ymin > (_yRangeMin + oldmargin) && ymax < (_yRangeMax - oldmargin); if (check) return; //in the range } _yscale = getYScale(ymax, ymin); _pts.clear(); _yminmax[0] = Float.MAX_VALUE; _yminmax[1] = -Float.MAX_VALUE; initPixmaps(); } repaint(); } /** * Requested by a user to remove it public void removeSelf() { // _var.setDisplay(false); _gaugePage.removeGaugeFromWidget(this); //use GaugePageThread instead } */ private void resetHistoryPainter() { if (_historyPainter != null) _historyPainter.end(); _historyPainter = new QPainter(_historyPixmap); _historyPainter.setPen(_historyColor); } // not synchronized, only called from other synchronized methods private void resetPainter() { synchronized(this) { if (_painter != null) _painter.end(); _pixmap = _historyPixmap.copy(); QPainter ptr = new QPainter(_pixmap); paintText(ptr); ptr.end(); //_pixmap = map.copy(); _painter = new QPainter(_pixmap); _painter.setPen(_traceColor); } } /** * Paint the plot label, unit, and scales */ private void paintText(QPainter painter) { // if (painter == null) return; synchronized(this) { painter.setPen(new QColor(Qt.GlobalColor.yellow)); QFont font = painter.font(); int fpixels = Math.min(Math.max(height() / 12, 10), 24); int ticlen = Math.min(Math.max(width() / 20, 8), 16); QPen hPen = painter.pen(); int w = rect().width(); if (font.pixelSize() != fpixels) { font.setPixelSize(fpixels); painter.setFont(font); } QFontMetrics fm = new QFontMetrics(font); /* System.err.printf("fpixels=%d, font.pixelSize=%d, font width(\"X\")=%d, height=%d\n", fpixels, font.pixelSize(), fm.width("X"), fm.height()); */ int th = fm.lineSpacing(); // rectangle height for text // name, upper left QRect rect = new QRect(0, 0, w, th); painter.drawText(rect, Qt.AlignmentFlag.AlignLeft.value() | Qt.AlignmentFlag.AlignTop.value(), _name); // units, bottom left rect = new QRect(0, rect().height() - th, w, th); painter.drawText(rect, Qt.AlignmentFlag.AlignLeft.value() | Qt.AlignmentFlag.AlignBottom.value(), _units); // max label, upper right rect = new QRect(0, 0, w, th); painter.drawText(rect, Qt.AlignmentFlag.AlignRight.value() | Qt.AlignmentFlag.AlignTop.value(), getLabel(_yRangeMax)); // min label, lower right rect = new QRect(0, rect().height() - th, w, th); painter.drawText(rect, Qt.AlignmentFlag.AlignRight.value() | Qt.AlignmentFlag.AlignBottom.value(), getLabel(_yRangeMin)); // tics, both right and left int rofts = (int)((_yRangeMax - _yRangeMin) / _ticDelta) - 1; for (int i = 1; i <= rofts; i++) { int y = ypixel(_yRangeMax - i * _ticDelta); painter.drawLine(0, y, ticlen, y); // left painter.drawLine(w, y, w - ticlen, y); // right } int lpixels = Math.round(fpixels * 0.8f); QFont lfont = new QFont(font); lfont.setPixelSize(lpixels); painter.setFont(lfont); fm = new QFontMetrics(lfont); th = fm.lineSpacing(); // rectangle height for text // label the middle one or two points, right if (rofts % 2 == 1) { int i = rofts / 2 + 1; float yval = _yRangeMax - i * _ticDelta; int y = ypixel(yval); rect = new QRect(0, y - th / 2, w - ticlen - 2, th); painter.drawText(rect, Qt.AlignmentFlag.AlignRight.value() | Qt.AlignmentFlag.AlignVCenter.value(), getLabel(yval)); } else { int i = rofts / 2 ; float yval = _yRangeMax - i * _ticDelta; int y = ypixel(yval); rect = new QRect(0, y - th / 2, w - ticlen - 2, th); painter.drawText(rect, Qt.AlignmentFlag.AlignRight.value() | Qt.AlignmentFlag.AlignVCenter.value(), getLabel(yval)); i = rofts / 2 + 1; yval = _yRangeMax - i * _ticDelta; y = ypixel(yval); rect = new QRect(0, y - th / 2, w - ticlen - 2, th); painter.drawText(rect, Qt.AlignmentFlag.AlignRight.value() | Qt.AlignmentFlag.AlignVCenter.value(), getLabel(yval)); } //reset history color painter.setPen(hPen); painter.setFont(font); } } public void closePlot() { if (_painter != null) _painter.end(); if (_historyPainter!=null) _historyPainter.end(); super.close(); } /** * based on the max and min, calculate _ticDelta, _yRangeMax, and _yRangeMin * @param ymax * @param ymin * * _ticDelta will be 1,2,5, or 10 times a power of 10, where there * are at most 6 _ticDeltas on the Y axis. */ public void calTics(float ymax, float ymin) { if (ymax <= ymin) return; double ytic = (ymax - ymin) / 6; // approximately 6 tics double l10 = Math.floor(Math.log10(ytic)); double p10 = Math.pow(10.0,l10); int icoef = (int)Math.ceil(ytic / p10); // round 6-9 up to 10, 3-4 to 5 if (icoef > 5) icoef = 10; else if (icoef > 1) icoef = 5; synchronized (this) { _ticDelta = (float)(icoef * p10); _yRangeMax = getMaxTick(ymax, _ticDelta); _yRangeMin = getMinTick(ymin, _ticDelta); } } private float getMaxTick(float max, float tic) { return (float)Math.ceil(max / tic) * tic; } private float getMinTick(float min, float tic) { return (float)Math.floor(min / tic) * tic; } private String getLabel(float f) { String str = Float.toString(f).trim(); if (str.endsWith(".0")) return str.substring(0,str.length()-2); return str; } private void status(String msg, int tm) { _gaugePage.status(msg, tm); } private float getYScale(float ymax, float ymin) { calTics(ymax, ymin); //_ticDelta , _yRangeMax, and _yRangeMin return getYScale(); } private float getYScale() { return _pheight / (_yRangeMax - _yRangeMin); } /** * Transparency of an image */ public static class Transparency { public static Image makeColorTransparent(Image im, final Color color) { ImageFilter filter = new RGBImageFilter() { // the color we are looking for... Alpha bits are set to opaque public int markerRGB = color.getRGB() | 0xFF000000; public final int filterRGB(int x, int y, int rgb) { if ( ( rgb | 0xFF000000 ) == markerRGB ) { // Mark the alpha bits as zero - transparent return 0x00FFFFFF & rgb; } else { // nothing to do return rgb; } } }; ImageProducer ip = new FilteredImageSource(im.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(ip); } } /** * check the points out of the plot-range and draw an eclipse at the position */ private void drawOutliners(List<QPoint> pts){ for (int i = 0; i< pts.size(); i++){ float yy = _yRangeMax - pts.get(i).y()/_yscale; if (yy > _yRangeMax && _painter != null) { _painter.setPen(_red); _painter.drawEllipse(pts.get(i).x(), ypixel(_yRangeMax), 2, 2); _painter.setPen(_traceColor); } if (yy < _yRangeMin && _painter != null) { _painter.setPen(_red); _painter.drawEllipse(pts.get(i).x(), ypixel(_yRangeMin)-3, 2, 2); _painter.setPen(_traceColor); } } } public float getYMax() { return _yRangeMax; } public float getYMin() { return _yRangeMin; } //public void setDataTimeout(float ymax) exists public int getDataTimeout(){ return _timeoutSec; } public int getWidthMsec() { return _xwidth; } public String getName() { return _name; } public void setTraceColor(QColor c) { changeTraceColor(c); } public QColor getTraceColor() { return _traceColor; } public void setHistoryColor(QColor c) { changeHistoryColor(c); } public QColor getHistoryColor() { return _historyColor; } public void setBGColor(QColor c) { changeBGColor(c); } public QColor getBGColor() { return _bgColor; } /** * Inner class implementing DataClient. */ class GaugeDataClient implements DataClient { /** * get the new data, and plot it * @param samp - sample-data * @param offset -beginning index to read the pair of min and max */ public void receive(FloatSample samp, int offset) { synchronized (this) { long x = samp.getTimeTag(); if (_xmin == 0) { _xmin = x - (x % _xwidth); // show(); } int xd = (int)(x - _xmin); // milliseconds into plot // reach eof plot if (xd > _xwidth) { drawHistData(); resetPainter(); _pts.clear(); _yminmax[0] = Float.MAX_VALUE; _yminmax[1] = -Float.MAX_VALUE; _xmin = x - (x % _xwidth); xd = (int)(x - _xmin); } int xp = xpixel(xd); // x pixel position // String str = getName(); // if (str.equals("P.2m") || str.equals("Lon")) System.out.println(" var="+str +" x="+x + " xd="+xd+ " _xp="+ xp +" (int)_xp="+(int)xp); float ymin = samp.getData(offset); float ymax = samp.getData(offset+1); /* System.out.printf("name=%s, ymin=%f,ymax=%f\n", getName(),ymin,ymax); */ if (!Float.isNaN(ymin) && !Float.isNaN(ymax)) { _noDataPaint = false; _lastTm = x; int ypmin = ypixel(ymin); int ypmax = ypixel(ymax); if (ypmin == ypmax) ypmax++; List<QPoint> pa = new ArrayList<QPoint>(); //check the _xp - gap int xpts = xp - _prevXp; if (_prevTtag > 0 && (x - _prevTtag) == _statisticsPeriod ) { // fill in intervening pixels if there is no data gap for (int i = 0; i < xpts; i++) { int xind = _prevXp + 1 + i; pa.add(new QPoint(xind, ypmin)); pa.add(new QPoint(xind, ypmax)); } } else{ pa.add(new QPoint(xp, ypmin)); pa.add(new QPoint(xp, ypmax)); } if (_painter != null) { _painter.drawLinesFromPoints(pa); drawOutliners(pa); } else { status(" plot=" + getName() + " in receive, null painter.", 10000); } _pts.addAll(pa); //push all to the pts _yminmax[0] = Math.min(ymin, _yminmax[0]); _yminmax[1] = Math.max(ymax, _yminmax[1]); _prevTtag = x; //keep prevtime _prevXp = xp; update(); } } } } }
Java
CL
527433bdb83df14ea7b92cf040b2b21bf7815d7381deb8f0f1679cab5cdad52a
package dcu.service; import com.google.gson.Gson; import dcu.DAO.ExtraSessionDAOImpl; import dcu.datamodel.ExtraSession; import dcu.datamodel.Session; import javassist.NotFoundException; import org.json.JSONException; import org.json.JSONObject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.Date; import java.util.List; /** * Created by Sean on 08/04/2016. */ @Path("extraSession") public class ExtraSessionController { ExtraSessionDAOImpl extraSessionDAOImpl = new ExtraSessionDAOImpl(); @GET @Path("/getAllExtraSessions") @Produces(MediaType.APPLICATION_JSON) public String getAllExtraSessions()throws IOException, NotFoundException, JSONException { List<ExtraSession> extraSessionList = extraSessionDAOImpl.getAllExtraSessions(); if (extraSessionList == null) { throw new NotFoundException("extra sessions do not exist"); } JSONObject jsonObj = new JSONObject(); jsonObj.put("extraSession",extraSessionList); Gson gson = new Gson(); String extraSessions = gson.toJson(jsonObj); return extraSessions; } @GET @Path("/getExtraSessionById/{extraSessionId}") @Produces(MediaType.APPLICATION_JSON) public String getExtraSessionById(@PathParam("extraSessionId") final int extraSessionId) throws IOException, NotFoundException,JSONException{ List<ExtraSession> extraSessionList = extraSessionDAOImpl.getExtraSessionById(extraSessionId); if (extraSessionList == null) { throw new NotFoundException("extra session does not exist"); } JSONObject jsonObj = new JSONObject(); jsonObj.put("extraSession",extraSessionList); Gson gson = new Gson(); String extraSession = gson.toJson(jsonObj); return extraSession; } @GET @Path("/getExtraSessionByWeekIdPlayerId/weekId/{weekId}/playerId/{playerId}") @Produces(MediaType.APPLICATION_JSON) public String getExtraSessionByWeekIdPlayerId(@PathParam("weekId") final int weekId,@PathParam("playerId") final int playerId) throws IOException, NotFoundException,JSONException{ List<ExtraSession> extraSessionList = extraSessionDAOImpl.getExtraSessionByWeekIdPlayerId(weekId,playerId); if (extraSessionList == null) { throw new NotFoundException("extra sessions do not exist"); } JSONObject jsonObj = new JSONObject(); jsonObj.put("extraSession",extraSessionList); Gson gson = new Gson(); String extraSessions = gson.toJson(jsonObj); return extraSessions; } @GET @Path("/getExtraSessionByPlayer/playerId/{playerId}") @Produces(MediaType.APPLICATION_JSON) public String getExtraSessionPlayerId(@PathParam("playerId") final int playerId) throws IOException, NotFoundException,JSONException{ List<ExtraSession> extraSessionList = extraSessionDAOImpl.getExtraSessionByPlayerId(playerId); if (extraSessionList == null) { throw new NotFoundException("extra sessions do not exist"); } JSONObject jsonObj = new JSONObject(); jsonObj.put("extraSessions",extraSessionList); Gson gson = new Gson(); String extraSessions = gson.toJson(jsonObj); return extraSessions; } @POST @Produces(MediaType.APPLICATION_JSON) @Path("/createExtraSession/weekId/{weekId}/playerId/{playerId}/sessionType1/{sessionType1}/sessionType2/{sessionType2}/sessionType3/{sessionType3}/sessionType4/{sessionType4}/sessionType5/{sessionType5}/sessionType6/{sessionType6}/sessionType7/{sessionType7}") public String createExtraSession(@PathParam("weekId") final int weekId,@PathParam("playerId") final int playerId,@PathParam("sessionType1") final String sessionType1,@PathParam("sessionType2") final String sessionType2,@PathParam("sessionType3") final String sessionType3,@PathParam("sessionType4") final String sessionType4,@PathParam("sessionType5") final String sessionType5,@PathParam("sessionType6") final String sessionType6,@PathParam("sessionType7") final String sessionType7) throws IOException, NotFoundException,JSONException{ extraSessionDAOImpl.createExtraSession(weekId,playerId,sessionType1,sessionType2,sessionType3,sessionType4,sessionType5,sessionType6,sessionType7); return "createExtraSession"; } @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/updateExtraSession/weekId/{weekId}/playerId/{playerId}/sessionType1/{sessionType1}/sessionType2/{sessionType2}/sessionType3/{sessionType3}/sessionType4/{sessionType4}/sessionType5/{sessionType5}/sessionType6/{sessionType6}/sessionType7/{sessionType7}") public String updateExtraSession2(@PathParam("weekId") final int weekId,@PathParam("playerId") final int playerId,@PathParam("sessionType1") final String sessionType1,@PathParam("sessionType2") final String sessionType2,@PathParam("sessionType3") final String sessionType3,@PathParam("sessionType4") final String sessionType4,@PathParam("sessionType5") final String sessionType5,@PathParam("sessionType6") final String sessionType6,@PathParam("sessionType7") final String sessionType7)throws IOException, NotFoundException,JSONException{ extraSessionDAOImpl.updateExtraSession(weekId,playerId,sessionType1,sessionType2,sessionType3,sessionType4,sessionType5,sessionType6,sessionType7); return "updatedExtraSession"; } }
Java
CL
96271bcbe5d3611351a4a8295f326049a1bb4be46fe5fddd8a72f9417842da7a
package mvc.vga.cate; import java.util.List; public interface CateProcInter { /** * 등록 * @param cateVO * @return */ public int create(CateVO cateVO); /** * 출력 순서별 목록 * @return */ public List<CateVO> list_seqno_asc(); /** * 조회, 수정폼 * @param categrpno 카테고리 그룹 번호, PK * @return */ public CateVO read(int cateno); /** * 수정 * @param cateVO * @return */ public int update(CateVO cateVO); /** * 삭제 처리 * @param cateno * @return */ public int delete(int cateno); /** * 우선순위 상향, up 10 ▷ 1 * @param cateno * @return */ public int update_seqno_up(int cateno); /** * 우선순위 하향, up 10 ▷ 1 * @param cateno * @return */ public int update_seqno_down(int cateno); /** * 출력 모드의 변경 * @param cateVO * @return */ public int update_visible(CateVO cateVO); /** * <xmp> * 통합 VO 기반 join * <select id="list_join" resultType="Categrp_Cate_join"> * </xmp> * @return */ public List<Categrp_Cate_join> list_join(); /** * <xmp> * categrpno 별 cate 목록: categrp + cate inner join, 1 : 다, 통합 VO * <select id="list_join_by_categrpno" resultType="Categrp_Cate_join" parameterType="int"> * </xmp> * @param categrpno * @return */ public List<Categrp_Cate_join> list_join_by_categrpno(int categrpno); /** * <xmp> * 전체 카테고리 목록 * <resultMap type="Categrp_Cate_VO" id="Categrp_Cate_VO_Map"> * ↑ ↑ * ┌────┘ └──┐ * │ │ * │ <select id="list_all" resultMap="Categrp_Cate_VO_Map"> * public List<Categrp_Cate_VO> list_all(); * </xmp> * @return */ public List<Categrp_Cate_VO> list_all(); /** * <xmp> * categrpno 변수의 값에 해당하는 cate 목록만 추출 * <resultMap type="Categrp_Cate_VO_list" id="Categrp_Cate_VO_list_Map"> * ↑ ↑ * ┌────────┘ └──┐ * │ │ * │<select id="list_by_categrpno" resultMap="Categrp_Cate_VO_list_Map" * │ parameterType="int"> * public Categrp_Cate_VO_list list_by_categrpno(); * </xmp> * @return */ public Categrp_Cate_VO_list list_by_categrpno(int categrpno); /** * 글 수 증가 * <update id="increaseCnt" parameterType="int"> * @return */ public int increaseCnt(int cateno); /** * 글 수 감소 * <update id="decreaseCnt" parameterType="int"> * @return */ public int decreaseCnt(int cateno); }
Java
CL
66a552a99bccea5ba607ca47a901594207b173e0143c323ed794dab03e836034
package org.gamboni.cloudspill.shared.api; import org.gamboni.cloudspill.shared.domain.ClientUser; import org.gamboni.cloudspill.shared.domain.InvalidPasswordException; import org.gamboni.cloudspill.shared.domain.IsItem; import org.gamboni.cloudspill.shared.domain.IsUser; import org.gamboni.cloudspill.shared.domain.Items; import org.gamboni.cloudspill.shared.util.Func; import org.gamboni.cloudspill.shared.util.Log; import org.gamboni.cloudspill.shared.util.Splitter; import org.gamboni.cloudspill.shared.util.UrlStringBuilder; import java.net.URLConnection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; /** Specifies a way to access an Item: either by logging in (user+password), or by supplying an item-specific key String. * * @author tendays */ public interface ItemCredentials { public enum Power { SINGLE, PUBLIC, USER } public interface Matcher<E extends Throwable> { void when(UserPassword password) throws E; void when(UserToken token) throws E; void when(PublicAccess pub) throws E; void when(ItemKey key) throws E; } public interface Mapper<R> { R when(UserPassword password); R when(UserToken token); R when(PublicAccess pub); R when(ItemKey key); } <E extends Throwable> void match(Matcher<E> matcher) throws E; <R> R map(Mapper<R> mapper); AuthenticationStatus getAuthStatus(); /** True if these credentials identify a user belonging to the given group. */ boolean hasGroup(String groupName); /** If these credentials work by setting an HTTP header, do so in this method. Otherwise, * this method should just do nothing. */ void setHeaders(URLConnection connection, Base64Encoder b64); /** If these credentials work by setting an HTTP header, do so in this method (by modifying the given Map). Otherwise, * this method should just do nothing. */ void setHeaders(Map<String, String> headers, Base64Encoder b64); Power getPower(); public enum AuthenticationStatus { LOGGED_IN { @Override protected ItemCredentials credentialsForNonPublicItem(IsItem item) { return new UserPassword(); } }, PENDING { @Override protected ItemCredentials credentialsForNonPublicItem(IsItem item) { return ANONYMOUS.credentialsForNonPublicItem(item); } }, ANONYMOUS { @Override protected ItemCredentials credentialsForNonPublicItem(IsItem item) { return new ItemKey(item.getChecksum()); } }; public ItemCredentials credentialsFor(IsItem item) { return Items.isPublic(item) ? new PublicAccess() : credentialsForNonPublicItem(item); } protected abstract ItemCredentials credentialsForNonPublicItem(IsItem item); } void setQueryParams(UrlStringBuilder url); /** String to put after the server url and before the api paths ("public/" or "") */ String getUrlPrefix(); class UserPassword extends UserCredentials { public final String password; /** Use this constructor when you only need to generate a URL in an HTML page. The browser will take care of passing the actual credentials. */ public UserPassword() { this.password = null; } /** Use this constructor when you actually need to send a request to the server. */ public UserPassword(IsUser user, String password) { super(user); this.password = password; } @Override public <E extends Throwable> void match(Matcher<E> matcher) throws E { matcher.when(this); } @Override public <R> R map(Mapper<R> mapper) { return mapper.when(this); } public String getPassword() { if (password == null) { throw new IllegalStateException("No password available"); } return password; } @Override public void setHeaders(URLConnection connection, Base64Encoder b64) { connection.setRequestProperty("Authorization", authHeader(b64)); } protected String authHeader(Base64Encoder b64) { final String credentials = user.getName() + ":" + getPassword(); return "Basic " + b64.encode(credentials.getBytes()); } @Override public void setHeaders(Map<String, String> headers, Base64Encoder b64) { } } class UserToken extends UserCredentials { public static final String AUTH_TYPE = "Token"; public final long id; public final String secret; public UserToken(IsUser user, long id, String secret) { super(user); this.id = id; this.secret = secret; } public UserToken(IsUser user, String token) { super(user); final Splitter splitter = new Splitter(token, ':'); this.id = splitter.getLong(); this.secret = splitter.getString(); } @Override public <E extends Throwable> void match(Matcher<E> matcher) throws E { matcher.when(this); } @Override public <R> R map(Mapper<R> mapper) { return mapper.when(this); } @Override protected String authHeader(Base64Encoder b64) { return AUTH_TYPE +" "+ encodeCookie(); } public String encodeCookie() { return user.getName() + ":" + id + ":" + secret; } public String encodeLoginParam() { return id +":"+ secret; } public static UserToken decodeCookie(String cookie) { Splitter splitter = new Splitter(cookie, ':'); return new UserToken( new ClientUser(splitter.getString()), splitter.getLong(), splitter.getString()); } public static UserToken decodeLoginParam(IsUser user, String loginParam) { Splitter splitter = new Splitter(loginParam, ':'); return new UserToken( user, splitter.getLong(), splitter.getString()); } } abstract class UserCredentials implements ItemCredentials { public final IsUser user; protected UserCredentials() { this.user = null; } protected UserCredentials(IsUser user) { this.user = user; } @Override public AuthenticationStatus getAuthStatus() { return AuthenticationStatus.LOGGED_IN; } @Override public boolean hasGroup(String groupName) { return this.user != null && this.user.hasGroup(groupName); } @Override public void setQueryParams(UrlStringBuilder url) { } @Override public String getUrlPrefix() { return ""; } public Power getPower() { return Power.USER; } @Override public void setHeaders(URLConnection connection, Base64Encoder b64) { connection.setRequestProperty("Authorization", authHeader(b64)); } @Override public void setHeaders(Map<String, String> connection, Base64Encoder b64) { connection.put("Authorization", authHeader(b64)); } protected abstract String authHeader(Base64Encoder b64); } class ItemKey implements ItemCredentials { public final String checksum; public ItemKey(String checksum) { this.checksum = checksum; } @Override public <E extends Throwable> void match(Matcher<E> matcher) throws E { matcher.when(this); } @Override public <R> R map(Mapper<R> mapper) { return mapper.when(this); } @Override public AuthenticationStatus getAuthStatus() { return AuthenticationStatus.ANONYMOUS; } @Override public boolean hasGroup(String groupName) { return false; } @Override public void setHeaders(URLConnection connection, Base64Encoder b64) { } @Override public void setHeaders(Map<String, String> headers, Base64Encoder b64) { } @Override public Power getPower() { return Power.SINGLE; } @Override public void setQueryParams(UrlStringBuilder url) { url.appendQueryParam("key", checksum); } @Override public String getUrlPrefix() { return ""; } } /** No credentials are needed because the item is public. */ class PublicAccess implements ItemCredentials { @Override public AuthenticationStatus getAuthStatus() { return AuthenticationStatus.ANONYMOUS; } @Override public boolean hasGroup(String groupName) { return false; } @Override public void setHeaders(URLConnection connection, Base64Encoder b64) { } @Override public void setHeaders(Map<String, String> headers, Base64Encoder b64) { } @Override public Power getPower() { return Power.PUBLIC; } @Override public <E extends Throwable> void match(Matcher<E> matcher) throws E { matcher.when(this); } @Override public <R> R map(Mapper<R> mapper) { return mapper.when(this); } @Override public void setQueryParams(UrlStringBuilder url) { } @Override public String getUrlPrefix() { return "public/"; } } }
Java
CL
d449beb7fb74480163f5fbeb0172db8309c92b6d1cbff3a211ab5139fb98bc8b
/* * Copyright (C) 2019 Parrot Drones SAS * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the Parrot Company nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ package com.parrot.drone.groundsdk.internal.tasks; import android.os.ConditionVariable; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.support.annotation.NonNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; public class ExecutorTests { private Thread mTestThread; private Thread mMainThread; private Handler mMainThreadHandler; @Before public void setUp() { mTestThread = Thread.currentThread(); mMainThread = Looper.getMainLooper().getThread(); mMainThreadHandler = new Handler(Looper.getMainLooper()); } @After public void tearDown() { mMainThreadHandler.removeCallbacksAndMessages(null); runOnMainThread(Executor::dispose); } @Test public void testDispose() { runOnMainThread(() -> { ConditionVariable fgLock = new ConditionVariable(); // this task should be canceled Task<Void> task = Executor.runInBackground(() -> { // this runnable should never get a chance to run Executor.postOnMainThread(SHOULD_NEVER_RUN); fgLock.open(); return BLOCKS_UNTIL_CANCELED.call(); }); // ensure the runnable is posted fgLock.block(); // Dispose the executor now Executor.dispose(); assertThat(task, notNullValue()); assertThat(task.cancel(), is(false)); // false means already canceled }); } @Test public void testPostOnMainThread() { runOnMainThread(() -> assertThat(Thread.currentThread(), is(mMainThread))); } @Test(expected = IllegalStateException.class) public void testPostFromMainThread() { callOnMainThread((Callable<Void>) () -> { // postOnMainThread should throw when called from main thread. Executor.postOnMainThread(SHOULD_NEVER_RUN); return null; }); } @Test public void testSchedule() { ConditionVariable fgLock = new ConditionVariable(); long delayMs = 100; runOnMainThread(() -> { // now on main thread long now = SystemClock.currentThreadTimeMillis(); Executor.schedule(() -> { // should still be on main thread... assertThat(Thread.currentThread(), is(mMainThread)); // ... but later assertThat(System.currentTimeMillis(), greaterThanOrEqualTo(now + delayMs)); fgLock.open(); }, delayMs); }); fgLock.block(); } @Test(expected = IllegalStateException.class) public void testScheduleNotFromMainThread() { // schedule should throw when not called from main thread. Executor.schedule(SHOULD_NEVER_RUN, 1000); } @Test public void testUnschedule() { runOnMainThread(() -> { // now on main thread Executor.schedule(SHOULD_NEVER_RUN, 0); Executor.unschedule(SHOULD_NEVER_RUN); }); } @Test(expected = IllegalStateException.class) public void testUnscheduleNotFromMainThread() { // unschedule should throw when not called from main thread. Executor.unschedule(SHOULD_NEVER_RUN); } @Test public void testRunInBackground() { ConditionVariable fgLock = new ConditionVariable(); Task<?> task = callOnMainThread((Callable<Task<?>>) () -> Executor.runInBackground((Callable<Void>) () -> { assertThat(Thread.currentThread(), not(mTestThread)); assertThat(Thread.currentThread(), not(mMainThread)); fgLock.open(); return null; })); assertThat(task, notNullValue()); fgLock.block(); } @Test public void testBackgroundTaskResult() { ConditionVariable fgLock = new ConditionVariable(); // first we register the listener _before_ the task completes Task.CompletionListener<Object> listensBefore = newMockListener(() -> { // should be called on the main thread when complete assertThat(Thread.currentThread(), is(mMainThread)); fgLock.open(); }); Task<Object> task = callOnMainThread(() -> { ConditionVariable bgLock = new ConditionVariable(); Task<Object> t = Executor.runInBackground(() -> { bgLock.block(); return RESULT; }).whenComplete(listensBefore); Mockito.verify(listensBefore, Mockito.never()).onTaskComplete( Mockito.any(), Mockito.any(), Mockito.anyBoolean()); bgLock.open(); return t; }); assertThat(task, notNullValue()); fgLock.block(); Mockito.verify(listensBefore, Mockito.times(1)).onTaskComplete(RESULT, null, false); runOnMainThread(() -> { // now we register another listener _after_ the task has complete Task.CompletionListener<Object> listensAfter = newMockListener(() -> { // should be called immediately on the main thread assertThat(Thread.currentThread(), is(mMainThread)); }); task.whenComplete(listensAfter); Mockito.verify(listensAfter, Mockito.times(1)).onTaskComplete(RESULT, null, false); // finally, cancelling a completed task should do nothing assertThat(task.cancel(), is(false)); Mockito.verifyNoMoreInteractions(listensBefore, listensAfter); }); } @Test public void testBackgroundTaskError() { ConditionVariable fgLock = new ConditionVariable(); // first we register the listener _before_ the task completes Task.CompletionListener<Object> listensBefore = newMockListener(() -> { // should be called on the main thread when complete assertThat(Thread.currentThread(), is(mMainThread)); fgLock.open(); }); Task<Object> task = callOnMainThread(() -> { ConditionVariable bgLock = new ConditionVariable(); Task<Object> t = Executor.runInBackground(() -> { bgLock.block(); throw FAILURE; }).whenComplete(listensBefore); Mockito.verify(listensBefore, Mockito.never()).onTaskComplete( Mockito.any(), Mockito.any(), Mockito.anyBoolean()); bgLock.open(); return t; }); assertThat(task, notNullValue()); fgLock.block(); Mockito.verify(listensBefore, Mockito.times(1)).onTaskComplete(null, FAILURE, false); runOnMainThread(() -> { // now we register another listener _after_ the task has complete Task.CompletionListener<Object> listensAfter = newMockListener(() -> { // should be called immediately on the main thread assertThat(Thread.currentThread(), is(mMainThread)); }); task.whenComplete(listensAfter); Mockito.verify(listensAfter, Mockito.times(1)).onTaskComplete(null, FAILURE, false); // finally, cancelling a completed task should do nothing assertThat(task.cancel(), is(false)); Mockito.verifyNoMoreInteractions(listensBefore, listensAfter); }); } @Test public void testBackgroundTaskCancel() { ConditionVariable fgLock = new ConditionVariable(); // first we register the listener _before_ the task is canceled Task.CompletionListener<Object> listensBefore = newMockListener(() -> { // should be called on the main thread when canceled assertThat(Thread.currentThread(), is(mMainThread)); fgLock.open(); }); Task<Void> task = callOnMainThread(() -> { Task<Void> t = Executor.runInBackground(BLOCKS_UNTIL_CANCELED).whenComplete(listensBefore); Mockito.verify(listensBefore, Mockito.never()).onTaskComplete( Mockito.any(), Mockito.any(), Mockito.anyBoolean()); // now cancel the task assertThat(t.cancel(), is(true)); return t; }); fgLock.block(); Mockito.verify(listensBefore, Mockito.times(1)).onTaskComplete(null, null, true); runOnMainThread(() -> { // now we register another listener _after_ the task has been canceled Task.CompletionListener<Object> listensAfter = newMockListener(() -> { // should be called immediately on the main thread assertThat(Thread.currentThread(), is(mMainThread)); }); task.whenComplete(listensAfter); Mockito.verify(listensAfter, Mockito.times(1)).onTaskComplete(null, null, true); // finally, cancelling a completed task should do nothing assertThat(task.cancel(), is(false)); Mockito.verifyNoMoreInteractions(listensBefore, listensAfter); }); } @Test(expected = IllegalStateException.class) public void testRunInBackgroundFromNonMainThread() { // runInBackground should throw when not called from main thread. Executor.runInBackground(RETURNS_NULL); } @Test(expected = IllegalStateException.class) public void testBackgroundTaskObservationFromNonMainThread() { Task<?> task = callOnMainThread((Callable<Task<?>>) () -> Executor.runInBackground(RETURNS_NULL)); // whenComplete should throw when not called from main thread. task.whenComplete((Task.CompletionListener<Object>) (result, error, canceled) -> { throw new AssertionError("Reached the unreachable"); }); } @Test(expected = IllegalStateException.class) public void testBackgroundTaskCancelFromNonMainThread() { Task<?> task = callOnMainThread((Callable<Task<?>>) () -> Executor.runInBackground(RETURNS_NULL)); // cancel should throw when not called from main thread. task.cancel(); } @NonNull private static Task.CompletionListener<Object> newMockListener(@NonNull Runnable onCalled) { @SuppressWarnings("unchecked") Task.CompletionListener<Object> listener = Mockito.mock(Task.CompletionListener.class); Mockito.doAnswer((Answer<Void>) invocationOnMock -> { onCalled.run(); return null; }).when(listener).onTaskComplete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); return listener; } private void runOnMainThread(@NonNull Runnable runnable) { callOnMainThread(Executors.callable(runnable)); } // posts the given callable on the main thread and waits for it on the current thread then return the result // Rethrows on the current thread any exception thrown from the callable on the main thread private <T> T callOnMainThread(@NonNull Callable<T> callable) { ConditionVariable sync = new ConditionVariable(); @SuppressWarnings({"unchecked", "SuspiciousArrayCast"}) T[] result = (T[]) new Object[] {null}; Throwable[] exception = new Exception[] {null}; mMainThreadHandler.post(() -> { try { result[0] = callable.call(); } catch (Exception e) { exception[0] = e; } finally { sync.open(); } }); sync.block(); if (exception[0] != null) { throwUnchecked(exception[0]); } return result[0]; } private static final Object RESULT = new Object(); private static final Exception FAILURE = new Exception(); private static final Callable<Void> RETURNS_NULL = () -> null; private static final Callable<Void> BLOCKS_UNTIL_CANCELED = () -> { new Semaphore(0).acquire(); // blocks until thread is interrupted then throws InterruptException throw new AssertionError("Reached the unreachable"); }; private static final Runnable SHOULD_NEVER_RUN = () -> { throw new AssertionError("Reached the unreachable"); }; private static void throwUnchecked(@NonNull Throwable throwable) { final class Thrower<T extends Throwable> { @SuppressWarnings("unchecked") private Thrower() throws T { throw (T) throwable; } } //noinspection Convert2Diamond,ResultOfObjectAllocationIgnored new Thrower<RuntimeException>(); } }
Java
CL
a41461fc8f51e61d061a60c9c1571b47d0722fd3aaab53f968fafed83b43e0fc
package kotlin.reflect.jvm.internal.impl.metadata.deserialization; import java.util.LinkedList; import java.util.List; import kotlin.Triple; import kotlin.jvm.internal.Intrinsics; import kotlin.reflect.jvm.internal.impl.metadata.ProtoBuf.QualifiedNameTable; import kotlin.reflect.jvm.internal.impl.metadata.ProtoBuf.QualifiedNameTable.QualifiedName; import kotlin.reflect.jvm.internal.impl.metadata.ProtoBuf.QualifiedNameTable.QualifiedName.Kind; import kotlin.reflect.jvm.internal.impl.metadata.ProtoBuf.StringTable; /* compiled from: NameResolverImpl.kt */ public final class NameResolverImpl implements NameResolver { private final QualifiedNameTable qualifiedNames; private final StringTable strings; public final /* synthetic */ class WhenMappings { public static final /* synthetic */ int[] $EnumSwitchMapping$0 = new int[Kind.values().length]; static { $EnumSwitchMapping$0[Kind.CLASS.ordinal()] = 1; $EnumSwitchMapping$0[Kind.PACKAGE.ordinal()] = 2; $EnumSwitchMapping$0[Kind.LOCAL.ordinal()] = 3; } } public NameResolverImpl(StringTable stringTable, QualifiedNameTable qualifiedNameTable) { this.strings = stringTable; this.qualifiedNames = qualifiedNameTable; } private final Triple<List<String>, List<String>, Boolean> traverseIds(int i) { LinkedList linkedList = new LinkedList(); LinkedList linkedList2 = new LinkedList(); boolean z = false; while (i != -1) { QualifiedName qualifiedName = this.qualifiedNames.getQualifiedName(i); StringTable stringTable = this.strings; Intrinsics.checkReturnedValueIsNotNull((Object) qualifiedName, "proto"); String string = stringTable.getString(qualifiedName.getShortName()); Kind kind = qualifiedName.getKind(); if (kind != null) { int i2 = WhenMappings.$EnumSwitchMapping$0[kind.ordinal()]; if (i2 == 1) { linkedList2.addFirst(string); } else if (i2 == 2) { linkedList.addFirst(string); } else if (i2 == 3) { linkedList2.addFirst(string); z = true; } i = qualifiedName.getParentQualifiedName(); } else { Intrinsics.throwNpe(); throw null; } } return new Triple<>(linkedList, linkedList2, Boolean.valueOf(z)); } public String getQualifiedClassName(int i) { Triple traverseIds = traverseIds(i); List list = (List) traverseIds.mo31020a(); String a = C13199w.m40559a((List) traverseIds.mo31021b(), ".", null, null, 0, null, null, 62, null); if (list.isEmpty()) { return a; } StringBuilder sb = new StringBuilder(); sb.append(C13199w.m40559a(list, "/", null, null, 0, null, null, 62, null)); sb.append('/'); sb.append(a); return sb.toString(); } public String getString(int i) { String string = this.strings.getString(i); Intrinsics.checkReturnedValueIsNotNull((Object) string, "strings.getString(index)"); return string; } public boolean isLocalClassName(int i) { return ((Boolean) traverseIds(i).mo31026f()).booleanValue(); } }
Java
CL
7501d2b3fefe30b7588f0f5841b0e1c316f3b754c65912b1504117ef1c3be3cd
package com.sustain.workflow; import com.sustain.cases.model.CaseComponent; import com.sustain.metadata.model.MdEntity; import com.sustain.util.spring.TaskProcessor; import com.sustain.workflow.model.*; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * User: Sarbjit Samra * Date: July 22, 2005 */ public class WMControllerImpl implements WMSyncController { protected final Logger logger = LoggerFactory.getLogger(getClass()); private TaskProcessor taskProcessor; private WMStateMachine wmStateMachine; public void setTaskProcessor(TaskProcessor taskProcessor) { this.taskProcessor = taskProcessor; } public void setWmStateMachine(WMStateMachine wmStateMachine) { this.wmStateMachine = wmStateMachine; } public void handleEvent(WMApplicationTrigger applicationTrigger) { List<WMMessageTrigger> triggers = WMMessageTrigger.findTriggersByEvent(applicationTrigger); if (CollectionUtils.isEmpty(triggers)) { logger.debug("no triggers found matching event[" + applicationTrigger + "]"); return; } handleTriggers(new WMTrackedData(applicationTrigger), triggers); } private void handleTriggers(WMTrackedData eventData, List<? extends WMTrigger> triggers) { for (WMTrigger trigger : triggers) { if (trigger.getActivity().isStartEventType()) { createProcessInst(trigger, eventData); } else if (trigger.getActivity().isImplementationActivityType()) { completeActivities(trigger, eventData); } else { logger.warn("unknown trigger effect for trigger: " + trigger + "; event: " + eventData); } } } public void completeThisTaskAndSelectResult( final Long wmActivityInstId, final Long wmPostTransitionRestrictionId, final WMExternalData externalData) { taskProcessor.runInSession(new Runnable() { public void run() { wmStateMachine.completeAndSelectResult(wmActivityInstId, wmPostTransitionRestrictionId, externalData); } }); } public void retryWorkItemInst(final Long workItemInstId) { taskProcessor.runInSession(new Runnable() { public void run() { WMWorkItemInst workItemInst = WMWorkItemInst.get(workItemInstId); wmStateMachine.retryWorkItemInst(workItemInst, new WMExternalData(workItemInst.getActivityInst())); } }); } public void terminateWorkItemInst(final Long workItemInstId) { taskProcessor.runInSession(new Runnable() { public void run() { WMWorkItemInst workItemInst = WMWorkItemInst.get(workItemInstId); wmStateMachine.terminateWorkItemInst(workItemInst, new WMExternalData()); } }); } public void terminateActivityInst(final Long activityInstId) { taskProcessor.runInSession(new Runnable() { public void run() { WMActivityInst activityInst = WMActivityInst.get(activityInstId); wmStateMachine.terminateActivityInst(activityInst); } }); } public void retryActivityInst(final Long activityInstId) { taskProcessor.runInSession(new Runnable() { public void run() { WMActivityInst activityInst = WMActivityInst.get(activityInstId); wmStateMachine.retryActivityInst(activityInst, new WMExternalData(activityInst)); } }); } public void sendToWorkflow(final String username, final Long triggerId, final Long eventObjectId, final WMExternalData externalData) { taskProcessor.runInSession(new Runnable() { public void run() { WMMessageTrigger trigger = WMMessageTrigger.get(triggerId); MdEntity eventEntity = trigger.getEventEntity(); CaseComponent eventObject = CaseComponent.get(eventEntity, eventObjectId); WMTrackedData event = new WMTrackedData(username, eventObject); wmStateMachine.startProcess(trigger, event, externalData); } }); } public void terminateProcessInst(final Long processInstId) { taskProcessor.runInSession(new Runnable() { public void run() { WMProcessInst processInst = WMProcessInst.get(processInstId); wmStateMachine.terminateProcessInst(processInst); } }); } public void createProcessInst(WMTrigger trigger, WMTrackedData event) { if (event == null) return; try { wmStateMachine.startProcess(trigger, event, new WMExternalData(event)); } catch (Exception e) { logger.error(e.toString(), e); } } public void completeActivities(WMTrigger trigger, WMTrackedData evet) { try { wmStateMachine.completeActivities(trigger, evet); } catch (Exception e) { logger.error(e.toString(), e); } } }
Java
CL
05a90a689c139c1956a3110fb73d663d0813ba081de705ce1bf84e6d4e11fea4
/* * Copyright 2022 Yelp Inc. * * 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.yelp.nrtsearch.server.luceneserver.highlights; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import com.google.protobuf.BoolValue; import com.google.protobuf.StringValue; import com.google.protobuf.UInt32Value; import com.yelp.nrtsearch.server.grpc.AddDocumentRequest; import com.yelp.nrtsearch.server.grpc.AddDocumentRequest.MultiValuedField; import com.yelp.nrtsearch.server.grpc.FieldDefRequest; import com.yelp.nrtsearch.server.grpc.Highlight; import com.yelp.nrtsearch.server.grpc.Highlight.Settings; import com.yelp.nrtsearch.server.grpc.Highlight.Type; import com.yelp.nrtsearch.server.grpc.MatchQuery; import com.yelp.nrtsearch.server.grpc.PhraseQuery; import com.yelp.nrtsearch.server.grpc.Query; import com.yelp.nrtsearch.server.grpc.SearchRequest; import com.yelp.nrtsearch.server.grpc.SearchResponse; import com.yelp.nrtsearch.server.grpc.SearchResponse.Hit; import com.yelp.nrtsearch.server.grpc.TermQuery; import com.yelp.nrtsearch.server.luceneserver.ServerTestCase; import io.grpc.StatusRuntimeException; import io.grpc.testing.GrpcCleanupRule; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.ClassRule; import org.junit.Test; public class NRTFastVectorHighlighterTest extends ServerTestCase { private static final List<String> ALL_FIELDS = List.of("doc_id", "comment"); @ClassRule public static final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); protected FieldDefRequest getIndexDef(String name) throws IOException { return getFieldsFromResourceFile("/highlights/register_fields_highlights.json"); } protected void initIndex(String name) throws Exception { List<AddDocumentRequest> docs = new ArrayList<>(); AddDocumentRequest request = AddDocumentRequest.newBuilder() .setIndexName(name) .putFields("doc_id", MultiValuedField.newBuilder().addValue("1").build()) .putFields( "comment", MultiValuedField.newBuilder() .addValue("the food here is amazing, service was good") .build()) .putFields( "comment2", MultiValuedField.newBuilder() .addValue("This is my regular place, the food is good") .build()) .putFields( "comment_multivalue", MultiValuedField.newBuilder() .addAllValue( List.of( "The food is good there, but the service is terrible.", "I personally don't like the staff at this place", "Not all food are good.")) .build()) .putFields( "boundary_scanner_field", MultiValuedField.newBuilder() .addValue( "This is a super longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle-it-in a very decent way and stops at.") .build()) .build(); docs.add(request); request = AddDocumentRequest.newBuilder() .setIndexName(name) .putFields("doc_id", MultiValuedField.newBuilder().addValue("2").build()) .putFields( "comment", MultiValuedField.newBuilder() .addValue( "This is my first time eating at this restaurant. The food here is pretty good, the service could be better. My favorite food was chilly chicken.") .build()) .putFields( "comment2", MultiValuedField.newBuilder() .addValue("There is some amazing food and also drinks here. Must visit!") .build()) .putFields( "comment_multivalue", MultiValuedField.newBuilder() .addValue("High quality food. Fresh and delicious!") .build()) .build(); docs.add(request); addDocuments(docs.stream()); } @Test public void testBasicHighlight() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings(Settings.newBuilder().setScoreOrdered(BoolValue.of(true))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo("the <em>food</em> here is amazing, service was good"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo( "restaurant. The <em>food</em> here is pretty good, the service could be better. My favorite <em>food</em> was chilly chicken"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithName() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings(Settings.newBuilder().setHighlighterType(Type.FAST_VECTOR)) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo("the <em>food</em> here is amazing, service was good"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo( "restaurant. The <em>food</em> here is pretty good, the service could be better. My favorite <em>food</em> was chilly chicken"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithUnknownName() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings( Settings.newBuilder() .setHighlighterType(Type.CUSTOM) .setCustomHighlighterName("doesn't-exist")) .build(); assertThatThrownBy(() -> doHighlightQuery(highlight)) .isInstanceOf(StatusRuntimeException.class) .hasMessageContaining("Unknown highlighter name"); } @Test public void testHighlightMultivalueField() { Highlight highlight = Highlight.newBuilder() .addFields("comment_multivalue") .setSettings( Settings.newBuilder() .setScoreOrdered(BoolValue.of(true)) .setDiscreteMultivalue(BoolValue.of(true))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("comment_multivalue").getFragmentsList()) .containsExactly( "The <em>food</em> is good there, but the service is terrible.", "Not all <em>food</em> are good."); assertThat(response.getHits(1).getHighlightsMap().get("comment_multivalue").getFragmentsList()) .containsExactly("High quality <em>food</em>. Fresh and delicious!"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightGlobalSettings() { Settings settings = Settings.newBuilder() .addPreTags("<START>") .addPostTags("<END>") .setFragmentSize(UInt32Value.newBuilder().setValue(18)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(3)) .setHighlightQuery( Query.newBuilder() .setMatchQuery( MatchQuery.newBuilder().setField("comment").setQuery("food is good"))) .setScoreOrdered(BoolValue.of(true)) .build(); Highlight highlight = Highlight.newBuilder().setSettings(settings).addFields("comment").build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "the <START>food<END> here <START>is<END> amazing", "service was <START>good<END>"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "The <START>food<END> here <START>is<END> pretty", "This <START>is<END> my first time", "pretty <START>good<END>, the service"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightFieldSettings() { Settings globalSettings = Settings.newBuilder() .addPreTags("<s>") .addPostTags("<e>") .setFragmentSize(UInt32Value.newBuilder().setValue(50)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(5)) .setHighlightQuery( Query.newBuilder() .setMatchQuery(MatchQuery.newBuilder().setField("comment").setQuery("pretty"))) .setScoreOrdered(BoolValue.of(true)) .build(); Settings fieldSettings = Settings.newBuilder() .addPreTags("<START>") .addPostTags("<END>") .setFragmentSize(UInt32Value.newBuilder().setValue(18)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(3)) .setHighlightQuery( Query.newBuilder() .setMatchQuery( MatchQuery.newBuilder().setField("comment").setQuery("food is good"))) .build(); Highlight highlight = Highlight.newBuilder() .setSettings(globalSettings) .addFields("comment") .putFieldSettings("comment", fieldSettings) .build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "the <START>food<END> here <START>is<END> amazing", "service was <START>good<END>"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "The <START>food<END> here <START>is<END> pretty", "This <START>is<END> my first time", "pretty <START>good<END>, the service"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testNotScoreOrdered() { Settings globalSettings = Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setMatchQuery( MatchQuery.newBuilder().setField("comment").setQuery("food is good"))) .setFragmentSize(UInt32Value.newBuilder().setValue(18)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(3)) .setScoreOrdered(BoolValue.of(false)) .build(); Highlight highlight = Highlight.newBuilder().setSettings(globalSettings).addFields("comment").build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly("the <em>food</em> here <em>is</em> amazing", "service was <em>good</em>"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "This <em>is</em> my first time", "The <em>food</em> here <em>is</em> pretty", "pretty <em>good</em>, the service"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightsAbsentForOneHit() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setPhraseQuery( PhraseQuery.newBuilder() .setField("comment") .setSlop(5) .addTerms("food") .addTerms("pretty") .addTerms("good")))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap()).isEmpty(); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "first time eating at this restaurant. The <em>food</em> here is <em>pretty good</em>, the service could be better. My favorite"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightIncompatibleField() { Highlight highlight = Highlight.newBuilder().addFields("comment.no_search").build(); try { doHighlightQuery(highlight); fail("No error for invalid field"); } catch (StatusRuntimeException e) { assertThat(e.getMessage()) .contains("Field comment.no_search is not searchable and cannot support highlights"); } highlight = Highlight.newBuilder().addFields("comment.no_store").build(); try { doHighlightQuery(highlight); fail("No error for invalid field"); } catch (StatusRuntimeException e) { assertThat(e.getMessage()) .contains( "Field comment.no_store is not stored and cannot support fast-vector-highlighter"); } highlight = Highlight.newBuilder().addFields("comment.no_term_vectors_with_offsets").build(); try { doHighlightQuery(highlight); fail("No error for invalid field"); } catch (StatusRuntimeException e) { assertThat(e.getMessage()) .contains( "Field comment.no_term_vectors_with_offsets does not have term vectors with positions and offsets and cannot support fast-vector-highlighter"); } } @Test public void testHighlightMaxNumFragmentsZeroGlobal() { Settings globalSettings = Settings.newBuilder() .setFragmentSize(UInt32Value.newBuilder().setValue(10)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(0)) .build(); Highlight highlight = Highlight.newBuilder().setSettings(globalSettings).addFields("comment").build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly("the <em>food</em> here is amazing, service was good"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "This is my first time eating at this restaurant. The <em>food</em> here is pretty good, the service could be better. My favorite <em>food</em> was chilly chicken."); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightMaxNumFragmentsZeroForField() { Settings globalSettings = Settings.newBuilder() .setFragmentSize(UInt32Value.newBuilder().setValue(10)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(1)) .build(); Settings fieldSettings = Settings.newBuilder() .setFragmentSize(UInt32Value.newBuilder().setValue(10)) .setMaxNumberOfFragments(UInt32Value.newBuilder().setValue(0)) .build(); Highlight highlight = Highlight.newBuilder() .setSettings(globalSettings) .addFields("comment") .putFieldSettings("comment", fieldSettings) .build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly("the <em>food</em> here is amazing, service was good"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragmentsList()) .containsExactly( "This is my first time eating at this restaurant. The <em>food</em> here is pretty good, the service could be better. My favorite <em>food</em> was chilly chicken."); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightFieldMatchFalse() { Highlight highlight = Highlight.newBuilder() .setSettings(Settings.newBuilder().setFieldMatch(BoolValue.of(false))) .addFields("comment2") .build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHitsCount()).isEqualTo(2); assertThat(response.getHits(0).getHighlightsMap().get("comment2").getFragmentsList()) .containsExactly("This is my regular place, the <em>food</em> is good"); assertThat(response.getHits(1).getHighlightsMap().get("comment2").getFragmentsList()) .containsExactly("There is some amazing <em>food</em> and also drinks here. Must visit!"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testHighlightFieldMatchTrue() { Highlight highlight = Highlight.newBuilder() .setSettings( Settings.newBuilder() .setFieldMatch(BoolValue.of(true)) .setScoreOrdered(BoolValue.of(true))) .addFields("comment2") .build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHitsCount()).isEqualTo(2); assertThat(response.getHits(0).getHighlightsMap()).isEmpty(); assertThat(response.getHits(1).getHighlightsMap()).isEmpty(); } @Test public void testMaxFragmentSize() { Highlight highlight = Highlight.newBuilder() .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setMatchQuery( MatchQuery.newBuilder() .setField("comment_multivalue") .setQuery("food"))) .setMaxNumberOfFragments(UInt32Value.of(2)) .setFragmentSize(UInt32Value.of(0)) .setDiscreteMultivalue(BoolValue.of(true)) .setFieldMatch(BoolValue.of(true))) .addFields("comment_multivalue") .build(); SearchResponse response = doHighlightQuery(highlight); assertThat(response.getHitsCount()).isEqualTo(2); assertThat(response.getHits(0).getHighlightsMap().get("comment_multivalue").getFragmentsList()) .containsExactly( "The <em>food</em> is good there, but the service is terrible.", "Not all <em>food</em> are good."); assertThat(response.getHits(1).getHighlightsMap().get("comment_multivalue").getFragmentsList()) .containsExactly("High quality <em>food</em>. Fresh and delicious!"); } @Test public void testBasicHighlightWithExplicitBoundaryScanner() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings( Settings.newBuilder() .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("simple"))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo("the <em>food</em> here is amazing, service was good"); assertThat(response.getHits(1).getHighlightsMap().get("comment").getFragments(0)) .isEqualTo( "restaurant. The <em>food</em> here is pretty good, the service could be better. My favorite <em>food</em> was chilly chicken"); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithWrongBoundaryScanner() { Highlight highlight = Highlight.newBuilder() .addFields("comment") .setSettings( Settings.newBuilder() .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("doesnt_exist"))) .build(); assertThatThrownBy(() -> doHighlightQuery(highlight)) .isInstanceOf(StatusRuntimeException.class) .hasMessageContaining("Unknown boundary scanner"); } @Test public void testBasicHighlightWithCustomCharsBoundaryScanner() { Highlight highlight = Highlight.newBuilder() .addFields("boundary_scanner_field") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setTermQuery( TermQuery.newBuilder() .setField("boundary_scanner_field") .setTextValue("super") .build()) .build()) .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("simple")) .setFragmentSize(UInt32Value.of(75)) .setBoundaryChars(StringValue.of("-"))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("boundary_scanner_field").getFragments(0)) .isEqualTo( "This is a <em>super</em> longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle"); assertThat(response.getHits(1).getHighlightsCount()).isEqualTo(0); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithBoundaryScannerAndMaxScan() { Highlight highlight = Highlight.newBuilder() .addFields("boundary_scanner_field") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setTermQuery( TermQuery.newBuilder() .setField("boundary_scanner_field") .setTextValue("super") .build()) .build()) .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("simple")) .setFragmentSize(UInt32Value.of(75)) .setBoundaryMaxScan(UInt32Value.of(100))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("boundary_scanner_field").getFragments(0)) .isEqualTo( "This is a <em>super</em> longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle-it-in"); assertThat(response.getHits(1).getHighlightsCount()).isEqualTo(0); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithWordBoundaryScanner() { Highlight highlight = Highlight.newBuilder() .addFields("boundary_scanner_field") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setTermQuery( TermQuery.newBuilder() .setField("boundary_scanner_field") .setTextValue("super") .build()) .build()) .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("word")) .setFragmentSize(UInt32Value.of(75))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("boundary_scanner_field").getFragments(0)) .isEqualTo( "This is a <em>super</em> longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle-it-in"); assertThat(response.getHits(1).getHighlightsCount()).isEqualTo(0); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithSentenceBoundaryScanner() { Highlight highlight = Highlight.newBuilder() .addFields("boundary_scanner_field") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setTermQuery( TermQuery.newBuilder() .setField("boundary_scanner_field") .setTextValue("super") .build()) .build()) .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("sentence")) .setFragmentSize(UInt32Value.of(75))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("boundary_scanner_field").getFragments(0)) .isEqualTo( "This is a <em>super</em> longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle-it-in a very decent way and stops at. "); assertThat(response.getHits(1).getHighlightsCount()).isEqualTo(0); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } @Test public void testBasicHighlightWithSentenceBoundaryScannerAndExplicitLocale() { Highlight highlight = Highlight.newBuilder() .addFields("boundary_scanner_field") .setSettings( Settings.newBuilder() .setHighlightQuery( Query.newBuilder() .setTermQuery( TermQuery.newBuilder() .setField("boundary_scanner_field") .setTextValue("super") .build()) .build()) .setScoreOrdered(BoolValue.of(true)) .setBoundaryScanner(StringValue.of("sentence")) .setBoundaryScannerLocale(StringValue.of("en-US")) .setFragmentSize(UInt32Value.of(75))) .build(); SearchResponse response = doHighlightQuery(highlight); assertFields(response); assertThat(response.getHits(0).getHighlightsMap().get("boundary_scanner_field").getFragments(0)) .isEqualTo( "This is a <em>super</em> longWordICouldEverImagineAndTheBoundaryScannerShouldProperlyHandle-it-in a very decent way and stops at. "); assertThat(response.getHits(1).getHighlightsCount()).isEqualTo(0); assertThat(response.getDiagnostics().getHighlightTimeMs()).isGreaterThan(0); } private String indexName() { return getIndices().get(0); } private SearchResponse doHighlightQuery(Highlight highlight) { return getGrpcServer() .getBlockingStub() .search( SearchRequest.newBuilder() .setIndexName(indexName()) .setStartHit(0) .setTopHits(2) .addAllRetrieveFields(ALL_FIELDS) .setQuery( Query.newBuilder() .setMatchQuery( MatchQuery.newBuilder().setField("comment").setQuery("food"))) .setHighlight(highlight) .build()); } private void assertFields(SearchResponse response) { Set<String> seenSet = new HashSet<>(); for (Hit hit : response.getHitsList()) { String id = hit.getFieldsOrThrow("doc_id").getFieldValue(0).getTextValue(); seenSet.add(id); if (id.equals("1")) { assertThat(hit.getFieldsOrThrow("comment").getFieldValue(0).getTextValue()) .isEqualTo("the food here is amazing, service was good"); } else if (id.equals("2")) { assertThat(hit.getFieldsOrThrow("comment").getFieldValue(0).getTextValue()) .isEqualTo( "This is my first time eating at this restaurant. The food here is pretty good, the service could be better. My favorite food was chilly chicken."); } else { fail("Unknown id: " + id); } } assertThat(seenSet).containsExactly("1", "2"); } }
Java
CL
c3eba8cf0c895200f44e8c3627dc7309a5e9175e33ccb3a64abd85bd0283eb0e
import java.io.IOException; import java.sql.SQLException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.OptionBuilder; import com.highgo.hgdbadmin.myutil.MigrateConstraint; import com.highgo.hgdbadmin.myutil.ShellEnvironment; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 1.根据传入的信息,创建一个xml代码段 2.创建一个Connection,看看信息是否有效 3.将代码段写入c3p0的配置文件 * * @author u * */ public class MigrateConstraintFKFunction extends AquilaFunction { @SuppressWarnings("static-access") public MigrateConstraintFKFunction() { this.addOption(OptionBuilder.withDescription("migrate Unique Constraint.").withLongOpt("name").hasArg().create("name")); } public Object executeFunction(CommandLine line) { if (!line.hasOption("name")) { ShellEnvironment.println("Required argument --name is missing."); return null; } try { String name = line.getOptionValue("name"); migrateCheckConstraint(name); } catch (IOException | SQLException | InterruptedException ex) { ex.printStackTrace(); } return null; } private void migrateCheckConstraint(String constrName) throws IOException, SQLException, InterruptedException { ShellEnvironment.println("Create Check Constraint:" + constrName); MigrateConstraint.createConstraintUK(constrName); ShellEnvironment.println("Create Check Constraint:" + constrName + " successfully!"); } }
Java
CL
8d396caad6dbfc79dc445f65468a2cf4edc581b21c5a7c57f90d74dcd9c567f7
package com.bdxh.user.entity; import javax.persistence.Table; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import javax.persistence.*; import java.util.Date; import java.lang.String; import java.lang.Long; import java.lang.Byte; /** * @Description: 实体类 * @Author WanMing * @Date 2019-06-25 10:17:12 */ @Data @Table(name = "t_family_black_url") public class FamilyBlackUrl { /** * 主键 */ @Id @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 学校主键 */ @Column(name = "school_id") private Long schoolId; /** * 学校编码 */ @Column(name = "school_code") private String schoolCode; /** * 学校名称 */ @Column(name = "school_name") private String schoolName; /** * 家长号 */ @Column(name = "card_number") private String cardNumber; /** * 家长主键 */ @Column(name = "family_id") private Long familyId; /** * 家长名称 */ @Column(name = "family_name") private String familyName; /** * 学生主键 */ @Column(name = "student_id") private Long studentId; /** * 学生姓名 */ @Column(name = "student_name") private String studentName; /** * 学生学号 */ @Column(name = "student_number") private String studentNumber; /** * 网站名称 */ @Column(name = "site_name") private String siteName; /** * 填写域名或者ip */ @Column(name = "ip") private String ip; /** * 状态 1 启用 2 禁用 */ @Column(name = "status") private Byte status; /** * 创建时间 */ @Column(name = "create_date") private Date createDate; /** * 更新时间 */ @Column(name = "update_date") private Date updateDate; /** * 备注 */ @Column(name = "remark") private String remark; }
Java
CL
18bf94344a27209f0129f6410fd228ef11596e9771d4845fa9eb37920198b66f
package com.wiscess.oauth.config; import static com.wiscess.oauth.config.OauthProperties.SECURITY_OAUTH_PREFIX; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import lombok.extern.slf4j.Slf4j; /** * Oauth Memory Away Support * @author wh */ @Slf4j @Configuration @ConditionalOnClass(AbstractAuthorizationServerConfig.class) @EnableConfigurationProperties(OauthProperties.class) @ConditionalOnBean(RedisConnectionFactory.class) @EnableAuthorizationServer @ConditionalOnProperty(prefix = SECURITY_OAUTH_PREFIX, name = "away", havingValue = "redis") @AutoConfigureAfter(RedisAutoConfiguration.class) public class AuthorizationServerRedisAutoConfiguration extends AuthorizationServerAutoConfiguration{ /** * redis connection factory */ private RedisConnectionFactory redisConnectionFactory; public AuthorizationServerRedisAutoConfiguration(OauthProperties oauthProperties, RedisConnectionFactory redisConnectionFactory) { super(oauthProperties); this.redisConnectionFactory=redisConnectionFactory; } /** * configuration clients * * @param clients client details service configuration * @throws Exception exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { log.info("AuthorizationServerRedisAutoConfiguration configure."); InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = clients.inMemory(); oauthProperties.getClients().stream().forEach(client -> inMemoryClientDetailsServiceBuilder.withClient(client.getClientId()) .secret(passwordEncoder.encode(client.getClientSecret())) .authorizedGrantTypes(client.getGrantTypes()) .scopes(client.getScopes()) .resourceIds(client.getResourceId()) .refreshTokenValiditySeconds(client.getRefreshTokenValiditySeconds()) .accessTokenValiditySeconds(client.getAccessTokenValiditySeconds())); } /** * Redis Token Store * @return TokenStore */ @Bean public TokenStore redisTokenStore() { RedisTokenStore tokenStore= new RedisTokenStore(redisConnectionFactory); tokenStore.setAuthenticationKeyGenerator(authenticationKeyGenerator()); return tokenStore; } }
Java
CL
8efb22660834d2d86d9ce86b98c673b5ee558d4f35e6dbc27b604f9e2258d8e2
package beeiqnamecard.com.htk.modelexample.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Metadata { @SerializedName("total") @Expose private Integer total; @SerializedName("page") @Expose private Integer page; @SerializedName("limit") @Expose private Integer limit; /** * * @return * The total */ public Integer getTotal() { return total; } /** * * @param total * The total */ public void setTotal(Integer total) { this.total = total; } /** * * @return * The page */ public Integer getPage() { return page; } /** * * @param page * The page */ public void setPage(Integer page) { this.page = page; } /** * * @return * The limit */ public Integer getLimit() { return limit; } /** * * @param limit * The limit */ public void setLimit(Integer limit) { this.limit = limit; } }
Java
CL
03e33b9084118f31aba10457ae73b245ac70191ebcde0ece7836799e65167183
/** * Java Card 3.0.5 API * url: https://docs.oracle.com/javacard/3.0.5/index.html * * Copyright (C) 2020, Oracle and/or its affiliates. All rights reserved. */ package javacard.framework.service; import javacard.framework.CardRuntimeException; import javacard.framework.JCSystem; /** * <code>ServiceException</code> represents a service framework-related * exception. * <p> * The service framework classes throw Java Card runtime environment-owned * instances of <code>ServiceException</code>. * <p> * Java Card runtime environment-owned instances of exception classes are * temporary Java Card runtime environment Entry Point Objects and can be * accessed from any applet context. References to these temporary objects * cannot be stored in class variables or instance variables or array * components. See * <em>Runtime Environment Specification, Java Card Platform, Classic * Edition</em>, section 6.2.1 for details. * * @version 1.0 */ public class ServiceException extends CardRuntimeException { /** * This reason code is used to indicate that an input parameter is not * allowed. */ public static final short ILLEGAL_PARAM = 1; /** * This reason code is used to indicate that a dispatch table is full. */ public static final short DISPATCH_TABLE_FULL = 2; /** * This reason code is used to indicate that the incoming data for a command * in the <code>APDU</code> object does not fit in the APDU buffer. */ public static final short COMMAND_DATA_TOO_LONG = 3; /** * This reason code is used to indicate that the command in the * <code>APDU</code> object cannot be accessed for input processing. */ public static final short CANNOT_ACCESS_IN_COMMAND = 4; /** * This reason code is used to indicate that the command in the * <code>APDU</code> object cannot be accessed for output processing. */ public static final short CANNOT_ACCESS_OUT_COMMAND = 5; /** * This reason code is used to indicate that the command in the * <code>APDU</code> object has been completely processed. */ public static final short COMMAND_IS_FINISHED = 6; /** * This reason code is used by RMIService to indicate that the remote method * returned a remote object which has not been exported. */ public static final short REMOTE_OBJECT_NOT_EXPORTED = 7; /** * Constructs a <code>ServiceException</code>. To conserve on resources * use <code>throwIt()</code> to use the Java Card runtime * environment-owned instance of this class. * * @param reason * the reason for the exception */ public ServiceException(short reason) { super(reason); } /** * Throws the Java Card runtime environment-owned instance of * <code>ServiceException</code> with the specified reason. * <p> * Java Card runtime environment-owned instances of exception classes are * temporary Java Card runtime environment Entry Point Objects and can be * accessed from any applet context. References to these temporary objects * cannot be stored in class variables or instance variables or array * components. See * <em>Runtime Environment Specification, Java Card Platform, Classic * Edition</em>, section 6.2.1 for details. * * @param reason * the reason for the exception * @exception ServiceException * always */ public static void throwIt(short reason) throws ServiceException { ServiceException se = new ServiceException(reason); throw se; } }
Java
CL
101b3abd7d71847a70df76aa2fe7d681415774506e368dd142d135b8e31c9d21
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pt.uc.dei.ar.proj5.grupob.controllers; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import pt.uc.dei.ar.proj5.grupob.ejbs.SessionController; import pt.uc.dei.ar.proj5.grupob.entities.Criteria; import pt.uc.dei.ar.proj5.grupob.entities.Paj; import pt.uc.dei.ar.proj5.grupob.facades.CriteriaFacade; import pt.uc.dei.ar.proj5.grupob.facades.PajFacade; import pt.uc.dei.ar.proj5.grupob.util.PajDeleteException; /** * @author Ana Sofia Mendes * @author Orlando Neves */ @Named @RequestScoped public class PajController { private Paj paj; @Inject private PajFacade pajFacade; private Criteria criteria; @Inject private SessionController userEJB; @Inject private CriteriaFacade criteriaFacade; public PajController() { } @PostConstruct public void initPajController() { this.paj = new Paj(); this.criteria = new Criteria(); } public CriteriaFacade getCriteriaFacade() { return criteriaFacade; } public void setCriteriaFacade(CriteriaFacade criteriaFacade) { this.criteriaFacade = criteriaFacade; } public SessionController getUserEJB() { return userEJB; } public void setUserEJB(SessionController userEJB) { this.userEJB = userEJB; } public Criteria getCriteria() { return criteria; } public void setCriteria(Criteria criteria) { this.criteria = criteria; } public Paj getPaj() { return paj; } public void setPaj(Paj paj) { this.paj = paj; } public PajFacade getPajFacade() { return pajFacade; } public void setPajFacade(PajFacade pajFacade) { this.pajFacade = pajFacade; } /** * Create a new Edition Paj */ public String createPaj() { pajFacade.create(paj); this.addMessage("PAJ Edition created successfuly"); return "adminHome"; } /** * * @return boolean if exists Evaluations */ public boolean existsEvaluations() { return pajFacade.exitsEvaluations(userEJB.getPajSelected()); } /** * remove PAJ Edition */ public String removepaj() { try { pajFacade.removePaj(paj); this.addMessage("PAJ Edition has been sucessfully removed"); } catch (PajDeleteException ex) { Logger.getLogger(PajController.class.getName()).log(Level.SEVERE, null, ex); this.errorMessage(ex.getMessage()); } return "adminHome?faces-redirect=true"; } /** * list all the pajs editions * * @return List of pajs Editions */ public List<Paj> listAllPajs() { return pajFacade.findAll(); } /** * create a new Criterion * * @return xhtml page - setCriteriaView */ public String createCriteria() { criteriaFacade.createCriteria(criteria, userEJB.getPajSelected()); criteria = null; return "setCriteriaView"; } /** * * @param criteria * @return remove the selected criteria */ public String removeCriteria(Criteria criteria) { criteriaFacade.removeCriteria(criteria, userEJB.getPajSelected()); return "setCriteriaView"; } /** * add a new message * * @param summary message */ public void addMessage(String summary) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null); FacesContext.getCurrentInstance().addMessage(null, message); } /** * add a new error message * * @param summary message */ public void errorMessage(String summary) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null); FacesContext.getCurrentInstance().addMessage(null, message); } }
Java
CL
32b1edbf918266bfcf4977e0c8a949dd9ab59b5c78687c8cd4e6921bcf465485
package com.hjy.business.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * (TNews)实体类 * * @author wangdengjun * @since 2020-09-28 17:48:11 */ @Data public class TNews implements Serializable { private static final long serialVersionUID = -2654819087415453966L; /** * 新闻主键id */ private String pkNewsId; /** * 新闻标题 */ private String newsTitle; /** * 新闻内容 */ private String newsContent; /** * 新闻封面 */ private String newsCover; /** * 新闻状态1已上线2未上线 */ private int newsStatus; /** * 新闻类型 1普通新闻2党内行业新闻3公司党建动态4成功案例 */ private int newsType; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8") private Date createDate; /** * 创建人id */ private String createUserId; /** * 创建人姓名 */ private String createUseFullName; /** * 最后修改人id */ private String lastModifyUserId; /** * 最后修改人姓名 */ private String lastModifyUserFullName; /** * 最后修改时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8") private Date lastModifyDate; }
Java
CL
b2a946a3b2296809ab283139f0fa54442f3b9ca40e2989f1e0d4343c1022cd92
package com.katrasolutions.feedbackservice.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.katrasolutions.feedbackservice.entity.Feedback; import com.katrasolutions.feedbackservice.exception.CustomExceptionHandler; import com.katrasolutions.feedbackservice.model.UserModel; import com.katrasolutions.feedbackservice.repository.FeedbackRepository; import com.katrasolutions.feedbackservice.response.FeedbackResponse; import com.katrasolutions.feedbackservice.service.FeedbackService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; import javax.persistence.EntityManager; import java.time.LocalDate; import java.util.Date; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest public class FeedbackControllerIntegrationTest { private static final ObjectMapper om = new ObjectMapper(); @Autowired private FeedbackService feedbackService; @Autowired private FeedbackRepository feedbackRepository; @Autowired private CustomExceptionHandler customExceptionHandler; @Autowired private Validator validator; @Autowired private EntityManager em; private MockMvc mockMvc; private Feedback feedback; private UserModel userModel; private static final String DEFAULT_DESCRIPTION = "hkjfshfskgsksk"; private static final String DEFAULT_DESCRIPTION_UPDATED = "hej"; private static final String DEFAULT_FIRST_NAME = "first"; private static final String DEFAULT_LAST_NAME = "last"; private static final String DEFAULT_EMAIL = "test@test.com"; @Before public void initTest() { feedback = createEntity(em); this.userModel = defaultUser(em); } @Before public void setUp() { MockitoAnnotations.initMocks(this); FeedbackController feedbackController = new FeedbackController(feedbackService); this.mockMvc = MockMvcBuilders.standaloneSetup(feedbackController) .setControllerAdvice(customExceptionHandler) .setValidator(validator) .build(); } private static Feedback createEntity(EntityManager em) { Feedback feedback = new Feedback(); feedback.setDescription(DEFAULT_DESCRIPTION); feedback.setCreatedOn(new Date()); return feedback; } private static UserModel defaultUser(EntityManager em) { UserModel user = new UserModel(); user.setLastName(DEFAULT_LAST_NAME); user.setFirstName(DEFAULT_FIRST_NAME); user.setEmail(DEFAULT_EMAIL); return user; } @Test @Transactional public void findFeedbackById() throws Exception { Feedback feedback = feedbackRepository.saveAndFlush(this.feedback); mockMvc.perform(MockMvcRequestBuilders.get("/feedback/{id}", feedback.getId())) .andDo(print()) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.description").value(DEFAULT_DESCRIPTION)); } @Test public void findFeedbackWithNoExistingId() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/feedback/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @WithMockUser("test@test.com") @Transactional public void findAllFeedback() throws Exception { feedbackRepository.saveAndFlush(feedback); mockMvc.perform(MockMvcRequestBuilders.get("/feedback")) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.[0].description").value(DEFAULT_DESCRIPTION)); } @Test @WithMockUser("test@test.com") @Profile({"dev"}) @Transactional public void createFeedback() throws Exception { FeedbackResponse feedbackResponse = new FeedbackResponse(); feedbackResponse.setDescription(DEFAULT_DESCRIPTION); mockMvc.perform(post("/feedback/") .content(om.writeValueAsString(feedbackResponse)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(MockMvcResultMatchers.jsonPath("$.description").value(DEFAULT_DESCRIPTION)); } @Test @WithMockUser("test@test.com") @Transactional public void updateFeedback() throws Exception { FeedbackResponse feedbackResponse = new FeedbackResponse(); feedbackResponse.setDescription(DEFAULT_DESCRIPTION_UPDATED); Feedback feedback = feedbackRepository.saveAndFlush(this.feedback); mockMvc.perform(put("/feedback/{id}", feedback.getId()) .content(om.writeValueAsString(feedbackResponse)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.description").value(DEFAULT_DESCRIPTION_UPDATED)); } @Test @WithMockUser("test@test.com") @Transactional public void deleteFeedback() throws Exception { Feedback feedback = feedbackRepository.saveAndFlush(this.feedback); mockMvc.perform(delete("/feedback/{id}", feedback.getId())) .andExpect(status().isNoContent()); } }
Java
CL
0a6aa50223e295f508de70d125aab834fbb535a48337cc3a0976f78545ec4661
package com.hps.mayo.services; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.hps.mayo.configuration.AppConstants; import com.hps.mayo.configuration.ApplicationConfiguration; @Service public class HttpService extends BaseHttpAction { protected Logger logger = LogManager.getLogger(this.getClass()); private CloseableHttpClient httpClient = null; private RestTemplate restTemplate = null; @Autowired private ApplicationConfiguration appConfig; public HttpService() { } @PostConstruct private void initialize() { initializeHttpClient(); initializeRestTemplate(); } @PreDestroy private void destroy() { HttpClientUtils.closeQuietly(httpClient); } public String getAuthHashCookie() { return authHashCookie; } private void setAuthHashCookie(String authHashCookie) { this.authHashCookie = authHashCookie; } private void initializeHttpClient() { httpClient = HttpClients.createDefault(); } private void initializeHttpClient(String userId, String pw) { httpClient = HttpClients.createDefault(); if (authHashCookie == null) startAuthorizedHTTPClient(userId, pw, appConfig.getActiveEndPoint() + AppConstants.AUTHORIZATION_URI); } private void initializeRestTemplate() { restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); messageConverters.add(new AllEncompassingFormHttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); } public RestTemplate getRestTemplate() { return restTemplate; } public CloseableHttpClient getHttpClient() { if (httpClient == null) initializeHttpClient(); return httpClient; } public void startAuthorizedHTTPClient(String user, String pw, String targetUrl) { try { String httpAuthRequest = "{ user:'" + user + "', password:'" + pw + "'}"; URL url = new URL(targetUrl); URLConnection urlConnection = handleBasicAuthentication(url, user, pw); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/json"); OutputStream os = urlConnection.getOutputStream(); os.write(httpAuthRequest.getBytes()); os.flush(); os.close(); Map<String, List<String>> headerFields = urlConnection.getHeaderFields(); setAuthCookie(headerFields); if (authHashCookie == null) logger.fatal("Unable to create a client connection to the target ORS. Application will not function."); } catch (Exception e) { logger.error("Error in startAuthorizedHTTPClient call: " + targetUrl + " Error:" + e.getMessage()); e.printStackTrace(); } } private void setAuthCookie(Map<String, List<String>> headerFields) { boolean cookieFound = false; Set<String> headerFieldSet = headerFields.keySet(); Iterator<String> headerFieldIter = headerFieldSet.iterator(); while (headerFieldIter.hasNext() && !cookieFound) { String headerFieldKey = headerFieldIter.next(); if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) { List<String> headerFieldValue = headerFields.get(headerFieldKey); for (String headerValue : headerFieldValue) { if (cookieFound) break; String[] fields = headerValue.split(";"); for (int i = 0; i < fields.length; i++) { if (fields[i].toLowerCase().startsWith("auth_hash_cookie")) { setAuthHashCookie(fields[i]); cookieFound = true; break; } } } } } } public HttpRequestBase buildHttpPostRequest(String requestUri) { HttpRequestBase baseGetRequest = new HttpGet(); baseGetRequest.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); baseGetRequest.setHeader("Accept-Language", "en-US,en;q=0.5"); baseGetRequest.setHeader("Connection", "keep-alive"); baseGetRequest.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { baseGetRequest.setURI(new URI(requestUri)); } catch (URISyntaxException e) { e.printStackTrace(); } return baseGetRequest; } public URL getPostUri() { URL url = null; try { url = new URL(appConfig.getActiveEndPoint() + AppConstants.PATH_DELIMITER + appConfig.getContextRoot() + AppConstants.PATH_DELIMITER + AppConstants.PUT_URI); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public URL getMergeUri() { URL url = null; try { url = new URL(appConfig.getActiveEndPoint() + AppConstants.PATH_DELIMITER + appConfig.getContextRoot() + AppConstants.PATH_DELIMITER + AppConstants.MERGE_URI); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public URL getUnmergeUri() { URL url = null; try { url = new URL(appConfig.getActiveEndPoint() + AppConstants.PATH_DELIMITER + appConfig.getContextRoot() + AppConstants.PATH_DELIMITER + AppConstants.UMERGE_URI); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public URL getPingUri() { URL url = null; try { url = new URL(appConfig.getActiveEndPoint() + AppConstants.PATH_DELIMITER + appConfig.getContextRoot() + AppConstants.PATH_DELIMITER + AppConstants.PING_URI); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } }
Java
CL
811e51530364f46cbd42bce04d77dac3bf79e4be975b608cace4bd305d42a936
package springdatarest.reactive.repository; import springdatarest.reactive.model.User; import org.springframework.data.r2dbc.repository.R2dbcRepository; import reactor.core.publisher.Flux; public interface UserRepository extends R2dbcRepository<User, Long> { Flux<User> findByName(String name); }
Java
CL
3b7e94746c913cf677b76c93e1d41f45e4905d5945640c386f020356bf215006
import java.io.*; import java.net.URI; import java.util.ArrayList; import java.util.concurrent.atomic.*; import org.apache.log4j.Level; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.permission.*; import org.apache.hadoop.hdfs.*; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.StringUtils; import org.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; import static org.junit.Assert.*; public class TestFuseDFS
Java
CL
d18b189517d7351e1f8dab0739c8963597c8c924173e3d1cc40ea9675bbeee3a
package com.alone.hotel.dao; import com.alone.hotel.entity.Recreation; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @BelongsProject: hotel * @BelongsPackage: com.alone.hotel.dao * @Author: Alone * @CreateTime: 2020-03-17 19:48 * @Description: */ public interface RecreationDao { /** * 添加其他娱乐项目 * @param recreation * @return */ int addRecreation(Recreation recreation); /** * 根据娱乐项目号查询对应娱乐项目信息 * @param recreationId * @return */ Recreation queryRecreationById(int recreationId); /** * 根据查询条件查询对应娱乐项目信息 * @param recreationCondition * @param rowIndex * @param pageSize * @return */ List<Recreation> queryRecreationList(@Param("recreationCondition") Recreation recreationCondition, @Param("rowIndex") int rowIndex, @Param("pageSize") int pageSize); /** * 娱乐项目信息总数 * @return */ int queryRecreationCount(@Param("recreationCondition") Recreation recreationCondition); /** * 修改娱乐项目信息 * @param recreation * @return */ int updateRecreation(Recreation recreation); /** * 删除娱乐项目信息 * @param recreationId * @return */ int deleteRecreation(int recreationId); }
Java
CL
78dfb84a497c89d8ece9db14265476442ecae5262d5eafa421ed17a584d8f6ed
package io.oasp.gastronomy.restaurant.suppliermanagement.service.impl.rest; import javax.inject.Inject; import javax.inject.Named; import io.oasp.gastronomy.restaurant.suppliermanagement.logic.api.Suppliermanagement; import io.oasp.gastronomy.restaurant.suppliermanagement.logic.api.to.SupplierCto; import io.oasp.gastronomy.restaurant.suppliermanagement.logic.api.to.SupplierEto; import io.oasp.gastronomy.restaurant.suppliermanagement.logic.api.to.SupplierSearchCriteriaTo; import io.oasp.gastronomy.restaurant.suppliermanagement.service.api.rest.SuppliermanagementRestService; import io.oasp.module.jpa.common.api.to.PaginatedListTo; /** * The service implementation for REST calls in order to execute the logic of component {@link Suppliermanagement}. */ @Named("SuppliermanagementRestService") public class SuppliermanagementRestServiceImpl implements SuppliermanagementRestService { @Inject private Suppliermanagement suppliermanagement; @Override public SupplierEto getSupplier(long id) { return this.suppliermanagement.findSupplier(id); } @Override public SupplierEto saveSupplier(SupplierEto supplier) { return this.suppliermanagement.saveSupplier(supplier); } @Override public void deleteSupplier(long id) { this.suppliermanagement.deleteSupplier(id); } @Override public PaginatedListTo<SupplierEto> findSuppliersByPost(SupplierSearchCriteriaTo searchCriteriaTo) { return this.suppliermanagement.findSupplierEtos(searchCriteriaTo); } @Override public SupplierCto getSupplierCto(long id) { return this.suppliermanagement.findSupplierCto(id); } @Override public PaginatedListTo<SupplierCto> findSupplierCtosByPost(SupplierSearchCriteriaTo searchCriteriaTo) { return this.suppliermanagement.findSupplierCtos(searchCriteriaTo); } }
Java
CL
cafed884b026f2ff4a30a73e167c0310de33e8d1b33ab1a054e5d7da6d740184
package org.hisp.dhis.reporting.action.scheduletask; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementService; import org.hisp.dhis.program.ProgramStageInstance; import org.hisp.dhis.program.ProgramStageInstanceService; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValueService; import org.hisp.dhis.user.CurrentUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import com.opensymphony.xwork2.Action; /** * @author Mithilesh Kumar Thakur */ public class ScheduleAutoApproveTrackerData implements Action { private final static int CURRENT_STATUS_DATAELEMENT_ID = 38576348; private final static String PROGRAM_STAGE_IDS = "38565722,38565580,38565712,38565696"; // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- @Autowired private ProgramStageInstanceService programStageInstanceService; @Autowired private CurrentUserService currentUserService; @Autowired private TrackedEntityDataValueService trackedEntityDataValueService; @Autowired private TrackedEntityInstanceService trackedEntityInstanceService; @Autowired private DataElementService dataElementService; @Autowired private JdbcTemplate jdbcTemplate; // ------------------------------------------------------------------------- // Input & Output // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Action IMplementation // ------------------------------------------------------------------------- public String execute() throws Exception { System.out.println("INFO: scheduler job has started at : " + new Date() ); List<Integer> programStageInstanceIds = new ArrayList<Integer>( getProgramStageInstanceIds() ); //System.out.println( " Size of programStageInstanceIds List -- " + programStageInstanceIds.size() ); String storedBy = "admin"; String importStatus = ""; Integer updateCount = 0; Integer insertCount = 0; /* long t; Date d = new Date(); t = d.getTime(); java.sql.Date lastUpdatedDate = new java.sql.Date( t ); java.sql.Date createdDate = new java.sql.Date( t ); */ Date date = new Date(); java.sql.Timestamp lastUpdatedDate = new Timestamp(date.getTime()); java.sql.Timestamp createdDate = new Timestamp(date.getTime()); //System.out.println( new Timestamp(date.getTime() ) ); String insertQuery = "INSERT INTO trackedentitydatavalue ( programstageinstanceid, dataelementid, value, providedelsewhere, storedby, created, lastupdated ) VALUES "; String updateQuery = ""; String value = "Auto-Approved"; int insertFlag = 1; int count = 1; if( programStageInstanceIds != null && programStageInstanceIds.size() > 0 ) { try { for( Integer psiId : programStageInstanceIds ) { updateQuery = "SELECT value FROM trackedentitydatavalue WHERE dataelementid = " + CURRENT_STATUS_DATAELEMENT_ID + " AND programstageinstanceid = " + psiId; SqlRowSet updateSqlResultSet = jdbcTemplate.queryForRowSet( updateQuery ); if ( updateSqlResultSet != null && updateSqlResultSet.next() ) { String tempUpdateQuery = "UPDATE trackedentitydatavalue SET value = '" + value + "', storedby = '" + storedBy + "',lastupdated='" + lastUpdatedDate + "' WHERE dataelementid = " + CURRENT_STATUS_DATAELEMENT_ID + " AND programstageinstanceid = " + psiId; jdbcTemplate.update( tempUpdateQuery ); updateCount++; } else { insertQuery += "( " + psiId + ", " + CURRENT_STATUS_DATAELEMENT_ID + ", '" + value + "', false ,'" + storedBy + "', '" + createdDate + "', '" + lastUpdatedDate + "' ), "; insertFlag = 2; insertCount++; } if ( count == 1000 ) { count = 1; if ( insertFlag != 1 ) { insertQuery = insertQuery.substring( 0, insertQuery.length() - 2 ); //System.out.println( " insert Query 2 - " ); jdbcTemplate.update( insertQuery ); } insertFlag = 1; insertQuery = "INSERT INTO trackedentitydatavalue ( programstageinstanceid, dataelementid, value, providedelsewhere, storedby, created, lastupdated ) VALUES "; } count++; } //System.out.println(" Count - " + count + " -- Insert Count : " + insertCount + " Update Count -- " + updateCount ); if ( insertFlag != 1 ) { insertQuery = insertQuery.substring( 0, insertQuery.length() - 2 ); //System.out.println(" insert Query 1 - "); jdbcTemplate.update( insertQuery ); } importStatus = "Successfully populated tracker data : "; importStatus += "<br/> Total new records : " + insertCount; importStatus += "<br/> Total updated records : " + updateCount; //System.out.println( importStatus ); } catch ( Exception e ) { importStatus = "Exception occured while import, please check log for more details" + e.getMessage(); } } System.out.println("ImportStatus : " + importStatus ); System.out.println("INFO: Scheduler job has ended at : " + new Date() ); return SUCCESS; } //-------------------------------------------------------------------------------- // Get ProgramStageInstanceIds //-------------------------------------------------------------------------------- public List<Integer> getProgramStageInstanceIds() { List<Integer> programStageInstanceIds = new ArrayList<Integer>(); //String current_date = "2018-06-06"; //String endDateOfCurrentMonth1 = "2017-12-31"; //SELECT trackedentityinstanceid, value FROM trackedentityattributevalue WHERE CURRENT_DATE > value::date and trackedentityattributeid = 1085; try { String query = "SELECT psi.programstageinstanceid, psi.completeddate from programstageinstance psi " + "WHERE psi.programstageid in ( "+ PROGRAM_STAGE_IDS +" ) AND " + "psi.completeddate <= CURRENT_DATE - interval '7 day' AND psi.status = 'COMPLETED' order by psi.completeddate desc; "; //System.out.println( "query = " + query ); SqlRowSet rs = jdbcTemplate.queryForRowSet( query ); //System.out.println( "-- RS " + rs.toString() + " -- " + rs.isFirst() + " -- " + rs.next() ) ; while ( rs.next() ) { Integer psiId = rs.getInt( 1 ); //System.out.println( i + " -- psi Id added " + psiId ) ; if ( psiId != null ) { ProgramStageInstance psi = programStageInstanceService.getProgramStageInstance( psiId ); DataElement de = dataElementService.getDataElement( CURRENT_STATUS_DATAELEMENT_ID ); if( psi != null && de != null) { TrackedEntityDataValue teDataValue = trackedEntityDataValueService.getTrackedEntityDataValue( psi, de ); if( teDataValue == null || teDataValue.getValue().equalsIgnoreCase( "Re-submitted" )) { programStageInstanceIds.add( psi.getId() ); } } } } return programStageInstanceIds; } catch ( Exception e ) { throw new RuntimeException( "Illegal ProgramStage ids", e ); } } }
Java
CL
4dccd40309f99f38505aae4962d9855bb8e9fdb7991d38b6724a678192c560c8